Kotlin - convert cycle to functional style

I have the following Kotlin function:

fun func(n: Int): Int {

    var count = 1

    var m = n
    while(m != 1) {

        m = if(m.isOdd()) 3 * m + 1 else m / 2

        count++
    }

    return count
}

I would like to write this simple algorithm in a “functional” style using Kotlin operators like map (), count (), etc. The closest I could come up with was the following:

fun func(n: Int): Int {

    return n.toList()
            .map{ if(it.isOdd()) 3*it+1 else it/2 }
            .takeWhile { it != 1 }
            .count()

}

Obviously, the code above does not work, because the card runs only once, but you get an idea of ​​what I'm trying to achieve.

PS: toList () is just an extension function that converts an int to a list containing this int:

fun Int.toList() = listOf(this)
+4
source share
1 answer

, , (, ) , , it != 1 , :

return generateSequence(n) { if (it.isOdd()) 3 * it + 1 else it / 2 }
        .takeWhile { it != 1 }
        .count()

generateSequence(n) { ... }, Sequence<Int>, n , , ( , .. ).

+6

Source: https://habr.com/ru/post/1683853/


All Articles