Not able to find possible solutions for N-Queens puzzle - java

I am trying to find all possible solutions for N-Queens puzzle. I have to print single queen on each row, and no two queens should be adjacent to each other like no one or more queens diagonally, no one or more queens in a same row, no one or more queens in a same column.
I have written the algorithm and think that most part of it is correct, but the solutions are not getting printed. I don't understand why. I have spent a lot of time on this.
Any help will be appreciated.
Following is my code:
public class NQueens {
int[] x;
public NQueens(int n) {
x = new int[n];
} // CONSTRUCTOR
public void printQueens(int[] x) {
int N = x.length;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (x[i] == j) {
System.out.print("Q ");
} else {
System.out.print("* ");
}
}
System.out.println();
}
System.out.println();
}
//Promising method
public boolean canPlaceQueen(int r, int c) {
for (int i = 0; i < r; i++) {
if (x[i] == c || (i - r) == (x[i] - c) ||(i - r) == (c - x[i]))
{
return false;
}
}
return true;
}
//permute method
public void placeNqueens(int r, int n) {
for (int c = 0; c < n; c++) {
if (canPlaceQueen(r, c)) {
x[r] = c;
if (validSol(r,n)) {
printQueens(x);
} else {
placeNqueens(r + 1, n);
}
}
}
}
public boolean validSol(int r, int n){
if(r== n) {
return true;
}
else {
return false;
}
}
public void callplaceNqueens() {
placeNqueens(0, x.length);
}
public static void main(String args[]) {
NQueens Q = new NQueens(8);
Q.callplaceNqueens();
}
}

Your code looks fine. It is only missing a key check in the validSol method.
Change the validSold method to the following and your code should work fine.
public boolean validSol(int r, int n){
if(r== n-1) {
return true;
}
else {
return false;
}
}
Let me know if this works for you.

Related

Java Parameters, If-then statements, loops

