I am trying to initialize a 2D array, in which the type of each element is char.
So far, I can only initialize this array in the follow way.
public class ticTacToe
{
private char[][] table;
public ticTacToe()
{
table[0][0] = '1';
table[0][1] = '2';
table[0][2] = '3';
table[1][0] = '4';
table[1][1] = '5';
table[1][2] = '6';
table[2][0] = '7';
table[2][1] = '8';
table[2][2] = '9';
}
}
I think if the array is 10*10, it is the trivial way.
Is there any efficient way to do that?
Shorter way is do it as follows:
private char[][] table = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};
How about something like this:
for (int row = 0; row < 3; row ++)
for (int col = 0; col < 3; col++)
table[row][col] = (char) ('1' + row * 3 + col);
The following complete Java program:
class Test {
public static void main(String[] args) {
char[][] table = new char[3][3];
for (int row = 0; row < 3; row ++)
for (int col = 0; col < 3; col++)
table[row][col] = (char) ('1' + row * 3 + col);
for (int row = 0; row < 3; row ++)
for (int col = 0; col < 3; col++)
System.out.println (table[row][col]);
}
}
outputs:
1
2
3
4
5
6
7
8
9
This works because the digits in Unicode are consecutive starting at \u0030 (which is what you get from '0').
The expression '1' + row * 3 + col (where you vary row and col between 0 and 2 inclusive) simply gives you a character from 1 to 9.
Obviously, this won't give you the character 10 (since that's two characters) if you go further but it works just fine for the 3x3 case. You would have to change the method of generating the array contents at that point such as with something like:
String[][] table = new String[5][5];
for (int row = 0; row < 5; row ++)
for (int col = 0; col < 5; col++)
table[row][col] = String.format("%d", row * 5 + col + 1);
Easy to read/type.
table = new char[][] {
"0123456789".toCharArray()
, "abcdefghij".toCharArray()
};
You can use for loop if you really want to.
char table[][] table = new char[row][col];
for(int i = 0; i < row * col ; ++i){
table[i/row][i % col] = char('a' + (i+1));
}
or do what bhesh said.
You can follow what paxdiablo(on Dec '12) suggested for an automated, more versatile approach:
for (int row = 0; row < 3; row ++)
for (int col = 0; col < 3; col++)
table[row][col] = (char) ('1' + row * 3 + col);
In terms of efficiency, it depends on the scale of your implementation.
If it is to simply initialize a 2D array to values 0-9, it would be much easier to just define, declare and initialize within the same statement like this:
private char[][] table = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};
Or if you're planning to expand the algorithm, the previous code would prove more, efficient.
Related
I am using java and I would like to print a 2d array horizontally multiple time based on user input. However, my array prints vertically, can anyone help?
n=3; //user input
char[][] board = new char[2][3];
char[][] f = new char[board.length][n * board[0].length];
for (int i = 1; i < n + 1; i++) {
int Start = (i * board[0].length) - board[0].length;
int End = i * board[0].length;
for (int row = 0; row < f.length; row++) {
for (int col = nStart; col < nEnd; col++) {
f[row][col] = board[row][col - nStart];
System.out.print(f[row][col]);
}
System.out.println();
}
}
For example board array =
xx
xx
I would like
xxxxxx
xxxxxx
If you want to print 2d array horizontally, you have to repeat printing row n times before next row:
int n = 3; // user input
char[][] board = new char[][] { { 'x', 'x', 'x' }, { '0', '0', '0' } }; //example board
for (int row = 0; row < board.length; row++)
{
for (int i = 0; i < n; i++)
{
for (int col = 0; col < board[row].length; col++)
{
System.out.print(board[row][col]);
}
System.out.print("\t"); //arrays separated by tab
}
System.out.println();
}
Output:
xxx xxx xxx
000 000 000
I hope this help.
Your solution works fine except that you made a little mistake in the last lines of your code. I think you want to print a space between every entry by using System.out.println() but println prints a line-break at the end. So your code should look like this:
n=3; //user input
char[][] board = new char[2][3];
char[][] f = new char[board.length][n * board[0].length];
for (int i = 1; i < n + 1; i++) {
int Start = (i * board[0].length) - board[0].length;
int End = i * board[0].length;
for (int row = 0; row < f.length; row++) {
for (int col = nStart; col < nEnd; col++) {
f[row][col] = board[row][col - nStart];
System.out.print(f[row][col]);
}
System.out.print(" "); // Print a space between every single output
}
}
Or if you dont wan't a space at all remove the line completely. Or change the space to a comma, point or whatever you need.
Removing the copied array f.
What you need is exchanging row,col in loop.
n=3; //user input
char[][] board = new char[2][3];
for (int j = 0; j < board[0].length; j++) {
for (int i = 0; i < n ; i++) {
System.out.print(board[i][j]);
System.out.print(" ");
}
System.out.println();
}
I'm building a 2d array filled with 1's.
when the array is initialized everything seems fine. I am attempting to print it to the console but as I iterate through the nested for loop to go through each element and I get 33 printed instead of 1. I've been running this through the debugger trying to figure it out but I'm stumped. In the debugger all the array elements are filled with 1's but it keeps printing 33.
int NUMBER_OF_ROWS = 5;
int NUMBER_OF_COLUMNS = 5;
int[][] matrix = new int[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS];
int row=0;
int col=0;
// The column gets filled first in the nested loop, then the row gets
// incremented. Then the next column gets filled.
// After intializing all rows and columns are filled with 0
for (row = 0; row < NUMBER_OF_ROWS; row++) {
col = 0;
for (col = 0; col < NUMBER_OF_COLUMNS; col++)
matrix[row][col] = 1;
}
for (row = 0; row < NUMBER_OF_ROWS; row++) {
System.out.println(' ');
for (col =0; col < NUMBER_OF_COLUMNS; col++)
System.out.print(matrix[row][col] + ' ');
}
It is not crap. There is a problem with your code.
System.out.print(matrix[row][col] + ' ');
1 + 32 = 33 (Space is 32 in ASCII.)
Use:
System.out.print(matrix[row][col] + " "); //Convert to String and appends space.
I'm having a strange issue trying to print a 9x9 grid of integers. When I try this code in the main method:
for (int row = 0; row < 9; row++) {
for (int col = 0; col < 0; col++) {
System.out.format( "%d ", entries[row][col] );
}
System.out.print("\n");
}
The output is just a bunch of spaces and newlines, without the actual integers. I've tested 'entries' to make sure it actually contains the correct values (and it does). The weird thing is, when I try the following code also in the main method:
System.out.format("%d ", entries[0][0]);
It works. For some reason the for loop is messing up the output. Any ideas?
You did a mistake in the inner for loop:
for (int col = 0; col < 0; col++)
This wont do any iteration because zero is equals zero.
I think this is what you want:
for (int col = 0; col < 9; col++)
Problem is with the condition in second for loop
for (int col = 0; col < 0; col++) {
It is always false and hence never gets executed.
You should instead use:
for (int col = 0; col < 9; col++) {
This condition is never met:
for (int col = 0; col < 0; col++) {
so you can just simplify it by doing:
for (int row = 0; row < 9; row++) {
System.out.format( "%d ", entries[row][0] );
System.out.print("\n");
}
To print a two-dimensional array , you have to print each element in the array using a loop like the following:
int[][] matrix = new int[9][9];//9*9 grid container
for(int row=0 ; row < matrix.length ;row++){
for(int column= 0 ; column < matrix[row].length;column++){
System.out.print(matrix[row][column] + "");
}
System.out.println();
}
I have a 2D array with values in it. Example below:
010101
101010
010101
I want to create a loop that shifts these values to the left like the example below.
101010
010101
101010
So the element that "falls off" goes back in to the end. I'm having a hard time solving this issue in code.
Anyone got any advice?
So far I have made it scroll but I have no clue how to get the elements that fall off to go back in.
This is what I have so far.
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[row].length; col++) {
if (!(row >= array.length) && !(col >= array[row].length - 1)) {
array[row][col] = array[row][col + 1];
}
}
}
Try using the modulus operator:
arrayShifted[row][col] = array[row][(col + 1) % array[row].length];
Remove your condition check as well. Also note, to avoid overwriting values, you'll need to store the results in a new array.
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[row].length; col++) {
arrayShifted[row][col] = array[row][(col + 1) % array[row].length]
}
}
Here is a full method that takes in a variable amount of spots to shift each row and properly handles copying the same elements as in the modulus approach.
public void shiftArray(int[][] array, int shift) {
for (int row = 0; row < array.length; row++) {
int rowLength = array[row].length;
// keep shift within bounds of the array
shift = shift % rowLength;
// copy out elements that will "fall off"
int[] tmp = new int[shift];
for (int i = 0; i < shift; i++) {
tmp[i] = array[row][i];
}
// shift like normal
for (int col = 0; col < rowLength - shift; col++) {
array[row][col] = array[row][col + shift];
}
// copy back the "fallen off" elements
for (int i = 0; i < shift; i++) {
array[row][i + (rowLength - shift)] = tmp[i];
}
}
}
Test Run
int[][] array = new int[][] {
{0,1,0,1,0,1},
{1,0,1,0,1,0},
{0,1,0,1,0,1}
};
shiftArray(array, 1);
for (int[] row : array) {
for (int col : row) {
System.out.print(col);
}
System.out.println();
}
// 101010
// 010101
// 101010
I have a 2D Array (inputMatrix with x rows and y columns) and need to subtract all vectors(rows) with eachother.
Here's the input:
1,5
3,7
2,3
6,5
4,7
The output(a distance matrix) should look like:
subtraction[0][0] = {0,0} // first row - first row
subtraction[0][1] = {-2,-2} // first row - 2nd row -> {1,5}-{3,7}=-2,2
subtraction[0][2] = {-1,2} // first row - 3rd row
...
subtraction[4][2] = {2,4}
subtraction[4][3] = {-2,2}
subtraction[4][4] = {0,0}
However i'm having a problem on storing the values, since subtraction[row][col] values are being overwritten on the "col for-loop". Also a note, each subtraction index is getting as output another array.
for(int row = 0; row < inputMatrix.length; row++){
for(int col = 0; col < inputMatrix[0].length; col++){
subtraction[row][col] = inputMatrix[0][row] - inputMatrix[row][col];
System.out.print(subtraction[row][col] + " ");
}
System.out.print("\n");
}
Based on your description of the output, you need a 3-dimensional array to store the output, since for each pair of input rows, you are producing an output row.
for(int row1 = 0; row1 < inputMatrix.length; row1++){
for(int row2 = 0; row2 < inputMatrix.length; row2++){
for(int col = 0; col < inputMatrix[0].length; col++){
subtraction[row1][row2][col] = inputMatrix[row1][col] - inputMatrix[row2][col];
}
}
}
If you must have a two dimensional output, you can flatten the output :
int outputRow = 0;
for(int row1 = 0; row1 < inputMatrix.length; row1++){
for(int row2 = 0; row2 < inputMatrix.length; row2++){
for(int col = 0; col < inputMatrix[0].length; col++){
subtraction[outputRow][col] = inputMatrix[row1][col] - inputMatrix[row2][col];
}
outputRow++;
}
}
subtraction[row][col] = inputMatrix[0][row] - inputMatrix[**row**][**col**];
You've mixed up your indices here.