Sudoku Solver Java - java

OK so I have programmed a Sudoku solver.. And when I run the debug to check if its going through everything.. it is.. But it does not seem to work. It will print it out, and it will change the "." to 0's. But thats as far as it goes. It will not change the 0's, to the numbers when it loops over it.
public class SudokuSolver {
int[][] sudoku;
String data;
public SudokuSolver()
{
getPuzzle();
solvePuzzle(0,0);
}
private void getPuzzle()
{
try
{
Scanner in = new Scanner(new File("C:/Users/Ben/workspace/Sudoku Solver/src/puzzle1.txt"));
sudoku = new int[9][9];
for(int y = 0; y<9;y++)
{
for(int x = 0; x<9; x++)
{
data = in.next();
if(data.equals("."))
sudoku[x][y]=0;
else
sudoku[x][y] = Integer.parseInt(data);
}
}
in.close();
}
catch(Exception e)
{
}
for(int y = 0; y<9; y++)
{
for(int x = 0; x<9; x++)
{
System.out.print(sudoku[x][y]);
if(x ==2 || x ==5)
System.out.print(" ");
if(x==8)
{
System.out.print("\n");
}
}
if(y == 2|| y == 5)
{
System.out.println(" ");
}
}
}
private boolean isValid(int x, int y, int num)
{
int xSection = x/3;
int ySection = y/3;
for ( int row = 0; row < sudoku.length; row++ )
{
if(sudoku[row][y] == num)
{
return false;
}
}
for( int col = 0; col < sudoku.length; col++)
{
if(sudoku[x][col] == num)
{
return false;
}
}
for(int box = 3*xSection; box < 3*xSection + 3; box++)
{
for(int boxY = 3*ySection; boxY < 3*ySection + 3; boxY++)
{
if(sudoku[box][boxY] == num)
{
return false;
}
}
}
return true;
}
private int xPosition(int x, int y)
{
if(x<8)
{
return x+1;
}
else
{
return 0;
}
}
private int yPosition(int x, int y)
{
if(x<8)
{
return y;
}
else
{
return y+1;
}
}
private boolean solvePuzzle(int x, int y)
{
if( x >= 9 || y >= 9)
{
return true;
}
else
{
for(int num = 1; num < 10; num++)
{
if(isValid(x,y,num))
{
sudoku[x][y] = num;
if( solvePuzzle(xPosition(x,y), yPosition(x,y)) )
{
return true;
}
else
{
sudoku[x][y] = 0;
}
}
}
return false;
}
}
public static void main(String args[])
{
SudokuSolver solver = new SudokuSolver();
}
}

You're printing the puzzle inside the getPuzzle-method, which is before solvePuzzle has been called. You need to print the puzzle after it has been solved.

Related

N Queens - Java

