は、本質的に、我々は、グループに各アレイ値場所を必要とします。すべてのポジションを知ったら、これらのポジションがすべて隣接しているかどうかを調べる必要があります(pos1ごとにpos2、pos1、pos2)。< 2)。 JUnitテストとともに
public class ContiguousArray {
public static <E> boolean isContiguous(E[][] array) {
Map<E, Collection<Integer[]>> groupedPositions = groupLocations(array);
return groupedPositions.values().stream().allMatch(ContiguousArray::allContiguous);
}
private static <E> Map<E, Collection<Integer[]>> groupLocations(E[][] array) {
Map<E, Collection<Integer[]>> locations = new HashMap<>();
for(int x = 0; x < array.length; x++) {
for(int y = 0; y < array[x].length; y++) {
Collection<Integer[]> knownIndices;
Integer[] currentPosition = new Integer[] { x, y };
E currentElement = array[x][y];
if(locations.containsKey(currentElement)) {
knownIndices = locations.get(currentElement);
} else {
knownIndices = new HashSet<>();
locations.put(currentElement, knownIndices);
}
knownIndices.add(currentPosition);
}
}
return locations;
}
/**
* @return true, if all of the provided indices have an adjacent index in
* the same collection. Also true, if the collection's size < 2.
* False, otherwise.
*/
private static boolean allContiguous(Collection<Integer[]> indices) {
return indices.stream().allMatch(thisIndex -> hasAdjacent(indices, thisIndex) || indices.size() < 2);
}
private static boolean hasAdjacent(Collection<Integer[]> indices, Integer[] thisIndex) {
return indices.stream().anyMatch(thatIndex -> isAdjacent(thisIndex, thatIndex));
}
private static boolean isAdjacent(Integer[] thisIndex, Integer[] thatIndex) {
return thatIndex != thisIndex && calculateDistance(thisIndex, thatIndex) < 2;
}
private static int calculateDistance(Integer[] indexA, Integer[] indexB) {
int sum = 0;
for (int i = 0; i < indexA.length; i++) {
sum += Math.abs(indexA[i] - indexB[i]);
}
return sum;
}
}
:
public class ContiguousArrayTest {
@Test
public void test() {
assertFalse(ContiguousArray.isContiguous(new Integer[][] {
{ 1, 2, 3, 3 },
{ 1, 4, 4, 5 },
{ 2, 6, 6, 5 },
{ 7, 7, 8, 8 }
}));
assertFalse(ContiguousArray.isContiguous(new Character[][] {
{ 'a', 'b' },
{ 'b', 'a' },
}));
assertTrue(ContiguousArray.isContiguous(new Character[][] {
{ 'a', 'a', 'a' },
{ 'b', 'a' },
{ 'b' },
}));
assertTrue(ContiguousArray.isContiguous(new Integer[][] {
{ 1, 2, 3, 3 },
{ 1, 4, 4, 5 },
{ 6, 7, 7, 5 },
{ 8, 8, 9, 9 }
}));
assertTrue(ContiguousArray.isContiguous(new Integer[][] {
{ 1, 2, 3, 3 },
{ 1, 1, 4, 5 },
{ 6, 1, 7, 5 },
{ 8, 8, 9, 9 }
}));
assertTrue(ContiguousArray.isContiguous(new Integer[][] {
{ 1, 2 },
{ 2, 2 }
}));
}
}
私はそれが2次元配列ですので、方法を発見していない、と私はのためにソートされていない2次元配列を確認したいと私は配列をソートすることはできません不連続な値。 – michaeladrian39
は隣接して隣接している数字ですか? – msagala25
は、値が斜めに連続していてもかまいませんか? –