How to escape infinite loop in this recursive code? - java

I am implementing N-Queen problem solver with backjumping algorithm and I have caught infinite loop error in recursive call.
I have mainly caused trouble in returning function.I think I have error in designing recursive calls.
package Backjumping;
import org.python.google.common.primitives.Ints;
import java.util.*;
public class Backjumping {
int size;
List<Integer> columns;
int numberofplaces;
int numberofbacktracks;
HashMap<Integer, List<Integer>> conflict;
boolean noBreak = true;
Backjumping(int size) {
this.size = size;
columns = new ArrayList();
conflict = new HashMap<>(size);
for (int i = 0; i < size; i++) {
conflict.put(i, new ArrayList<>());
}
}
List place(int startRow) {
if (columns.size() == size) {
System.out.println("Solution Found! The board size was :" + size);
System.out.println(numberofplaces + " total nodes assigned were made.");
System.out.println(numberofbacktracks + " total backtracks were executed.");
return this.columns;
} else {
for (int row = 0; row < size; row++) {
if (isSafe(columns.size(), row)) {
if (indexExists(columns, columns.size()))
columns.set(columns.size(), row);
else
columns.add(columns.size(), row);
numberofplaces += 1;
return place(startRow);
}
}
if (noBreak) {
List<Integer> max_check = conflict.get(columns.size());
int lastRow = Collections.min(max_check);
numberofbacktracks += 1;
conflict.replace(columns.size(), new ArrayList<>());
int previous_variable = columns.remove(lastRow);
return place(previous_variable);
}
}
return this.columns;
}
private boolean isSafe(int cols, int rows) {
for (int threatrow : columns) {
int threatcol = columns.indexOf(threatrow);
if (rows == threatrow || cols == columns.indexOf(threatrow)) {
(conflict.get(cols)).add(threatcol);
return false;
} else if ((threatrow + threatcol) == (rows + cols) || (threatrow - threatcol) == (rows - cols)) {
(conflict.get(cols)).add(threatcol);
return false;
}
}
return true;
}
public boolean indexExists(final List list, final int index) {
return index >= 0 && index < list.size();
}
public static void main(String[] args) {
System.out.println("Enter the size of board");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Backjumping bj = new Backjumping(n);
double start = System.currentTimeMillis();
List cols = bj.place(0);
double end = System.currentTimeMillis();
System.out.println("Time to solve in second = " + (end - start) * 0.001 + " s");
System.out.print("Ths solution is : ");
cols.forEach(i -> System.out.print(((int) i + 1) + ", "));
System.out.println("\n\nPlotting CSP result on N_Queens board");
System.out.println("......................................\n");
bj.getBoardPic(n, cols);
}
public void getBoardPic(int size, List columns) {
int[] cols = Ints.toArray(columns);
int[][] matrix = new int[size][size];
for (int a = 0; a < size; a++) {
int j = cols[a];
matrix[a][j] = 1;
}
for (int a = 0; a < size; a++) {
for (int b = 0; b < size; b++) {
if (matrix[b][a] == 1)
System.out.print(" Q ");
else
System.out.print(" - ");
}
System.out.println();
}
}
}
The main errors are that when I assign row=0 in for (int row = 0; row < size; row++) the input size of n=6 goes wrong and other values are right.
When I assign row=startrow in for (int row = startrow; row < size; row++) the input size of n=6 goes right and other values are wrong.

Related

All the possible path to reach bottom of a m*n matrix

