Can't subtract from the row/column of a 2d array.[Java] - java

I'm trying to make a knight's tour program but when I try to subtract from the row/column in the 2d array for the board so I move around the board. But everything I try to do it keeps trying to set the board to -1 instead of subtracting 1.
Kind of hard to explain what the problem is, but if anyone could help me out here that would be well appreciated here's my code:
public class Knight1 {
public static void main(String[] args) {
int board[][] = new int[8][8];
int horizontal[] = new int[8];
int vertical[] = new int[8];
horizontal[0] = 2;
horizontal[1] = 1;
horizontal[2] = -1;
horizontal[3] = -2;
horizontal[4] = -2;
horizontal[5] = -1;
horizontal[6] = 1;
horizontal[7] = 2;
vertical[0] = -1;
vertical[1] = -2;
vertical[2] = -2;
vertical[3] = -1;
vertical[4] = 1;
vertical[5] = 2;
vertical[6] = 2;
vertical[7] = 1;
int move = 1;
int moveNumber = 0;
int currentRow = 0;
int currentCol = 0;
int counter = 1;
while (moveNumber != 7) {
currentRow += vertical[moveNumber];
currentCol += horizontal[moveNumber];
board[currentRow][currentCol] = counter;
moveNumber++;
counter++;
}
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
}

Problem come up on this point:
int currentRow = 0;
int currentCol = 0;
You are trying to add -1 to currentRow variable
vertical[0] = -1;
currentRow += vertical[moveNumber];
I just look at Knight's tour problem and your code. If I understood both of them correctly, you should start from ROW 7 and COLUMN 4.
So only change this two variable:
int currentRow = 7;
int currentCol = 4;
It is going to compile this result:
0 0 0 0 0 0 0 0
0 0 0 0 4 0 0 0
0 0 5 0 0 0 3 0
0 0 0 0 0 0 0 0
0 6 0 0 0 0 0 2
0 0 0 0 0 0 0 0
0 0 7 0 0 0 1 0
0 0 0 0 0 0 0 0
I also edited your main method a little bit:
You don't need to horizontal and vertical arrays. You can do it with multi-dimensional arrays.
public static void main(String[] args) {
int board[][] = new int[8][8];
int moveNumber = 0;
int currentRow = 7;
int currentCol = 4;
int counter = 1;
//moves[moveNumber][0] = columnValues;
//moves[moveNumber][1] = rowValues;
int moves[][] = new int[][]{{ 2,-1},
{ 1,-2},
{-1,-2},
{-2,-1},
{-2, 1},
{-1, 2},
{ 1, 2},
{ 2, 1}};
while (moveNumber != 7) {
currentCol += moves[moveNumber][0];
currentRow += moves[moveNumber][1];
board[currentRow][currentCol] = counter;
moveNumber++;
counter++;
}
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++)
System.out.print(board[i][j] + " ");
System.out.println();
}
}

Related

