Solving Sudoku Programmatically - java

I'm attempting to solve a Sudoku puzzle using Java. Currently this class is unable to solve a Sudoku properly.
This class attempts to look for the 0s (blank spaces) within the 9x9 matrix and notes down the position of the 0 in a list for later referencing. Following which it will then use those positions to solve that one 0. Unfortunately, it does not seem to work as I'd hope.
Here is my 9x9 matrix that I used:
0 6 0 1 0 4 0 5 0
0 0 8 3 0 5 6 0 0
2 0 0 0 0 0 0 0 1
8 0 0 4 0 7 0 0 6
0 0 6 0 0 0 3 0 0
7 0 0 9 0 1 0 0 4
5 0 0 0 0 0 0 0 2
0 0 7 2 0 6 9 0 0
0 4 0 5 0 8 0 7 0
There are 51 0s in this 9x9 matrix, however when it solves the puzzle, it appends 66 positions for some weird reason. I can't seem to pinpoint the issue. Any help would be greatly appreciated!
This is the attempted solution that it spits out:
9 6 3 1 8 4 7 5 0
4 7 8 3 9 5 6 2 0
2 5 0 7 6 0 8 9 1
8 9 5 4 3 7 2 1 6
1 2 6 8 5 0 3 0 9
7 3 0 9 2 1 5 8 4
5 8 9 0 7 3 4 6 2
3 1 7 2 4 6 9 0 8
6 4 2 5 1 8 0 7 3
Code:
package com.dc.soduku;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Sudoku {
int[][] grid = new int[9][9];
int emptyCell = 0;
List<String> EmptyCells = new ArrayList<String>();
public Sudoku() {
for (int i = 0; i < 9; i++) {
for (int x = 0; x < 9; x++) {
Scanner scanner = new Scanner(System.in);
System.out.println("Row " + i + " Column " + x + " (Enter values from 1-9): ");
int temp = scanner.nextInt();
grid[i][x] = temp;
}
}
}
public Sudoku(int[][] gridInput) {
grid = gridInput;
}
public void emptyCellsChecker() {
int count = 0;
EmptyCells.clear();
for (int i = 0; i < 9; i++) {
for (int x = 0; x < 9; x++) {
if (grid[i][x] == 0) {
System.out.println("Blank at row " + i + " column " + x + ".");
count++;
EmptyCells.add(i + "," + x);
}
}
}
System.out.println("Total number of empty cells: " + count);
// System.out.print(mm.toString());
System.out.println((EmptyCells.get(1)).substring(0, 1));
System.out.println((EmptyCells.get(1)).substring(2, 3));
}
public void printSudoku() {
for (int i = 0; i < 9; i++) {
for (int x = 0; x < 9; x++) {
System.out.print(grid[i][x] + " ");
}
System.out.println("");
}
}
public void appendCell(int row, int col, int replacement) {
this.grid[row][col] = replacement;
}
public int getCell(int row, int col) {
return grid[row][col];
}
public boolean isEmpty() {
for (int i = 0; i < 9; i++) {
for (int x = 0; x < 9; x++) {
if (grid[i][x] == emptyCell) {
return true;
}
}
}
return false;
}
public boolean checkRow(int row, int guess) {
for (int i = 0; i < 9; i++) {
if (grid[row][i] == guess) {
return false;
}
}
return true;
}
public boolean checkColumn(int col, int guess) {
for (int i = 0; i < 9; i++) {
if (grid[i][col] == guess) {
return false;
}
}
return true;
}
public boolean checkBox(int row, int col, int guess) {
row = (row / 3) * 3;
col = (col / 3) * 3;
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 3; c++) {
if (grid[row + r][col + c] == guess) {
return false;
}
}
}
return true;
}
public boolean checkGuess(int row, int col, int guess) {
return (checkRow(row, guess) && checkColumn(col, guess) && checkBox(row, col, guess));
}
public void solve() {
int nEmptyCells = EmptyCells.size();
String tempR, tempC;
int tRow, tCol, counter = 0;
if (isEmpty() == false) {
System.out.println(
"Sudoku has no empty cells, you have either provided a solved sudoku or entered something incorrectly.");
} else {
for (int i = 0; i < nEmptyCells; i++) {
tempR = ((EmptyCells.get(i)).substring(0, 1));
tempC = ((EmptyCells.get(i)).substring(2, 3));
tRow = Integer.parseInt(tempR);
tCol = Integer.parseInt(tempC);
for (int v = 1; v < 10; v++) {
if (checkGuess(tRow, tCol, v) == true) {
this.grid[tRow][tCol] = v;
counter++;
System.out.println("Solved row " + tRow + " column " + tCol + " with " + v);
}
}
}
}
System.out.println("Total appended: " + counter);
}
}