I was solving the N queens question myself and went with a different approach thaat was mentioned in the solution as well as online.
My code is working for inputs up to 4 but starts to print every case (even those are wrong) for any value after 4. I've checked it a lot of times but I'm unable to find any bug in the code.
PFA the code and see if you can find the bug.
Thanks!
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Scanner scn = new Scanner(System.in);
int n= scn.nextInt();
int[][] arr = new int[n][n];
printNQueens(arr,"",0);
System.out.println();
}
public static void printNQueens(int[][] chess, String qsf, int row) {
if(row==chess.length)
{
qsf = qsf + ".";
System.out.println(qsf);
return;
}
for(int j=0;j<chess[0].length;j++)
{
if(chess[row][j]==0)
{
int x=row,y=j;
while(x<chess.length)
{
chess[x][y] = 1;
x++;
}
x = row;
while(x<chess.length && y>=0)
{
chess[x][y] = 1;
x++;
y--;
}
x = row;
y = j;
while(x<chess.length && y<chess[0].length)
{
chess[x][y] = 1;
x++;
y++;
}
printNQueens(chess,qsf + row + "-" + j + ", ",row+1);
x = row;
y = j;
while(x<chess.length)
{
chess[x][y] = 0;
x++;
}
x = row;
while(x<chess.length && y>=0)
{
chess[x][y] = 0;
x++;
y--;
}
x = row;
y = j;
while(x<chess.length && y<chess[0].length)
{
chess[x][y] = 0;
x++;
y++;
}
}
}
}
}
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Scanner scn = new Scanner(System.in);
int n= scn.nextInt();
int[][] arr = new int[n][n];
printNQueens(arr,"",0);
System.out.println();
}
public static void printNQueens(int[][] chess, String qsf, int row) {
if(row==chess.length)
{
qsf = qsf + ".";
System.out.println(qsf);
return;
}
for(int j=0;j<chess[0].length;j++)
{
if(chess[row][j]==0)
{
chess[row][j] = 1;
ArrayList<Integer> ro = new ArrayList<>();
ArrayList<Integer> co = new ArrayList<>();
int x=row+1,y=j;
while(x<chess.length)
{
if(chess[x][y]==1)
{
ro.add(x);
co.add(y);
}
chess[x][y] = 1;
x++;
}
x = row+1;
y = j - 1;
while(x<chess.length && y>=0)
{
if(chess[x][y]==1)
{
ro.add(x);
co.add(y);
}
chess[x][y] = 1;
x++;
y--;
}
x = row+1;
y = j+1;
while(x<chess.length && y<chess[0].length)
{
if(chess[x][y]==1)
{
ro.add(x);
co.add(y);
}
chess[x][y] = 1;
x++;
y++;
}
printNQueens(chess,qsf + row + "-" + j + ", ",row+1);
x = row;
y = j;
while(x<chess.length)
{
chess[x][y] = 0;
x++;
}
x = row;
while(x<chess.length && y>=0)
{
chess[x][y] = 0;
x++;
y--;
}
x = row;
y = j;
while(x<chess.length && y<chess[0].length)
{
chess[x][y] = 0;
x++;
y++;
}
x = 0;
y = 0;
while(x<ro.size() && y<co.size())
{
chess[ro.get(x)][co.get(y)] = 1;
x++;
y++;
}
}
}
}
}

coinFlip heads streak output

I'm supposed to flip a coin 100 times, and find out the longest streak of heads, then output it, but so far, it's only giving me how many heads there are in total. I've tried a bunch of things but can't find a solution.
public class LongestStreak extends ConsoleProgram
{
public static final int FLIPS = 100;
public void run()
{
int h = 0;
int t = 0;
boolean wasHeads = false;
boolean isHeads = false;
int streak = 0;
int ih = 0;
for (int i = 0; i < FLIPS; i++) {
int coinFlip = Randomizer.nextInt(1, 2);
if (coinFlip == 2) {
System.out.println("Heads");
h++;
ih++;
isHeads = true;
if (ih > 1) {
wasHeads = true;
}
if ((isHeads = true) && (wasHeads = true)) {
streak++;
} else {
streak = 0;
}
} else if (coinFlip == 1) {
System.out.println("Tails");
t++;
isHeads = false;
ih = 0;
}
}
System.out.println(streak);
}
}
You need to substantially simplify your code.
public class LongestStreak extends ConsoleProgram
{
public static final int FLIPS = 100;
public void run()
{
int wasHeads = 0;
int streak = 0;
int bestStreak = 0;
for (int i = 0; i < FLIPS; i++) {
int coinFlip = Randomizer.nextInt(1, 2);
if (coinFlip == 2) {
streak++;
wasHeads = 1;
} else if (coinFlip == 1) {
wasHeads = 0;
if (steak > bestStreak) {
bestStreak = streak;
}
streak = 0;
}
}
System.out.println(streak);
}
}
Reset streak when it ends (coinFlip is 1), but first check if it's better than your best streak before then, updating the bestStreak if so accordingly. Otherwise, just iterate streak and keep wasHeads at 1 for each head. Note there's not need for a boolean here; a 1 or 0 integer is literally and logically the same thing.
You can simplify your code a bit, wasHeads and isHeads are not really needed. Also, more descriptive variable names makes your code easier to understand. So, something like this:
public void run() {
int highestNumberOfConsecutiveHeads = 0;
int currentNumberOfConsecutiveHeads = 0;
for (int i = 0; i < 100; i++) {
if (Randomizer.nextInt(1, 2) == 2) {
currentNumberOfConsecutiveHeads++;
if (currentNumberOfConsecutiveHeads > largestNumberOfConsecutiveHeads) {
highestNumberOfConsecutiveHeads = currentNumberOfConsecutiveHeads;
}
} else {
currentNumberOfConsecutiveHeads = 0;
}
}
System.out.println("Longest streak: " + highestnumberOfConsecutiveHeads);
}
First and foremost, fix your line here so it's easier to read: }} else if (coinFlip == 1) {
(You need a newline between those two close braces)
I would consider setting up some more clear variable names. For example: totalHeads, totalTails. I'm not quite getting what your ih variable is SUPPOSED to be, but the variable names I would use for solving this problem are thisStreak and bestStreak. is/washeads should be unnecessary. I think that should be enough of a push to get you to a solution.
Thanks for the help, fixed my code :)
public class LongestStreak extends ConsoleProgram
{
public static final int FLIPS = 100;
public void run()
{
int h = 0;
int t = 0;
boolean wasHeads = false;
boolean isHeads = false;
int longest = 0;
int streak = 0;
int ih = 0;
for (int i = 0; i < FLIPS; i++) {
int coinFlip = Randomizer.nextInt(1, 2);
if (coinFlip == 2) { //heads
System.out.println("Heads");
if (wasHeads = true) {
streak++;
} else {
streak = 0;
}
wasHeads = true;
} else if(coinFlip == 1) { //tails
System.out.println("Tails");
t++;
isHeads = false;
if (streak > longest){
longest = streak;
}
streak = 0;
ih = 0;
}
}
System.out.println("Longest streak of heads: " + longest);
}
}

