How to print a 2d array horizontally multiple times - java

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

Related

How should I understand a "for" statement in a tilemap?

I'm following a tutorial online and I'm having troubles understanding the code which is written there.
public Tilemap() {
int[][] tilemap = new int[30][50];
System.out.println("New Tilemap created.");
Random r = new Random();
int rows = tilemap.length;
int columns = tilemap[1].length;
printTiles(rows, columns, tilemap, r);
}
public void printTiles(int rows, int columns, int[][] tilemap, Random r) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
tilemap[i][j] = r.nextInt(5);
System.out.print(" " + tilemap[i][j]);
}
System.out.println(" ");
}
}
I understand everything up until the for statement:
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
tilemap[i][j] = r.nextInt(5);
System.out.print(" " + tilemap[i][j]);
}
System.out.println(" ");
}
The tutorial doesn't explain one bit about them. So if anyone could help me understand, what is the purpose of most of the lines in the for statement, I'd appreciate that.
It looks like it's iterating through the entire 2D array and placing random integers at every index.
I've commented the code below. Hopefully this explains it.
for (int i = 0; i < rows; i++) { //iterate through every row
for (int j = 0; j < columns; j++) { //iterate through every column
tilemap[i][j] = r.nextInt(5); //place an integer between 0 (inclusive) and 5 (exclusive) at the specified location in the 2d array
System.out.print(" " + tilemap[i][j]); //print the integer that was just placed with a preceding space
}
System.out.println(" "); //print a new line since we've reached the end of the row
}

Shifting a 2D array to the left loop

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

Filling a vertical matrix Java

