This game uses a 2d array(7x7) and uses two array lists to store the ship (of lengths 2,3,4) and user guesses. The user first types the row and column of each ship and the orientation (either extending down or right). Then a blank board is printed to console and the user will guess row and column. If there is a ship in that spot "hit!" is printed to console, else "miss!" is printed. After each guess, the new state of the board is printed where each hit is a "X" and each miss is a "M". also each guess is added to the guess array list. once the user guesses where each element of the ship is, the game is over and the guess history is printed. My code seems to be working however I am having trouble ending the game. It never gets out of the while loop in the main. Here is my code, is there something that I am doing wrong or need to change?
===========================================================================
My code:
class Ship {
int x;
int y;
//String orient;
public Ship (int x, int y) {
super();
this.x = x;
this.y = y;
//this.orient = orient;
}
}
class Guess {
int row;
int col;
public Guess (int row, int col) {
super();
this.row = row;
this.col = col;
}
}
public class CS125_Project5
{
//create the 2d arrays for the realBoard where the user will add the ships
// and the guessBoard which will update when user makes guesses
/////////what i had at first but kept getting nullpointerexception
//static String realBoard[][];
//static String guessBoard[][];
//with these i get the thing printed but it says null for all values
static String gameBoard[][] = new String[7][7];
static String guessBoard[][] = new String[7][7];
//creating the arrayList for both ships and guesses
static ArrayList<Ship> ships = new ArrayList<>();
static ArrayList<Guess> guesses = new ArrayList<>();
////////////////////////////////////////////////////////
////// Constructor
////////////////////////////////////////////////////////
public CS125_Project5() {
//initializing the arrays to have a fixed size of 7x7
//realBoard = new String[7][7];
//guessBoard = new String[7][7];
ships = new ArrayList<>();
guesses = new ArrayList<>();
//adding a '-' to each element of the 2d arrays for both boards
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
gameBoard[i][j] = "-";
guessBoard[i][j] = "-";
}
}
}
////////////////////////////////////////////////////////
/////// Method to Print the game maker board
////////////////////////////////////////////////////////
public static void printGameMakerBoard(){
System.out.print("r\\c\t");
//printing the column numbers
for(int i=0;i<7;i++){
System.out.print(i+"\t");
}
//printing the row numbers
System.out.println();
//printing the gameMaker board to show user what the board looks like
for(int i=0;i<7;i++){
System.out.print(i+"\t");
for(int j=0;j<7;j++){
System.out.print(gameBoard[i][j] +"\t");
}
System.out.println();
}
}
public static void updateBoard(int row, int col, String orient, int length) {
//if statement to determine orientation of ship
if (orient.contains("r")) {
int updateCol;
for (int j = 0; j < length; j++) {
updateCol = j + col;
gameBoard[row][updateCol] = "S";
}
} else {
int updateRow;
for (int j = 0; j < length; j++) {
updateRow = row + j;
gameBoard[updateRow][col] = "S";
}
}
printBoard(gameBoard);
}
public static void printBoard(String[][] board) {
System.out.print("r\\c"+"\t");
//printing the column numbers
for(int i=0;i<7;i++){
System.out.print(i+"\t");
}
System.out.println();
//printing the row numbers
// printing the guess board
for(int i=0;i<7;i++){
System.out.print(i+"\t");
for(int j=0;j<7;j++){
System.out.print(board[i][j] +"\t");
}
System.out.println();
}
}
private static void addShip(int x, int y, int length, String orient) {
gameBoard[x][y] = "S";
if (length == 2 || length == 3 || length == 4) {
if (orient.contains("d")) {
for (int i = 0; i < length; i++) {
Ship ship = new Ship(x, y+i);
ships.add(ship);
}
} else { //orient.contains("s")
for (int j = 0; j < length; j++) {
Ship ship = new Ship(x+j, y);
ships.add(ship);
}
}
}
// Ship ship = new Ship(x, y);
// ships.add(ship);
}
public void guess(int x, int y) {
//adding user guesses to ArrayList
Guess g = new Guess(x , y);
guesses.add(g);
//check to see if hit or miss, if hit replace user guess with 'X'
// else if its a miss replace guess with 'M'
if (gameBoard[x][y] == "S") {
guessBoard[x][y] = "X";
System.out.println("Hit!");
//now remove the ship from the list
for(int i = 0; i < ships.size(); i++) {
Ship ship = ships.get(i);
if (ship.x== x && ship.y == y){
ships.remove(i);
break;
}
}
} else {
guessBoard[x][y] = "M";
System.out.println("Miss!");
}
}
public static boolean gameOver() {
if(ships.size() == 0) {
return true;
} return false;
}
public static void printGuesses() {
System.out.println("Guess || Row Col");
System.out.println("=====================");
for(int i = 0; i < guesses.size(); i++) {
Guess g = guesses.get(i);
System.out.println(" " + i + " || " + g.row + " " + g.col);
}
}
////////////////////////////////////////////////////////
////// Main
////////////////////////////////////////////////////////
public static void main(String[] args)
{
// Your program should always output your name and the project number.
// DO NOT DELETE OR COMMENT OUT. Replace with relevant info.
System.out.println("Mason Sarna");
System.out.println("Project 5");
System.out.println("");
// Your code should go below this line
System.out.println("------------Welcome to BattleShip------------");
//printGameMakerBoard();
CS125_Project5 userShip = new CS125_Project5();
//CS125_Project5.printGameMakerBoard();
printBoard(guessBoard);
// create scanner
Scanner sc = new Scanner(System.in);
//initializing variables
int row = 0;
int col = 0;
String orient = "";
int length = 0;
/////////////////////
// Getting user input for row, col, and orientation of 3 different ships, updates/prints the board after each ship input
for (int i = 2; i < 5; i++) {
System.out.println("Please enter coordinates for ship of length "+ i);
System.out.println("Starting Row (0-6):");
row = sc.nextInt();
System.out.println("Starting column (0-6):");
col = sc.nextInt();
System.out.println("From the starting point, extend down or right? (d/r):");
orient = sc.next().toLowerCase();
length = i;
//CS125_Project5.updateBoard(row, col, orient, length);
updateBoard(row,col,orient,length);
CS125_Project5.addShip(row,col, i, orient);
}
System.out.println();
System.out.println("------------Final Game Maker Board------------");
CS125_Project5.printGameMakerBoard();
System.out.println();
System.out.println();
System.out.println("------------GAME STARTING NOW------------");
printBoard(guessBoard);
while(!gameOver()) {
System.out.println("Enter guess in row/col:");
int r = sc.nextInt();
int c = sc.nextInt();
if (guesses.contains(r) && guesses.contains(c)) {
System.out.println("r\\c = " + r + "\\" + c + " has already been guessed");
} else {
userShip.guess(r, c);
CS125_Project5.printBoard(guessBoard);
}
System.out.println("---------------------------------------------------");
}
System.out.println("------------Game Over------------");
CS125_Project5.printGuesses();
}
Related
so basically I've been making a minesweeper clone in Java. I had it working perfectly until I added the game win and lose parts and the big opening print. Now when I run it some of the spots that are next to zero's don't get revealed, even though they should. I can't figure out where the bug is though. Here's my code:
/**
* A program to play Scat Scout...
*/
import static java.lang.System.*; // so you can write out.println() instead of System.out.println()
import java.util.*;
class ScatScout {
static final int boardSize = 10;
static final Random rand = new Random();
static final boolean SCAT = true;
static final boolean CLEAR = false;
static int clearCounter = 100;
static boolean gameWon = false;
static boolean gameLost = false;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean[][] board = new boolean[boardSize+2][boardSize+2]; // scat or no scat
boolean[][] exposed = new boolean[boardSize+2][boardSize+2]; // showing or hidden
int[][] counts = new int[boardSize+2][boardSize+2]; // number of neighbors with scat
if (args.length > 0) {
rand.setSeed(Integer.parseInt(args[0]));
}
System.out.println("comment explaining game");
createScat(board); //initialize the board
compareScat(board, counts); //find how many scat are next to each spot
while(!gameWon&&!gameLost){ //keep going until game win or loss
printBoard(board, counts, exposed);
System.out.println("Enter two integers (row and column):");
expose(input.nextInt()+1, input.nextInt()+1, board, exposed, counts);
if (gameLost){
for (int i = 1; i<= board.length-2; i++){
for (int j = 1; j<= board.length-2; j++){
if (!board[i][j]){
exposed[i][j] = true;
}
}
}
printBoard(board, counts, exposed);
System.out.print("You stepped in it! Yucky!"); //game lose
break;
}
gameWon = true; //game is one if all blanks but the bombs are exposed
for(int i = 1; i<= board.length-2; i++){
for(int j = 1; j<= board[0].length-2; j++){
if(!exposed[i][j]&&!board[i][j]){
gameWon=false; //otherwise continue loop
}
}
}
if (gameWon){
System.out.print("You cleared the scat! Congrats!"); //game win message
break;
}
}
input.close();
}
public static void printBoard(boolean[][] board, int[][] counts, boolean[][] exposed){ //initialize board
int numRows = counts.length;
int numCols = counts[0].length;
System.out.println(" 0123456789"); //print the border
for(int i=1; i<=numRows-2; i++){
System.out.print(i-1 + " "); //border
for(int j=1; j<=numCols-2; j++){
if (exposed[i][j] == true){
System.out.print(counts[i][j]); //print the scat near a spot if it's exposed
}
else{
System.out.print("*"); //print unknown spot
}
}
System.out.print(" ");
System.out.print(i-1); //border
System.out.println(" ");
}
System.out.println(" 0123456789"); //border
}
public static void createScat(boolean[][] board){ //randomly seed scat into field
for(int i=1; i<= board.length-2; i++){
int x = rand.nextInt(board.length-3)+1;
int y = rand.nextInt(board.length-3)+1;
if(x!=0&&x!=11&&y!=0&&y!=11&&board[x][y]==CLEAR){
board[x][y]=SCAT; //scat in this random spot
}
}
}
public static void compareScat(boolean[][] board, int[][] counts){ //checks #scat in surrounding spots
int numRows = counts.length;
int numCols = counts[0].length;
for(int i=1; i<=numRows-2; i++){
for(int j=1; j<=numCols-2; j++){
for(int ii=i-1; ii<=i+1; ii++){
for(int jj=j-1; jj<=j+1; jj++){
if(board[ii][jj]==SCAT){ //this looks at all scat in all directions around the original spot
counts[i][j]=counts[i][j]+1; //adds to the counter if scat found around it
}
}
}
}
}
}
static void expose(int c, int r, boolean[][] board, boolean[][] exposed, int[][] counts) { //exposes chosen spot
if (exposed[r][c]) return; // nothing to do
if (board[r][c]== SCAT){
gameLost=true; //lose game if choose a spot with scat
}
exposed[r][c] = true; // expose any neighbors that have zero counts
if (counts[r][c] > 0) return;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
int x = r+i;
int y = c+j;
if (!(i==1 && j==1) && x >= 1 && x < board.length-1 && y >= 1 && y < board[x].length-1) {
if (counts[x][y] == 0) {
expose(x, y, board, exposed, counts);
}
else {
exposed[x][y] = true;
}
}
}
}
}
}
Basically, the project description asks the user to create a matching game, consisting of:
A two dimensional playing table (4x4), 16 pairs of matching cards, and a running count of the number of face-down cards. Include a method to retrieve a specific card from the table at an input x,y position.
A gameBoard, and loop that continues play until all cards remain face up.
The loop includes an interface with the user to pick two cards (inputting x,y table positions), checking if two cards are equal,
decrementing the count of faceDown cards, and setting the faceUp boolean of the cards.
Essnetially, the program should run until all the cards are face up, and the game is won. I separated my program in to four separate classes below.
1.
public class Card {
private final int cardValue;
private boolean faceUp;
public Card(int value) {
cardValue = value;
faceUp = false;
}
public int getValue() {
return cardValue;
}
public boolean isFaceUp() {
return faceUp;
}
public void setFaceUp(boolean input) {
faceUp = input;
}
public static void printBoard(Card[][] cards) {
System.out.println("\t\t1\t2\t3\t4");
System.out.println("\t____________");
for(int i = 0; i < cards.length; i++) {
System.out.println((i + 1) + "\t|\t");
for(int j = 0; j < cards[0].length; j++)
if(cards[i][j].isFaceUp()) {
System.out.print(cards[i][j].getValue() + "\t"); }
else
System.out.println("*\t");
}
System.out.println();
}
}
2.
public class CreateBoard {
public static Card[][] createBoard() {
Card[][] board = new Card[4][4];
for(int i = 1; i <= 8; i++) {
for(int j = 1; j <= 2; j++) {
boolean boardLocation = false;
while(!boardLocation) {
int row = (int)(Math.random() * 4);
int column = (int)(Math.random() * 4);
if(board[row] == null && board[column] == null) {
boardLocation = true;
board[row][column] = new Card(i);
}
}
}
}
return board;
}
}
3.
public class Game {
public static boolean wonGame(Card[][] board) {
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[0].length; j++) {
if(!board[i][j].isFaceUp())
return false;
}
}
return true;
}
}
And finally, the main class:
public class GameDriver {
public static void main(String[] args) {
Card[][] board = CreateBoard.createBoard();
Scanner keyboard = new Scanner(System.in);
System.out.println("Starting Game...");
while(!Game.wonGame(board)) {
Card.printBoard(board);
System.out.println("Enter X-Coordinate #1 (1-4): ");
int column1 = keyboard.nextInt();
System.out.println("Enter Y-Coordinate #1 (1-4): ");
int row1 = keyboard.nextInt();
System.out.println("Enter X-Coordinate #2 (1-4): ");
int column2 = keyboard.nextInt();
System.out.println("Enter Y-Coordinate #2 (1-4): ");
int row2 = keyboard.nextInt();
Card card1 = board[row1][column1];
Card card2 = board[row2][column2];
if(card1.getValue() == card2.getValue() && !(row1 == row2 && column1 == column2))
{
card1.setFaceUp(true);
card2.setFaceUp(true);
}
else if(row1 == row2 && column1 == column2)
{
System.out.println("Points selected are the same, try again");
}
else
{
System.out.println(card1.getValue() + " and " + card2.getValue() + " do not match");
}
}
Card.printBoard(board);
}
}
The code seems to run fine, no errors or anything. However, after multiple test trials, the glaring issue is that it does not output anything to console... Am I missing something? Help would be appreciated!
Create board should be
public class CreateBoard {
public static Card[][] createBoard() {
Card[][] board = new Card[4][4];
for(int i = 1; i <= 8; i++) {
for(int j = 1; j <= 2; j++) {
boolean boardLocation = false;
while(!boardLocation) {
int row = (int)(Math.random() * 4);
int column = (int)(Math.random() * 4);
if(board[row][column] == null) {
boardLocation = true;
board[row][column] = new Card(i);
}
}
}
}
return board;
}
}
And for the Game class, since java array index is starting with 0 then
these lines should be
Card card1 = board[row1-1][column1-1];
Card card2 = board[row2-1][column2-1];
So I made this code using various snippets on the web so that I could see how it all works, But For some strange reason the 4th "For" loop is skipped entirely, And I'm not sure why. Any help would be appreciated. It is a command line using code.
public class New1
{
public static void main(String[] args) throws InterruptedException
{
Scanner in = new Scanner(System.in);
System.out.print("Enter number of clicks before repeat: ");
int Clicks = in.nextInt();
int rep2 = 0;
int Waits[] = new int[Clicks];
Clicks = Clicks * 2;
int Coords[] = new int[Clicks];
Clicks = Clicks / 2;
int Gung;
int Ho;
int Yo;
int xco = 0;
int yco = 1;
if(Clicks > 0)
{
for (int rep = 0; rep < Coords.length; rep++)
{
System.out.print("Enter x coord: ");
Coords[rep] = in.nextInt();
rep++;
System.out.println(" ");
System.out.print("Enter y coord: ");
Coords[rep] = in.nextInt();
System.out.println(" ");
System.out.print("Enter the pause (In seconds) between this click and the next click: ");
Waits[rep2] = in.nextInt();
rep2++;
System.out.println(" ");
}
rep2 = 0;
for (int rep3 = 0; rep3 < Waits.length; rep3++)
{
Waits[rep3] = Waits[rep3] * 1000;
}
System.out.print("How many times to repeat click sequence? : ");
int Revolutions = in.nextInt();
for (int counter = 0; counter > Revolutions; counter++)
{
for (int Flicks = 0; Flicks > Clicks; Flicks++)
{
Gung = Coords[xco];
Ho = Coords[yco];
Yo = Waits[Flicks];
Click(Gung, Ho);
Thread.sleep(Yo);
xco += 2;
yco += 2;
}
xco = 0;
yco = 1;
}
}
}
public static void Click(int x, int y)
{
Robot bot = null;
try
{
bot = new Robot();
}
catch (Exception failed)
{
System.err.println("Failed instantiating Robot: " + failed);
}
int mask = InputEvent.BUTTON1_DOWN_MASK;
bot.mouseMove(x, y);
bot.mousePress(mask);
bot.mouseRelease(mask);
}
public static void printArray(int arr[])
{
int n = arr.length;
for (int ar = 0; ar < n; ar++)
{
System.out.print(arr[ar] + " ");
}
System.out.println(" ");
}
}
Edit: The 4th "For" loop is
for (int Flicks = 0; Flicks > Clicks; Flicks++)
{
Gung = Coords[xco];
Ho = Coords[yco];
Yo = Waits[Flicks];
Click(Gung, Ho);
Thread.sleep(Yo);
xco += 2;
yco += 2;
}
The fourth for loop is:
public static void printArray(int arr[])
{
int n = arr.length;
for (int ar = 0; ar < n; ar++)
{
System.out.print(arr[ar] + " ");
}
System.out.println(" ");
}
As you can see it is inside a method called printArray(). There is nothing wrong with the array. It is just fine. The problem is that the method is never called thus the for loop never runs.
Here is a java methods tutorial.
//first way
System.out.println(Arrays.toString(arr));
//second way
for(int i : arr) {
System.out.print(i + " ");
}
//third way
for(int i = 0; i < arr.length; ++i) {
System.out.print(arr[i] + " ");
}
There three basic ways to print all elements in array. Advice: you should avoid using static methods, it is wrong in your case.
New1 task = new New1();
task.doSomething();
I am doing a game called 1010! Probably some of you have heard of it. Bascially I encouter some trouble when writing the Algorithm for clearance.
The rule is such that if any row or any column is occupied, then clear row and column respectively.
The scoring is such that each move gains a+10*b points. a is the number of square in the input piece p and b is the total number of row&column cleared.
To start, I create a two dimensional Array board[10][10], poulate each elements in the board[][] with an empty square.
In the class of Square, it has public void method of unset()-> "empty the square" & boolean status() -> "judge if square is empty"In the class of piece, it has int numofSquare -> "return the number of square in each piece for score calculation"
In particular, I don't know how to write it if both row and column are occupied as they are inter-cross each other in an two dimensional array.
It fail the test under some condition, in which some of the squares are not cleared but they should have been cleared and I am pretty sure is the logic problem.
My thinking is that:
Loop through squares in first row and first column, record the number of square that are occupied (using c and r); if both are 10, clear row&column, otherwise clear row or column or do nothing.
reset the c &r to 0, loop through square in the second row, second column…
update score.
Basically the hard part is that if I seperate clear column and clear row algorithm ,I will either judge row or column first then clear them . However, as every column contains at least one square belong to the row, and every row contains at least one square belong to the column, there will be mistake when both row and column are full.
Thanks for help.
import java.util.ArrayList;
public class GameState{
public static final int noOfSquares = 10;
// the extent of the board in both directions
public static final int noOfBoxes = 3;
// the number of boxes in the game
private Square[][] board; // the current state of the board
private Box[] boxes; // the current state of the boxes
private int score; // the current score
// initialise the instance variables for board
// all squares and all boxes are initially empty
public GameState()
{
getboard();
score = 0;
board = new Square[10][10];
for(int i =0;i<board.length;i++){
for(int j =0;j<board[i].length;j++){
board[i][j] = new Square();
}
}
boxes = new Box[3];
for(int k =0;k<boxes.length;k++){
boxes[k] = new Box();
}
}
// return the current state of the board
public Square[][] getBoard()
{
return board;
}
// return the current score
public int getScore()
{
return score;
}
// place p on the board with its (notional) top-left corner at Square x,y
// clear columns and rows as appropriate
int r =0;
int c = 0;
int rowandcolumn = 0;
for (int row=0;row<10;row++){
for (int column=0;column<10;column++) {
if (board[row][column].status() == true){
c = c + 1;
if( c == 10 ) {
rowandcolumn = rowandcolumn + 1;
for(int z=0;z<10;z++){
board[row][z].unset(); //Clear column
}
}
}
if (board[column][row].status() == true){
r = r + 1;
if( r == 10) {
rowandcolumn = rowandcolumn + 1;
for(int q=0;q<10;q++){
board[q][row].unset(); //Clear row
}
}
}
}
r=0; //reset
c=0;
}
score = score + p.numberofBox()+10*rowandcolumn;
}
how about this
void Background::liquidate(int &score){
int arr_flag[2][10]; //0 is row,1 is column。
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 10; j++)
{
arr_flag[i][j] = 1;
}
}
//column
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
if (arr[i][j].type == 0)
{
arr_flag[0][i] = 0;
break;
}
}
}
//row
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
if (arr[j][i].type == 0)
{
arr_flag[1][i] = 0;
break;
}
}
}
//clear column
for (int i = 0; i < 10; i++)
{
if (arr_flag[0][i] == 1)
{
for (int j = 0; j < 10; j++)
{
arr[i][j].Clear();
}
}
}
//clear row
for (int i = 0; i < 10; i++)
{
if (arr_flag[1][i] == 1)
{
for (int j = 0; j < 10; j++)
{
arr[j][i].Clear();
}
}
}
}
I tried to write somme code for the idea I posted
// place p on the board with its (notional) top-left corner at Square x,y
// clear columns and rows as appropriate
int r =0;
int c = 0;
int rowandcolumn = 0;
int row=FindFirstRow();
int column=FindFirstColumn();
if(row!=-1 && column!=-1)
{
rowandcolumn++;
//actions here: row found and column found
//clear row and column
clearRow(row);
clearColumn(column);
}
else if(row!=-1)
{
//only row is found
//clear row
clearRow(row);
}
else if(column!=-1)
{
//only column is found
//clear column
clearColumn(column);
}
else
{
//nothing is found
}
public void clearRow(int row)
{
for(int i=0; i<10;i++)
{
board[row][i].unset();
}
}
public void clearColumn(int column)
{
for(int i=0; i<10;i++)
{
board[i][column].unset();
}
}
//this method returns the first matching row index. If nothing is found it returns -1;
public int FindFirstRow()
{
for (int row=0;row<10;row++)
{
int r=0;
for (int column=0;column<10;column++)
{
if (board[row][column].status() == true)
{
r = r + 1;
if( r == 10)
{
//row found
return row;
}
}
}
r=0; //reset
}
//nothing found
return -1;
}
//this method returns the first matching column index. If nothing is found it returns -1;
public int FindFirstColumn()
{
for (int column=0;column<10;column++)
{
int c=0;
for (int row=0;row<10;row++)
{
if (board[row][column].status() == true)
{
c = c + 1;
if( c == 10 )
{
//matching column found
return column;
}
}
}
c=0; //reset
}
//nothing found
return -1;
}
In my last question seen here: Sudoku - Region testing I asked how to check the 3x3 regions and someone was able to give me a satisfactory answer (although it involved a LOT of tinkering to get it working how I wanted to, since they didn't mention what the class table_t was.)
I finished the project and was able to create a sudoku generator, but it feels like it's contrived. And I feel like I've somehow overcomplicated things by taking a very brute-force approach to generating the puzzles.
Essentially my goal is to create a 9x9 grid with 9- 3x3 regions. Each row / col / region must use the numbers 1-9 only once.
The way that I went about solving this was by using a 2-dimensional array to place numbers at random, 3 rows at a time. Once the 3 rows were done it would check the 3 rows, and 3 regions and each vertical col up to the 3rd position. As it iterated through it would do the same until the array was filled, but due to the fact that I was filling with rand, and checking each row / column / region multiple times it felt very inefficient.
Is there an "easier" way to go about doing this with any type of data construct aside from a 2d array? Is there an easier way to check each 3x3 region that might coincide with checking either vert or horizontal better? From a standpoint of computation I can't see too many ways to do it more efficiently without swelling the size of the code dramatically.
I built a sudoku game a while ago and used the dancing links algorithm by Donald Knuth to generate the puzzles. I found these sites very helpful in learning and implementing the algorithm
http://en.wikipedia.org/wiki/Dancing_Links
http://cgi.cse.unsw.edu.au/~xche635/dlx_sodoku/
http://garethrees.org/2007/06/10/zendoku-generation/
import java.util.Random;
import java.util.Scanner;
public class sudoku {
/**
* #antony
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int p = 1;
Random r = new Random();
int i1=r.nextInt(8);
int firstval = i1;
while (p == 1) {
int x = firstval, v = 1;
int a[][] = new int[9][9];
int b[][] = new int[9][9];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if ((x + j + v) <= 9)
a[i][j] = j + x + v;
else
a[i][j] = j + x + v - 9;
if (a[i][j] == 10)
a[i][j] = 1;
// System.out.print(a[i][j]+" ");
}
x += 3;
if (x >= 9)
x = x - 9;
// System.out.println();
if (i == 2) {
v = 2;
x = firstval;
}
if (i == 5) {
v = 3;
x = firstval;
}
}
int eorh;
Scanner in = new Scanner(System.in);
System.out
.println("hey lets play a game of sudoku:take down the question and replace the 0's with your digits and complete the game by re entering your answer");
System.out.println("enter your option 1.hard 2.easy");
eorh = in.nextInt();
switch (eorh) {
case 1:
b[0][0] = a[0][0];
b[8][8] = a[8][8];
b[0][3] = a[0][3];
b[0][4] = a[0][4];
b[1][2] = a[1][2];
b[1][3] = a[1][3];
b[1][6] = a[1][6];
b[1][7] = a[1][7];
b[2][0] = a[2][0];
b[2][4] = a[2][4];
b[2][8] = a[2][8];
b[3][2] = a[3][2];
b[3][8] = a[3][8];
b[4][2] = a[4][2];
b[4][3] = a[4][3];
b[4][5] = a[4][5];
b[4][6] = a[4][6];
b[5][0] = a[5][0];
b[5][6] = a[5][6];
b[6][0] = a[6][0];
b[6][4] = a[6][4];
b[6][8] = a[6][8];
b[7][1] = a[7][1];
b[7][2] = a[7][2];
b[7][5] = a[7][5];
b[7][6] = a[7][6];
b[8][4] = a[8][4];
b[8][5] = a[8][5];
b[0][0] = a[0][0];
b[8][8] = a[8][8];
break;
case 2:
b[0][3] = a[0][3];
b[0][4] = a[0][4];
b[1][2] = a[1][2];
b[1][3] = a[1][3];
b[1][6] = a[1][6];
b[1][7] = a[1][7];
b[1][8] = a[1][8];
b[2][0] = a[2][0];
b[2][4] = a[2][4];
b[2][8] = a[2][8];
b[3][2] = a[3][2];
b[3][5] = a[3][5];
b[3][8] = a[3][8];
b[4][0] = a[4][0];
b[4][2] = a[4][2];
b[4][3] = a[4][3];
b[4][4] = a[4][4];
b[4][5] = a[4][5];
b[4][6] = a[4][6];
b[5][0] = a[5][0];
b[5][1] = a[5][1];
b[5][4] = a[5][4];
b[5][6] = a[5][6];
b[6][0] = a[6][0];
b[6][4] = a[6][4];
b[6][6] = a[6][6];
b[6][8] = a[6][8];
b[7][0] = a[7][0];
b[7][1] = a[7][1];
b[7][2] = a[7][2];
b[7][5] = a[7][5];
b[7][6] = a[7][6];
b[8][2] = a[8][2];
b[8][4] = a[8][4];
b[8][5] = a[8][5];
break;
default:
System.out.println("entered option is incorrect");
break;
}
for (int y = 0; y < 9; y++) {
for (int z = 0; z < 9; z++) {
System.out.print(b[y][z] + " ");
}
System.out.println("");
}
System.out.println("enter your answer");
int c[][] = new int[9][9];
for (int y = 0; y < 9; y++) {
for (int z = 0; z < 9; z++) {
c[y][z] = in.nextInt();
}
}
for (int y = 0; y < 9; y++) {
for (int z = 0; z < 9; z++)
System.out.print(c[y][z] + " ");
System.out.println();
}
int q = 0;
for (int y = 0; y < 9; y++) {
for (int z = 0; z < 9; z++)
if (a[y][z] == c[y][z])
continue;
else {
q++;
break;
}
}
if (q == 0)
System.out
.println("the answer you have entered is correct well done");
else
System.out.println("oh wrong answer better luck next time");
System.out
.println("do you want to play a different game of sudoku(1/0)");
p = in.nextInt();
firstval=r.nextInt(8);
/*if (firstval > 8)
firstval -= 9;*/
}
}
}
I think you can use a 1D array, in much the same way a 1D array can model a binary tree. For example, to look at the value below a number, add 9 to the index.
I just made this up, but could something like this work?
private boolean makePuzzle(int [] puzzle, int i)
{
for (int x = 0; x< 10 ; x++)
{
if (//x satisfies all three conditions for the current square i)
{
puzzle[i]=x;
if (i==80) return true //terminal condition, x fits in the last square
else
if makePuzzle(puzzle, i++);//find the next x
return true;
}// even though x fit in this square, an x couldn't be
// found for some future square, try again with a new x
}
return false; //no value for x fit in the current square
}
public static void main(String[] args )
{
int[] puzzle = new int[80];
makePuzzle(puzzle,0);
// print out puzzle here
}
Edit: its been a while since I've used arrays in Java, sorry if I screwed up any syntax. Please consider it pseudo code :)
Here is the code as described below in my comment.
public class Sudoku
{
public int[] puzzle = new int[81];
private void makePuzzle(int[] puzzle, int i)
{
for (int x = 1; x< 10 ; x++)
{
puzzle[i]=x;
if(checkConstraints(puzzle))
{
if (i==80)//terminal condition
{
System.out.println(this);//print out the completed puzzle
puzzle[i]=0;
return;
}
else
makePuzzle(puzzle,i+1);//find a number for the next square
}
puzzle[i]=0;//this try didn't work, delete the evidence
}
}
private boolean checkConstraints(int[] puzzle)
{
int test;
//test that rows have unique values
for (int column=0; column<9; column++)
{
for (int row=0; row<9; row++)
{
test=puzzle[row+column*9];
for (int j=0;j<9;j++)
{
if(test!=0&& row!=j&&test==puzzle[j+column*9])
return false;
}
}
}
//test that columns have unique values
for (int column=0; column<9; column++)
{
for(int row=0; row<9; row++)
{
test=puzzle[column+row*9];
for (int j=0;j<9;j++)
{
if(test!=0&&row!=j&&test==puzzle[column+j*9])
return false;
}
}
}
//implement region test here
int[][] regions = new int[9][9];
int[] regionIndex ={0,3,6,27,30,33,54,57,60};
for (int region=0; region<9;region++) //for each region
{
int j =0;
for (int k=regionIndex[region];k<regionIndex[region]+27; k=(k%3==2?k+7:k+1))
{
regions[region][j]=puzzle[k];
j++;
}
}
for (int i=0;i<9;i++)//region counter
{
for (int j=0;j<9;j++)
{
for (int k=0;k<9;k++)
{
if (regions[i][j]!=0&&j!=k&®ions[i][j]==regions[i][k])
return false;
}
}
}
return true;
}
public String toString()
{
String string= "";
for (int i=0; i <9;i++)
{
for (int j = 0; j<9;j++)
{
string = string+puzzle[i*9+j];
}
string =string +"\n";
}
return string;
}
public static void main(String[] args)
{
Sudoku sudoku=new Sudoku();
sudoku.makePuzzle(sudoku.puzzle, 0);
}
}
Try this code:
package com;
public class Suduku{
public static void main(String[] args ){
int k=0;
int fillCount =1;
int subGrid=1;
int N=3;
int[][] a=new int[N*N][N*N];
for (int i=0;i<N*N;i++){
if(k==N){
k=1;
subGrid++;
fillCount=subGrid;
}else{
k++;
if(i!=0)
fillCount=fillCount+N;
}
for(int j=0;j<N*N;j++){
if(fillCount==N*N){
a[i][j]=fillCount;
fillCount=1;
System.out.print(" "+a[i][j]);
}else{
a[i][j]=fillCount++;
System.out.print(" "+a[i][j]);
}
}
System.out.println();
}
}
}