Module and how to use it in the situation below

public class AirplaneLab
{
private int [][] first;
private int [][] economy;
private boolean [] seat;
private boolean okay;
private boolean okayokay;
public AirplaneLab()
{
}
public AirplaneLab(int [][] first1, int [][] economy1)
{
}
public boolean viewFirstClass(boolean set[], int [][] first, int [][] economy)
{
if (okay = true)
{
boolean seating1[] = new boolean[20];
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 4; j++)
{
if(seat[((j + 1) + (i * 4)) - 1])
{
System.out.print("x ");
seating1[i * j] = true;
}
else
{
System.out.print("o ");
seating1[i * j] = flase;
}
}
System.out.println();
}
System.out.println("The x's are the sets that are taken, o's are not");
return seating1[];
}
else
{
return false;
}
}
public boolean viewEconomyClass(boolean set[], int [][] first, int [][] economy)
{
if (okayokay = true)
{
boolean seating2[] = new boolean[30];
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 3; j++)
{
if(seat[((j + 1) + (i * 3)) - 1])
{
System.out.print("x ");
seating2[i * j] = true;
}
else
{
System.out.print("o ");
seating2[i * j] = false;
}
}
System.out.println();
}
System.out.println("The x's are the sets that are taken, o's are not");
return seating2[];
}
else
{
return false;
}
}
public void decision()
{
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Please choose an option:");
System.out.println("1 for “booking in first class”");
System.out.println("2 for “booing in economy class”");
System.out.println("3 to view seating chart for first class ");
System.out.println("4 to view seating chart for economy class");
System.out.println("0 to exit");
System.out.print("? ");
while(true)
{
int mOpt = input.nextInt();
if ((mOpt == 1) || (mOpt == 3))
{
if (mOpt == 1)
{
okay = true;
System.out.println("Based on the following setting arrangement, please pick a window middle or end seat");
viewFirstClass(boolean set[], int [][] first, int [][] economy);
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 4; j++)
{
if (seating1[i * j] == true)
{
if ((i * j) ________________)
}
}
}
}
}
}
}
}
In the code above, where the blank is:
The last if statement before all of the closed brackets:
I was wondering how you would use module there.
Let's say I wanted to do (i * j) module of 4; how would I do that? Can you fill in the blank? Thank you for your help!
If you are looking for some thing (modulo) like
if ((i * j) mod 4 )
in java ,the syntax would be
if ((i * j) % 4 )

Unable to determine win condition in Tic Tac Toe