This problem solved already as well by Backtracking algorithms:
Sudoku backtracking algorithm (Java)
Sudoku solving algorithm with back-tracking

Your question in a nutshell "For the given input why do I get 66 appends when there are only 51 empty cells?"
Your current algorithm:
For each empty cell in the grid
Use the current state of the grid
Guess each number 1 to 9
Verify current guess as a possible solution in col, row, and box
Update grid state with possible solution
Continue trying each number to 9
To answer your question you are accepting all possible solutions as solutions for a particular cell given the current state of the grid. According to your algorithm it correctly results in 66 solutions.
What you could do is:
Record all possible solutions for each empty cell in the grid without grid updates
Determine all permutations of possible solutions for the grid
Loop through all permutations and verify each permutation set as a solution to the grid

Related

Java print a pattern with nested for loop

I am struggling to build an algorithm that would print the much needed pattern.
The code is the following:
public static void printPatternH(int size)
{
for (int row = 1; row <= size; row++)
{
for (int col = 1; col <= 2*size; col++)
{
if (col > size + row - 1) {
continue;
}
if (col <= size) {
System.out.print((row + col >= size + 1 ? (row + col)%size : " ") + " ");
}
else {
System.out.print((row + col >= size + 1 ? (row + size)%col : " ") + " ");
}
}
System.out.println();
}
}
The result is:
I understand that if size is 9 the last number in the middle will be 0 as (row + size)%col = 0, however I couldn't figure out a way to modify it without changing the rest of the values.
Change
(row + col)%size
to
(row + col - 1) % size + 1
You can check for the "0" and replace it before printing it out:
if (col <= size) {
//print left hand side
int remainder = (row + col) % size;
if (remainder == 0) remainder = size; //replace the "0" with size here.
System.out.print((row + col >= size + 1 ? remainder : " ") + " ");
} else {
//print right hand side
System.out.print((row + col >= size + 1 ? (row + size) % col : " ") + " ");
}
It will give this output:
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
1 2 3 4 5 6 5 4 3 2 1
1 2 3 4 5 6 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1
public class Testb
{
int item = 9;
int limit = 5;
int half = item/2;
public static void main(String[] args)
{
//System.out.println("Hello World!");
for(int i=0;i<limit;i++){
for(int j=0;j<half;j++){
if(j<(half-i)){
print(" ");
}else{
print(j-(half-i))
}
}
print(i);
for(int k=half;k<(half+i);k++){
print((half+i)-(k+1));
}
println();
}
}
}
output:
0
0 1 0
0 1 2 1 0
0 1 2 3 2 1 0
0 1 2 3 4 3 2 1 0
int rowCount = 1;
System.out.println("Here Is Your Pyramid");
//Implementing the logic
for (int i = noOfRows; i > 0; i--)
{
//Printing i*2 spaces at the beginning of each row
for (int j = 1; j <= i*2; j++)
{
System.out.print(" ");
}
//Printing j value where j value will be from 1 to rowCount
for (int j = 1; j <= rowCount; j++)
{
System.out.print(j+" ");
}
//Printing j value where j value will be from rowCount-1 to 1
for (int j = rowCount-1; j >= 1; j--)
{
System.out.print(j+" ");
}
System.out.println();
//Incrementing the rowCount
rowCount++;
}

how can i generate 0's in stair case in 2d array?

