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

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();
}
}
}

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

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;

How can I add up the elements of a row in a 2 dimensional array Java

Hey I'm trying to code a model for the Least Recently Used paging algorithm. I'm relatively new to Java and coding in general and I just can't find the error in my code.
I want to implement the free memory with a 2 dimensional array, and when referencing a row i change the bits in the corresponding row to 1 and in the corresponding column to 0. Then I want to add up the elements in each row and sort them using the bubblesort algorithm.
There lies my Problem: it seems I just can't get the adding up or the sorting right. I hope someone can help me because it seems no matter what I try, it doesn't work.
Here is the part of my code in question since it seems to be in stackoverflows rules that I can't post the whole code.
page [][] is the 2d array which i use to change the bytes.
I would be very grateful for any help because I'm getting demotivated slowly but surely.
// array for bubblesort and adding up of rows
int sort[] = new int[page.length];
int sumtemp = 0;
int sum = 0;
for (int i = 0; i < page.length; i++) {
for (int j = 0; j < page[i].length; j++) {
sumtemp += page[i][j];
sum = sumtemp;
}
for (i = 0; i < page.length; i++)
sort[i] = sum;
sumtemp = 0;
}
// bubblesort
int n1 = sort.length;
int temp = 0;
for (int i = 0; i < n1; i++) {
for (int j = 1; j < (n1 - i); j++) {
if (sort[j - 1] > sort[j]) {
// sort
temp = sort[j - 1];
sort[j - 1] = sort[j];
sort[j] = temp;
}
}
}
My Output: it works until the last output, where the page to be deleted should be 5 not 4:
How many pages shall fit in the memory?
5
Which page do you want to reference? Please choose a number between 1 and 5. Have you finished referencing, please type in
4
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
1 1 1 0 1
0 0 0 0 0
Page to delete = 1
Which page do you want to reference? Please choose a number between 1 and 5.
Have you finished referencing, please type in
3
0 0 0 0 0
0 0 0 0 0
1 1 0 1 1
1 1 0 0 1
0 0 0 0 0
Page to delete = 1
Which page do you want to reference? Please choose a number between 1 and 5.
Have you finished referencing, please type in
1
0 1 1 1 1
0 0 0 0 0
0 1 0 1 1
0 1 0 0 1
0 0 0 0 0
Page to delete = 5
Which page do you want to reference? Please choose a number between 1 and 5.
Have you finished referencing, please type in
2
0 0 1 1 1
1 0 1 1 1
0 0 0 1 1
0 0 0 0 1
0 0 0 0 0
Page to delete = 4
Which page do you want to reference? Please choose a number between 1 and 5. Have you finished referencing, please type in
This should be the Bubble Sort logic:
for (int i = 0; i < n1; i++) {
for (int j = 0; j < (n1 - i - 1); j++) {
if (sort[j + 1] > sort[j]) { //ascending order
// sort
temp = sort[j + 1];
sort[j + 1] = sort[j];
sort[j] = temp;
}
}

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