Skip to content
Advertisement

IntStream.iterate with alternating values to add

I want to create a sequence of integers, preferably as an IntStream, which follows a certain condition. some simple examples to explain what I am trying to do:

Sequence of first 10 even numbers starting from 0 (Here i have no problems, I do it with the below snippet)

JavaScript

Sequence of first 10 numbers starting from 0 by alternately adding 2 and 3 to the privious number; desired output:

JavaScript

I would love to use for this scenario also IntStream.iterate() or IntStream.generate() but couldn’t make it on my own. I am using classic for loops, which works but is somehow long for such a relative simple task

JavaScript

Any easy way to achieve the same as above with IntStream.iterate() or IntStream.generate()?

For three and more alternating values I am out of ideas how to do it elegantly. If for example I want to create the Sequence of first 10 numbers starting from 0 by alternately adding +2, +5 and +7 to the previous number with the desired output:

JavaScript

I have thought about using i%3 in a for loop with 3 if-else blocks or switch cases but this will grow when i need more alternating values and i have to add more ifs or cases. Any ideas how to do it? I am open for other approaches too if you think IntStream.iterate() or IntStream.generate() is not the proper way of solving the described task.

Advertisement

Answer

You can look at this mathematically. Say you want to add x1, x2, x3 … xn, alternately.

The first n terms can be written as:

JavaScript

The next n terms can be written the same way, except you replace all the 0s with 1s.

JavaScript

And the next n terms you replace all the 1’s with 2’s, and so on.

So we just need to generate the stream (1, 2, 3, 4…) and flatMap each element i to the stream of

JavaScript

Using this pattern, you can write your 2, 5, 7 stream like this:

JavaScript

If you wanted to do 2,3,5,7 instead:

JavaScript

I’ll leave it to you to generalise this to any int[] of numbers.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement