Home > Net >  How do iterate a sequence with varying starting positions
How do iterate a sequence with varying starting positions

Time:02-08

Say I have an array:

[10,12,20,50]

I can iterate though this array like normal which would look at the position at 0, then 1, 2, and 3.

What if I wanted to start an any arbritrary position in the array, and then go through all the numbers in order.

So the other permutations would be:

10,12,20,50
12,20,50,10
20,50,10,12
50,10,12,20

Is there a general function that would allow me to do this type of sliding iteration?

so looking at the index positions from the above it would be:

0,1,2,3
1,2,3,0
2,3,0,1
3,0,1,2

It would be great if some languages have this built in, but I want to know the algorithm to do this also so I understand.

CodePudding user response:

Let's iterate over an array.

val arr = Array(10, 12, 20, 50)

for (i <- 0 to arr.length - 1) {
    println(arr(i))
}

With output:

10
12
20
50

Pretty basic.

What about:

val arr = Array(10, 12, 20, 50)

for (i <- 2 to (2   arr.length - 1)) {
    println(arr(i))
}

Oops. Out of bounds. But what if we modulo that index by the length of the array?

val arr = Array(10, 12, 20, 50)

for (i <- 2 to (2   arr.length - 1)) {
    println(arr(i % arr.length))
}
20
50
10
12

Now you just need to wrap it up in a function that replaces 2 in that example with an argument.

CodePudding user response:

There is no language builtin. There is a similar method permutations, but it will generate all permutations without the order, which doesn't really fit your need.

Your requirement can be implemented with a simple algorithm where you just concatenates two slices:

def orderedPermutation(in: List[Int]): Seq[List[Int]] = {
  for(i <- 0 until in.size) yield
    in.slice(i, in.size)    in.slice(0, i)
}

orderedPermutation(List(10,12,20,50)).foreach(println)

Working code here

  •  Tags:  
  • Related