public static int printStepsToReachBottom(int rows, int columns, String[] array) {
if (rows == 1) {
array[0] = "";
for (int i = 0; i < columns - 1; i++) {
array[0] += "H";
}
return 1;
}
if (columns == 1) {
array[0] = "";
for (int i = 0; i < rows - 1; i++) {
array[0] += "V";
}
return 1;
}
String[] temporary = new String[1000];
int k = 0;
int firstTypeMove = printStepsToReachBottom(rows - 1, columns, array);
for (int i = 0; i < firstTypeMove; i++) {
temporary[k] = array[i] + "V";
k++;
}
int secondTypeMove = printStepsToReachBottom(rows, columns - 1, array);
for (int i = 0; i < secondTypeMove; i++) {
temporary[k] = array[i] + "H";
k++;
}
for (int i = 0; i < secondTypeMove + firstTypeMove; i++) {
array[i] = temporary[i];
}
return secondTypeMove + firstTypeMove;
}
public static void main(String[] args) {
String[] array = new String[1000];
int outputSize = printStepsToReachBottom(2, 2, array);
for (int i = 0; i < outputSize; i++) {
System.out.println(array[i]);
}
}
I can't figure out how this code snippet is working. I didn't understand the logic. It prints All the possible paths to reach the bottom of an m*n matrix
It prints "HV" and "VH" for the 2x2 matrix. Help me.
You can breakdown the code into three parts;
if (rows == 1) {
array[0] = "";
for (int i = 0; i < columns - 1; i++) {
array[0] += "H";
}
return 1;
}
if (columns == 1) {
array[0] = "";
for (int i = 0; i < rows - 1; i++) {
array[0] += "V";
}
return 1;
}
This part is the end case of the recursion. It says that there is no more rows or columns to go and return an array with size 1 either containing H(or H's) or V(or V's)
String[] temporary = new String[1000];
int k = 0;
int firstTypeMove = printStepsToReachBottom(rows - 1, columns, array);
for (int i = 0; i < firstTypeMove; i++) {
temporary[k] = array[i] + "V";
k++;
}
int secondTypeMove = printStepsToReachBottom(rows, columns - 1, array);
for (int i = 0; i < secondTypeMove; i++) {
temporary[k] = array[i] + "H";
k++;
}
The second part executes the recursion through both H and V directions for any given step which adds two more recursive calls to the stack (Although, in execution it performs a depth-first search rather than a breadth-first one, the idea is easier to grasp that way)
int secondTypeMove = printStepsToReachBottom(rows, columns - 1, array);
for (int i = 0; i < secondTypeMove; i++) {
temporary[k] = array[i] + "H";
k++;
}
for (int i = 0; i < secondTypeMove + firstTypeMove; i++) {
array[i] = temporary[i];
}
return secondTypeMove + firstTypeMove;
And the last part collects the outputs from both H and V directions into the global array and returns the number of outputs to the upper stack.
Here is a simpler recursive Depth First Search that will do the same:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
dfsPrintAllPathesTopToBottom(3,3);
}
//performs dfs to map all possible paths on a rows x columns matrix
//from top left to bottom right by moving right (R) or down (R)
public static void dfsPrintAllPathesTopToBottom(int rows, int columns){
List<String> path = new ArrayList<>();
dfsPrintAllPathesTopToBottom(0, 0,rows,columns,path);
}
public static void dfsPrintAllPathesTopToBottom(int row, int col, int rows, int columns, List<String> path ){
if(row == rows -1 && col == columns -1){//bottom left reached
System.out.println(path);
return;
}
//move right
int newCol = col +1;
if(newCol < columns ){
List<String>newPath = new ArrayList<>(path);
newPath.add("R");//or newPath.add("H")
dfsPrintAllPathesTopToBottom(row, newCol, rows, columns, newPath);
}
//move down
int newRow = row +1;
if(newRow < rows ){
List<String>newPath = new ArrayList<>(path);
newPath.add("D"); //or newPath.add("V")
dfsPrintAllPathesTopToBottom(newRow, col, rows, columns, new ArrayList<>(newPath));
}
}
}

Sorting multidimensional array without sort method?

