I am trying to converting a for loop to functional code. I need to look ahead one value and also look behind one value. Is it possible using streams? The following code is
Not exactly a Java solution, but possible to get next element in Kotlin with zip
functions. Here is what I came up with functions. Looks much cleaner
enum class RomanNumeral(private val value: Int) {
I(1), V(5), X(10), L(50), C(100), D(500), M(1000);
operator fun minus(other: RomanNumeral): Int = value - other.value
operator fun plus(num: Int): Int = num + value
companion object {
fun toRoman(ch: Char): RomanNumeral = valueOf(ch.toString())
}
}
fun toNumber(roman: String): Int {
return roman.map { RomanNumeral.toRoman(it) }
.zipWithNext()
.foldIndexed(0) { i, currentVal, (num1, num2) ->
when {
num1 < num2 -> num2 - num1 + currentVal
i == roman.length - 2 -> num1 + (num2 + currentVal)
else -> num1 + currentVal
}
}
}