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