I was tasked with creating a 2D array (10-by-10), filling it with random numbers (from 10 to 99), and other tasks. I am, however, having difficulty sorting each row of this array in ascending order without using the array sort() method.
My sorting method does not sort. Instead, it prints out values diagonally, from the top leftmost corner to the bottom right corner. What should I do to sort the numbers?
Here is my code:
public class Program3
{
public static void main(String args[])
{
int[][] arrayOne = new int[10][10];
int[][] arrayTwo = new int[10][10];
arrayTwo = fillArray(arrayOne);
System.out.println("");
looper(arrayTwo);
System.out.println("");
sorter(arrayTwo);
}
public static int randomRange(int min, int max)
{
// Where (int)(Math.random() * ((upperbound - lowerbound) + 1) + lowerbound);
return (int)(Math.random()* ((max - min) + 1) + min);
}
public static int[][] fillArray(int x[][])
{
for (int row = 0; row < x.length; row++)
{
for (int column = 0; column < x[row].length; column++)
{
x[row][column] = randomRange(10,99);
System.out.print(x[row][column] + "\t");
}
System.out.println();
}
return x;
}
public static void looper(int y[][])
{
for (int row = 0; row < y.length; row++)
{
for (int column = 0; column < y[row].length; column++)
{
if (y[row][column]%2 == 0)
{
y[row][column] = 2 * y[row][column];
if (y[row][column]%10 == 0)
{
y[row][column] = y[row][column]/10;
}
}
else if (y[row][column] == 59)
{
y[row][column] = 99;
}
System.out.print(y[row][column] + "\t");
}
System.out.println();
}
//return y;
}
public static void sorter(int[][] z)
{
int temp = 0;
int tempTwo = 0;
int lowest;
int bravo = 0;
int bravoBefore = -1;
for (int alpha = 0; alpha < z.length; alpha++)
{
//System.out.println(alpha + "a");
lowest = z[alpha][bravoBefore + 1];
bravoBefore++;
for (bravo = alpha + 1; bravo < z[alpha].length; bravo++)
{
//System.out.println(alpha + "b");
temp = bravo;
if((z[alpha][bravo]) < lowest)
{
temp = bravo;
lowest = z[alpha][bravo];
//System.out.println(lowest + " " + temp);
//System.out.println(alpha + "c" + temp);
tempTwo = z[alpha][bravo];
z[alpha][bravo] = z[alpha][temp];
z[alpha][temp] = tempTwo;
//System.out.println(alpha + "d" + temp);
}
}
System.out.print(z[alpha][bravoBefore] + "\t");
}
/*
for (int alpha = 0; alpha < z.length; alpha++)
{
for (int bravo = 0; bravo < z.length - 1; bravo++)
{
if(Integer.valueOf(z[alpha][bravo]) < Integer.valueOf(z[alpha - 1][bravo]))
{
int[][] temp = z[alpha - 1][bravo];
z[alpha-1][bravo] = z[alpha][bravo];
z[alpha][bravo] = temp;
}
}
}
*/
}
}
for(int k = 0; k < arr.length; k++)
{
for(int p = 0; p < arr[k].length; p++)
{
least = arr[k][p];
for(int i = k; i < arr.length; i++)
{
if(i == k)
z = p + 1;
else
z = 0;
for(;z < arr[i].length; z++)
{
if(arr[i][z] <= small)
{
least = array[i][z];
row = i;
col = z;
}
}
}
arr[row][col] = arr[k][p];
arr[k][p] = least;
System.out.print(arr[k][p] + " ");
}
System.out.println();
}
Hope this code helps . Happy coding
let x is our unsorted array;
int t1=0;
int i1=0;
int j1=0;
int n=0;
boolean f1=false;
for(int i=0;i<x.length;i++){
for(int j=0;j<x[i].length;j++){
t1=x[i][j];
for(int m=i;m<x.length;m++){
if(m==i)n=j+1;
else n=0;
for(;n<x[m].length;n++){
if(x[m][n]<=t1){
t1=x[m][n];
i1=m;
j1=n;
f1=true;
}
}
}
if(f1){
x[i1][j1]=x[i][j];
x[i][j]=t1;
f1=false;
}
}
}
//now x is sorted; "-";