In 2D array we can generate n*n matrix. and how can replace number into 0's replace in the matrix.
public static void main(String[] args) {
int rows = 8;
int coulmns = 4;
int array;
for (int i = 1; i < rows; i++) {
for (int j = 1; j < coulmns; j++) {
System.out.print(i*j+" ");
}
System.out.println("");
}
}
}
output:
1 2 3
2 4 6
3 6 9
4 8 12
5 10 15
6 12 18
7 14 21
how can i replace as 0's in stair case in the form of output:
1 2 (0)
2 (0) 6
(0) 6 9
4 (0) 12
5 10 (0)
6 (0) 18
(0) 14 21
I assume the language is Java as that is the tag specified.
import java.util.*;
import java.lang.*;
import java.io.*;
class StairCase
{
public static void main (String[] args) throws java.lang.Exception
{
int rows = 8;
int coulmns = 4;
int col=3;
int row=1;
int flag=0;
int array;
for (int i = 1; i < rows; i++) {
for (int j = 1; j < coulmns; j++) {
if(col==j && row==i){
System.out.print("(0)");
if(col>1 && col<4 && flag==0){
col--;
if(col==1){
flag=1;
}
row++;
}else{
col++;
if(col==3){
flag=0;
}
row++;
}
}else{
System.out.print(i*j+" ");
}
}
System.out.println("");
}
}
}
Result :
1 2 (0)
2 (0) 6
(0) 6 9
4 (0) 12
5 10 (0)
6 (0) 18
(0) 14 21
In the second for loop try doing this:
for (int j = 1; j < coulmns; j++) {
int number = i*j;
if(i == 3 || i == 7) number = 0;
else if((j == 3 && i == 1) || (j == 3 && i == 5)) number = 0;
else if((j == 2 && i == 2) || (j == 2 && i == 6)) number = 0;
else System.out.print(number + " ");
}
You can also use modulus if you want.
I assume the language is Java as that is the tag specified.
I think the solution will be to use modulus arithmetic.
You want to replace the value in the cell position (4 - row number % 4) with (0). Where (row number % 4) = 0 then the (0)always goes in the second cell. So the code is:
public static void main(String[] args) {
int rows = 8;
int coulmns = 4;
int array;
for (int i = 1; i < rows; i++) {
for (int j = 1; j < coulmns; j++){
if((j == (4 - (i % 4)) || (i % 4 == 0 && j == 2)))
{
System.out.print("0 ");
}
else
{
System.out.print(i*j+" ");
}
}
System.out.println("");
}
}
}

Java Multidimensional Array Outprint

I dont understand, why these numbers are printed out. Shouldn't it just out print 3 2 1? Instead, it prints:
3
0
0
0
2
0
0
0
1
Thank you for your help :)
public static void main(String[] args) {
int i, j, n = 3;
int[][] polje = new int[n][n];
polje[0][0] = 3;
polje[1][1] = 2;
polje[2][2] = 1;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
System.out.print(polje[i][j] + " ");
System.out.println();
}
}
}
you have set likewise,
3 0 0
0 2 0
0 0 1
so obviously you get, 3 0 0 0 2 0 0 0 1
if you want to print only 3 2 1 then made this changes only,
if(i == j){
System.out.print(polje[i][j] + " ");
System.out.println();
}

How to print numbers in a triangle pattern?

