Create adjacency matrix from char[][] array provided rules - java

I want to change a char[][] array (lets call it cA) into an adjacency matrix. An adjacency matrix has columns and rows equal to the number of elements in an array, and each vertex in the adjacency matrix is either true or false depending if the elements in the initial array are adjacent. I want to bend the rules a little and also constrain an adjacency matrix vertex to true iff the elements are adjacent and one of the elements is not a specific value.
Here's what cA array looks like:
z y z
z z z
z y y
The adjacency matrix (lets call it aM) for the cA array will be an int array of size [3*3][3*3]. The conditions for aM(i,j) to be true are that the elements i and j in cA array must be adjacent, but neither i or j can be "y".
Lets number the cA array elements 1 through 9.
1 2 3
4 5 6
7 8 9
aM can be described by doing the below operations:
aM(1,1) //false, no self-adjacency
aM(1,2) //false, 2 is a "y"
aM(1,3) //false, 1 is not adjacent to 3
aM(1,4) //true, 1 is adjacent to 4, neither are "y"
aM(1,5) //false, 1 is not adjacent to 5
aM(1,6) //false, 1 is not adjacent to 6
aM(1,7) through aM(1,9) //false, there is no adjacency between 1 and 7, 8, or 9
aM(2,1) through aM(2,9) //false, 2 is a "y"
...
Hopefully you get the idea. From the above, the adjacency matrix for cA is as below:
1 2 3 4 5 6 7 8 9 (i)
1 0 0 0 1 0 0 0 0 0
2 0 0 0 0 0 0 0 0 0
3 0 0 0 0 0 1 0 0 0
4 1 0 0 0 1 0 1 0 0
5 0 0 0 1 0 1 0 0 0
6 0 0 1 0 1 0 0 0 0
7 0 0 0 1 0 0 0 0 0
8 0 0 0 0 0 0 0 0 0
9 0 0 0 0 0 0 0 0 0
(j)
The rule being aM(i,j) == 1 iff i != j, i != "y" && j != "y", and both i and j are adjacent to each other.
I'm having difficulty concocting an algorithm to create an adjacency matrix provided a char[][] array. I've defined the rules, but finding constraints for iteration is problematic.

Try this:
static void set(boolean[][] aM, int cols, int row0, int col0, int row1, int col1) {
int index0 = row0 * cols + col0;
int index1 = row1 * cols + col1;
aM[index0][index1] = aM[index1][index0] = true;
}
static boolean[][] adjacencyMatrix(char[][] cA) {
int rows = cA.length;
int cols = cA[0].length;
boolean[][] aM = new boolean[rows * cols][rows * cols];
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (cA[i][j] == 'y')
continue;
if (i + 1 < rows && cA[i + 1][j] != 'y')
set(aM, cols, i, j, i + 1, j);
if (j + 1 < cols && cA[i][j + 1] != 'y')
set(aM, cols, i, j, i, j + 1);
}
}
return aM;
}
public static void main(String[] args) {
char[][] cA = {
{'z', 'y', 'z'},
{'z', 'z', 'z'},
{'z', 'y', 'y'},
};
boolean[][] aM = adjacencyMatrix(cA);
for (boolean[] row : aM) {
for (boolean cell : row)
System.out.print(cell ? "1" : "0");
System.out.println();
}
}
The result is:
000100000
000000000
000001000
100010100
000101000
001010000
000100000
000000000
000000000

Related

Store prime factor by 2-d array for one number

