-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathalternatingOneAndZero.js
More file actions
42 lines (33 loc) · 903 Bytes
/
alternatingOneAndZero.js
File metadata and controls
42 lines (33 loc) · 903 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
* There are N coins, each showing either heads or tails.
* Make the coins to form a sequence of alternating heads or tails.
* What is the minimum number of coins that must be reversed to achieve this?
*/
/**
* Reverses a bit. Returns 1 if 0 is provided and vice versa.
*/
const reverse = (bit) => {
return bit === 0 ? 1 : 0;
};
/**
* Gets total number of reversals required if we were to transform
* provided array into an alternating sequence.
* Expected = 0 or 1
*/
const getReversals = (arr, expected) => {
let reversals = 0;
arr.forEach((digit) => {
if (expected !== digit) {
reversals++;
}
expected = reverse(expected);
});
return reversals;
};
/**
* Returns minimum number of reversals required to form
* a sequence of alternating bits
*/
const getMinimumReversals = (arr) => {
return Math.min(getReversals(arr, 0), getReversals(arr, 1));
};