Below is the pattern I would like to print in the console:
1
2 0 2
3 0 0 0 3
And below is the code I have right now. Each number should have 5 spaces between each other.
import java.util.Scanner;
public class Triangle {
public static void main(String args[]) {
System.out.println("Input the number of lines you want to print.");
Scanner a = new Scanner(System.in);
int n = a.nextInt();
int[] row = new int[0];
for(int i=0 ; i < n ; i++){
row = nextRow(row);
for(int j=0;j < n-i;j++){
//Padding For Triangle
System.out.print(" ");
}
//Output the values
for(int j=0 ; j < row.length ; j++){
System.out.print(row[j]+" ");
}
//Start New Line
System.out.println();
}
}
/*Find Values Of Next Row*/
public static int[] nextRow(int row[]){
int nextRow[] = new int [row.length+1];
nextRow[0] = row.length+1;
nextRow[nextRow.length-1] =row.length+1;
for(int i=1 ; i < nextRow.length-1 ; i++){
nextRow[i] = 0;
}
return nextRow;
}
}
Can anyone help me with this?
Here is some modified code. Its not complete and still something need to update your code to get desired result. That part I am leaving it for you. I also left hint in code so that you could modify.
1.
// Padding For Triangle
System.out.print(" "); // 6 white space
2.
System.out.print(row[k]);
System.out.print(" "); // 5 white space
3.
/* Find Values Of Next Row */
#SuppressWarnings("null")
public static int[] nextRow(int row[]) {
int nextRow[] = null;
if (row.length == 0) {
nextRow = new int[1];
nextRow[0] = 1;
} else {
// count++; // Hint
nextRow = new int[row.length + 2];
for (int i = 0; i < nextRow.length; i++) {
if ((i == 0 || i == nextRow.length - 1)) {
nextRow[i] = nextRow.length - 2;
// nextRow[i] = count;
} else {
nextRow[i] = 0;
}
}
}
return nextRow;
}
If you have any questions, just ask. Good Luck.
You first have to identify the pattern that the output expects, which in your case is:
Row0, columns 1
Row1, columns 3
Row2, columns 5
Row3, columns 7
which is, rowNum*2+1
Based, on this, I modified your code and here is the working solution:
import java.util.Scanner;
public class Triangle{
public static void main(String args[]) {
System.out.println("Input the number of lines you want to print.");
Scanner a = new Scanner(System.in);
int n = a.nextInt();
int[] row = null;
for(int i=0 ; i < n ; i++){
row = nextRow(i);
for(int j=0;j < n-i;j++){
//Padding For Triangle
System.out.print(" ");
}
//Output the values
for(int j=0 ; j < row.length ; j++){
System.out.print(row[j]+" ");
}
//Start New Line
System.out.println();
}
}
/*Find Values Of Next Row*/
public static int[] nextRow(int rowNum){
int nextRow[] = new int [rowNum*2+1];
nextRow[0] = rowNum+1;//-rowNum/2;
nextRow[nextRow.length-1] = nextRow[0];
for(int i=1 ; i < nextRow.length-1 ; i++){
nextRow[i] = 0;
}
return nextRow;
}
}
And here is some output:
2:
1
2 0 2
5:
1
2 0 2
3 0 0 0 3
4 0 0 0 0 0 4
5 0 0 0 0 0 0 0 5
10:
1
2 0 2
3 0 0 0 3
4 0 0 0 0 0 4
5 0 0 0 0 0 0 0 5
6 0 0 0 0 0 0 0 0 0 6
7 0 0 0 0 0 0 0 0 0 0 0 7
8 0 0 0 0 0 0 0 0 0 0 0 0 0 8
9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 9
10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 10
i saw your code, i think that we can do this, follow is my modified code:
public class Triangle {
public static void main(String args[]) {
System.out.println("Input the number of lines you want to print.");
Scanner a = new Scanner(System.in);
int n = a.nextInt();
int [] row = new int[0];
for (int i = 0; i < n; i++) {
row = nextRow(row);
for (int j = 0; j < n - i; j++) {
// Padding For Triangle
System.out.print(" ");
}
// Output the values
for (int j = 0; j < row.length; j++) {
System.out.print(row[j] + " ");
}
// Start New Line
System.out.println();
}
}
/* set space between each other. */
public static String printSpace(int n) {
String result = "";
for (int i = 0; i < n; i++) {
result += " ";// 5 space
}
return result;
}
/* Find Values Of Next Row */
public static int [] nextRow(int row[]) {
int nextRow[] = new int[row.length + 1];
nextRow[0] = row.length + 1;
nextRow[nextRow.length - 1] = row.length + 1;
for (int i = 1; i < nextRow.length - 1; i++) {
nextRow[i] = 0;
}
return nextRow;
}
}
may be this is answer what you want.
Look up the arithmetic sequence for printing out the zeros, the rest should be trivial.