one error in a code maxonebordersize.java [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 1 year ago.
the error ArrayIndexOutOfBoundsException in a loop
public class MaxOneBorderSize {
public static void setBorderMap(int[][] m, int[][] right, int[][] down) {
if(m == null){
return;
}
right = new int[m.length][m[0].length];
down = new int[m.length][m[0].length];
for(int row = 0; row <m.length;row++ ){
for(int col = 0; col <m[0].length; col++){
int index = 0;
int tempCol = col;
// 0 - N-1
while(tempCol<m[0].length && m[row][tempCol] == 1){
tempCol++;
index++;
}
right[row][tempCol-1] = index;
}
}
// 然后生成down的数据
for(int row = 0; row <m.length;row++ ){
for(int col = 0; col <m[0].length; col++){
int index = 0;
while(row<m.length&&m[row][col] == 1){
row++;
index++;
}
down[row-1][col] = index;
}
}
}
public static int getMaxSize(int[][] m) {
int[][] right = new int[m.length][m[0].length];
int[][] down = new int[m.length][m[0].length];
setBorderMap(m, right, down); // O(N^2); +
for (int size = Math.min(m.length, m[0].length); size != 0; size--) {
if (hasSizeOfBorder(size, right, down)) {
return size;
}
}
return 0;
}
public static boolean hasSizeOfBorder(int size, int[][] right, int[][] down) {
for (int i = 0; i != right.length - size + 1; i++) {
for (int j = 0; j != right[0].length - size + 1; j++) {
if (right[i][j] >= size && down[i][j] >= size
&& right[i + size - 1][j] >= size
&& down[i][j + size - 1] >= size) {
return true;
}
}
}
return false;
}
public static int[][] generateRandom01Matrix(int rowSize, int colSize) {
int[][] res = new int[rowSize][colSize];
for (int i = 0; i != rowSize; i++) {
for (int j = 0; j != colSize; j++) {
res[i][j] = (int) (Math.random() * 2);
}
}
return res;
}
public static void printMatrix(int[][] matrix) {
for (int i = 0; i != matrix.length; i++) {
for (int j = 0; j != matrix[0].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] matrix = generateRandom01Matrix(7, 8);
printMatrix(matrix);
System.out.println(getMaxSize(matrix));
}
}
1 0 0 0 1 0 1 1
1 0 0 1 0 1 1 0
0 0 1 1 0 1 1 0
0 0 0 1 0 0 1 1
1 1 1 0 1 0 0 1
0 0 1 1 1 0 1 0
0 1 0 0 1 1 0 0
I have completed the code to get the longest side of the rectangle consists of ‘1’. But the error java.lang.ArrayIndexOutOfBoundsException has occured in
for(int row = 0; row <m.length;row++ ){
for(int col = 0; col <m[0].length; col++){
int index = 0;
int tempCol = col;
// 0 - N-1
while(tempCol<m[0].length && m[row][tempCol] == 1){
tempCol++;
index++;
}
right[row][tempCol-1] = index;
}
}
I don't have any idea about that.
In this line you have not handled exception for the condition tempCol = 0
which would make tempcol = -1 in the code and it will be out of bounds.
right[row][tempCol-1] = index;
There are two ways to handle this either use try catch or if else with proper condition
for(int row = 0; row <m.length;row++ ){
for(int col = 0; col <m[0].length; col++){
int index = 0;
int tempCol = col;
while(tempCol<m[0].length && m[row][tempCol] == 1){
tempCol++;
index++;
}
if(tempCol!=0){
right[row][tempCol-1] = index;
}
else{
right[row][tempCol] = index;
}
}
}
There is same problem with the down array which has row-1.
Also next time posting a question use proper proportionate indentation.
Exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at MaxOneBorderSize.setBorderMap(MaxOneBorderSize.java:25)
at MaxOneBorderSize.getMaxSize(MaxOneBorderSize.java:51)
at MaxOneBorderSize.main(MaxOneBorderSize.java:96)

Scanner array (n x n)

My code :
import java.util.Scanner;
class Test1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[][] num = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
System.out.print(num[i][j] + " ");
System.out.println();
}
}
the answer come out
0 0 0
0 0 0
0 0 0
but i want to make
1 0 0
0 1 0
0 0 1
As explain in the doc of Java, a int is initialized with the value 0. So when you only declare your array without setting specific value, it only contains 0. That's why your output is
0 0 0
0 0 0
0 0 0
You need to first initialize your array to put the value 1 in the wanted places. In your case you want to make an identity matrix, so put 1 in the places that have the same index for row and column (In the diagonal). This should look like this :
for (int i = 0; i < n; i++)
num[i][i] = 1;
Place this initialization before printing the array, so the full code will look like :
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[][] num = new int[n][n];
for (int i = 0; i < n; i++)
num[i][i] = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
System.out.print(num[i][j] + " ");
System.out.println();
}

How can I make a border to a matrix in java?

