Array Index Out of Bounds Exception while solving N Queens - java

I am working on code that uses recursive backtracking to solve the 8 queens problem(placing n chess queens on an n × n board so that none of the queens attack each other).
My task was to create two methods:
Write a public solveQueens(int n) method to solve the problem for an nxn board
Write a private recursive placeQueen(board, column) method to attempt to place a queen in the specified column.
So far I have written this in my program:
public class Queen {
public static boolean isLegal(int[] board, int n) {
for (int i = 0; i < n; i++) {
if (board[i] == board[n]) {
return false;
}
if ((board[i] - board[n]) == (n - i)) {
return false;
}
if ((board[n] - board[i]) == (n - i)) {
return false;
}
}
return true;
}
public static void solver(int n) {
int[] board = new int[n];
PlaceQueen(board, 0);
}
private static int[] PlaceQueen(int[] board, int column) {
int n = board.length;
if (column == n); else {
for (int row = 0; row < n; row++) {
board[column] = row;
if (isLegal(board, column)) {
PlaceQueen(board, column + 1);
}
}
}
return (board);
}
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
solver(n);
}
}
My program successfully compiles, but whenever I try to run it, I get this error.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Queen.main(Queen.java:39)
Any suggestions on feedback on where I should edit my code to get rid of this Exception?

Do you provide a argument to the program ?
It expects to have a integer argument.
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
solver(n);
}
If you try to access to an index which is not in the range of the args array, it rises java.lang.ArrayIndexOutOfBoundsException

Related

Solving a backtracking question of N Queens

I am currently trying to learn the topic of Backtracking in Java. It is really really confusing for me because I am stuck.
The problem is to find ways in which N Queens can be placed in NxN Chess board so that none of the Queens can attack each other. A queen can attack in the same row, same column and diagonally. My code goes like this:
import java.util.Scanner;
class Main {
public static void putZero(int[][] board,int n){
for(int i = 0;i<n;i++){
for(int j=0;j<n;j++){
board[i][j]=0;
}
}
}
public static void printBoard(int[][] board,int n){
for(int i = 0;i<n;i++){
for(int j=0;j<n;j++){
System.out.print(board[i][j]);
}
System.out.print("\n");
}
System.out.print("\n\n\n");
}
public static void SolveNQ(int n){
int[][] board = new int[n][n];
putZero(board,n);
if(SolveQUtil(board,0,n)==true){
printBoard(board,n);
}
}
public static boolean isSafe(int row, int col, int[][] board,int n){
int i,j;
for(i=0;i<col;i++){
if(board[row][i]==1)
return false;
}
for(i=row,j = col; i >= 0 && j >= 0; i--, j--){
if(board[i][j]==1)
return false;
}
for (i = row, j = col; j >= 0 && i < n; i++, j--)
if (board[i][j] == 1)
return false;
return true;
}
public static boolean SolveQUtil(int[][] board, int col, int n){
if(col>=n){
return true;
}
else
for(int i=0;i<n;i++){
if(isSafe(i,col,board,n)==true){
board[i][col]=1;
boolean a = SolveQUtil(board,col+1,n);
if(a==true)
return true;
else
board[i][col]=0;
}
}
return false;
}
public static void main(String[] args){
Scanner scan = new Scanner(`enter code here`System.in);
int n = scan.nextInt();;
SolveNQ(n);
}
}
It is producing the result I want, but I am not understanding how this works. In my method SolveQUtil(), the method is called again which is "recursive". When col = 0 is called, the Q1 is placed at [0,0] as there are no existing queens. But when col = 1 is called recursively, it searches for the suitable place and returns 'true'. Now, isn't the SolveNQ() supposed to print the solution every time true is returned? When does it return false? How is this working? I am a beginner and can anyone please explain this to me, step by step? Thank you in advance.
SolveNQ, which does the printing, is not called recursively; SolveQUtil, which SolveNQ calls, and which does not print anything, is recursive.

Pascal's Triangle Recursive calling - Java

