Skip to content

Instantly share code, notes, and snippets.

@MasterOdin
Created February 29, 2016 20:38
Show Gist options
  • Save MasterOdin/18396a9b8cd6b3b5e4b1 to your computer and use it in GitHub Desktop.
Save MasterOdin/18396a9b8cd6b3b5e4b1 to your computer and use it in GitHub Desktop.
Given a matrix of 1s and 0s, determine the adjacency of the 1s with each other. (Created to solve http://stackoverflow.com/questions/34524153/algorithm-or-java-code-for-searching-patterns-in-matrix)
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class AdjacencyChecker {
public static void main(String[] args) {
int[][] matrix = {{1,1,1,0,0},{1,0,0,0,1},{1,1,1,0,0},{0,0,0,1,1}};
List<Integer> list = new ArrayList<>();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
list.add(matrix[i][j]);
System.out.print(matrix[i][j]+" ");
}
System.out.println();
}
System.out.println();
int adjustment = 0;
if (list.contains(0)) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == 1) {
list.add(list.remove(i));
i--;
adjustment++;
} else {
break;
}
}
}
int count = 0;
for (Integer a : list) {
if (a == 1) {
count++;
} else {
if (count > 0) {
System.out.println("Group of " + count + " adjacent 1's");
}
count = 0;
}
}
if (count > 0) {
System.out.println("Group of " + count + " adjacent 1's");
}
for (int num : Arrays.asList(5, 2, 2, 1)) {
int count2 = 0;
int start = -1;
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == 1) {
if (start == -1) {
start = i;
}
count2++;
} else {
start = -1;
count2 = 0;
}
if (count2 == num) {
System.out.println("Group of " + num + " adjacent 1's starting at " + ((start + adjustment) / 5) + "," + ((start + adjustment) % 5));
for (int j = start; j < start + count2; j++) {
list.set(j, 0);
}
break;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment