added finite state machine to calculate the number of ones and zeros in a binary string

This commit is contained in:
evitwilly
2022-09-02 08:17:07 +03:00
parent b363e9e88d
commit 346bef794c
7 changed files with 107 additions and 0 deletions

View File

@ -0,0 +1,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)
}
}

View File

@ -0,0 +1,45 @@
package other
import org.junit.Test
import org.junit.jupiter.api.Assertions
internal class BinaryDigitsCounterTest {
private val counter = BinaryDigitsCounter()
@Test
fun test_empty_string() {
val result = counter.compute("")
Assertions.assertEquals(BinaryDigitsCounter.Result(), result)
}
@Test
fun test_binary_string_1() {
val result = counter.compute("10101111000")
Assertions.assertEquals(BinaryDigitsCounter.Result(6, 5), result)
}
@Test
fun test_binary_string_2() {
val result = counter.compute("0100000111110010101010")
Assertions.assertEquals(BinaryDigitsCounter.Result(10, 12), result)
}
@Test
fun test_binary_string_3() {
val result = counter.compute("1111111111")
Assertions.assertEquals(BinaryDigitsCounter.Result(10, 0), result)
}
@Test
fun test_binary_string_4() {
val result = counter.compute("0000000000")
Assertions.assertEquals(BinaryDigitsCounter.Result(0, 10), result)
}
}