add or subtract 1 from a row in a 2D array - java

So I got this 2D Array that is a 5x5 array and I have to subtract or add 1 to one of the rows that the user chooses to change. All is fine when the user inputs to change the first row, but with the higher rows, for example 2, it adds more than 1.
The array values are
1 -2 1 0 0
-1 0 4 2 0
0 -4 1 -1 0
0 1 -1 -1 -2
0 -3 1 -1 0
And the method I used to add 1 is the following
public static void plusRow (int i){
for(int row = 0; row < board.length; row++){
int[] rows = board[i];
for(int col = 0; col < board.length; col++){
rows[col] = rows[col] + 1;
System.out.print(board[row][col] + " ");
}
System.out.println("");
}
}
My output value for example with 2 comes out like this
1 -2 1 0 0
1 2 6 4 2
0 -4 1 -1 0
0 1 -1 -1 -2
0 -3 1 -1 0
When it should be
1 -2 1 0 0
0 1 5 3 1
0 -4 1 -1 0
0 1 -1 -1 -2
0 -3 1 -1 0

The problem is that your nested for loop runs as many times as the function input int "i"

Your algorithm is very inefficient- you don't need to do a nested loop here. Break your ouput and your math into 2 different loops.
for(int j =0; j<boards[i].length; j++){
boards[i][j] += 1;
}
Then write a double loop to ouput board. In fact, that should be a separate function

Related

How to solve java 2D array

i wrote the code correctly for 2D array hourglass problem.but it shows only one error.i did not know how to rectify it and also i dint know how it will work on negative numbers.how i can get 13 as output from my code.
Input (stdin)
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 9 2 -4 -4 0
0 0 0 -2 0 0
0 0 -1 -2 -4 0
Your Output (stdout)
0
Expected Output
13
here is my code:
public class Solution {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int rows =sc.nextInt();
int column = sc.nextInt();
int[][] a = new int[rows][column];
for(int i=0;i<rows;i++){
for(int j=0;j<column;j++){
a[i][j]=sc.nextInt();
}
}
int sum=0,max=0;
for(int i=0;i<rows-2;i++){
for(int j=0;j<column-2;j++){
sum =(a[i][j]+a[i][j+1]+a[i][j+2]+a[i+1][j+1]+a[i+2][j]+a[i+2][j+1]+a[i+2][j+2]);
if(sum>max){
max = sum;
}
}
}
System.out.println(max);
}
}
In the stdin you haven't provided the rows and columns value as input. Your code works fine and gives the output 13.
For this particular problem, your stdin should be:
6 6
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 9 2 -4 -4 0
0 0 0 -2 0 0
0 0 -1 -2 -4 0
Where the first line represents rows and columns. And will be assigned to:
int rows =sc.nextInt();
int column = sc.nextInt();
So what was the problem in your code?
Previously these were assigned 1 and 1 [the first two inputs] and took only 1 and 0 (the next two inputs) as the corresponding value. As a result, it couldn't satisfy the entry conditions in loop. hence the sum remained 0 and showed that as an output.

Need help reading a text file

So far I have developed a program that uses an adjacency matrix to build a graph using linked implementation.
I'm stuck on how I can read a text file containing an adjacency matrix, and using that data instead of manually inputting the adjacency matrix.
For example, a text file containing the following:
4
0 1 1 0
1 1 1 1
1 0 0 0
1 1 0 1
6
0 1 0 1 1 0
1 0 0 1 1 0
0 0 1 0 0 1
0 0 0 0 1 0
1 0 0 0 0 0
0 0 1 0 0 1
3
0 1 1
1 0 1
1 1 0
You can use this method to read matrix data from file. This method returns a 2d array of bytes containing zeroes and ones.
public static void main(String[] args) throws IOException {
byte[][] matrix = getMatrixFromFile("matrix.txt");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + ((j + 1) == matrix[i].length ? "" : " "));
}
System.out.println();
}
}
public static byte[][] getMatrixFromFile(String filename) throws IOException {
List<String> lines = Files.readAllLines(Paths.get(filename));
int size = Byte.parseByte(lines.get(0));
byte[][] matrix = new byte[size][size];
for (int i = 1; i < lines.size(); i++) {
String[] nums = lines.get(i).split(" ");
for (int j = 0; j < nums.length; j++) {
matrix[i - 1][j] = Byte.parseByte(nums[j]);
}
}
return matrix;
}
Here I am assuming the file will contain data for one matrix, like following, but my code can easily be extended to read data for multiple matrices and return a list of 2d byte array.
4
0 1 1 0
1 1 1 1
1 0 0 0
1 1 0 1

