I currently need to produce an array consisting of the following elements:
-0.5, 0, 0.5, 0, -0.5, 0, 0.5, 0...
and so on. This is my current code:
// Sequence: -0.5, 0, 0.5, 0, -0.5, 0, 0.5...
public static double[] generateI(int n) {
if (n < 0) {
return null;
} else if (n == 0) {
return new double[0];
}
double[] arr = new double[n];
for (int i = 0; i < n; i++) {
arr[i] = ((0.5 * i) % 2) - 0.5; \\need help here.
}
return arr;
}
However, my output is:
[-0.5, 0.0, 0.5, 1.0, -0.5, 0.0, 0.5, 1.0, -0.5, 0.0, 0.5, 1.0].
Hence, my math equation is wrong.
(note that I have tried using the -Math.cos(i * Math.PI/2)/2 equation, and although it is a valid solution, I was tasked to do it using a modulus function in a single line of code.)
Another sequence (for those interested) is:
-0, 1, 2, 3, 1, 2, 3, 4, 2, 3, 4, 5...
Any help is appreciated!