Java: Print first, fourth, seventh... of an array using only ONE LOOP? -
given array of integer.
i want first print print 1st, 4th, 7th.. numbers. 2nd, 5th, 8th.. , 3rd, 6th, 9th..
i want use 1 loop iterate through array. how can this?
(note: size of array 4, 7, 10, 13.. , on, i.e. in increments of 3.)
thanks.
write function
private int index(int i, int length)
which computes right index loop variable i
edit
wasn't easy first thought:
public static void main(string[] args) { int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 }; (int = 0; < array.length; i++) { system.out.println(array[index(i, array.length)]); } } private static int index(int i, int length) { int third = (length + 2) / 3; if (length % 3 == 1 && >= third) { // spezial, because second third smaller return index(i - 1, length - 1); } int group = % third; return (group) * 3 + (i / third); }
edit did cleanup;
Comments
Post a Comment