how to print two dimensional array correctly? - java

my output is
4 4 8 7
3 3 3 5 6 3 3 4 5
when it should be
4 4 5
8 7 7
3 3 3 4
5 6 3 1
3 4 5 6
i need to use same method for all of arrays, summing up arrays of two matrices.
how can i do that when arrays are different length and how can i print output correctly?
public static void main(String[] args) {
int[][] m1 = { { 1, 2, 0 }, { 2, 3, 4 } };
int[][] m2 = { { 3, 2, 5 }, { 6, 4, 3 } };
int[][] m3 = { { 1, 1, 1, 1 }, { 3, 3, 2, 1 }, { 2, 2, 2, 2 } };
int[][] m4 = { { 2, 2, 2, 3 }, { 2, 3, 1, 0 }, { 1, 2, 3, 4 } };
printMatrixSum(m1, m2);
System.out.println();
printMatrixSum(m3, m4);
}
private static void printMatrixSum(int[][] x, int[][] y) {
int c[][] = new int[4][4];
for (int i=0; i < 2; ++i) {
for(int j=0;j<3;j++) {
c[i][j]=x[i][j]+y[i][j];
System.out.print(c[i][j]+" ");
}
}System.out.println();
}
}

Your code is close to working. I made some changes below, and it now produces this output:
4 4 5
8 7 7
3 3 3 4
5 6 3 1
3 4 5 6
Here's the code:
1. private static void printMatrixSum(int[][] x, int[][] y) {
2. int[][] c = new int[x.length][x[0].length];
3. for (int i = 0; i < x.length; i++) {
4. for (int j = 0; j < x[0].length; j++) {
5. c[i][j] = x[i][j] + y[i][j];
6. System.out.print(c[i][j] + " ");
7. }
8. System.out.println();
9. }
10. }
Here are the edits I made:
line 2: change int c[][] to int[][] c – this is minor, but follows Java style
line 2: change new int[4][4] to use actual values for array length. The first dimension is just x.length, and the second is x[0].length. This will work correctly with different array inputs vs. hard-coding to "4".
line 3: change i < 2 condition to use the length of one of the input arrays; I chose x but it could be y (and of course this code assumes that x and y are matching dimensions)
line 3: change ++i to i++ – not sure why you were using pre-increment, but in my opinion that makes it harder to reason about loop behavior, and also the second loop (line 4) was already doing post-increment (j++) so I edited this one to make it both clearer as well as consistent with the rest of your code.
line 4: change j < 3 to be dynamic, similar to edit on line 3
line 8: move the println() here, so that a newline is printed after each row of the array is printed