Java - Bit manipulation (count number of 1s in number)

Can someone explain to my why this method works, I've worked through what it does, but why does this work. Is there a pattern that binary numbers have? Like for example at i = 3, why does it do res[1] + 1 to get 2. How does res[3 >> 1] + (3&1) help to count the number of ones in the binary number of 3?
What the code should do: It works so don't worry about that. It is supposed to return a list that contains the number of ones in the binary representation of each number until num+1. And num is always >= 0. So for num = 5, you would get [0, 1, 1, 2, 1, 2], where the last index represents the number of 1s in the binary representation of 5, and the first index is number of ones in binary rep of 0.
Code:
public int[] countBits(int num) {
int[] res = new int[num+1];
for (int i = 0; i<num+1; i++){
res[i] = res[i >> 1] + (i & 1);
}
return res;
}
This is the part I can't wrap my head around:
res[i] = res[i >> 1] + (i & 1);
EDIT - This is not homework, so please fully explain your answer. This is to help with interviews.
int[] res = new int[num+1];
for (int i = 0; i<num+1; i++){
res[i] = res[i >> 1] + (i & 1);
}
return res;
rewritten as
int[] res = new int[num+1];
for (int i = 0; i<num+1; i++){
x = res[i >> 1];
y = (i & 1);
res[i] = x + y;
}
return res;
Create an array to fit the answers, +1?
for each, starting at the low end.
res[0] = res[0] + 0&1 = 0 + 0 = 0;
res[1] = res[0] + 1&1 = 0 + 1 = 1;
res[2] = res[1] + 0&1 = 1 + 0 = 0;
res[3] = res[1] + 1&1 = 1 + 1 = 2;
Looking at this pattern, I can see that because of the right shift, and the masking with &, it's splitting the problem into 2, one that's been solved previously due to the iteration order, and a bit check of the last digit.
assuming a 8 bit int, for brevity,
1 = 00000001
2 = 00000010
3 = 00000011
Split the binary into parts.
i i>>1 y&1
1 = 0000000 1
2 = 0000001 0
3 = 0000001 1
So it fetches the results for the number of ones in the first half of the array, then counts the last digit.
Because of the iteration order, and array initialisation values, this is guaranteed to work.
For values < 0 , due to 2's compliment it gets hairy, which is why it only works for values >=0
in 'res[i] = res[i >> 1] + (i & 1);'
one number's result is divide into 2 parts
the last bit is 1 or not,which can be calculate by (i & 1).
the first (n-1) bits,this number is equals to res[i >> 1]'s bitcount.this is a simple recursive call
shift by 1 gives the floor number divided by 2.
AND 1 returns 1 if the last bit of the number is 1
Hope the below table helps to see what is happening :) Just my 2 cents.
<pre>
--------------------------------
<b>
# 8 4 2 1 >>1 &1 Ans
</b>
-------------------------------
0 0 0 0 0 0 0 0
1 0 0 0 1 0 1 1
2 0 0 1 0 1 0 1
3 0 0 1 1 1 1 2
4 0 1 0 0 2 0 1
5 0 1 0 1 2 1 2
6 0 1 1 0 3 0 2
7 0 1 1 1 3 1 3
8 1 0 0 0 4 0 1
9 1 0 0 1 4 1 2
10 1 0 1 0 5 0 2
11 1 0 1 1 5 1 3
12 1 1 0 0 6 0 2
13 1 1 0 1 6 1 3
14 1 1 1 0 7 0 3
15 1 1 1 1 7 1 4
</pre>

set value for random element on matrix