I have been trying to get my tic tac toe program to work for a while now.
At the moment I'm stuck in the win condition.
The game can now end as a draw but no player (human || computer) can win it.
I need to determine the winning conditions (horizontal, vertical, across) in playerHasWon but have no idea how to implement them.
import java.util.Scanner;
import java.util.Random;
public class NewTicTacToe {
public static final int DRAW = 0;
public static final int COMPUTER = 1;
public static final int PLAYER = 2;
public static final char PLAYER_MARK = 'X';
public static final char COMPUTER_MARK = 'O';
public static int size;
public static String[][] board;
public static int score = 0;
public static Scanner scan = new Scanner(System.in);
/**
* Creates base for the game.
*
* #param args the command line parameters. Not used.
*/
public static void main(String[] args) {
while (true) {
System.out.println("Select board size");
System.out.print("[int]: ");
try {
size = Integer.parseInt(scan.nextLine());
} catch (Exception e) {
System.out.println("You can't do that.");
continue;
}
break;
}
int[] move = {};
board = new String[size][size];
setupBoard();
int i = 1;
loop:
while (true) {
if (i % 2 == 1) {
displayBoard();
move = getMove();
} else {
computerTurn();
}
switch (isGameFinished(move)) {
case PLAYER:
System.err.println("YOU WIN!");
break loop;
case COMPUTER:
System.err.println("Computer WINS!\nYOU LOSE!");
break loop;
case DRAW:
System.err.println("IT'S A DRAW");
break loop;
}
i++;
}
}
private static int isGameFinished(int[] move) {
if (isDraw()) {
return DRAW;
} else if (playerHasWon(board, move, COMPUTER_MARK)) {
return COMPUTER;
} else if (playerHasWon(board, move, PLAYER_MARK)) {
return PLAYER;
}
return -1;
}
/**
* Checks for win.
*
* #param board
* #return if the game is won.
*/
public static boolean playerHasWon(String[][] board, int[] move,
char playerMark) { //playermark x || o
boolean hasWon = false;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
// check if 5 in a line
if (board[i][j].equals(playerMark)) {
score++;
} else {
score = 0;
}
if (score == 5) {
return true;
}
}
}
return hasWon;
}
/**
* Checks for draws.
*
* #return if this game is a draw
*/
public static boolean isDraw() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (board[i][j] == " ") {
return false;
}
}
}
return true;
}
/**
* Displays the board.
*
*
*/
public static void displayBoard() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.printf("[%s]", board[i][j]);
}
System.out.println();
}
}
/**
* Displays the board.
*
*
*/
public static void setupBoard() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
board[i][j] = " ";
}
}
}
/*
* Takes in userinput and sends it to isValidPlay.
*
*
*/
public static int[] getMove() {
Scanner sc = new Scanner(System.in);
System.out.println("Your turn:");
while (true) {
try {
System.out.printf("ROW: [0-%d]: ", size - 1);
int x = Integer.parseInt(sc.nextLine());
System.out.printf("COL: [0-%d]: ", size - 1);
int y = Integer.parseInt(sc.nextLine());
if (isValidPlay(x, y)) {
board[x][y] = "" + PLAYER_MARK;
return new int[]{x, y};
}
} catch (Exception e) {
System.out.println("You can't do that.");
}
return null;
}
}
/*
* Randomizes computer's turn - where it inputs the mark 'O'.
*
*
*/
public static void computerTurn() {
Random rgen = new Random(); // Random number generator
while (true) {
int x = (int) (Math.random() * size);
int y = (int) (Math.random() * size);
if (isValidPlay(x, y)) {
board[x][y] = "" + COMPUTER_MARK;
break;
}
}
}
/**
* Checks if the move is possible.
*
* #param inX
* #param inY
* #return
*/
public static boolean isValidPlay(int inX, int inY) {
// Play is out of bounds and thus not valid.
if ((inX >= size) || (inY >= size)) {
return false;
}
// Checks if a play have already been made at the location,
// and the location is thus invalid.
return (board[inX][inY] == " ");
}
}
// End of file
You could use a different approach to check for victories. Maybe split in three parts? Horizontal, vertical, and diagonals?
I made some changes to your code to give an example:
public static boolean playerHasWon(String[][] board, int[] move,
String playerMark) { //playermark x || o
//Horizontal check
for (int i = 0; i < size; i++) {
if (board[i][0].equals(playerMark)) {
int j;
for (j = 1; j < size; j++) {
if (!board[i][j].equals(playerMark)) {
break;
}
}
if (j == size) {
return true;
}
}
}
//Vertical check
for (int i = 0; i < size; i++) {
if (board[0][i].equals(playerMark)) {
int j;
for (j = 1; j < size; j++) {
if (!board[j][i].equals(playerMark)) {
break;
}
}
if (j == size) {
return true;
}
}
}
//Diagonals
int i;
for (i = 0; i < size; i++) {
if (!board[i][i].equals(playerMark)) {
break;
}
}
if (i == size) {
return true;
}
for (i = 0; i < size; i++) {
if (!board[i][(size - 1) - i].equals(playerMark)) {
break;
}
}
if (i == size) {
return true;
}
return false;
}
Note that you have to change the playerMarks from char to String.
Also, I suggest displaying the board just before announcing who won. That way, if the computer wins, you can see its last move

