java - Comparing an array to its mirror -
okay have method needs take in array full of ints
, check against it's mirror see largest mirror matches to. example have array [7, 1, 2, 9, 7, 2, 1]
, largest array can match 2, being matched @ [1, 2]
.
right have broken 3 methods. 1 accepts array, reverses array , returns (mirrorarray
). , 3rd being counting size of array matches(groupcount
). here have far:
public int maxmirror(int[] nums) { int[] revarray = mirrorarray(nums); return groupcount(nums, revarray); } private int[] mirrorarray(int[] nums) { int[] newarray = new int[nums.length]; (int = nums.length-1, j = 0; >= 0; i--, j++) { newarray[j] = nums[i]; } return newarray; } private int groupcount(int[] afor, int[] brev) { int maxcount = 0; int groupsize = 1; //get afor value (int = 0; < afor.length; i++) { int[] tempa = arrays.copyofrange(afor, 0, groupsize); //loop through brev , check matches (int j = 0; j < brev.length; j++) { int[] tempb = arrays.copyofrange(brev, j, j+groupsize); if (arrays.equals(tempa, tempb)) { maxcount = tempa.length; } } groupsize++; } return maxcount; }
it failing in 3rd method somewhere (returning 1 instead of 2) , i'm stumped why loops have arnt returning want. appreciated.
alright curious...
here's problem:
int[] tempa = arrays.copyofrange(afor, 0, groupsize);
you comparing tempb first subarray of length groupsize
of afor. change line to
int[] tempa = arrays.copyofrange(afor, i, + groupsize);
and should work.
edit keep failure cases coming.. seems issue increment location of groupsize
while (groupsize < afor.length) { //get afor value (int = 0; < afor.length; i++) { int[] tempa = arrays.copyofrange(afor, i, + groupsize); //loop through brev , check matches (int j = 0; j < brev.length; j++) { int[] tempb = arrays.copyofrange(brev, j, j+groupsize); if (arrays.equals(tempa, tempb)) { maxcount = groupsize; } } } groupsize++; }
this not efficient, , might fun exercise optimize. 1 starting approach start groupsize @ afor.length
, decrement. maxcount
assigned, can return.
edit 2
int groupsize = afor.length; while (groupsize >= 0) { //get afor value (int = 0; <= afor.length - groupsize; i++) { // note change int[] tempa = arrays.copyofrange(afor, i, + groupsize); //loop through brev , check matches (int j = 0; j <= brev.length - groupsize; j++) { // note change int[] tempb = arrays.copyofrange(brev, j, j+groupsize); if (arrays.equals(tempa, tempb)) { return groupsize; } } } groupsize--; } return 1; }
what happening arrays.copyofrange filling out of bounds numbers zeroes. added exit opt mentioned earlier. there more optimizations can done
Comments
Post a Comment