Pulsing sequence generator
Imagine you need to generate a “pulsing” sequence of numbers which continuously repeats, going up and down between the given values, like this: 5-6-7-8-9-10-9-8-7-6-5-6-7…
Such a sequence may serve different purposes, but in any case, we want a universal solution even for this simple problem. The algorithm is simple too…
class Stairs {
private int min;
private int max;
private int diff;
private int value;
public Stairs(int min, int max) {
this.min = min;
this.max = max;
this.diff = max - min;
this.value = diff - 1;
}
public int next() {
value = (value + 1) % (2 * diff);
return min + Math.abs(value - diff);
}
}
Source code and output of the program are available at the end of this post. Moreover, you can try to play with it using the plotter below: change min and max values.
Source code
Example.java
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main {
public static void main (String[] args) {
Stairs s = new Stairs(5, 10);
for (int i = 0; i <= 20; ++i) {
System.out.println(s.next());
}
}
}
class Stairs {
private int min;
private int max;
private int diff;
private int value;
public Stairs(int min, int max) {
this.min = min;
this.max = max;
this.diff = max - min;
this.value = diff - 1;
}
public int next() {
value = (value + 1) % (2 * diff);
return min + Math.abs(value - diff);
}
}
Output
5
6
7
8
9
10
9
8
7
6
5
6
7
8
9
10
9
8
7
6
5
