'Java find Minimum rotation calculate in 2 Array
In a row of dominoes, tops[i] and bottoms[i] represent the top and bottom halves of the ith domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the ith domino, so that tops[i] and bottoms[i] swap values.
Return the minimum number of rotations so that all the values in tops are the same, or all the values in bottoms are the same.
I was able to solve it without the minimum requirement, how can I solve it with the minimum requirement, also is there a non-recursive solution?
@Test
public void runDomino(){
int[] tops = new int[]{2,1,2,4,2,2};
int[] bottoms = new int[]{5,2,6,2,3,2};
System.out.println(getCounter(tops, bottoms, 0,0));
}
private int getCounter(int[] tops, int[] bottoms, int counter, int i) {
if(i==tops.length-1){
return counter;
} else {
if(tops[i]== tops[i+1] || bottoms[i]== bottoms[i+1]){
i++;
return getCounter(tops, bottoms, counter, i);
}
else if(tops[i]== bottoms[i+1] || bottoms[i+1]== tops[i]){
counter++;
i++;
int temp = tops[i];
tops[i] = bottoms[i];
bottoms[i] = temp;
return getCounter(tops, bottoms, counter, i);
} else {
System.out.println("not matches anyway");
return Integer.MAX_VALUE;
}
}
}
Solution 1:[1]
I'm going to assume reasonable inputs and that there are no duplicate dominoes in the set.
The first thing to do is identify the common value. I'll wave my hands at how you determine what the common value because it shouldn't be hard given the assumptions. So I'll leave that as a method to be implemented...
int value = findCommonValue(tops, bottoms);
Count the number of times that value occurs in each of the arrays. Since we can get all of the common values in either tops or bottoms, the minimum number of swaps is the shared length of the arrays minus the larger value.
int numValuesTops = (int) Arrays.stream(tops).filter(e -> e == value).count();
int numValuesBottoms = (int) Arrays.stream(bottoms).filter(e -> e == value).count();
int minSwaps = Math.min(numValuesTop, numValuesBottoms);
So, given the tops/bottoms that follow:
int[] tops = new int[] {2, 1, 2, 4, 2, 2};
int[] bottoms = new int[] {5, 2, 6, 2, 3, 2};
- In this case, the common value is 2.
- The number of 2s in
topsis 4 - The number of 2s in
bottomsis 3 - Length of arrays (6) minus larger count (4) is 2
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
