Given integer n, create an array with the pattern {1, 1, 2, 1, 2, 3, ... 1, 2, 3 .. n} (spaces added to show the grouping). Note that the length of the array will be 1 + 2 + 3 ... + n, which is known to sum to exactly n*(n + 1)/2.
seriesUp(3) → {1, 1, 2, 1, 2, 3}
seriesUp(4) → {1, 1, 2, 1, 2, 3, 1, 2, 3, 4}
seriesUp(2) → {1, 1, 2}
An excellent Array question , I have posted a similar question before (squareIn). First thing to be done is declare a target array , as it’s size can be determined by the n*(n+1)/2 .
public int[] seriesUp(int n) {int x[]= new int[n*(n+1)/2];for(int i=0, k=0; i<n; i++){for(int j=0; j<=i;j++ ){x[k]=j+1;k++;}}return x;}