0

For example:

for ((x, y) in (1..100, 50 downTo 0)) {} 
for ((x, y, z) in (1..100, 50 downTo 0, 500..1000 step 2)) {} 

I have found the official kotlin document: Destructuring Declarations, but still can't write correct code.

5
  • For your first example, do you want all combinations of tuples? ie {(x,y) | x in [1, 100] and y in [0, 50]}? (<- that's math notation, not python syntax) Commented Nov 5, 2019 at 14:09
  • @SyntaxVoid Yes. Commented Nov 5, 2019 at 14:26
  • Maybe zip is what you are looking for, e.g.: (1..100).zip(50 downTo 0).forEach { (x, y) -> /* do something */ }... Commented Nov 5, 2019 at 14:58
  • For triple values it is a bit more complicated... (1..100).zip(50 downTo 0).zip(500..1000 step 2).forEach { (xy, z) -> xy.also { (x, y) -> /* do something with x, y and z */ } }... Note that if any of those ranges finishes earlier, it will stop with the latest possible value... e.g. in the last example the highest z would be 600... Commented Nov 5, 2019 at 15:00
  • if you want to have all values combined with each other instead, you may just want to nest those loops instead, e.g. for (x in 1..100) { for (y in 50 downTo 0) { for (z in 500..1000 step 2) { /* do something with x, y and z */ }}} Commented Nov 5, 2019 at 15:01

1 Answer 1

1

You can create a zipOf function, which returns a Sequence of all possible combinations. Here are 3 overloads of this function:

fun <T1, T2> zipOf(first: Iterable<T1>, second: Iterable<T2>) = sequence { for (t1 in first) for (t2 in second) yield(t1 to t2) } fun <T1, T2, T3> zipOf(first: Iterable<T1>, second: Iterable<T2>, third: Iterable<T3>) = sequence { for (t1 in first) for (t2 in second) for (t3 in third) yield(Triple(t1, t2, t3)) } fun <T> zipOf(vararg iterables: Iterable<T>): Sequence<List<T>> = iterables.fold(sequenceOf(emptyList())) { result, iterable -> result.flatMap { list -> iterable.asSequence().map { elm -> list + elm } } } 

You can use them like this:

for ((x, y) in zipOf(1..100, 50 downTo 0)) {} for ((x, y, z) in zipOf(1..100, 50 downTo 0, 500..1000 step 2)) {} for ((x, y, z, w) in zipOf(1..100, 50 downTo 0, 500..1000 step 2, 0..1)) {} 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.