I have this matrix :
So 2 line and 2 columns.
1 2
3 4
I have the reading function
for (int i = 0; i < m; i++) {
for (int j = 1; j < n; j++) {
try {// System.out.println("number is ");
a[i][j] = scanner.nextInt();
} catch (java.util.NoSuchElementException e) {
// e.printStackTrace();
}
}
} //print the input matrix
How can I make a border to a matrix? I've seen that in java there is no index -1.
I want a border with a number. For example :
0 0 0 0
0 0 0 0
0 1 2 0
0 3 4 0
0 0 0 0
How should I make that border function?
So, you need a (m+2) x (n+2) matrix:
// initialize m and n
...
// initialize the matrix with 0s
int a[][] = new int[m+2][n+2];
Then ignore the first elements (i and j should skip 0) and the last elements (i should skip m+1, j should skip n+1):
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
try {
a[i][j] = scanner.nextInt();
} catch (java.util.NoSuchElementException e) {
// e.printStackTrace();
}
}
}
First you need to create the matrix with extra rows and columns, for example in your case a 4x4 matrix. and them put 0 on the borders
when i==0 or i==n-1, j==0 or j==n-1,
int a[][] = new int[4][4];
int n,m;
n=4;
m=4;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(i==0 || j==0 || i==m-1 || j==n-1){
//a[i][j] = 0;
a[i][j] = 1;
}
System.out.print(a[i][j]+" ");
}
System.out.println();
}
then
for (int i = 1; i < m-1; i++) {
for (int j = 1; j < n-1; j++) {
try {// System.out.println("number is ");
a[i][j] = scanner.nextInt();
} catch (java.util.NoSuchElementException e) {
// e.printStackTrace();
}
}
} //print the input matrix
Elaborating on my comment:
If you first put in words what creating a border means, then translating it from English to Java is a simple task.
Let's take a look at the the two matrices that you have given:
Original one:
1 2
3 4
With border:
0 0 0 0
0 1 2 0
0 3 4 0
0 0 0 0
We see that when creating a border, we increase the width and height of the matrix by 2 respectively (to have an empty row of 0s on the top-bottom, and left-right), so instead of a 2x2 matrix we now have 4x4, and the indices of the elements are incremented by 1 (every element is pushed one step to the right, and one step downwards).
Putting this is in code:
int[][] createBorder(int[][] matrix) {
//this is our 4x4 matrix
int[][] borderedMatrix = new int[matrix.length+2][matrix[0].length+2];
//fill the 4x4 matrix with 0's
for(int i = 0; i < borderedMatrix.length; i++) {
for(int j = 0; j < borderedMatrix[0].length; j++) {
borderedMatrix[i][j] = 0;
}
}
//copy the values of the 2x2 into the 4x4 matrix, but push them one step to the right, and one step downwards
for(int k = 0; k < matrix.length; k++) {
for(int l = 0; l < matrix[0].length; l++) {
borderedMatrix[k+1][l+1] = matrix[k][k];
}
}
return borderedMatrix;
}
The simplest way would be to create a matrix of n+1xm+1, populate the border with 0 then fill in the remainder with the original nxm matrix.
So if I had your example matrix
int[][] original = {{1, 2},
{3, 4}};
int borderWidth = original[0].length + 2;
int borderHeight = original.length + 2;
int borderArray = new int[borderHeight][borderWidth];
for (int i = 0; i < borderWidth; i++) { //border
borderArray[0][i] = 0; //populate top row
borderArray[borderHeight - 1][i] = 0; //populate bottom row
if (i == 0 || i == borderWidth - 1) { //populate left and right columns
for (j = 1; j < borderHeight - 1; j++) {
borderArray[j][i] = 0;
}
}
}
for (int i = 0; i < original.length; i++) { //populate middle with original
System.arraycopy(original[i], 0, borderArray[i+1], 1, original[].length);
}

InsertionSort using multidimensional array