Instead of printing it with fixed sizes ( like i < 2 and j <3 ), use the dimension of the array to make your function more reusable.
ii) Secondly, the println() should be outside the inner loop but inside the outer loop .
private static void printMatrixSum(int[][] x, int[][] y) {
int c[][] = new int[4][4];
for (int i = 0; i < x.length; ++i) {
for (int j = 0; j < y[0].length; j++) {
c[i][j] = x[i][j] + y[i][j];
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
and this is the answer :
4 4 5
8 7 7
3 3 3 4
5 6 3 1
3 4 5 6

A couple suggestions.
Consider not writing a printMatrixSum method. Write a method to print a matrix. You may not always want to print a matrix after you compute the sum. Of course that means iterating over the matrix twice so it's ultimately going to be based on your requirements.
specify a width value to help nicely format the output.
And you don't need to index the matrix. Multi-dimensional arrays are simply arrays of other arrays. So you can use the enhanced forloop to first iterate the rows, and then the values in each row.
Here is an example.
int [][] data = {{203,2,3334,-22022, 23},{2,1,233, 42,33}};
matPrint(data, 7);
prints
203 2 3334 -22022 23
2 1 233 42 33
use the width to specify the largest value(including sign)
create a format for System.out.printf
then simply iterate the rows. and within each row, iterate the values.
public static void matPrint(int[][] m, int width) {
String fmt = "%" + width + "s";
for (int[] row : m) {
for (int col : row) {
System.out.printf(fmt, col);
}
System.out.println();
}
}
If you have a specific width that you want to use often you can overload the print method as follows. Then you can use the one argument version which invokes the two argument with the default width.
private static int DEFAULT_WIDTH = 4;
public static void matPrint(int[][] m) {
matPrint(m, DEFAULT_WIDTH);
}
And if you specify the field width as a negative value, it will left justify the output within each field.

Related

Need help shifting latin square in Java

I'm currently making a latin square that starts with a user-set number but for simplicity's sake I'll exclude Scanner code.
public static void main(String[] args){
int first = 2; // starting integer on square
int order = 4; //max integer
String space = new String(" ");
for (int row = 0; row < order; row++)
{
for (int column = 0; column < order; column++)
{
for (int shift = 0; shift < order; shift++)
{
int square = ((column+(first-1)) % order + 1); //this makes a basic square with no shifting
int latin = square+shift; //this is where my code becomes a mess
System.out.print(latin + space);
}
System.out.println();
}
}
}
}
Which prints out:
2 3 4 5
3 4 5 6
4 5 6 7
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7
1 2 3 4
It's so close, considering the fact that it does start with my pre-determined first digit and it's printing only 4 integers.
The problem I'm running into is the fact that it's going further than my order integer and that it's printing double the rows.
Any idea what I can do to fix this?
For reference, this is what I want it to print:
2 3 4 1
3 4 1 2
4 1 2 3
1 2 3 4
It seems that the innermost loop for (int shift...) is redundant and it causes duplication of the output, the latin value should be calculated using row parameter:
public static void main(String args[]) {
int first = 2; // starting integer on square
int order = 4; //max integer
String space = " ";
for (int row = 0; row < order; row++) {
for (int column = 0; column < order; column++) {
int latin = (row + column + first - 1) % order + 1;
System.out.print(latin + space);
}
System.out.println();
}
}
Output:
2 3 4 1
3 4 1 2
4 1 2 3
1 2 3 4

an int array from Command Line Arguments

I'm trying to convert command line arguments in an int array, but it appears a "0" in the end of the array. How can I fix it?
import java.util.Arrays;
public static void main(String[] args){
int[] game = new int[9];
for (int i = 0; i <= 8; i++)
game[i] = Integer.parseInt(args[i]);
System.out.println(Arrays.toString(game));
}
Example run:
$ java edu.kit.informatik.TicTacToe 5 6 4 1 2 3 7 8 9
[5, 6, 4, 1, 2, 3, 7, 8, 9, 0]
I have tested your code, there aren't '0' at the end of the list. I recommend you that use args.length for handling variety arguments count.
public static void main(String[] args) {
int[] game = new int[args.length];
for (int i = 0; i < args.length; i++)
game[i] = Integer.parseInt(args[i]);
System.out.println(Arrays.toString(game));
}
When you create a new int[] array in Java, its initial contents are all zeros. If you then fill it up with fewer numbers than it is long, you'll see the zeros that have not been overwritten at the end.
// creating an array of size 10
int[] array = new int[10];
// only filling up the first 8 elements
for (int i = 1; i <= 8; i++) {
array[i-1] = i;
}
// printing the full array
for (int i = 0; i < array.length; i++) {
System.out.print(i + " ");
}
System.out.println();
This will output:
1 2 3 4 5 6 7 8 0 0
The last two zeros are just the elements that have not been set to anything else.

How to count all possible cases?

For example I have array with length n=3:
for(int i = 0; i < n; i++) {
array[i] = i;
}
So the cases should be:
1. 0
2. 1
3. 2
4. 0 1
5. 0 2
6. 1 2
7. 0 1 2
So the number of cases should be 7 for n = 3.
In my code:
int n = 3;
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = i;
}
int sum = 0;
for (int i = 0; i < n; i++) {
System.out.println(array[i] + " ");
sum++;
for (int j = i; j < n; j++) {
System.out.print(array[j] + " ");
}
System.out.println();
sum++;
}
System.out.println("sum = " + sum);
Output is:
0
0 1 2
1
1 2
2
2
sum = 6
The number 2 is two times so it is wrong and sum is actually = 5. And I don't get cases
4. 0 1
and
5. 0 2
How to count all possible cases?
Sets, not arrays
The first important observance is that you are not using fixed length arrays here but sets of different lengths.
Take a look at your example. You allow
0
1
2
0, 1
0, 2
1, 2
which are not all of size 3.
Also you don't differentiate between
0, 1
1, 0
so order doesn't matter, like in sets.
Power set
That's why you're actually describing power sets here. For the example set {0, 1, 2} its power set is defined as
P({0, 1, 2}) = {
{}, // empty set
{0},
{1},
{2},
{0, 1},
{0, 2},
{1, 2},
{0, 1, 2}
}
Fortunately there exists an easy closed formula for their size. If n is the size of the input set the size of the power set is
2^n
But they also count the empty set, so you will need to -1 if you don't want that:
2^n - 1
Solution
Thus in Java you could write
int Set<Integer> input = ...
int size = (int) Math.pow(2, input.size()) - 1;
and that's all, you don't need to build the contents manually.
But if you're curious and want to build them, take a look at questions like Obtaining a powerset of a set in Java. It's an implementation of the recursive formula shown at Wikipedia.
So, totally inefficient but also working:
int Set<Integer> input = ...
// Build the power-set using the method from linked question
Set<Set<Integer>> power = powerSet(input);
int size = power.size() - 1;

Doubling a Matrix

I've created a two dimensional matrix and populated it with random numbers. I've then printed it out. I need help creating a second matrix that is twice the size of the first, and is populated with the numbers from the first one (which are now 2x2). For example:
Starting Matrix:
3 4
2 1
Doubled Matrix:
3 3 4 4
3 3 4 4
2 2 1 1
2 2 1 1
import java.util.Scanner;
import java.util.Random;
public class MatrixDoubler {
public static void main(String[] arg) {
Scanner keyboard = new Scanner(System.in);
Random rand = new Random();
System.out.println("Enter the size of the matrix");
int size = keyboard.nextInt();
int A[][] = new int[size][size];
for (int row = 0; row < size; ++row) {
for (int col = 0; col < size; ++col) {
A[row][col] = rand.nextInt(10);
}
}
System.out.println("Matrix A:");
printMatrix(A);
int[][] B = doubleMatrix(A);
System.out.println("Matrix B:");
printMatrix(B);
}
private static int[][] doubleMatrix(int[][] A) {
int rows = A.length;
assert(rows > 0);
int cols = A[0].length;
assert(cols > 0);
int B[][] = new int[rows * 2][cols * 2];
for (int row = 0; row < rows * 2; ++row) {
for (int col = 0; col < cols * 2; ++col) {
B[row][col] = A[row / 2][col / 2];
}
}
return B;
}
private static void printMatrix(int[][] M) {
for(int i = 0; i < M.length; i++) {
for(int j = 0; j < M.length; j++) {
System.out.print(M[i][j] + " ");
}
System.out.println();
}
}
}
I'm no sure if that is what you are looking for but try this:
for (int i = 0; i < newMatrix.length; i++) {
for (int j = 0; j < newMatrix.length; j++) {
newMatrix[i][j] = matrix[i/size][j/size];
}
}
Note: This code is surely not the best solution but a fast an easy one. It only works if both dimensions are the same size and it won't work if newMatrix is not exactly two times matrix. If it's always just to "double" a matrix it should work fine.
Output:
If you choose size 2 than it will output:
Enter the size of the matrix
2
The Matrix is
3 5
5 2
The newMatrix is
3 3 5 5
3 3 5 5
5 5 2 2
5 5 2 2
and for size 3 it would be for example
Enter the size of the matrix
3
The Matrix is
4 4 3
5 9 4
7 4 1
The newMatrix is
4 4 4 4 3 3
4 4 4 4 3 3
5 5 9 9 4 4
5 5 9 9 4 4
7 7 4 4 1 1
7 7 4 4 1 1
It's not clear what you are asking but I hope this helps (:
In Java 8 you can handle this pretty easily using maps and collectors. Here is a full example:
public class DoubleMatrix {
public static void main(String[] args) {
List<List<Integer>> startingMatrix = Arrays.asList(
Arrays.asList(3, 4),
Arrays.asList(2, 1)
);
List<List<Integer>> doubleMatrix
= startingMatrix.stream()
.map(innerList -> { //For each list
List<Integer> doubled = innerList.stream()
.map(element -> Arrays.asList(element, element)) //Return a list doubling each element
.flatMap(l -> l.stream()) //Flatten out/join all doubled lists
.collect(Collectors.toList());
return Arrays.asList(doubled, doubled); //Double the list
})
.flatMap(l -> l.stream())
.collect(Collectors.toList()); //Collect into a final list
System.out.println(doubleMatrix);
}
}
This avoids needing to know the size of the list beforehand, and is also tolerant of there being a difference between the width and height of your matrix - simply doubling every element in both directions.

How to print Two-Dimensional Array like table

I'm having a problem with two dimensional array. I'm having a display like this:
1 2 3 4 5 6 7 9 10 11 12 13 14 15 16 . . . etc
What basically I want is to display to display it as:
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20
21 22 23 24 ... etc
Here is my code:
int twoDm[][]= new int[7][5];
int i,j,k=1;
for(i=0;i<7;i++){
for(j=0;j<5;j++) {
twoDm[i][j]=k;
k++;}
}
for(i=0;i<7;i++){
for(j=0;j<5;j++) {
System.out.print(twoDm[i][j]+" ");
System.out.print("");}
}
If you don't mind the commas and the brackets you can simply use:
System.out.println(Arrays.deepToString(twoDm).replace("], ", "]\n"));
public class FormattedTablePrint {
public static void printRow(int[] row) {
for (int i : row) {
System.out.print(i);
System.out.print("\t");
}
System.out.println();
}
public static void main(String[] args) {
int twoDm[][]= new int[7][5];
int i,j,k=1;
for(i=0;i<7;i++) {
for(j=0;j<5;j++) {
twoDm[i][j]=k;
k++;
}
}
for(int[] row : twoDm) {
printRow(row);
}
}
}
Output
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
26 27 28 29 30
31 32 33 34 35
Of course, you might swap the 7 & 5 as mentioned in other answers, to get 7 per row.
You need to print a new line after each row... System.out.print("\n"), or use println, etc. As it stands you are just printing nothing - System.out.print(""), replace print with println or "" with "\n".
You could write a method to print a 2d array like this:
//Displays a 2d array in the console, one line per row.
static void printMatrix(int[][] grid) {
for(int r=0; r<grid.length; r++) {
for(int c=0; c<grid[r].length; c++)
System.out.print(grid[r][c] + " ");
System.out.println();
}
}
A part from #djechlin answer, you should change the rows and columns. Since you are taken as 7 rows and 5 columns, but actually you want is 7 columns and 5 rows.
Do this way:-
int twoDm[][]= new int[5][7];
for(i=0;i<5;i++){
for(j=0;j<7;j++) {
System.out.print(twoDm[i][j]+" ");
}
System.out.println("");
}
I'll post a solution with a bit more elaboration, in addition to code, as the initial mistake and the subsequent ones that have been demonstrated in comments are common errors in this sort of string concatenation problem.
From the initial question, as has been adequately explained by #djechlin, we see that there is the need to print a new line after each line of your table has been completed. So, we need this statement:
System.out.println();
However, printing that immediately after the first print statement gives erroneous results. What gives?
1
2
...
n
This is a problem of scope. Notice that there are two loops for a reason -- one loop handles rows, while the other handles columns. Your inner loop, the "j" loop, iterates through each array element "j" for a given "i." Therefore, at the end of the j loop, you should have a single row. You can think of each iterate of this "j" loop as building the "columns" of your table. Since the inner loop builds our columns, we don't want to print our line there -- it would make a new line for each element!
Once you are out of the j loop, you need to terminate that row before moving on to the next "i" iterate. This is the correct place to handle a new line, because it is the "scope" of your table's rows, instead of your table's columns.
for(i=0;i<7;i++){
for(j=0;j<5;j++) {
System.out.print(twoDm[i][j]+" ");
}
System.out.println();
}
And you can see that this new line will hold true, even if you change the dimensions of your table by changing the end values of your "i" and "j" loops.
Just for the records, Java 8 provides a better alternative.
int[][] table = new int[][]{{2,4,5},{6,34,7},{23,57,2}};
System.out.println(Stream.of(table)
.map(rowParts -> Stream.of(rowParts
.map(element -> ((Integer)element).toString())
.collect(Collectors.joining("\t")))
.collect(Collectors.joining("\n")));
More efficient and easy way to print the 2D array in a formatted way:
Try this:
public static void print(int[][] puzzle) {
for (int[] row : puzzle) {
for (int elem : row) {
System.out.printf("%4d", elem);
}
System.out.println();
}
System.out.println();
}
Sample Output:
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
You can creat a method that prints the matrix as a table :
Note: That does not work well on matrices with numbers with many digits and
non-square matrices.
public static void printMatrix(int size,int row,int[][] matrix){
for(int i = 0;i < 7 * size ;i++){
System.out.print("-");
}
System.out.println("-");
for(int i = 1;i <= matrix[row].length;i++){
System.out.printf("| %4d ",matrix[row][i - 1]);
}
System.out.println("|");
if(row == size - 1){
// when we reach the last row,
// print bottom line "---------"
for(int i = 0;i < 7 * size ;i++){
System.out.print("-");
}
System.out.println("-");
}
}
public static void main(String[] args){
int[][] matrix = {
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16}
};
// print the elements of each row:
int rowsLength = matrix.length;
for(int k = 0; k < rowsLength; k++){
printMatrix(rowsLength,k,matrix);
}
}
Output :
---------------------
| 1 | 2 | 3 | 4 |
---------------------
| 5 | 6 | 7 | 8 |
---------------------
| 9 | 10 | 11 | 12 |
---------------------
| 13 | 14 | 15 | 16 |
---------------------
I created this method while practicing loops and arrays, I'd rather use:
System.out.println(Arrays.deepToString(matrix).replace("], ", "]\n")));
Iliya,
Sorry for that.
you code is work. but its had some problem with Array row and columns
here i correct your code this work correctly, you can try this ..
public static void printMatrix(int size, int row, int[][] matrix) {
for (int i = 0; i < 7 * matrix[row].length; i++) {
System.out.print("-");
}
System.out.println("-");
for (int i = 1; i <= matrix[row].length; i++) {
System.out.printf("| %4d ", matrix[row][i - 1]);
}
System.out.println("|");
if (row == size - 1) {
// when we reach the last row,
// print bottom line "---------"
for (int i = 0; i < 7 * matrix[row].length; i++) {
System.out.print("-");
}
System.out.println("-");
}
}
public static void length(int[][] matrix) {
int rowsLength = matrix.length;
for (int k = 0; k < rowsLength; k++) {
printMatrix(rowsLength, k, matrix);
}
}
public static void main(String[] args) {
int[][] matrix = { { 1, 2, 5 }, { 3, 4, 6 }, { 7, 8, 9 }
};
length(matrix);
}
and out put look like
----------------------
| 1 | 2 | 5 |
----------------------
| 3 | 4 | 6 |
----------------------
| 7 | 8 | 9 |
----------------------
Declared a 7 by 5 array which is similar to yours, with some dummy data. Below should do.
int[][] array = {{21, 12, 32, 14, 52}, {43, 43, 55, 66, 72}, {57, 64, 52, 57, 88},{52, 33, 54, 37, 82},{55, 62, 35, 17, 28},{55, 66, 58, 72, 28}};
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println(); // the trick is here, print a new line after iterating first row.
}
public class class1 {
public static void main(String[] args){
int[][] a={{1, 2, 3}, {4, 5, 6}};
for (int i = 0; i< a.length; i++){
System.out.print("Row" + (i + 1) + ": ");
for (int j = 0; j < a[i].length; j++){
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
}
result:
Row1: 1 2 3
Row2: 4 5 6
This might be late however this method does what you ask in a perfect manner, it even shows the elements in ' table - like ' style, which is brilliant for beginners to really understand how an Multidimensional Array looks.
public static void display(int x[][]) // So we allow the method to take as input Multidimensional arrays
{
//Here we use 2 loops, the first one is for the rows and the second one inside of the rows is for the columns
for(int rreshti = 0; rreshti < x.length; rreshti++) // Loop for the rows
{
for(int kolona = 0; kolona < x[rreshti].length;kolona++) // Loop for the columns
{
System.out.print(x[rreshti][kolona] + "\t"); // the \t simply spaces out the elements for a clear view
}
System.out.println(); // And this empty outputprint, simply makes sure each row (the groups we wrote in the beggining in seperate {}), is written in a new line, to make it much clear and give it a table-like look
}
}
After you complete creating this method, you simply put this into your main method:
display(*arrayName*); // So we call the method by its name, which can be anything, does not matter, and give that method an input (the Array's name)
NOTE. Since we made the method so that it requires Multidimensional Array as a input it wont work for 1 dimensional arrays (which would make no sense anyways)
Source: enter link description here
PS. It might be confusing a little bit since I used my language to name the elements / variables, however CBA to translate them, sorry.
For traversing through a 2D array, I think the following for loop can be used.
for(int a[]: twoDm)
{
System.out.println(Arrays.toString(a));
}
if you don't want the commas you can string replace
if you want this to be performant you should loop through a[] and then print it.
public static void main(String[] args) {
int[][] matrix = {
{ 1, 2, 5 },
{ 3, 4, 6 },
{ 7, 8, 9 }
};
System.out.println(" ** Matrix ** ");
for (int rows = 0; rows < 3; rows++) {
System.out.println("\n");
for (int columns = 0; columns < matrix[rows].length; columns++) {
System.out.print(matrix[rows][columns] + "\t");
}
}
}
This works,add a new line in for loop of the row. When the first row will be done printing the code will jump in new line.
ALL OF YOU PLEASE LOOT AT IT I Am amazed it need little IQ
just get length by arr[0].length and problem solved
for (int i = 0; i < test.length; i++) {
for (int j = 0; j < test[0].length; j++) {
System.out.print(test[i][j]);
}
System.out.println();
}

Categories