I was given directions to write a method that takes two parameters. If the first parameter is equal to second parameter. Multiply both and print result.
If the first parameter is less than the second parameter, add the two and print the result 10 times.
If the first parameter is greater than the second parameter, subtract the first parameter from the second and print the result 50 times.
This is what I've coded:
public class IfHomeworkRedo {
{
public static void two(int a, int b) {
if (a == b) System.out.println(a*b);
else if (a < b) {
for (int i = 0; i < 10; i++) {
System.out.println(a+b);
}
}
else if (a > b) {
for (int i = 0; i < 50; i++) {
System.out.println(b-a);
}
}
public static void main (String[] args)
{
two(3, 3);
two(3, 4);
two(4, 3);
}
}
Can you help me with the errors? Thanks!
Problem #1
public class IfHomeworkRedo {
{
public static void two(int a, int b) {
There are two {{ before the two method declaration, you need to get rid of one
public class IfHomeworkRedo {
public static void two(int a, int b) {
Problem #2
You're missing a closing } after the end of the two method...
public static void two(int a, int b) {
if (a == b) System.out.println(a*b);
else if (a < b) {
for (int i = 0; i < 10; i++) {
System.out.println(a+b);
}
}
else if (a > b) {
for (int i = 0; i < 50; i++) {
System.out.println(b-a);
}
}
//??? Add } here
As general advice, it's easier to wrap all logic in a {...}, even it's just one line, as it will make it easier to read and reduce the risk on introducing logic errors, for example...
public static void two(int a, int b) {
if (a == b) {
System.out.println(a * b);
} else if (a < b) {
for (int i = 0; i < 10; i++) {
System.out.println(a + b);
}
} else if (a > b) {
for (int i = 0; i < 50; i++) {
System.out.println(b - a);
}
}
}
There should be no public on the class (if using ideone), and you had misplaced brackets. Solution: (http://ideone.com/7wBaSF)
class IfHomeworkRedo {
public static void main (String[] args)
{
two(3, 3);
two(3, 4);
two(4, 3);
}
public static void two(int a, int b) {
if (a == b) {System.out.println(a*b);}
else if (a < b) {
for (int i = 0; i < 10; i++) {
System.out.println(a+b);
}
}
else if (a > b) {
for (int i = 0; i < 50; i++) {
System.out.println(b-a);
}
}
}
}

(8 Queens) Find out if a Queen fits in 2D matrix

I'm attempting to write a program which solves the 8 Queens Problem using a 2 dimensional array of booleans. I will use backtracking to find the solution. I know this is not the optimal way to solve this problem, and that I should probably go for a 1D array for simplicity, but I want to solve it this way.
Right now I'm stuck on the function which is supposed to check whether a queen fits at a given coordinate. My row, column and down-right diagonal checks work, but I can't get the down-left diagonal check to work. I'm struggling to find the correct indexes of i and j (x and y) to start at, and which counter to increment/decrement for each iteration. Right now my function looks like this:
public static boolean fits(int x, int y) {
for(int i = 0; i < N; i++) {
if(board[x][i]) {
return false; // Does not fit on the row
}
}
for(int i = 0; i < N; i++) {
if(board[i][y]) {
return false; // Does not fit on the column
}
}
for(int i = Math.max(x-y, 0), j = Math.max(y-x, 0); i < N && j < N; i++, j++) {
if(board[i][j]) {
return false; // Down right diagonal issue
}
}
for(int i = Math.min(x+y, N-1), j = Math.max(N-1-x, 0); i >= 0 && j < N; i--, j++) {
if(board[i][j]) {
return false; // Supposed to check the down-left diagonal, but does not work.
}
}
return true;
}
As you can see there's a problem with the last loop here. I'd be very, very happy if someone could give me a working for-loop to check the down-left diagonal. Thanks in advance!
Edit: Here's the working code:
public class MyQueens {
static boolean[][] board;
static final int N = 8;
public static void main(String[] args) {
int p = 0;
board = new boolean[N][N];
board[1][1] = true;
System.out.println(fits(0, 2));
System.out.println(fits(2, 2));
}
public static boolean fits(int x, int y) {
for(int i = 0; i < N; i++) {
if(board[x][i]) {
return false; // Row
}
}
for(int i = 0; i < N; i++) {
if(board[i][y]) {
return false; // Column
}
}
for(int i = 0, j = 0; i < N && j < 0; i++, j++) {
if(board[i][j]) {
return false; // for right diagonal
}
}
int mirrorx = (N-1)-x;
for(int i = Math.max(mirrorx-y, 0), j = Math.max(y-mirrorx, 0); i < N && j < N; i++, j++) {
if(board[(N-1)-i][j]) {
return false;
}
}
return true;
}
}
I'm attempting to write a program which solves the 8 Queens Problem using a 2 dimensional array of booleans.
This is not the optimal representation, because you must use four loops to check if a queen can be placed or not. A much faster way of doing it is available.
For the purposes of your program, there are four things that must be free of threats in order for a queen to be placed:
A row,
A column,
An ascending diagonal, and
A descending diagonal
Each of these four things can be modeled with a separate array of booleans. There are eight rows, eight columns, fifteen ascending diagonals, and fifteen descending diagonals (including two degenerate cases of one-cell "diagonals" in the corners).
Declare four arrays row[8], col[8], asc[15] and desc[15], and use these four methods to work with it:
public static boolean fits(int r, int c) {
return !row[r] && !col[c] && !asc[r+c] && !desc[c-r+7];
}
public static void add(int r, int c) {
set(r, c, true);
}
public static void remove(int r, int c) {
set(r, c, false);
}
private static void set(int r, int c, boolean q) {
row[r] = col[c] = asc[r+c] = desc[c-r+7] = q;
}
Just flip the board horizontally and reuse the same algorithm as for the down right diagonal:
int mirrorx = (N-1)-x;
for(int i = Math.max(mirrorx-y, 0), j = Math.max(y-mirrorx, 0); i < N && j < N; i++, j++) {
if(board[(N-1)-i][j]) {
return false;
}
}
You could re-arrange it to make it more optimal.
Why don't you just use:
for(int i = 0, j = 0; i < N && j < 0; i++, j++) {
if(board[i][j]) {
return false; // for right diagonal
}
}
Similarly:
for(int i = 0, j = N-1; i < N && j >= 0; i++, j--) {
if(board[i][j]) {
return false; // for left diagonal
}
}

Game of life malfunctioning

Why isn't my game of life working correctly?
They don't always die when they're too crowded.
Relevant code is grann(x,y) which is supposed to return the number of living cells surrounding matrix[x][y],
run is supposed to calculate the next generation:
private int grann(int x,int y) {
int n = 0;
for(int i=-1; i<2; i++) {
for(int j=-1; j<2; j++) {
if(i!=0 || j!=0) {
if(matrix[x+i][y+j]) {
n++;
}
}
}
}
return n;
}
public void run() {
boolean[][] next = matrix;
for(int i=1; i<w; i++) {
for(int j=1; j<h; j++) {
int n = grann(i,j);
if(matrix[i][j]) {
if(!(n==2 || n==3)) {
next[i][j] = false;
}
} else {
if(n==3) {
next[i][j] = true;
}
}
}
}
matrix = next;
}
The object has a matrix, width and height.
matrix is a boolean[w+2][h+2], and w and h are ints.
If you don't know the rules of Conway's game of life:
http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life
I think the problem is that grann should say:
if(i != 0 && j != 0)
because you want to eliminate just the centre square of the 3x3 area you are checking (the cell itself), not the row and column it is in also.

How to call to function

I'm new in java.
I need to write a function that gets array A (The array size is n) and return true only if:
A[x]>A[y]-10 (While 0≤x<n 0≤y<n x≠y)
for example this array return true: A={1, 2, 5, 7, 9, 3}
Ok so here's my code, I'm trying to call the function "checkIfLargebyTen" but it doesn't work. what's wrong?
package Ass2;
public class Part0 {
public static boolean forAllExists(int[] A) {
boolean ans = true;
for(int i=0; i<A.length; i++)
{
if(checkIfLargebyTen(A,i)==false)
{
ans=false;
}//if
}//for
//Boolean function that check if A[x]>A[y]-10
boolean checkIfLargebyTen(int[] arr, int x) {
boolean ans=false;
for(int y=0; y<arr.length && ans==false; y++)
{
if (x!=y && arr[x]>arr[y]-10)
{
ans=true;
}//if
}//for
return ans;
}//CheckFunction
return ans;
}//AllExixstsFunction
}//class
In Java, you cannot define a method within a method. You should close the 'forAllExistsmethod before declaring thecheckIfLargeByTen` one:
public class Part0 {
public static boolean forAllExists(int[] A) {
boolean ans = true;
for(int i=0; i<A.length; i++)
{
if(checkIfLargebyTen(A,i)==false)
{
ans=false;
}//if
}//for
return ans; // return missing in the OP
} // close forAllExists - missing in the OP
//Boolean function that check if A[x]>A[y]-10
static boolean checkIfLargebyTen(int[] arr, int x) {
boolean ans=false;
for(int y=0; y<arr.length && ans==false; y++)
{
if (x!=y && arr[x]>arr[y]-10)
{
ans=true;
}//if
}//for
return ans;
}//CheckFunction
}//class
I guess you could make function which goes through all the values with two for loops and as soon as some pair (x, y) does not fit your condition, return false. I think you are doing the same thing, but this is all in one method.
public static boolean checkSomething(int[] arr)
{
for(int i = 0;i < arr.length;i ++)
{
for(int j = 0;j < arr.length;j ++)
{
if(arr[i]<=arr[j]-10) return false;
}
}
return true;
}
Jesse.

Inheritance problems in Java

I have some problems with getting inheritance to work. In the parent class, the array Coefficients is private. I have some access methods but I still can't get it to work.
import java.util.ArrayList;
public class Poly {
private float[] coefficients;
public static void main (String[] args){
float[] fa = {3, 2, 4};
Poly test = new Poly(fa);
}
public Poly() {
coefficients = new float[1];
coefficients[0] = 0;
}
public Poly(int degree) {
coefficients = new float[degree+1];
for (int i = 0; i <= degree; i++)
coefficients[i] = 0;
}
public Poly(float[] a) {
coefficients = new float[a.length];
for (int i = 0; i < a.length; i++)
coefficients[i] = a[i];
}
public int getDegree() {
return coefficients.length-1;
}
public float getCoefficient(int i) {
return coefficients[i];
}
public void setCoefficient(int i, float value) {
coefficients[i] = value;
}
public Poly add(Poly p) {
int n = getDegree();
int m = p.getDegree();
Poly result = new Poly(Poly.max(n, m));
int i;
for (i = 0; i <= Poly.min(n, m); i++)
result.setCoefficient(i, coefficients[i] + p.getCoefficient(i));
if (i <= n) {
//we have to copy the remaining coefficients from this object
for ( ; i <= n; i++)
result.setCoefficient(i, coefficients[i]);
} else {
// we have to copy the remaining coefficients from p
for ( ; i <= m; i++)
result.setCoefficient(i, p.getCoefficient(i));
}
return result;
}
public void displayPoly () {
for (int i=0; i < coefficients.length; i++)
System.out.print(" "+coefficients[i]);
System.out.println();
}
private static int max (int n, int m) {
if (n > m)
return n;
return m;
}
private static int min (int n, int m) {
if (n > m)
return m;
return n;
}
public Poly multiplyCon (double c){
int n = getDegree();
Poly results = new Poly(n);
for (int i =0; i <= n; i++){ // can work when multiplying only 1 coefficient
results.setCoefficient(i, (float)(coefficients[i] * c)); // errors ArrayIndexOutOfBounds for setCoefficient
}
return results;
}
public Poly multiplyPoly (Poly p){
int n = getDegree();
int m = p.getDegree();
Poly result = null;
for (int i = 0; i <= n; i++){
Poly tmpResult = p.multiByConstantWithDegree(coefficients[i], i); //Calls new method
if (result == null){
result = tmpResult;
} else {
result = result.add(tmpResult);
}
}
return result;
}
public void leadingZero() {
int degree = getDegree();
if ( degree == 0 ) return;
if ( coefficients[degree] != 0 ) return;
// find the last highest degree with non-zero cofficient
int highestDegree = degree;
for ( int i = degree; i <= 0; i--) {
if ( coefficients[i] == 0 ) {
highestDegree = i -1;
} else {
// if the value is non-zero
break;
}
}
float[] newCoefficients = new float[highestDegree + 1];
for ( int i=0; i<= highestDegree; i++ ) {
newCoefficients[i] = coefficients[i];
}
coefficients = newCoefficients;
}
public Poly differentiate(){
int n = getDegree();
Poly newResult = new Poly(n);
if (n>0){ //checking if it has a degree
for (int i = 1; i<= n; i++){
newResult.coefficients[i-1]= coefficients[i] * (i); // shift degree by 1 and multiplies
}
return newResult;
} else {
return new Poly(); //empty
}
}
public Poly multiByConstantWithDegree(double c, int degree){ //used specifically for multiply poly
int oldPolyDegree = this.getDegree();
int newPolyDegree = oldPolyDegree + degree;
Poly newResult = new Poly(newPolyDegree);
//set all coeff to zero
for (int i = 0; i<= newPolyDegree; i++){
newResult.coefficients[i] = 0;
}
//shift by n degree
for (int j = 0; j <= oldPolyDegree; j++){
newResult.coefficients[j+degree] = coefficients[j] * (float)c;
}
return newResult;
}
}
Can anyone help me fix my Second class that inherits from the one above? I cant seem to get my multiply and add methods for the second class to work properly.
public class QuadPoly extends Poly
{
private float [] quadcoefficients;
public QuadPoly() {
super(2);
}
public QuadPoly(int degree) {
super(2);
}
public QuadPoly(float [] f) {
super(f);
if (getDegree() > 2){
throw new IllegalArgumentException ("Must be Quadratic");
}
}
public QuadPoly(Poly p){
super(p.coefficients);
for (int i = 0; i < coefficients.length; i++){
if (coefficients[i] < 0){
throw new Exception("Expecting positive coefficients!");
}
}
}
// public QuadPoly(Poly p){
// super(p.coefficients);
//}
public QuadPoly addQuad (QuadPoly p){
return new QuadPoly(super.add(p));
}
public QuadPoly multiplyQuadPoly (QuadPoly f){
if (quadcoefficients.length > 2){
throw new IllegalArgumentException ("Must be Quadratic");
}
return new QuadPoly(super.multiplyPoly(f));
}
I would make the coefficients protected or use an accessor method.
I wouldn't throw a plain checked Exception. An IllegalArgumentException would be a better choice.
What is quadcoefficients? They don't appear to be set anywhere.
You put coefficients private. I wouldn't change this but I would add a getter method into Poly class:
public class Poly {
//somecode here
public float[] getCoefficients(){
return this.coefficients;
}
}
Then I would use it by the getter method in other code;
public QuadPoly(Poly p){
super(p.getCoefficients);
//some more code here
}
Even if you make coefficient protected, you are trying to reach coefficients field of another Object, which is a parameter. So it is not related to inheritance and the problem.

Categories