I'm writing a method to store a number's prime factor.
I'm asked to use 2-d array to store its prime factor and the factor's number.
public static int[][] getMatrix (long x){
int[][] matrix =new int[10][2];
int count;
for (int i = 2, j = 0; i <=x / 2; i++) {
count=0;
while (x % i == 0) {
x = x/i;
count++;
}
matrix[j][0] = i;
matrix[j][1] = count;
j++;
}
return matrix;
}
But this code only store data into the first row of the array.
Could someone help me correct it or privide other ideas?
if I use the following code to output the result.
for(int row=0;row<b_matrix.length;row++)
{
for(int column=0;column<2;column++)
{
System.out.print(b_matrix[row][column]+" ");
}
}
And x=9 I got this:
2 0 3 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
x=6 I got this:
2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
such as :6
matrix[0][0]=2 matrix[0][1]=1
matrix[1][0]=3 matrix[1][1]=1 //can't store
such as :9
matrix[0][0]=2 matrix[0][1]=0//only output the next row when this equals to 0
matrix[1][0]=3 matrix[1][1]=2
Your logic is right except, in the for loop i should go till x instead of x/2 as follows,
for (int i = 2, j = 0; i <= x; i++)
Output for getMatrix(60):
2 2
3 1
4 0
5 1
0 0
0 0
0 0
0 0
0 0
0 0

Java undirected Graph distance computation

I am having the following matrix stored in 2d int array result[][]:
0 1 1 0 0 0
1 0 0 1 0 0
1 0 0 1 1 0
0 1 1 0 0 1
0 0 1 0 0 1
0 0 0 1 1 0
I am trying to compute if there are any nodes that are connected with distance of 2 (there is 1 node in between them and no direct connection)
So far I have the following code:
Size is the size of the matrix (n * n) and dis is the distance I am looking for.
for(int row = 0; row < size; row++){
for(int column = 0; column < size; column++){
if(dis == 2){
if((result[row][column] == dis-1 && result[column][column+1] == 1 && result[row][column+1] == 0)){
if(row != column+1){
result[row][column+dis-1] = dis;
result[column+dis-1][row] = dis;
}
}
}
}
}
However, the code does not always work and is not universal if I try to change the distance to 3 or 4 for example.

How do I generate all possible combinations of a 3 x 2 matrix?

I'm stuck trying to create a 3 x 2 matrix that only contains 0 and 1 and prints out all the possible combinations, BUT it can only contain one 1 and one 0 for each row, the numbers have nothing to do with each other than that they are unique, much like a betting table for say tennis or something:
0 1 1 0 0 1 0 1 0 1
0 1 1 0 0 1 1 0 1 0
0 1 1 0 1 0 1 0 0 1
Here's the code:
public class Program {
public static void main(String[] args) {
int[][] array = {{0,1}};
System.out.println("Array:");
for(int row = 0; row < array.length; row++){
for(int column = 0; column < array[row].length; column++){
System.out.print(array[row][column] + " ");
}
System.out.println();
}
}
}
This is what I got right know. I don't know where to take it from here.
For a general case of an N-by-2 matrix there will be 2^N combinations that meet your criteria. Consider that each row can only be in two states: [0, 1], or [1, 0].
Start with a matrix where every row is in the initial state [0, 1]. Then, for every number X where 0 <= X < 2^N, convert X to binary. When the Mth bit is 1, reverse the Mth row's values.
For example, binary 000 would correspond to:
0 1
0 1
0 1
While binary 101 would correspond to:
1 0 (swapped)
0 1
1 0 (swapped)

Stringbuilder to 2D array Java

