Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin loop with irregular steps

Tags:

java

kotlin

I have been trying to translate a Java for expression into Kotlin which produces this sequence:

1,2,4,8,16,32,64

This is the Java code:

for(int i = 1; i < 100; i = i + i) {
    System.out.printf("%d,", i);
}

The only way I have found to translate this into Kotlin is:

var i = 1
while (i < 100) {
    print("$i,")
    i += i
}

I have tried to use step expressions, but this does not seem to work. Is there any way to express this type of sequence more elegantly in Kotlin?

I know you can have code like this one using Kotlin + Java 9:

Stream.iterate(1, { it <= 100 }) { it!! + it }.forEach { print("$it,") }

But this relies on Java libraries and I would prefer Kotlin native libraries.

like image 839
gil.fernandes Avatar asked Mar 07 '23 23:03

gil.fernandes


1 Answers

You can use the generateSequence function to create an infinite sequence, then use takeWhile to limit it at a specific value and then use forEach instead of a for-in construct to handle each iteration:

generateSequence(1) { it + it }.takeWhile { it < 100 }.forEach { print("$it,") }

like image 196
Kiskae Avatar answered Mar 14 '23 23:03

Kiskae