Check Horizontal & Vertical work

This commit is contained in:
Matti 2024-05-20 17:10:12 +02:00
parent 3aa56bd3fb
commit 7c7a91a762
2 changed files with 35 additions and 10 deletions

View File

@ -4,7 +4,9 @@ public class Demo {
public static void main(String[] args) { public static void main(String[] args) {
Queenproblem Q = new Queenproblem(); Queenproblem Q = new Queenproblem();
System.out.println(Q.field[2]); System.out.println(Q.field[2]);
Q.setField(new int[] {0,1,2,3,4,5,6,7}); Q.setField(new int[] {0,0,2,3,4,5,0,0});
Q.print(); Q.print();
}
} }
}

View File

@ -3,6 +3,8 @@ package part5.aufg2;
import java.util.Arrays; import java.util.Arrays;
public class Queenproblem { public class Queenproblem {
// 0 means empty
// 1-8 is the y position of the Queen
int[] field; int[] field;
public Queenproblem(){ public Queenproblem(){
@ -21,8 +23,12 @@ public class Queenproblem {
} }
for (int i=0; i<8; i++) { for (int i=0; i<8; i++) {
int index = this.field[i]; try {
field[i][index] = 1; int yPosition = this.field[i];
field[i][yPosition-1] = 1; // -1 to handle 0 as empty and 8 as lowest possible with actual index 7
}catch (IndexOutOfBoundsException e){
System.out.println("Ignored Index Error while making it 2D");
}
} }
return field; return field;
@ -35,13 +41,25 @@ public class Queenproblem {
} }
} }
public boolean isPossible(int x, int y){ public boolean checkVertical(int col){
// Horizontal if (this.field[col-1] != 0){
for (int value: this.field) { return false;
if (value == y){ }
return true;
}
public boolean checkHorizontal(int col){
for (int colFilled : this.field) {
if (colFilled == col){
return false; return false;
} }
} }
return true;
}
public boolean isPossible(int row, int col){
int x = --row;
int y = --col;
// Vertical // Vertical
if (this.field[x] != 0) if (this.field[x] != 0)
@ -50,9 +68,14 @@ public class Queenproblem {
// Diagonal \ // Diagonal \
for (int i=0; i<8; i++){ for (int i=0; i<8; i++){
try{ try{
if (this.field[x+i] == y+i){
return false;
}
if (this.field[x-i] == y-i){
return false;
}
}catch (IndexOutOfBoundsException e){ }catch (IndexOutOfBoundsException e){
System.out.println(e); System.out.println("Ignored index Error with Diagonal Possibility Check");
} }
} }