'Java: Generate array from 1 to n with step size

I have trouble with a quite easy task. I want to have an array from 0 to a value n with step size t, always ending with n.

Example 1: n=10, t=3, array={0, 3, 6, 9, 10}

Example 2: n=20, t=5, array={0, 5, 10, 15, 20}

Example 3: n=1, t=1, array={0, 1}

I have code which I have been using for a while, but I found out there are some weird edge cases and its quite heavy to read.

int numOfElements = (int)(Math.ceil(n/2.0)+1);
int[] array = new int[numOfElements];

for(int pos=0; pos < numOfElements; pos++) {
    int val = t*pos;
    val = Math.min(val, n);
    array[pos] = val;
}

Is there a better solution for that?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source