Method testing and nothing prints out - java

I'm testing a part of my Sudoku program to test if the row is valid or not. The board from file method makes a 9x9 array, but I can't understand why when I try running this isValidRow() method there is no indication of it being true or false. Why is this so?
public static boolean isValidRow(int[][] grid, int row) {
int i = 0;
int j = 0;
while (i < 9){
while (j < 9){
if (grid[row][i] == grid[row][j]){
if (i == j){
continue;
}
return false;
}
j++;
}
i++;
}
System.out.println("hii");
return true;
}
public static void main(String[] args) throws IOException {
int[][] board = new int[9][9];
boardFromFile(board, "sudoku.txt");
System.out.println(isValidRow(board, 0));
}

You have an infinite loop in isValidRow().
When you first call this function i and j are both zero (0). Thus,
if (grid[row][i] == grid[row][j])
will always evaluate to true. As will:
if (i == j)
The next action is:
continue;
which will start the inner while loop again. And as i and j are unchanged the same thing will happen again and again.

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.

Java tictactoe problems with minmax algorithm

i want to implement the MinMax algorithm for tictactoe. I have two methods
min() and max() and a evaluation method, but it doesn't works. For example when i call
max(9);
Field[bestCol][bestRow]='O';
min(8);
Field[bestCol][bestRow]='X';
in the main function the result is
OX-
---
---
But the best Move for Player 'X' is to put the 'X' in the middle.
Here is my Code without the evaluation Method:
static char[][] Field = { { '-', '-', '-' },
{ '-', '-', '-' },
{ '-', '-', '-' } };
static char Player = 'O';
static char Computer = 'X';
static int Depth =9; // searchdepth
static int bestRow=0, bestCol=0; // best Move
public static int max(int depth) {
if (depth == 0) {
return evaluateMove();
}
int maxValue = Integer.MIN_VALUE;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (Field[i][j] == '-') {
Field[i][j] = Computer;
int value = min(depth - 1);
Field[i][j] ='-';
if (value > maxValue) {
maxValue = value;
if (depth == Depth) {
bestCol=i;
bestRow=j;
}
}
}
}
}
return maxValue;
}
public static int min(int depth) {
int minValue = Integer.MAX_VALUE;
if (depth == 0) {
return evaluateMove();
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (Field[i][j] == '-') {
Field[i][j] = Player;
int value = max(depth - 1);
Field[i][j] = '-';
if (value < minValue) {
minValue = value;
bestCol=i;
bestRow=j;
}
}
}
}
return minValue;
}
Best Regards
EDIT:
Thanks for your answer. To the first point i have forgotten to change the '*' to '-' Here is my Evaluation Method:
public static int evaluateMove() {
for(int i=0; i<3; i++) {
int countX=0; int countY=0;
for(int j=0; j<3; j++) {
if(Feld[i][j]==Computer) countX++;
if(Feld[i][j]==Player) countY++;
}
if(countX==3) return 10;
if(countY==3) return -10;
}
for(int j=0; j<3; j++) { // Spalten
int countX=0; int countY=0;
for(int i=0; i<3; i++) {
if(Feld[i][j]==Computer) countX++;
if(Feld[i][j]==Player) countY++;
if(countX==3) return 10;
if(countY==3) return -10;
}
}
return 0; // Unentschieden
}
Some things that struck me:
you are initializing the empty squares of the playing field with '-', but in the min/max-functions you assume that '*' is an empty square
in the min-function, as opposed to the max-function you set the best move at every level instead of the top level, so the deeper levels will overwrite the best result from the top level (so I think you should also check for depth==Depth)
I don't know what you do in main, but should also decrement "Depth" after each move, because this defines the top level (and thus the level where the best move should be assigned), and according to your question you decrement the "depth" argument during each call
I guess you know that you will only get the optimal result if you recurse until the end of the game (which is another argument for decrementing depth and Depth after every move)
You are not checking the diagonals in your evaluateMove function
In your second double loop in evaluateMove you check the condition for countX, countY inside the innermost loop (works, but it is irritating that it's different to first double loop => not so good for finding errors)
Edit: and finally (drum roll...):
In the first move you maximize the gain (for a Computer move ('X')) but you actually perform a Player move ('O'). For the second move vice versa. However, you have to minimize the gain in the first move (which means player wins) and maximize in the second move.
That is, what you actually do:
public static void ComputeAndExecuteBestMove()
{
// since Player begins, we minimize the gain value for the first move
if ((MaxDepth-Depth) % 2 == 0)
{
max(Depth);
Field[bestCol,bestRow] = Player;
}
else
{
min(Depth);
Field[bestCol,bestRow] = Computer;
}
// next move
Depth--;
}
but what you should do:
public static void ComputeAndExecuteBestMove()
{
// since Player begins, we minimize the gain value for the first move
if ((MaxDepth-Depth) % 2 == 0)
{
min(Depth);
Field[bestCol,bestRow] = Player;
}
else
{
max(Depth);
Field[bestCol,bestRow] = Computer;
}
// next move
Depth--;
}

I am learning java and i want java program in a particular issue

i want to create java program for a number when divided by 2, 3, 4, 5, 6 leaves a remainder of 1 but it is divided by 7 completely.
I tried this logic
for (int a=1;a<=500;a++){
if (a%2==1 && a%3==1 && a%4==1 && a%5==1 && a%6==1 && a%7==0)
and it works fine but I want it by this logic
for (int a=1;a<=500;a++){
for(int b=2;b<=6; b++){
if (a%b==1 && a%7==0){
System.out.println(a);
help me if it is possible to create in this way?Thank you
You could count how many of the iterations pass your test, like this:
for (int a=1; a<=500; a++) {
int flag=0;
for (int b=2; b<=6; b++) {
if (a%b == 1) {
flag += 1;
} else {
break;
}
}
if (flag == 5) {
if (a%7 == 0) {
System.out.println("Value "+a);
}
}
}
If any of the tests fail, flag will be less than 5 at the end of the loop. If you change the number of tests, you will need to remember to update that magic number.
you could name the outer loop and check and continue it in the inner loop like this:
public static void main(String[]args){
// That´s your mainloop
mainLoop: for (int a=1; a<=500; a++){
for(int b=2; b<7;++b) {
// If anything doesn´t leave a remainder of 1 youll continue with the mainloop here
if(a%b != 1) {
continue mainLoop;
}
}
// 2-6 had a remainder of 1, so just check if the number is dividible by 7 now, if so print it.
if(a%7 ==0) {
System.out.println(a);
}
}
}
It can make things easier if you split your code into functions. Start with the outer (a) loop:
public static void main(String[] args)
{
for (int a = 1; a <= 5000; ++a)
if (test(a))
System.out.println(a);
}
We've deferred the actual logic to the test() function, and assumed we'll define that later.
Now write the test. As soon as any of the sub-tests fail, we can return false immediately. If all tests pass and we reach the end, then we must return true:
static boolean test(int x)
{
// i is the candidate factor
for (int i = 2; i <= 7; ++i) {
int expected = i==7 ? 0 : 1;
if (x%i != expected)
return false;
}
return true;
}
We can simplify further through use of a magic number to encode the different values of expected:
static boolean test(int x)
{
for (int i = 2; i <= 7; ++i)
if (x%i != 301%i)
return false;
return true;
}
You can iterate over all the b values, and set a flag if any of them fail the test. If the flag is unset at the end of the loop, you know they all passed:
for (int a=1; a<=500; a++) {
int flag = 0;
for (int b=2; b<=6; b++) {
if (a%b!=1 || a%7!=0) {
// doesn't satisfy the condition, so flag it
flag = 1;
break; // exit the inner loop
}
}
if (flag == 0)
// If we got here without setting flag, it means that all of the
// 'b' values passed the test.
System.out.println(a);
}

Java Connect four method full board

okay so what I have to do is make a java connect four game. One of the methods which is named full is used to check if the board is full or not. If it is it returns true, if not then it returns false. White is used for empty spaces. The problem is I can't compare board and Color.White and I don't know what to do from here. My code is below
public static boolean full(Color[][] board) {
for(int i = 0; i < board.length; i++){
if (board != Color.WHITE){
return true;
} else {
return false;
}
}
}
It is hard to say with only the snippet of code. What kind of object is 'board'?
To me it seems like you should increment through the Color[][] array in a double for-loop and see if any of the elements are equal to Color.WHITE.
public static boolean full(Color[][] board) {
for(int i = 0; i < board.length; i++){
for(int j=0; j<board.length;j++) {
if (board[i][j] == Color.WHITE){
return false;
} else {
return true;
}
}
}
}
Do you have any logs, error messages, or print statements to help debug? Good luck!

Getting every combination of Queens?

public class SomeQueens {
static Stack<Integer> s= new Stack<Integer>();
static int Solved = 0;
static int current = 0;
public static int solve(int n) { // n is 8
while(current < n) { // should I use current < n instead
for (int i = current; i < n; i++) {
if(validPosition(i)) {
s.push(i);
current = 0;
}
}
if(!validPosition(current)) {
if(s.empty()) {
break;
}
if(!s.empty()) {
s.pop();
current++;
}
}
if(s.size() == n) {
s.pop();
current++;
printSolution(s);// this is a method, but it shouldn't matter for this
Solved++;
}
}
return Solved;
}
public static boolean validPosition(int column) {
for( int row = 0; row < s.size(); row++)
if(s.get(row) == column || ((column - s.get(row)) == (s.size() - row)) ||
((s.get(row) - column) == (s.size() - row)) )
return false; // there's a conflict
return true; // no conflict;
}
//it's called by int num = solve(n);
//sop("There're" + num + "sols to the" + n "queens prob");
This is a subsection of my program for NQueens, but I seem to always get: There are 0 solutions to the 8-queens problem. I tried debugging with system.out.prints in the main method, which led me to guess that there would be something wrong in my boolean method, but I don't think it's doing anything wrong.
I'm unsure if my while statement is incorrect or if the break inside the while loop is initialized before anything is even done. Thanks for the help and guidance and I'm sorry if my program and explanation makes no sense
Here is why you instantly get a zero:
s.push(0);
while(s.size() > n) // n is 8
{
//...
}
return Solved;
When the program arrives at the while-condition s has a size of one and n is 8. This will instantly fail and cause the method to return a zero.
But that's not the only problem with the algorithm. You should seriously rethink it.

Categories

Resources