Pascal's Triangle Format [duplicate]

This question already has answers here:
Pascal's triangle 2d array - formatting printed output
(5 answers)
Closed 1 year ago.
The assignment is to create Pascal's Triangle without using arrays. I have the method that produces the values for the triangle below. The method accepts an integer for the maximum number of rows the user wants printed.
public static void triangle(int maxRows) {
int r, num;
for (int i = 0; i <= maxRows; i++) {
num = 1;
r = i + 1;
for (int col = 0; col <= i; col++) {
if (col > 0) {
num = num * (r - col) / col;
}
System.out.print(num + " ");
}
System.out.println();
}
}
I need to format the values of the triangle such that it looks like a triangle:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
I can't for the life of me figure out how to do that. Please answer keeping in mind that I'm a beginner in Java programming.
public static long pascalTriangle(int r, int k) {
if (r == 1 || k <= 1 || k >= r) return 1L;
return pascalTriangle(r - 1, k - 1) + pascalTriangle(r - 1, k);
}
This method allows you to find the k-th value of r-th row.
This is a good start, where it's homework, I'll leave the rest to you:
int maxRows = 6;
int r, num;
for (int i = 0; i <= maxRows; i++) {
num = 1;
r = i + 1;
//pre-spacing
for (int j = maxRows - i; j > 0; j--) {
System.out.print(" ");
}
for (int col = 0; col <= i; col++) {
if (col > 0) {
num = num * (r - col) / col;
}
System.out.print(num + " ");
}
System.out.println();
}
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
In each row you will need to print:
n spaces
m numbers
n spaces
Your job is to figure out n (which will be zero in the last line) and m based on row number.
[This is more like a comment but I needed more formatting options than comments provide]
You need to print the spaces (like others have mentioned) and also as this is homework I'm leaving it to you but you might want to look at this handy little function
System.out.printf();
Here is a handy reference guide
Also note that you will need to take into account that some numbers are more than 1 digit long!
import java.util.*;
class Mine {
public static void main(String ar[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 1; i < n; i++) {
int size = 1;
for (int j = 1; j <= i; j++) {
int a[] = new int[size];
int d[] = new int[size];
for (int k = 1; k <= size; k++) {
a[1] = 1;
a[size] = 1;
for (int p = 1; p <= size; p++) {
d[p] = a[p];
}
if (size >= 3) {
for (int m = 2; m < size; m++) {
a[m] = d[m] + d[m - 1];
}
}
}
for (int y = 0; y < size; y++) {
System.out.print(a[y]);
}
System.out.println(" ");
}
++size;
}
}
}
public class HelloWorld {
public static void main(String[] args) {
int s = 7;
int k = 1;
int r;
for (int i = 1; i <= s; i++) {
int num = 1;
r = i;
int col = 0;
for (int j = 1; j <= 2 * s - 1; j++) {
if (j <= s - i)
System.out.print(" ");
else if (j >= s + i)
System.out.print(" ");
else {
if (k % 2 == 0) {
System.out.print(" ");
} else {
if (col > 0) {
num = num * (r - col) / col;
}
System.out.print(num + " ");
col++;
}
k++;
}
}
System.out.println("");
k = 1;
}
}
}
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
You can try this code in java. It's simple :)
public class PascalTriangle {
public static void main(String[] args) {
int rows = 10;
for (int i = 0; i < rows; i++) {
int number = 1;
System.out.format("%" + (rows - i) * 2 + "s", "");
for (int j = 0; j <= i; j++) {
System.out.format("%4d", number);
number = number * (i - j) / (j + 1);
}
System.out.println();
}
}
}
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
Code perfectly prints pascal triangle:
public static void main(String[] args) {
int a, num;
for (int i = 0; i <= 4; i++) {
num = 1;
a = i + 1;
for (int j = 4; j > 0; j--) {
if (j > i)
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
if (j > 0)
num = num * (a - j) / j;
System.out.print(num + " ");
}
System.out.println();
}
}
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

Categories

Resources