Magic Square Code (java)

I've been having an issue with my Magic Square code. It continually prints "This is a magic square" even when I'm positive it isn't.
You enter 16 integers, and then the code is supposed to run and determine whether the entered integers create a magic square (i.e. the sum of all rows, columns, and diagonals are all equal).
I can't figure out how to make it print false.
import java.util.*;
public class MagicSquare {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner (System.in);
int [] [] square = new int [4][4];
for (int row = 0; row < 4; row++)
{
for (int col = 0; col < 4; col++)
{
System.out.println("Input value for row " + (row+1) + " column " + (col+1));
square[row][col] = keyboard.nextInt();
}
}
int [] sumRow = new int [4];
int [] sumCol = new int [4];
int sum = 0;
for (int row = 0; row < 4; row ++)
{
for (int col = 0; col < 4; col ++)
{
sum = sum + square[row][col];
sumRow[row] = sum;
}
System.out.println("sum row " + row + "\n" + sumRow[row]);
sum = 0;
}
sum = 0;
for (int col = 0; col < 4; col ++)
{
for (int row = 0; row < 4; row ++)
{
sum = sum + square[row][col];
sumCol[col] = sum;
}
System.out.println("sum columns " + col + "\n" + sumCol[col]);
sum = 0;
}
int [] sumDiag = new int [4];
sum = 0;
for (int row = 0; row < 4; row++)
{
for (int col = 3; col > -1; col--)
{
sum = sum + square [row][col];
sumDiag[row] = sum;
}
System.out.println("sum diagonal " + row + "\n" + sumDiag[row]);
sum = 0;
}
int [] sumDiag2 = new int [4];
sum = 0;
for (int col = 0; col < 4; col ++)
{
for (int row = 3; row > -1; row --)
{
sum = sum + square[row][col];
sumDiag2[col] = sum;
}
System.out.println("sum diagonal 2 " + col + "\n" + sumDiag2[col]);
}
boolean bool = false;
int k = 0; int j = 1;
do
{
if (sumRow[k] == sumRow[j])
{
k = j;
j += 1;
bool = true;
}
else
{
bool = false;
System.out.println("Not a magic square");
break;
}
} while ((k < 4) && (j >- 1));
k = 0; j = 1;
do
{
if (sumCol[k] == sumRow[j])
{
k = j;
j += 1;
bool = true;
}
else
{
bool = false;
System.out.println("Not a magic square");
break;
}
} while ((k < 4) && (j >= -1));
String TorF = "";
if (bool = true)
{
TorF = "is";
}
else if (bool = false)
{
TorF = "is not";
}
System.out.println("This " + TorF + " a magic square.");
}
}
There is a number of issues in your code, as said in the comments.
First, you only need to verify the main and secondary diagonals.
Second, your code to compare the sums doesn't work for all cases and doesn't compare the diagonals.
Also, the if in the end is just wrong. Do this instead:
if (bool) {
} else {
}
And here is a solution:
int order = square.length;
int[] sumRow = new int[order];
int[] sumCol = new int[order];
int[] sumDiag = new int[2];
Arrays.fill(sumRow, 0);
Arrays.fill(sumCol, 0);
Arrays.fill(sumDiag, 0);
for (int row = 0; row < order; row++) {
for (int col = 0; col < order; col ++) {
sumRow[row] += square[row][col];
}
System.out.println("sum row " + row + "\n" + sumRow[row]);
}
for (int col = 0; col < order; col++) {
for (int row = 0; row < order; row ++) {
sumCol[col] += square[row][col];
}
System.out.println("sum columns " + col + "\n" + sumCol[col]);
}
for (int row = 0; row < order; row++) {
sumDiag[0] += square[row][row];
}
System.out.println("sum diagonal 0 " + "\n" + sumDiag[0]);
for(int row = 0; row < order; row++) {
sumDiag[1] += square[row][order - 1 - row];
}
System.out.println("sum diagonal 1 " + "\n" + sumDiag[1]);
boolean bool = true;
int sum = sumRow[0];
for (int i = 1; i < order; i++) {
bool = bool && (sum == sumRow[i]);
}
for (int i = 0; i < order; i++) {
bool = bool && (sum == sumCol[i]);
}
for (int i = 0; i < 2; i++) {
bool = bool && (sum == sumDiag[i]);
}
String tOrF = "";
if (bool) {
tOrF = "is";
} else {
tOrF = "is not";
}
System.out.println("This " + tOrF + " a magic square.");
Furthermore, there are some things you could do to optimize this code.