In my code i recieve in the first line the values n and d. N will be the number of values i want to write and d the number of numbers in each position n.
So in the next n values i introduze d values. The point of this exercise is to use insertion sort but if the first coord is equal it compares the second and if that happens again compares the third and so on. Example:
Input:
5 3
1 1 1
1 0 1
1 1 0
0 1 1
0 1 0
Output:
0 1 0
0 1 1
1 0 1
1 1 0
1 1 1
This is my code:
public static void main(String[] args) {
int n,d,aux;
Scanner sc = new Scanner( System.in );
n = sc.nextInt();
d = sc.nextInt();
int tab [][] = new int[n][d];
for(int i=0;i<n;i++){
for(int j=0;j<d;j++){
aux = sc.nextInt();
tab[i][j] = aux;
}
}
insertionSort(tab,d);
System.out.println("---");
for(int u=0;u<tab.length;u++){
for(int y=0;y<d;y++){
System.out.print(tab[u][y]+" ");
}
System.out.println();
}
}
public static void insertionSort(int tab[][],int d){
int i,j;
int pos = 0;
int tmp [][] = new int[1][d];
for(i = 1;i < tab.length;i++)
{
for(int k=0;k<d;k++)
tmp[0][k] = tab[i][k];
for(j = i; j>0 && tmp[0][0] <= tab[j-1][0];j--)
{
while(tmp[0][pos] == tab[j-1][pos] && pos+1<d){
pos++;
if(tmp[0][pos] < tab[j-1][pos]){
pos=0;
break;
}
}
if(pos==0){
for(int k=0;k<d;k++)
tab[j][k] = tab[j-1][k];
}
}
for(int k=0;k<d;k++)
tab[j][k] = tmp[0][k];
pos = 0;
}
}
The problem is that my output is wrong:
0 1 0
0 1 1
1 1 0
1 1 1
1 1 1
I found a solution for you with recursion, with the code below you can sort your multidimensional binary array, in binary sorted format (I used constant array here, you can add your scanner to get inputs from console):
public static void main(String[] args)
{
int n, d;
int tab[][] = new int[][] { { 1, 1, 1, 1 }, { 1, 0, 1, 1 }, { 1, 1, 0, 0 }, { 0, 0, 0, 1 },
{ 0, 1, 0, 1 }, { 0, 0, 0, 1 } };
n = 6;
d = 4;
System.out.println("---");
for (int u = 0; u < tab.length; u++)
{
for (int y = 0; y < d; y++)
{
System.out.print(tab[u][y] + " ");
}
System.out.println();
}
insertionSort(tab, n);
System.out.println("---");
for (int u = 0; u < tab.length; u++)
{
for (int y = 0; y < d; y++)
{
System.out.print(tab[u][y] + " ");
}
System.out.println();
}
}
public static void insertionSort(int tab[][], int n)
{
doSort(tab, 0, n, 0);
}
/**
* Recurring Method for Insertion Sort in MulitDimentional array.
*
* #param tab mulitidiamentional array.
* #param rowsStart the rows start index
* #param rowEnd the row end index
* #param column the current column
*/
public static void doSort(int tab[][], int rowsStart, int rowEnd, int column)
{
int totalColumn = tab[0].length;
for (int j = rowsStart; j < rowEnd; j++)
{
for (int k = j + 1; k < rowEnd; k++)
{
if (tab[j][column] > tab[k][column])
{
for (int l = column; l < totalColumn; l++)
{
int t = tab[j][l];
tab[j][l] = tab[k][l];
tab[k][l] = t;
}
}
}
}
int value = tab[rowsStart][column];
if (rowEnd - rowsStart > 2)
{
for (int i = rowsStart; i < rowEnd; i++)
{
if (value != tab[i][column])
{
doSort(tab, rowsStart, i, column + 1);
value = tab[i][column];
rowsStart = i;
}
}
}
if (column < totalColumn - 1)
{
doSort(tab, rowsStart, rowEnd, column + 1);
}
}

display my output in a matrix form

Above is the image of my application.i am build an application to do the alignment of two string.the two string will be compared and a 2d array will be populated.the values of the 2d array will be the values of the matrix.All works perfectly fine the only prob i ma having is that i want when it print the values of the matrix it prints it in a matrix format as it the example below instead of having an output of "0000000011011000002100013" i want it to display as this
0 0 0 0 0
0 0 1 0 0
0 0 1 0 0
0 1 0 2 1
0 1 0 1 3
When print out it has to see if the number of character printed is equal to my row size and then move to next line and continues to print until all matrix values has been displayed.Below are my pieces of my codes.thank you in advance
Code for my Compute matrix button
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
match_reward = Integer.parseInt (match_tf.getText());
mismatch_penalty =Integer.parseInt (mismatch_tf.getText());
gap_cost=Integer.parseInt(gap_tf.getText());
build_matrix();
collumn_tf.setText(String.valueOf(max_col));
row_tf.setText(String.valueOf(max_row));
highest_score_tf.setText(String.valueOf(max_score));
StringBuilder sb = new StringBuilder();
for (int i =0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sb.append(String.valueOf(matrix[i][j]));
sb.append(' ');
}
}
matrix_tf.setText(sb.toString());
}
Code to build my matrix
private void build_matrix() {
String seq1 = sequence1_tf.getText();
String seq2 = sequence2_tf.getText();
int r, c, ins, sub, del;
rows = seq1.length();
cols = seq2.length();
matrix = new int [rows][cols];
// initiate first row
for (c = 0; c < cols; c++)
matrix[0][c] = 0;
// keep track of the maximum score
max_row = max_col = max_score = 0;
// calculates the similarity matrix (row-wise)
for (r = 1; r < rows; r++)
{
// initiate first column
matrix[r][0] = 0;
for (c = 1; c < cols; c++)
{
sub = matrix[r-1][c-1] + scoreSubstitution(seq1.charAt(r),seq2.charAt(c));
ins = matrix[r][c-1] + scoreInsertion(seq2.charAt(c));
del = matrix[r-1][c] + scoreDeletion(seq1.charAt(r));
// choose the greatest
matrix[r][c] = max (ins, sub, del, 0);
if (matrix[r][c] > max_score)
{
// keep track of the maximum score
max_score = matrix[r][c];
max_row = r; max_col = c;
}
}
}
}
Just append a \n newline after the inner loop:
for (int i =0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sb.append(String.valueOf(matrix[i][j]));
sb.append(' ');
}
sb.append('\n');
}

Categories