Print 2D array to console in board format - java

I'm trying to print my 2D array to the console as if the array were co-ordinates on a chess board for example, my code looks like this:
public Piece[][] getBoardView() throws NoBoardDefinedException
{
System.out.println(Arrays.deepToString(board));
return board;
}
This currently prints the 2D array in one straight line across the console, can anyone suggest a way to change this into a board style format?

Try this.
for (Piece[] row : board)
System.out.println(Arrays.toString(row));

if this is the case then you would get likewise,
int chessboard [][] = {
{1,2,3},
{4,5,6},
{7,8,9}
};
for(int i = 0; i < chessboard.length ; i ++){
System.out.println();
for(int j = 0 ; j < chessboard[i].length ; j++){
System.out.print(" | " + chessboard[i][j] );
}
System.out.print(" |");
System.out.println();
}
OUT PUT :
| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |

Related

While loop gets terminated before condition is met when backtracking

I'm trying to write an iterative program that will help me palce 4 queens on a 4x4 board without them hitting each other. The problem is after looping through each position and backtracking a couple of times my main while loop that keeps looping until a solution is found gets terminated and the program ends even though the condition is not yet met.
I tried the following code:
static int[] solve(char[][] board){
int[] position = new int[4];
int row = 0;
int column = 0;
while(row < 4){
for(boolean check; column < board.length; column++){
System.out.println("["+row+","+column+"]");
check = true;
for(int queen= 0; queen < row; queen++){
if (position[queen] == column || queen- position[queen] == row - column || queen + position[queen] == row + column) {
check = false;
break;
}
}
if(check){
position[row] = column;
column = 0;
row++;
}
if(column > 2){
column = position[--row];
}
}
}
return position;
}
I'm currently getting the following output:
| Q | X | X | X |
| X | X | X | Q |
| X | Q | X | X |
| Q | X | X | X |
To check when exactly the while loop is getting terminated I printed the location (row and column)
System.out.println("["+row+","+column+"]"); and got the following:
[0,0][1,0][1,1][1,2][2,0][2,1][2,2][2,3][1,3][2,0][2,1][3,0][3,1][3,2][3,3][2,2][2,3]
After backtracking to [2,3] the while loop ends even though my row count is still less than 4.
I was expecting the following output:
| X | Q | X | X |
| X | X | X | Q |
| Q | X | X | X |
| X | X | Q | X |
I tried the code in a different compiler and still got the same wrong output. Is there a logical mistake that I missed out?
I'm new to programming so I'm still trying to get the hang of the fundamentals.

How can I solve java.lang.ArrayIndexOutOfBoundsException error in Java

I'm solving a challenge about making an algorithm.
There is a game of land.
The Land of Landing game consists of 4 rows in total N rows, with scores in all the columns.
When stepping down from the first row, down one row, you must step down on one of the four squares of each row.
However, there is a special rule that can not be repeated in the same row when landing one row at a time.
For example,
| 1 | 2 | 3 | 5 |
| 5 | 6 | 7 | 8 |
| 4 | 3 | 2 | 1 |
If you have stepped on line 1 through line 4 (5), you can not step on line 4 (8) on line 2.
I was trying to use Dynamic Programming in Java.
import java.lang.Math;
import java.util.*;
class Solution {
int [][] dp = new int[100001][4];
int solution(int[][] land) {
int r = land.length;
for (int i = 0; i < 4; i++)
{
dp[0][i] = land[0][i];
}
for (int i = 0; i <r; i++)
{
for (int j = 0; j < 4; ++j)
{
for(int k = 0; k < 4; ++k)
{
if (j != k)
{
dp[i][j] = Math.max(dp[i][j], land[i][j] + dp[i-1][k]);
}
}
}
}
int ans = 0;
for (int i = 0; i < 4; ++i)
{
ans = Math.max(ans, dp[r-1][i]);
}
return ans;
}
}
it shows error
java.lang.ArrayIndexOutOfBoundsException: -1
I was thinking that it was probably something wrong with the Conditional statement.
In C++, these conditional statements are right. It's running perfect. Why am I getting an error in Java? Is there any difference using array between Java and C++?
Can you please tell me how can I solve this error?
dp[i-1][k] - i starts from ZERO in upper loop, so results of this expression becomes -1 as index.
Java array index starts from ZERO, not -1, which is why ArrayIndexOutOfBoundsException.
I don't know the business case, but one way to solve this is, start first for loop from 1 instead 0.

Fill the last n elements of a 2d array

How can I fill the last n cells (inclusive) of a 2d array in java?
This is what I've tried:
if(numOfUnusedCells != 0) {
for (int k = matrix[0].length; k >= numOfUnusedCells; k--) {
matrix[rows-1][k -1] = "*";
}
}
Example
for a 2d array as such as 2 elements to fill:
+---+---+---+
| | | |
+---+---+---+
| | * | * |
+---+---+---+
Arrays.fill can do that for you:
see this example where you can fill the 1st element of the array with -21
example:
final int[][] a2dArr = new int[3][3];
System.out.println("Before: " + Arrays.deepToString(a2dArr));
for (int i = 0; i < a2dArr.length; i++) {
Arrays.fill(a2dArr[i], 0, 1, -21);
}
System.out.println("After: " + Arrays.deepToString(a2dArr));

Printing dashes with and array