I'm trying to generate a 8 by 8 matrix. Each element of matrix needs to have a value of 1 except one element on each column which is set as 0, that one element is chosen by generating a random int between 0-7.
What I get when I run the code:
1 1 1 1 1 1 1 1
1 1 1 0 1 1 1 1
1 1 0 1 1 1 1 1
1 0 1 1 1 1 1 1
1 0 1 1 1 1 1 1
1 0 0 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 0 1 1
My matrix should look like this:
1 1 1 1 1 1 1 1
1 1 0 1 1 1 1 1
1 1 1 1 1 0 1 0
0 1 1 1 1 1 1 1
1 1 1 0 1 1 0 1
1 0 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 0 1 1 1
code
for (int[] row: grid)
Arrays.fill(row, 1);
for (int i=0; i<grid.length; i++) {
int j = getRandom();
grid[i][j] = 0;
}
// print matrix
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++)
System.out.format("%2s%2d%2s", " ", Main.grid[i][j], " ");
System.out.println();
}
In your nested loop, both initialization and nulling of cells are in the innermost loop. This will cause both to run once per cell, but nulling is only done once per column.
If we change the order that the cells are initialized in from row after row to column after column, we can move the nulling logic out to the outermost loop.
for (int c = 0; c < 8; c++) {
for (int r = 0; r < 8; r++) {
Main.grid[r][c] = 1;
}
Main.grid[getRandom()][c] = 0; // assuming your getRandom() is within range
}
Firstly let's make the matrix all 1s:
//fill however you like
int[][] matrix = IntStream.range(0, 8).mapToObj(i
-> IntStream.range(0, 8).map(i -> 1).toArray());
Then, based on your question, it seems like you want a unique row per column to have a zero. So just shuffle your column indexes:
List<Integer> rows = IntStream.range(0, 8).collect(Collectors.toList());
Collections.shuffle(rows); //random rows per 0-8 column
AtomicInteger column = new AtomicInteger();
//iterate columns, and select random row
rows.forEach(i -> matrix[i][column.getAndIncrement()] = 0);
This'll disperse the random 0s to be unique per row (and column), and there's not really any RNG involved so it's O(n)
First of all, use the Arrays.fill api, it will make your code much cleaner and concise.
int[][] matrix = new int[m][n];
// Fill each row with 1
for (int[] row: matrix)
Arrays.fill(row, 1);
Then, for each row, pick a column number at random and insert '0' thereby replacing the 1.
for(int i=0; i<matrix.length; i++) {
int j = Math.Random(0,matrix[0].length); // Or any other api for random number generation
matrix[i][j] = 0;
}

Add extra number beside array

i want setting an array and below is my code
public static void setArray()
{
int i = 5;
int j = 5;
int testarray[][] = new int[i][j];
for(int x = 0;x<i;x++)
{
for(int y=0;y<j;y++)
{
System.out.print("0 ");
}
System.out.println("");
}
}
the result is something 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
if i want to put a number/alphabet beside to let the user know which column, how can i do that ?
Expected Result:
====================
1 2 3 4 5
A|0 0 0 0 0
B|0 0 0 0 0
C|0 0 0 0 0
D|0 0 0 0 0
E|0 0 0 0 0
You need another initial for-loop to print the numbers, then you need to add another print statement within your second for-loop to print the letter for each row:
System.out.print(" ");
for (int x = 0; x < i; x++) { // this prints the numbers on the first row
System.out.print(" " + x);
}
System.out.println();
for (int x = 0; x < i; x++) {
System.out.print((char) ('A' + x) + "|"); // this prints the letters
for (int y = 0; y < j; y++) {
System.out.print("0 ");
}
System.out.println("");
}
0 1 2 3 4
A|0 0 0 0 0
B|0 0 0 0 0
C|0 0 0 0 0
D|0 0 0 0 0
E|0 0 0 0 0
You need to print 1, 2, 3, 4, 5 .. column number of times and print A, B, C, D .. till you reach the number of rows. Try coding it yourself, it's not that difficult (I don't want to provide a ready-made code)

Categories

Resources