I am doing a school project and I'm having a bit of trouble transforming a Stringbuilder into a 2D array.
The stringbuilder sb contains a 2D matrix, which I want to convert into a 2D int.
0 1 1 1 0 0 0 0
1 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0
1 0 0 0 1 0 1 0
0 0 0 1 0 1 0 0
0 0 0 0 1 0 0 0
0 0 0 1 0 0 0 1
0 0 0 0 0 0 1 0
This is the matrix I have in the sb that I want to convert into an int[][].
Any ideas?
Try this (explanations are in the code)
public static void main(String[] args) {
//assuming the stringbuilder has the contents below (each line ending in space followed by a newline character)
final StringBuilder sb = new StringBuilder();
sb.append("0 1 1 1 0 0 0 0 \n");
sb.append("1 0 0 0 0 0 0 0 \n");
sb.append("1 0 0 0 0 0 0 0 \n");
sb.append("1 0 0 0 1 0 1 0 \n");
sb.append("0 0 0 1 0 1 0 0 \n");
sb.append("0 0 0 0 1 0 0 0 \n");
sb.append("0 0 0 1 0 0 0 1 \n");
sb.append("0 0 0 0 0 0 1 0 \n");
//extract each line from the sb by splitting after the newline character \n
final String[] rows = sb.toString().split("\n");
//each line represent a row, so the numbers of lines is the number of rows in our matrix
final int totalRows = rows.length;
//the lenght of each line, if we replace space with nothing, represents the number of columns
//columns have the same number of elements for each line so we can read it from the first row, row[0]. it will be the same for all the others
final int totalColumns = rows[0].replace(" ", "").length();
//create matrix with proper size
final int[][] matrix = new int[totalRows][totalColumns];
//initialize first row index
int currentRow = 0;
//initialize first column index
int currentColumn = 0;
for (String row : rows) { //for each row
row = row.substring(0, row.length() - 1); //remove last space character
final String[] elements = row.split(" "); //store each element of the row in an array by splitting after the space character
for (final String element : elements) { //for each element
//add element in matrix at correct position
matrix[currentRow][currentColumn] = Integer.parseInt(element); //convert string to int
//increment column count for the next element
currentColumn++;
}
//increment row count for the next row
currentRow++;
//reset column counter for the next row
currentColumn = 0;
}
//display the matrix
for (int i = 0; i < totalRows; i++) {
for (int j = 0; j < totalColumns; j++) {
if (j == 7) {
//if last column add a newline after the element
System.out.print(matrix[i][j] + "\r\n"); // where \r\n = CarriageReturn + LineFeed and is used as a new line character in Windows
//or simply replace the above line with System.out.println(matrix[i][j]);
} else {
//if not last column add just a space after the element
System.out.print(matrix[i][j] + " ");
}
}
}
}

Function to set row, column, and diagonal elements in a 2D array given a cell in the array

I need a function with the following signature:
public void requiredFunction(int[][] array, int row, int column) {
// code
}
The function should increment all the values in the same row, column and diagonal as array[row][column] (except array[row][column] itself).
Suppose I have the following 2D array:
int[][] array = {
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
};
Now when I call this function with the following values:
requiredFunction(array, 2, 2);
It should convert the array to:
array = {
1 0 1 0 1 0
0 1 1 1 0 0
1 1 0 1 1 1
0 1 1 1 0 0
1 0 1 0 1 0
0 0 1 0 0 1
};
If you think of the array as a chess board, then the function takes the position of the queen (row and column) and increments those places on the chess board, that the queen can move to.
Here is something shorter :
public void requiredFunction(int[][] array, int row, int column) {
for (int i = 0; i < array.length; ++i) {
for (int j = 0; j < array[i].length; ++j) {
if (i == column && j == row)
continue;
if (Math.abs(i - column) == Math.abs(j - row) ||
i - column == 0 || j - row == 0)
array[i][j]++;
}
}
}
First of all, the row and column is easy, say:
public void requiredFunction(int[][] array, int row, int column) {
//row
for(int i=0;i<arr.length;i++){
if(i==col)continue;
arr[row][i]++;
}
//col
for(int i=0;i<arr[0].length;i++){
if(i==col)continue;
arr[i][col]++;
}
}
For the diagonals, it's a little bit more complicated. You can start from the selected point, and move through the diagonals one by the other. For example, this code:
for(int i=row+1,j=col+1;;++i,++j){
try{
arr[i][j]++;
}catch(IndexOutOfBoundsException e){//the i or j went too far from the board
break;
}
}
will increase the values which is in the right-and-down diagonal. Similar loops with --i instead of ++i or --j instead of ++j will do the same for the other diagonals.
EDIT:
As commented bellow, it is better to use regular termination condition instead of IndexOutOfBoundsException, so the loop should be:
for(int i = row+1, j = col+1; i <= arr.length && j <= arr[0].length; ++i, ++j){
arr[i][j]++;
}

Categories