the difference between 2d array - java

I'm wondering what is the difference between these loops in 2D arrays:
for (int r = row - 1, c = column - 1; r >= 0 && c >= 0; r--, c--) {
...
}
for(int r=row-1;r>=0;r--){
for(int c=column-1;c>=0;c--){
...
}
}

for (int r = row - 1, c = column - 1; r >= 0 && c >= 0; r--, c--)
The first example is one loop that decrements both r and c every cycle, meaning that the indices r and c will draw a diagonal starting at array[row-1][column-1].
for(int r=row-1;r>=0;r--){
for(int c=column-1;c>=0;c--){
The second example calls a loop for columns for each index of row, so it will access all the indices array[r][c]

I assume you are asking for the difference between a single outer loop and a nested loop. The difference is that the single loop will iterate over the diagonal of the 2D array and the nested loops with iterate over every index of the array. For instance, if there are 6 rows and 4 columns then:
for (int r = row - 1, c = column - 1; r >= 0 && c >= 0; r--, c--) {
System.out.println(r + " " + c);
}
will yield:
5 3
4 2
3 1
2 0
Whereas the nested loop
for(int r=row-1; r>=0; r--) {
for(int c=column-1; c>=0; c--) {
System.out.println(r + " " + c);
}
}
would yield
5 3
5 2
5 1
5 0
4 3
4 2
4 1
4 0
3 3
3 2
3 1
3 0
2 3
2 2
2 1
2 0
1 3
1 2
1 1
1 0
0 3
0 2
0 1
0 0

The first iterates for n times, where n is the least of row and column. The second iterates for m times, where m is row * column. That is
Math.min(row, column)
and
row * column
respectively.

Related

Creating this number pattern in Java

I am trying to create a pattern in java by using a for-loop and nested for-loop based on the user input of a positive integer.
Here is an example:
User input = 5
Output:
5 5 5 5 5 5 5 5 5
5 4 4 4 4 4 4 4 5
5 4 3 3 3 3 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 2 1 2 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 3 3 3 3 4 5
5 4 4 4 4 4 4 4 5
5 5 5 5 5 5 5 5 5
This is what I have so far. I am getting a list of integers, but I cannot find out where to go from here to get a pattern such as the one above. All I am getting is "5 5 5 5 5 4 4 4 4 3 3 3 2 2 1 "
System.out.print("Enter the value of n: ");
int n = scan.nextInt();
for (int row = 1; row <= n; row++) { //rows
for (int col = 1; col <= n; col++) { //columns
if (n - col + 1 <= n - row + 1 && row <= n && col <= n) { //what to print
System.out.print(n - row + 1 + " ");
} else if (n - col + 1 <= n - row + 1 && row <= n && col <= n) {
System.out.print(n - row + 1 + " ");
}
}
}
In this code I'm mirroring the column's and after that mirroring the rows. From mirroring I mean first creating mirror of the data.
First writing data to columns(left side) and then mirroring the column hence I get the right side of the column.
After writing data to the upper rows then mirroring the upper row I get bottom row.
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
public class Pattern {
static final PrintStream out = System.out;
public static void displayPattern(int n) {
final int arr[][] = new int[n * 2 - 1][];
for (int i = 0; i < arr.length; i++)
arr[i] = new int[n * 2 - 1];
final List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
int current = n - i;
list.add(current);
for (int j = 0; j < list.size(); j++) {
arr[i][j] = list.get(j);
}
int remainings = n - list.size();
for (int j = list.size(), count = 0; count < remainings; j++, count++) {
arr[i][j] = current;
}
//writing data to right side of the columns(mirroring columns)
for (int j = n, count = 1; j < arr[i].length; j++, count++)
arr[i][j] = arr[i][j - count * 2];
}
//writing data to bottom half of the rows(mirroring rows)
for (int i = n, count = 1; i < n * 2 - 1; i++, count++) {
for (int j = 0; j < n * 2 - 1; j++)
arr[i][j] = arr[i - count * 2][j];
}
for (int a[] : arr) {
for (int b : a)
out.print(b + " ");
out.println();
}
}
public static void main(final String... $) {
displayPattern(5);
}
}
Output:
5 5 5 5 5 5 5 5 5
5 4 4 4 4 4 4 4 5
5 4 3 3 3 3 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 2 1 2 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 3 3 3 3 4 5
5 4 4 4 4 4 4 4 5
5 5 5 5 5 5 5 5 5

Fill an integer array with a series of number that is a string (java)

Im trying to write the following program, where i have a string that a number is generated possibly like 37 digits.
Is it possible to fill an array that i know the length but not the rows because the string can be anything.
String number; //110034043312132121220023020423340432 but can be any big number that is converted to a string
System.out.println("Give length in a form of a string: ");
String input= scan.nextLine(); //abcdefg
int length = input.length(); //this means i get 6 back.
And save this in a character array where i know the length from input.lenght() and i dont know the rows
A B C D E F G
1 1 0 0 3 4 0
4 3 3 1 2 1 3
2 1 2 1 2 2 0
0 2 3 0 2 0 4
2 3 3 4 0 4 3
2
I know the answer might be something stupid simple but please be coder noob friendly. Thanks
The solution may be as follows:
Use input.length as the max number of columns in the resulting 2D array
Calculate the number of rows in the resulting 2D array nums / cols, adding one extra row if there's a remainder.
The last row in the result may be jagged: contain less than cols elements.
String number = "110034043312132121220023020423340432"; // but can be any big number that is converted to a string
System.out.println("Give length in a form of a string: ");
String input= "ABCDEFG" ; //scan.nextLine(); //abcdefg
int cols = input.length(); // columns in the resulting array
int nums = number.length(); // total count of numbers
int rows = nums / cols + (nums % cols == 0 ? 0 : 1);
int[][] result = new int[rows][]; // the result may be jagged
for (int i = 0; i < rows - 1; i++) {
result[i] = new int[cols];
}
result[rows - 1] = new int[nums % cols == 0 ? cols : nums % cols];
for (int i = 0; i < nums; i++) {
int r = i / cols;
int c = i % cols;
result[r][c] = number.charAt(i) - '0';
}
// print the result
System.out.println(input.replaceAll(".", "$0 ")); // print header with spaces between columns
for (int[] row : result) {
System.out.println(Arrays.toString(row)
.replaceAll("[^\\s\\d]", "") // remove brackets and comma from output
);
}
Output:
A B C D E F G
1 1 0 0 3 4 0
4 3 3 1 2 1 3
2 1 2 1 2 2 0
0 2 3 0 2 0 4
2 3 3 4 0 4 3
2
To do this, you might be able to use a list instead.
ArrayList<int[]> list = new ArrayList<int[]>();
and in each line, you can add a new array into the list.
If you want the final result to be a 2d array, you can easily convert a list to an array.
public static char[][] createMatrix(String num, String title) {
int totalRows = (int)Math.ceil((double)num.length() / title.length());
char[][] matrix = new char[totalRows + 1][title.length()];
for (int i = 0; i < matrix[0].length; i++)
matrix[0][i] = title.charAt(i);
for (int i = 0, row = 1, col = 0; i < num.length(); i++) {
matrix[row][col++] = num.charAt(i);
if (col == matrix[row].length) {
row++;
col = 0;
}
}
return matrix;
}

How to improve performance while calculating matrix sum

I was given a task during an interview, where I was given a matrix, now I need to generate another matrix out of it using below formula:
Given matrix A[R][C], generate B[R][C]
val = 0;
for (i = 0; i ≤ xPosition; i += 1) {
for (j = 0; j ≤ yPosition; j += 1) {
val = val + a(i, j);
}
}
B(xPosition,yPosition) = val;
I have come up with below code:
public List<List<Integer>> generate(List<List<Integer>> A) {
List<List<Integer>> top = new ArrayList<>();
for (int i = 0; i < A.size(); i++) {
List<Integer> inner = new ArrayList<>();
for (int j = 0; j < A.get(0).size(); j++) {
inner.add(generateValue(A, i, j));
}
top.add(inner);
}
return top;
}
int generateValue(List<List<Integer>> A, int xPosition, int yPosition) {
int val = 0;
for (int i = 0; i <= xPosition; i++) {
for (int j = 0; j <= yPosition; j++) {
int value = A.get(i).get(j);
val += value;
}
}
return val;
}
Sample input :
1 2 3
4 5 6
Output :
1 3 6
5 12 21
How to improve the performance of this logic?
mathematicaly for your solution in array b,each element is related to it's previous one.
to improve your code / optimise it you need to see this relation.
so for every B[i][j] is related to it's previous element and value from the array A.
below is solution mathematically,
b[i][j] = b[i-1][j] + a[i][0]+a[i][1] + a[i][2]+...+a[i][y-1]
for so if you able to implement this, your code will pass all test cases
i am not a java dev, but if you want code, i can write it for you in python
The key is to think of this as a dynamic programming problem, assuming that we have already calculated B[x][y] for all 0 <= x < i, 0 <= y < j when we go to calculate B[i][j].
B[i][j] contains the sum of all elements in the submatrix of A that starts at 0, 0 and ends at i, j. Thus B[i-1][j] will contain the sum of the all the elements in this submatrix except the ones in the ith row. Similarly, B[i][j-1] will contain the sum of the all the elements in this submatrix except the ones in the jth column. Adding these two together, we get the sum of all the elements in the submatrix except for element A[i][j]. However, while doing this we count all the elements from 0, 0 to i-1, j-1 twice, and we have to subtract their sum (which is B[i-1][j-1]) once so that we only sum them up once in total. Then we add the missing element, A[i][j]. Hence
B[i][j] = B[i-1][j] + B[i][j-1] - B[i-1][j-1] + A[i][j]
This recursion can now be implemented as a O(RC) dynamic programming algorithm.
To help understand this further, consider the following figure representing the submatrix for which we have to find the sum of the elements. The figure is a matrix C[i][j], where the x, yth element is the number of times we have summed A[x][y]. In terms of C[i][j], our end goal (B[i][j]) is
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
B[i-1][j] corresponds to the matrix C[i-1][j], which is
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
0 0 0 0 0
B[i][j-1] corresponds to the matrix C[i][j-1], which is
1 1 1 1 0
1 1 1 1 0
1 1 1 1 0
1 1 1 1 0
B[i-1][j] + B[i][j-1] corresponds to the matrix C[i-1][j] + C[i][j-1], which is
2 2 2 2 1
2 2 2 2 1
2 2 2 2 1
1 1 1 1 0
B[i-1][j] + B[i][j-1] - B[i-1][j-1] corresponds to the matrix C[i-1][j] + C[i][j-1] - C[i-1][j-1], which is
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 0
Now B[i-1][j] + B[i][j-1] - B[i-1][j-1] + A[i][j] corresponds to
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
which is the same as B[i][j].

Nested for loop Java confusion

Hi i have a beginner question about nested for-loop in java.
int sum = 0;
for(int i = 1; i < 3; i++){
for(int j = i; j>= 0; j--){
sum += j;
}
}
so here is my trace table
i j sum
1 1 1
0 1
2 2 2
1 3
0 3
My question is why is the output at the end of the loop is 4? is it because 3+1?
Your trace table is wrong. This is the correct one:
i j sum
1 1 1
0 1
2 2 3
1 4
0 4
You sum all values of j (second column), which essentially is 1 + 0 + 2 + 1 + 0 = 4.
Actually we need to make a correction for your table result:
i j sum
1 1 1
0 1
2 2 2 (sum is 2+1(existing sum, sum is not 0 anymore) )
1 3 (sum is 3 + 1 = 4)
0 3 (sum is 4+ 0 = 4)
The output is 4 because sum is:
0 +
1 +
2 + 1 =
= 4
First you add 1, then 2 and 1. Your loops sums all triangle numbers below 3. Triangle numbers are sums of numbers from 1 to n. These are 1, 3, 6, 10 etc..

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)

Categories