Sudoku Checker java

public class Sudoku {
public static void main(String[] args) {
// Row and column Latin but with invalid subsquares
String config1 = "1234567892345678913456789124567891235678912346" + "78912345789123456891234567912345678";
String[][] puzzle1 = makeSudoku(config1);
if (isValidSudoku(puzzle1)) {
System.out.println("This puzzle is valid.");
} else {
System.out.println("This puzzle is invalid.");
}
System.out.println(getPrintableSudoku(puzzle1));
System.out.println("--------------------------------------------------");
// Row Latin but column not Latin and with invalid subsquares
String config2 = "12345678912345678912345678912345678912345678" + "9123456789123456789123456789123456789";
String[][] puzzle2 = makeSudoku(config2);
if (isValidSudoku(puzzle2)) {
System.out.println("This puzzle is valid.");
} else {
System.out.println("This puzzle is invalid.");
}
System.out.println(getPrintableSudoku(puzzle2));
System.out.println("--------------------------------------------------");
// A valid sudoku
String config3 = "25813764914698532779324685147286319558149273663" + "9571482315728964824619573967354218";
String[][] puzzle3 = makeSudoku(config3);
if (isValidSudoku(puzzle3)) {
System.out.println("This puzzle is valid.");
} else {
System.out.println("This puzzle is invalid.");
}
System.out.println(getPrintableSudoku(puzzle3));
System.out.println("--------------------------------------------------");
}
public static String[][] makeSudoku(String s) {
int SIZE = 9;
int k = 0;
String[][] x = new String[SIZE][SIZE];
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
x[i][j] = s.substring(k, k + 1);
k++;
}
}
return x;
}
public static String getPrintableSudoku(String[][] x) {
int SIZE = 9;
String temp = "";
for (int i = 0; i < SIZE; i++) {
if ((i == 3) || (i == 6)) {
temp = temp + "=================\n";
}
for (int j = 0; j < SIZE; j++) {
if ((j == 3) || (j == 6)) {
temp = temp + " || ";
}
temp = temp + x[i][j];
}
temp = temp + "\n";
}
return temp;
}
//sudoku validation
public static boolean isValidSudoku(String[][] x) {
return rowsAreLatin(x) && colsAreLatin(x) && goodSubsquares(x);
}
public static boolean rowsAreLatin(String[][] x) {
// fill in your code here
boolean result = true; // Assume rows are latin
for (int i = 0; i < 9; i++) {
result = result && rowIsLatin(x, i); // Make sure each row is latin
}
return result;
}
public static boolean rowIsLatin(String[][] x, int i) {
boolean[] found = new boolean[9];
for (int j = 0; j < 9; j++) {
found[Integer.parseInt(x[i][j])] = true;
}
for (int j = 0; j < 9; j++) {
if (!found[j]) {
return false;
}
}
return true;
}
public static boolean colsAreLatin(String[][] x) {
// fill in your code here
boolean result = true; // Assume cols are latin
for (int j = 0; j < 9; j++) {
result = result && colIsLatin(x, j); // Make sure each row is latin
}
return result;
}
public static boolean colIsLatin(String[][] x, int j) {
// fill in your code here
boolean[] found = new boolean[9];
for (int i = 0; i < 9; i++) {
found[Integer.parseInt(x[i][j])] = true;
}
for (int i = 0; i < 9; i++) {
if (!found[i]) {
return false;
}
}
return true;
}
public static boolean goodSubsquares(String[][] x) {
return true;
}
public static boolean goodSubsquare(String[][] x, int i, int j) {
boolean[] found = new boolean[9];
// We have a 3 x 3 arrangement of subsquares
// Multiplying each subscript by 3 converts to the original array subscripts
for (int p = i * 3, rowEnd = p + 3; p < rowEnd; p++) {
for (int q = j * 3, colEnd = q + 3; q < colEnd; q++) {
found[Integer.parseInt(x[p][q])] = true;
}
}
for (int p = 0; p < 9; p++) {
if (!found[p]) {
return false;
}
}
return true;
}
}
This the error I am getting. Help!
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
at Sudoku.rowIsLatin(Sudoku.java:104)
at Sudoku.rowsAreLatin(Sudoku.java:93)
at Sudoku.isValidSudoku(Sudoku.java:85)
at Sudoku.main(Sudoku.java:8)
Java Result: 1
The problem is with the line:
Integer.parseInt(x[i][j])
Sudoku numbers range from [1, 9], but indices for an array (of length 9) range from [0, 8]. So, when the (i, j) element is a 9, the index is 9 and therefore the IndexOutOfBoundsException is being thrown.
You'll have to change it to
found[Integer.parseInt(x[i][j]) - 1] = true;
Note that you also make the same mistake in the column's respective method.