I know this question is old, and I solved the calculation part of it. but my problem is in the main method and I could not find a solution for it.
I need to call the Pascal triangle function recursively, but also have the ability to print it upside-down too. I can print the first 10 rows, but I don't know how to flip it to be upside down. here is my code:
public class RecursivePascalTriangle {
static int get_pascal(int row, int col) {
if (col == 0 || col == row) {
return 1;
} else {
return get_pascal(row - 1, col - 1) + get_pascal(row - 1, col);
}
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
for (int k = 0; k <= i; k++) {
System.out.print(get_pascal(i, k) + " ");
}
System.out.println();
}
}
}
Can anyone help me in this? I am stuck here. I don't want to use any for loops.Thank you!

How to use recursive backtracking to solve 8 queens? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
UPDATED CODE: My last question is how do I get it so that my program prints all 92 solutions of an 8x8 board, without any Queens attacking each other? So far, my code only prints 1 solution. For example, when I change it to a 4x4 board, I only have 1 solution, when there should be 2 I believe.
public class Queen{
public static void display(int[] board){
int n = board.length;
for(int column = 0; column < n; column++){
for(int row = 0; row < n; row++){
if(board[column] == row)
System.out.print('Q');
else
System.out.print('x');
}
System.out.print('\n');
}
}
public static int[] solveQueens(int n){
int board[] = new int[n];
placeQueen(board,0);
return board;
}
private static boolean placeQueen(int[] board, int column){
int n = board.length;
if (n == column){
return true;
}else{
for (int row = 0; row < n; row++){
int i; //remove
for (i = 0; i < column; i++){ //for (int i)
if (board[i] == row || i - column == board[i] - row || column - i == board[i] - row){
break;
}
}
if (i == column){
board[column] = row;
if (placeQueen(board, column + 1))
return true;
}
}
}
return false;
}
public static void main(String args[]){
int finished[] = solveQueens(8);
display(finished);
}
}
Now my programs returns:
Qxxxxxxx
xxxxQxxx
xxxxxxxQ
xxxxxQxx
xxQxxxxx
xxxxxxQx
xQxxxxxx
xxxQxxxx
OLD CODE:
I need to use recursive backtracking to solve the 8-queens problem. The n-queens problem is a puzzle that requires placing n chess queens on an n × n board so that none of the queens attack each other.
I need to Write a public solveQueens(int n) method to solve the problem for an nxn board
I also need to write a private recursive placeQueen(board, column) method to attempt to place a queen in the specified column.
This is my code so far:
public class Queen{
public static int[] solveQueens(int n){
int board[] = new int[n];
int finished[] = placeQueen(board,0);
return finished;
}
private static int[] placeQueen(int[] board, int column){
int n = board.length;
int row = column;
if (n == column){
return board;
}else{
for (row = n; row < n; row++){
board[column] = row;
if (board[n] == 0 && board[n-1] == 0 && board[n+1] == 0){
board[n] = 1;
placeQueen(board, column+1);
}
}
for (row = n; row < n; row++){
board[row] = column;
if (board[n] == 0 && board[n-1] == 0 && board[n+1] == 0){
board[n] = 1;
placeQueen(board, column+1);
}
}
}
return board;
}
public static void main(String args[]){
int finished[] = solveQueens(8);
for (int item: finished){
System.out.print(item);
}
}
}
Whenever I run my program, all it returns is
----jGRASP exec: java Queen
00000000
Is there any explanation on how to setup my 8x8 board, and how to place queens so they don't attack each other?
I made some changes in solveQueens and placeQueen:
public class Queen{
public static int[] solveQueens(int n){
int board[] = new int[n];
placeQueen(board,0); //it fills the board
return board;
}
private static boolean placeQueen(int[] board, int column){
int n = board.length;
int row;
if (n == column){
return true;
}else{
for (row = 0; row < n; row++){
int c;
for (c=0; c<column; c++){
if (board[c]==row || c-column==board[c]-row || column-c==board[c]-row){
//check if it is safe position (we know 2 queens couldn't place in a same column or row or diameter
break;
}
}
if (c==column){ //if previous loop didn't break...=> it is safe position
board[column]=row;
if (placeQueen(board, column+1)) //if it is possible to fill the rest of board //else: test the next row
return true;
}
}
}
return false;
}
public static void main(String args[]){
int finished[] = solveQueens(8);
for (int item: finished){
System.out.print(item);
}
}
}

Knapsack variation, Java

i have this assigment which is a variation of a knapsack problem.
I have a board (Knapstack type, which inner variable is int[][] knapsack) and an array of tiles(with size of nXm, not all of them with the same size). I need to write a function which returns true if i can place all the tiles within the knapsack board (without rotating them). For example:
if the tiles dimensions are:
and the board size is 4X4, a possible solution is:
this is the code i have thus far:
public boolean insertIntoKnapsack(Tile[] tiles) {
boolean ans = false;
ans=solution(this.knapsack,tiles,0,0,0);
return ans;
}
public boolean solution(int[][] knapsack, Tile[] tiles,int i,int j, int k) {
boolean ans=false; int a; int b=0;
if(j>=knapsack.length || k>=knapsack[0].length || i>=tiles.length)
return ans;
if(j<knapsack.length && k<knapsack[0].length && i==tiles.length) {
ans=isValid(knapsack,tiles);
return ans; }
for(a=0; knapsack.length-(j+a)>0 && a<tiles[i].getN(); a++) {
for(b=0; knapsack[0].length-(k+b)>0 && b<tiles[i].getM(); b++) {
if(knapsack[j+a][k+b]==0)
knapsack[j+a][k+b]=i+1;
}
}
return ans= solution(knapsack,tiles,i+1,j+a,k) || solution(knapsack,tiles,i+1,j,k+b) || solution(knapsack,tiles,i+1,j+a,k+b);
}
the knapsack class is defined as:
public class Knapsack {
// Holds the current state of the Knapsack
private int[][] knapsack;
public Knapsack(int n, int m) {
if(n<=0 || m<=0)
System.out.println("Bad Input");
else {
int knapsack[][] = new int[n][m];
}
}
the function isValid:
public boolean isValid(int[][] knapsack,Tile[] tiles) {
boolean ans=true;
for(int i=0;i<tiles.length; i++) {
int count=0;
for(int j=0; j<knapsack.length;j++) {
for(int k=0; k<knapsack[0].length; k++) {
if(knapsack[j][k]==i)
count=count+1;
}
}
if(count != tiles[i].getN() * tiles[i].getM())
ans=false;
}
return ans;
}
a tile is defined as:
public class Tile {
private int n;
private int m;
/*
* Construct a Tile of size nXm
*/
public Tile(int n, int m) {
if(n<=0 || m<=0)
System.out.println("Bad Input");
else {
this.n=n;
this.m=m;
}
}
/*
* Get the Tile's height
*/
public int getN(){
return n;
}
/*
* Get the Tile's width
*/
public int getM(){
return m;
}
}
Not only that i don't know if my solution is correct, whenever i try to test it i get a NullPointerException. I tried to change the conditions of the for loops at the solution method, but no matter how i change it i keep getting an error. Can someone please tell me if i'm headed the right way with the solution method or why do i keep getting a NullPointerException?

Find majority element in an array in java

I am trying to find out the majority Element in an array ad this code is working fine when I am checking with elements less than size. But it is giving me arrayindexoutofbound exception whenever any element is equal to size of array. Please let me know how to resolve this.
public class MajorityElement {
public static void main(String[] args) {
int a[]={2,2,7,5,2,2,6};
printMajority(a, 7);
}
//1st condition to check if element is in majority.
public static int findCandidate(int a[], int size){
int maj_index=0;
int count =1;
int i;
size=a.length;
for(i=1;i<a.length;i++ ){
if(a[maj_index]==a[i])
count++;
else
count--;
if(count==0)
{
maj_index=a[i]; //current element takes max_inex position.
count =1;
}
}
return a[maj_index];
}
public static boolean isMajority(int a[], int size, int cand){
int i, count =0;
for(i=0;i<a.length;i++)
{
if(a[i]==cand)
count++;
}
if(count>size/2){
return true;
}
else {
return false;
}
}
private static void printMajority(int a[],int size){
size=a.length;
int cand=findCandidate( a, 7);
if(isMajority(a,size,cand))
System.out.printf("%d",cand);
else
System.out.println("no such element as majority");
}
}
The problem is in the maj_index=a[i]; line. You take the value of one of the cells of the array and assign it to maj_index which is subsequently used as an index into the array (see a[maj_index] == a[i]). Thus, if the value at that position was larger than the size of the array an out-of-bounds situation will occur.
Here's your code slightly revised. In particular, I got rid of the maj_index variable so that the index vs. value mixup cannot happen. I also used a for-each loop for (int current : a) instead of the for-loop for(int i = 0; i < a.length; ++i). Finally, I eliminated the the size parameter (no need to pass it, it can be inferred from the array itself via a.length)
public class MajorityElement {
// 1st condition to check if element is in majority.
public static int findCandidate(int a[]) {
int cand = a[0];
int count = 1;
for (int i = 1; i < a.length; i++) {
if (cand == a[i])
count++;
else
count--;
if (count == 0) {
cand = a[i];
count = 1;
}
}
return cand;
}
public static boolean isMajority(int a[], int cand) {
int count = 0;
for (int current : a) {
if (current == cand)
count++;
}
return count > a.length / 2;
}
private static void printMajority(int a[]) {
int cand = findCandidate(a);
if (isMajority(a, cand))
System.out.printf("%d", cand);
else
System.out.println("no such element as majority");
}
public static void main(String[] args) {
int a[] = { 9, 7, 9, 5, 5, 5, 9, 7, 9, 9, 9, 9, 7 };
printMajority(a);
}
}
Problem is with your :
for(i=1;i<a.length;i++ ){
if(a[maj_index]==a[i])
count++;
else
count--;
if(count==0)
{
maj_index=a[i]; //current element takes max_inex position.
count =1;
}
}
return a[maj_index];
here you are getting the value as like :a[maj_index] for a test data int a[]={2,1,8,8,8,8,6}; the elemnt 8 is the major but a[maj_index] is invalid which is causing the issue,
Instead Complete code can be like below:
public class TestMajor {
/**
* #param args
*/
public static void main(String[] args) {
int a[]={2,1,8,8,8,8,6};
printMajority(a, 7);
}
//1st condition to check if element is in majority.
public static int findCandidate(int a[], int size){
int test = a[0];
int count =1;
int i;
size=a.length;
for(i=1;i<a.length;i++ ){
if(test ==a[i])
count++;
else
count--;
if(count==0)
{
test =a[i]; //current element takes max_inex position.
count =1;
}
}
return test;
}
public static boolean isMajority(int a[], int size, int cand){
int i, count =0;
for(i=0;i<a.length;i++)
{
if(a[i]==cand)
count++;
}
if(count>size/2){
return true;
}
else {
return false;
}
}
private static void printMajority(int a[],int size){
size=a.length;
int cand=findCandidate( a, 7);
if(isMajority(a,size,cand))
System.out.printf("%d",cand);
else
System.out.println("no such element as majority");
}
}
Majority Element in an Array using Java 8 OR Find the element appeared max number of times in an array :
public class MajorityElement {
public static void main(String[] args) {
int[] a = {1,3,4,3,4,3,2,3,3,3,3,3};
List<Integer> list = Arrays.stream(a).boxed().collect(Collectors.toList());
Map<Integer, Long> map = list.parallelStream()
.collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
System.out.println("Map => " + map);
//{1=1, 2=1, 3=8, 4=2}
map.entrySet()
.stream()
.max(Comparator.comparing(Entry::getValue))//compare the values and get the maximum value
.map(Entry::getKey)// get the key appearing maximum number of times
.ifPresentOrElse(System.out::println,() -> new RuntimeException("no such thing"));
/*
* OUTPUT : Map => {1=1, 2=1, 3=8, 4=2}
* 3
*/
System.out.println("...............");
// A very simple method
//method 2
Integer maxAppearedElement = list.parallelStream().max(Comparator.comparing(Integer::valueOf)).get();
System.out.println(maxAppearedElement);
}//main
}

Categories

Resources