Problems with the N queen homework exercice in Java

I'm using my own implementation of the stack.
I should not use recursion.
My code:
public static void solve(int bsize)
{
stack queenLoc = new stack();
int y=0;
int count=0;
boolean done = false;
while(done == false && queenLoc.size() != bsize)
{
queenLoc.push(count);
if(!isSafe(bsize,queenLoc,count))
{
while(queenLoc.getTop() == bsize)
{
y = queenLoc.pop();
count--;
}
if(queenLoc.top != null)
{
queenLoc.push(queenLoc.pop()+1);
count++;
}
else
{
queenLoc.push(y+1);
count++;
}
}
else if(queenLoc.size() == bsize)
{
done = true;
}
else
{
count++;
queenLoc.push(count);
}
}
queenLoc.showAll();
if(queenLoc.size() == bsize)
printBoard(bsize, queenLoc);
}
public static boolean isSafe(int bsize, stack s,int count)
{
for(int i = 1; i<s.size(); i++)
{
if(s.getTop() == s.get(i) || s.getTop()+count == s.get(i)+s.size() || s.getTop()-count == s.get(i)-s.size())
return false;
}
return true;
}
I'm not sure what is really going on, i'm getting wrong position and the printBoard function is only printing the queens on the first row.
I actually tried a lot of possibilities, but i got a bit confused.
Can anyone just point me out to the right direction and tell me where's the problem in my code. I am using the stack to store the column and the "count" variable in the stack class to point me to which row.
package mynqueens;
public class MyNQueens {
public static int board[][] = new int[4][4];
public static int row,column;
public MyNQueens(){
}
public static void main(String[] args) {
check(0,0);
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
System.out.print(board[i][j] + "\t");
}
System.out.println();
}
}
public static void check(int i, int j ){
while(i<3){
board[i][j] = 1;
i++;
}
while(i!=0){
board[i][j] = 1;
i--;
}
while(j<3){
board[i][j]=1;
j++;
}
while(j!=0){
board[i][j] = 1;
j--;
}
while(j<3 || i<3){
board[i][j] = 1;
i++;
j++;
}
while(j!=0 || i!=0){
board[i][j] = 1;
i--;
j--;
}
while(i<3 || j!=0){
board[i][j]=1;
i++;
j--;
}
while(i!=0 || j<3){
board[i][j]=1;
i--;
j++;
}
}
}
Before you start erasing elements in inner while section
while(queenLoc.getTop() == bsize)
{
y = queenLoc.pop();
count--;
}
number of elements in queenStack will exceed bsize.
You have while(done == false && queenLoc.size() != bsize) so when size of queenLoc will be equal to bsize you will print result.
What I am saying is that after bsize steps you are always printing results.
Advise: Your code should have invariant "queenLoc represents position where no two queens attack each other".
import java.util.Scanner;
/**
*
* #author Manimekalai
*/
public class Queen {
public static boolean isConsistent(int[] q, int n)
{
for (int i = 0; i < n; i++)
{
if (q[i] == q[n]) return false; // same column
if ((q[i] - q[n]) == (n - i)) return false; // same major diagonal
if ((q[n] - q[i]) == (n - i)) return false; // same minor diagonal
}
return true;
}
public static void printQueens(int[] q)
{
int N = q.length;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
if (q[i] == j) System.out.print("Q ");
else System.out.print("* ");
}
System.out.println();
}
System.out.println();
}
public static void enumerate(int N)
{
int[] a = new int[N];
enumerate(a, 0);
}
public static void enumerate(int[] q, int n)
{
int N = q.length;
if (n == N) printQueens(q);
else
{
for (int i = 0; i < N; i++)
{
q[n] = i;
if (isConsistent(q, n)) enumerate(q, n+1);
}
}
}
public static void main(String[] args)
{
//int N = Integer.parseInt(args[0]);
System.out.println("Enter N value");
Scanner s=new Scanner(System.in);
int N=s.nextInt();
enumerate(N);
}
}

Categories