Trouble printing chars thru a 2 dim java array

I tried to run this code as a score table where I have chars and ints as below for heading;
A B c
1
2 65 //this is where I'm stuck again!
3
In order to print the score like (65) above in a particular place (matrix) but as soon as I try to add the print statements the table falls apart. Any help would be appreciated;
public class Table3 {
static int[][] list = new int[4][4];
//private char column = 'A';
//private int row = 1;
private static int row = 1;
public Table3(){
//column = 'A';
for (int i = 0; i < 4; i++) {
for (int j = 1; j < 4; j++)
list[i][j] = 0;
}
}
public static void table(char col, int row, int value) {
//System.out.printf("\n\n%s\n", "Table");
for (int i = 1; i < 4; i++) {
System.out.print(row + " ");
row++;
for (int j = 1; j < 4; j++)System.out.print(col + " ");
System.out.println("\n");
col++;
if (row >= 0 && row <= 4 && col >=0 && col <= 4)
System.out.print(list[col][row]=value);
System.out.println("\n");
}
}
}
Client
public class TableTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Table3 t = new Table3();
t.table('A', 5, 5);
}
}
Learn how to use System.out.printf. The docs are here.
public class Table3
{
static int numRows = 4;
static int numCols = 4;
static int[][] list = new int[numRows][numCols];
public Table3()
{
//column = 'A';
for (int i = 0; i < 4; i++)
{
//this is the row number so you don't have to print it manually
//just print the array
list[i][0] = i;
//initialize the list to 0
for (int j = 1; j < 4; j++)
{
list[i][j] = 0;
}
}
}
public static void table(char col, int row, int value)
{
list[row][col] = value;
int columnWidth = 5; //in characters
//empty space before first column header
for (int i = 0; i < columnWidth; i++)
{
System.out.print(" ");
}
//print the column headers (A through C)
for (int i = 1; i < numCols; i++)
{
System.out.printf("%-" + columnWidth" + "c", (char)(64 + i));
}
System.out.println(); //get off of the column header row
//print the rest of the table
for (int i = 1; i < numRows; i++)
{
for (int j = 0; j < numCols; j++)
{
if (list[i][j] == 0)
{
System.out.printf("%" + columnWidth + "s", " ");
}
else
{
System.out.printf("%-" + columnWidth + "d", list[i][j]);
}
}
System.out.println("\n");
}
}
}

Categories