java - Split an array into 4 portions -
i have create method divides array of integers taken input array made in way:
- the first portion composed of elements which, divided 4, generate rest 0
- the second portion composed of elements which, divided 4, give rest 1
- the third portion composed of elements which, divided 4, give remainder 2
- the fourth portion composed of elements, divided 4, give rest 3
for example, following array:
[0,2,4,5,6,8,7,9,10,12,14,15,17,20,1]
must become here:
[0,4,8,12,20,5,9,17,1,2,6,10,14,7,15]
the result is:
[0,4,5,8,6,2,7,9,10,12,14,15,17,20,1]
within subsequences no matter order of items, in subsequence correct.
i wrote method doen't work properly, items out of place.
public static void separate4colors(int[] a) { int = 0; int j = 0; int k = 0; int h = a.length - 1; while(k <= h) { if(a[k] % 4 == 0) { swap(a, k, i); k++; i++; j++; } else if(a[k] % 4 == 1) { swap(a, k, i); k++; i++; } else if(a[k] % 4 == 2) { k++; } else { while(h > k && a[k] % 4 == 3) h--; swap(a, k, h); h--; } } } private static void swap(int[] a, int x, int y) { int temp = a[x]; a[x] = a[y]; a[y] = temp; }
can me fix it?
a similar exercise i've done , work divide array 3 portions instead 4:
public static void separate3colors(int[] a) { int j = 0; int k = a.length - 1; int = 0; while(j <= k) { if(a[j] % 3 == 0) { swap(a, j, i); j++; i++; } else if(a[j] % 3 == 1) { j++; } else { swap(a, j, k); k--; } } }
you can in single line sorting array using comparator compares numbers modulo 4. unfortunately, requires array of integer
objects.
another approach writing results different array. can walk array once determine indexes @ values each remainder start, , walk array again make ordered copy:
int[] index = new int[4]; for(int n : a) { int r = n % 4; if (r != 3) { index[r+1]++; } } index[2] += index[1]; index[3] += index[2]; // @ point each index[k] has position elements // remainder of k start int[] res = new int[a.length]; for(int n : a) { res[index[n%4]++] = n; }
this places re-ordered array res
variable.
Comments
Post a Comment