I'm trying to fill a matrix vertically, but 1 row is missing. Can you help me ? There is the code. Maybe there is an easier way to fill a matrix verically, but i cant find it.
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.print("Enter the value of matrix: ");
int n = input.nextInt();
int [][] matrix = new int [n][n];
for (int i = 1; i < matrix.length; i++) {
matrix[0][i] = matrix[0][i -1] + n;
}
for(int i = 1; i < matrix.length; i++){
for (int j = 0; j < matrix.length; j++){
matrix[i][j] = matrix[i -1][j] + 1;
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
input.close();
}
Output:
Enter the value of matrix: 4
1 5 9 13
2 6 10 14
3 7 11 15
Your row is missing because you never printed it in your first loop (the one that is initializing your first line) - you should have a row of 0 4 10 12 at the beginning. But you could do it much easier with only one nested loop.
Try
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.print("Enter the value of matrix: ");
int n = input.nextInt();
int [][] matrix = new int [n][n];
matrix[0][0]=0; //you have forgotten the first value
for (int i = 1; i < matrix.length; i++) {
matrix[0][i] = matrix[0][i -1] + n;
//initializing the first line
}
for(int i = 1; i < matrix.length; i++){
for (int j = 0; j < matrix.length; j++){
matrix[i][j] = matrix[i -1][j] + 1;
}
// re-loop to display but this time start with i=0
for(int i = 0; i < matrix.length; i++){
for (int j = 0; j < matrix.length; j++){
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
input.close();
}
To fill a matrix vertically, you must loop through columns in the outer loop and through rows in the inner(nested) loop. For example:
for(int j = 0; j < matrix.length; j++) {
for(int i = 0; i < matrix.length; i++) {
matrix[i][j] = /* The value you want to fill */;
.../* Other stuff you wanna do */
}
}
There is an easier way of doing this:
keep a variable like count and iterate the matrix on columns first then rows:
int count = 1; // or 0 if you start with 0
int[][] a = new int[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
a[j][i] = count; // notice j first then i
count++;
}
After that you can easly print out the values:
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
System.out.println(a[i][j]);

Inputs for column length is returning unintended length

While working on a code for making a irregular 2D-array, I discovered a weird error while messing with different inputted values for the column. While the row works, the column length input returns either the wrong amount or a null pointer error occurs. I'm not sure what might be causing this since inputs such as ( 1 , 2 , 3) returns the correct table but (2 , 1, 3) will not. Also in a row of 4 with column inputs of (2, 3, 4, 5) returns "index out of bounds exception: 5" when there shouldn't be able to be out of bounds because of the while loop that should keep it with in reasonable range. Neither the main nor the display method seems to be saving the intended column length correctly and I can't seem to spot why.
It seems the array is set to 3 rows with column length of 1 , 2 , 3.
The output for row(3) and column(2,3,1) gives:
A:2.0
B:2.0 2.0
C:2.0 2.0 2.0
when I want is:
A:2.0 2.0
B:2.0 2.0 2.0
C:2.0
The code:
import java.util.Scanner;
//================================================================
public class ArrayIrreg {
//----------------------------------------------------------------
private static Scanner Keyboard = new Scanner(System.in);
public static void main(String[] args) {
//----------------------------------------------------------------
char group, rLetter,letter;
String choice;
int sum = 0;
int num = 10; // for test
int rows = 10;
int columns = 8;
//greetings
System.out.println("");
System.out.println("Welcome to the Band of the Hour");
System.out.println("-------------------------------");
// creating 2d array
System.out.print("Please enter number of rows : ");
rows = Keyboard.nextInt();
Keyboard.nextLine();
while (rows < 0 || rows >= 10) {
System.out.print("ERROR:Out of range, try again : ");
rows = Keyboard.nextInt();
Keyboard.nextLine();
}
double[][] figures = new double[rows + 1][num];
for(int t = 0; t < rows; t++) {
rLetter = (char)((t)+(int)'A');
System.out.print("Please enter number of positions in row " + rLetter + " : ");
columns = Keyboard.nextInt();
Keyboard.nextLine();
while(columns < 0 || columns >= 8) {
System.out.print("ERROR:Out of range, try again : ");
columns = Keyboard.nextInt();
Keyboard.nextLine();
}
for(int j = 0; j <= columns; j++) {
figures[j] = new double[j] ;
}
}
// filling the array
for(int row = 0; row < figures.length; ++row) {
for(int col = 0; col < figures[row].length; ++col) {
figures[row][col] = 2.0;
}
}
// printing the array
for(int row = 1; row < figures.length; ++row) {
// printing data row
group = (char)((row-1)+(int)'A');
System.out.print(group + " : ");
for(int col = 0; col < figures[row].length; ++col) {
System.out.print(figures[row][col] + " ");
System.out.print(" ");
}
System.out.print("["+","+avg(figures)+"]");
System.out.println();
}
//----------MENU
System.out.print("(A)dd, (R)emove, (P)rint, e(X)it : ");
choice = Keyboard.next();
letter = choice.charAt(0);
letter = Character.toUpperCase(letter);
if(letter == 'P') {
display(figures);
}
}
public static void display(double x[][]) {
int average, total;
char group;
System.out.println(" ");
for(int row=1;row<x.length;row++) {
group = (char)((row-1)+(int)'A');
System.out.print(group+" : ");
for(int column=0;column<x[row].length;column++){
System.out.print(x[row][column]+" ");
}
System.out.print("["+","+avg(x)+"]");
System.out.println();
}
}
public static int avg(double[][] temp) {
int sum = 0;
int avg = 0;
for (int col = 0; col < temp[0].length; col++) {
sum = 0;
for (int row = 0; row < temp.length; row++)
sum += temp[row][col];
System.out.println(sum);
}
avg = sum / temp.length;
return avg;
}
}
In Creating 2D Array,
Change this
double[][] figures = new double[rows + 1][num];
to
double[][] figures = new double[rows][num];
and
for(int j = 0; j <= columns; j++) {
figures[j] = new double[j] ;
}
to
figures[t] = new double[columns] ;
In Printing Array
Change this
for(int row = 1; row < figures.length; ++row) {
group = (char)((row-1)+(int)'A');
to
for(int row = 0; row < figures.length; ++row) {
group = (char)((row)+(int)'A');
In display function
Change this
for(int row = 1; row < x.length; ++row) {
group = (char)((row-1)+(int)'A');
to
for(int row = 0; row < x.length; ++row) {
group = (char)((row)+(int)'A');
It's this
for(int j = 0; j <= columns; j++) {
figures[j] = new double[j] ;
}
I think you meant actually
figures[t] = new double[columns];

Initialize 2D array

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.

Categories