-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryDigitsCounter.kt
62 lines (53 loc) · 1.54 KB
/
BinaryDigitsCounter.kt
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package other
/**
* This algorithm counts the number of ones and zeros in a binary string
* and implemented on a finite state machine
*
*/
class BinaryDigitsCounter {
/**
* Stores the result of the algorithm
*
*/
data class Result(private val ones: Int = 0, private val zeros: Int = 0)
/**
* Represents two states
*
*/
private enum class State {
ONE, ZERO
}
fun compute(binaryString: String): Result { // 1010010011
if (binaryString.isEmpty()) {
return Result()
}
// define initial state
var currentState = if (binaryString.first() == '1') State.ONE else State.ZERO
var onesCount = 0
var zerosCount = 0
binaryString.forEach { symbol ->
// we use 'when' statement to toggle the state
when (currentState) {
State.ONE -> {
if (symbol == '0') {
zerosCount++
// move to another state
currentState = State.ZERO
} else {
onesCount++
}
}
State.ZERO -> {
if (symbol == '1') {
onesCount++
// move to another state
currentState = State.ONE
} else {
zerosCount++
}
}
}
}
return Result(onesCount, zerosCount)
}
}