Skip to content

Instantly share code, notes, and snippets.

@jmsaavedra
Created June 20, 2015 00:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmsaavedra/b6a0d1f0f450b1ea16db to your computer and use it in GitHub Desktop.
Save jmsaavedra/b6a0d1f0f450b1ea16db to your computer and use it in GitHub Desktop.
sudoku
import java.io.*;
import java.util.*;
/**
made this work.
- joe
**/
class Solution {
/***
* check all rows and cols for solution
*/
public static boolean isSolved(int[][] puzz) {
//first go through each row, easy
for(int i=0; i<9; i++){
boolean eval = checkSet(puzz[i]);
//System.out.println("row: "+ i + " has solution? "+eval);
if(eval){
System.out.println("found solution on row: "+i);
return true;
}
}
//now go through each column, little trickier
for(int i=0; i<9; i++){
int[] thisCol = new int[9];
for(int j=0; j<9; j++)
thisCol[j] = puzz[j][i]; //populate this column array
boolean eval = checkSet(thisCol);
//System.out.println("col: "+ i + " has solution? "+eval);
if(eval){
System.out.println("found solution on column: "+i);
return true;
}
}
return false;
}
/***
* check any set of 9 integers (any 1 col or row)
*/
public static boolean checkSet(int[] set){
int[] solution = {1,2,3,4,5,6,7,8,9};
for(int i=0; i<set.length; i++){
for(int j=0; j<solution.length; j++){
if(set[i] == solution[j])
solution[j] = 0;
}
}
for(int i=0; i<solution.length; i++){
if(solution[i] != 0)
return false;
}
return true;
}
/***
* main
*/
public static void main(String[] args) {
System.out.println("\n\n\n-------------\nWELCOME TO SNAPDOKU\n-------------\n");
int[][] puzzleAttempt = {
{1, 5, 7, 4, 9, 2, 6, 3, 3},
{2, 1, 1, 1, 8, 1, 1, 1, 1},
{2, 1, 1, 1, 7, 1, 1, 1, 1},
{4, 1, 1, 1, 6, 1, 1, 1, 1},
{5, 1, 1, 1, 5, 1, 1, 1, 1},
{6, 1, 1, 1, 4, 1, 1, 1, 1},
{8, 8, 6, 1, 3, 3, 2, 1, 9},
{7, 1, 1, 1, 2, 1, 1, 1, 1},
{9, 1, 1, 1, 1, 1, 1, 1, 1}
};
if(isSolved(puzzleAttempt))
System.out.println("\nWELL DONE, PUZZLE SOLVED. ");
else
System.out.println("\nNOPE, GET BETTER AT NUMBERS.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment