Stringbuilder to 2D array Java - 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] + " ");
}
}
}
}

Related

How to create a Java 2D array with 1s and 0s?

The printed result should be like this (I don't know how to format it, but imagine a 9x9 2d array where the 1's create an X):
1 0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 1 0
0 0 1 0 0 0 1 0 0
0 0 0 1 0 1 0 0 0
0 0 0 0 1 0 0 0 0
0 0 0 1 0 1 0 0 0
0 0 1 0 0 0 1 0 0
0 1 0 0 0 0 0 1 0
1 0 0 0 0 0 0 0 1
This is what I have so far:
int [][] myArray = new int[9][1];
for (int row = 0 ; row < 9 ; row++)
for (int column = 0 ; column < 1 ; column++)
myArray[row][column]= 0;
How would I create a while loop for this?
Try the following code:
public class Main
{
static int SIZE = 9;
public static void main(String []args){
int[][] arr = new int[SIZE][SIZE];
for(int i = 0; i < SIZE; i++){
arr[i][i] = 1;
arr[i][SIZE-1-i] = 1;
}
printArr(arr);
}
public static void printArr(int[][] arr){
for(int i = 0; i < SIZE; i++)
{
for(int j = 0; j < SIZE; j++)
{
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
I have added a print method so you will see the desired result.
few points about the above code:
there is no need to set all values to 0. this is by default.
so the only thing that left to do is to set the diagonals to 1's. that can be done in 1 for loop as suggested above. the first line in the loop creates the diagonal from top left to bottom right. the second line creates the other diagonal
you can change SIZE variable to any size that you want, I set it to 9, but it can be any int.
You can check if column-row==0 or column+row==8. With the first check you get the cross from the left top corner to the bottom right, with the second check the cross from the top right corner to the bottom left.
As mentioned in a comment you also need to initialize your array with [9][9] and change the upper bound check in the second array to 9 as well.
public class MyClass {
public static void main(String args[]) {
int [][] myArray = new int[9][9];
for (int row = 0 ; row < 9 ; row++) {
for (int column = 0 ; column < 9 ; column++){
myArray[row][column]= 0;
if (column-row==0 || column+row==8){
myArray[row][column]= 1;
}
System.out.print(myArray[row][column]);
}
System.out.println();
}
}
}

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.

Create two dimensional array with values dynamically in Java

My array currently looks like this:
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
And I am trying to make it look like this:
0 10 25 15 30
10 0 20 0 0
25 20 0 0 0
15 0 0 0 0
30 0 0 0 0
using the following code I create the first but don't know how I can get the result I want.
int rows = array.length;
int columns = array[0].length;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
Any ideas how to achieve this?.
If you want to print the second matrix you show on the post then you must assign those values to the corresponding cells of the matrix you have created before printing the matrix, because doing
int matrix[][] = new int[n][n];
will create a matrix of dimension NxN but filled in every cell with a 0
I don't know the logic to fill your matrix (reading from user input or generated by some algorithm) but for every row and column that you want to fill with a value different from 0 you need to do an assignment:
matrix[row][col] = someInt;

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

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

Categories