I have to write a method called print() that prints out the results as follows;
Original:
-----------
|9|7|9|4|3|
-----------
Sorted:
-----------
|3|4|7|9|9|
-----------
My new code is as follows:
for(int i=0;i< intArray.length; i++)
{
if(i==intArray.length-1)
{
System.out.print("----\n");
}
else{
System.out.print("----");
}
}
for(int i=0;i< intArray.length; i++)
{
if(i==0)
{
System.out.println("| "+intArray[i]+" | ");
}
else if(i==intArray.length-1)
{
System.out.print(intArray[i]+" |\n");
}
else{
System.out.print(intArray[i]+" | ");
}
}
for(int i=0;i< intArray.length; i++)
{
if(i==intArray.length-1)
{
System.out.print("----\n");
}
else{
System.out.print("----");
}
}
Its almost perfect except one number is out of place and is displaying as follows:
Original:
| 3 |
2 | 9 | 9 | 6 |
Sorted:
| 2 |
3 | 6 | 9 | 9 |
Frequencies:
Original:
| 9 |
1 | 6 | 6 | 4 | 8 | 5 | 8 | 5 | 1 |
Sorted:
| 1 |
1 | 4 | 5 | 5 | 6 | 6 | 8 | 8 | 9 |
Frequencies:
Can somebody please tell me what the problem is as I can't figure it out. Thanks for all of your help in the comments
System.out.println appends a newline after the output, that is, after every array item in your code. You should use System.out.print instead. Also it looks like you are only printing the pipes at the end of the array, making it look something like
34799|
For the example output you need something like
public void print()
{
//no need for \n, println produces one at the end of the string
System.out.println("-------------------");
System.out.print("|");
for(int i=0;i< intArray.length; i++)
{
System.out.print(intArray[i] + "|");
}
System.out.print("\n-------------------\n");
}
There is no need of if-else, we can print the array with a simple for loop, e.g.:
int[] array = new int[]{1,2,3,4,5};
System.out.println("--------------");
System.out.print("|");
for(int element : array){
System.out.print(element + "|");
}
System.out.println("--------------");
update
Here's how it works:
First println() prints first dashed line.
Second print() before the for loop prints initial '|'
print() in the for loop prints element appended by '|'
There is no need to print the last '|' it is already done in the for loop.
Last println() prints dashed line after the array contents.

Using a 2D arraylist to create a chessboard and pieces

I'm currently trying to create a program that will spit out a chessboard like this one (it looks better in the actual program, just to editor doesn't like me using the "-" symbol so I put them in quotation marks):
-----------------
| | | | |K| | | |
-----------------
| |P| | | |P| | |
-----------------
| | | | | | | | |
-----------------
| | | | | | | | |
-----------------
| | | | | | | | |
-----------------
| | | | | | | | |
-----------------
| | | | | |N| | |
-----------------
| | | | |K| | | |
-----------------
I'm using two methods, a showBoard method and an addPiece method. I'm currently stuck with the addPiece method, and I'm trying to make it so the method takes three inputs: the row int, the column int, and the string name (just K for king, for example). However, I can't get the addPiece method to put the pieces where I want them to go, or even at all. Here's what I have so far:
public class ChessBoard {
public static String[][] board = new String[8][8];
public static int row = 0;
public static int col = 0;
public static void addPiece(int x, int y, String r){
board[x][y] = new String(r);
}
public static void showBoard(){
for (row = 0; row < board.length; row++)
{
System.out.println("");
System.out.println("---------------");
for(col = 0; col < board[row].length; col++)
{
System.out.print("| ");
}
}
System.out.println("");
System.out.println("---------------");
}
public static void main(String[] args) {
System.out.println(board.length);
showBoard();
addPiece(1,2,"R");
}
}
I know it has something to do with the way I wrote my addpiece method, but I'm still kind of confused as to how writing the method should be, and that is my best attempt (which doesn't work). Does anyone have any suggestions? Thanks!
You never print the pieces values
for(col = 0; col < board[row].length; col++)
{
if ( board[row][col] != null ) {
System.out.print("|" + board[row][col]);
}
else
System.out.print("| ");
}
And also you'll need to add the pience before you show the board:
addPiece(1,2,"R"); //before
showBoard();
Why are you using new String(r)? Your board array is already an array of Strings, just use:
board[x][y] = r;
Also you are adding the piece after the showBoard method in main, switch them around
addPiece(1,2,"R");
showBoard();
Note that addPiece is changing the state of the board. If you want to see that change, you need to redisplay the new board state.
public class ChessBoard {
public static String[][] board = new String[8][8];
public static void addPiece(int x, int y, String r){
board[x][y] = r;//no need for new String(), board is already made of Strings.
}
public static void showBoard(){
//it's generally better practice to initialize loop counters in the loop themselves
for (int row = 0; row < board.length; row++)
{
System.out.println("");
System.out.println("---------------");
for(int col = 0; col < board[row].length; col++)
{
System.out.print("|"); //you're only printing spaces in the spots
if(board[column][row] == null){
System.ot.print(" ");
}else{
System.out.print(board[column][row]);
}
}
}
System.out.println("");
System.out.println("---------------");
}
public static void main(String[] args) {
System.out.println(board.length);
showBoard(); //board does not have R in it yet.
addPiece(1,2,"R"); //board now has R in it.
showBoard(); //display the new board with R in it.
}
}

Categories

Resources