Translate

Monday, 4 April 2016

Sudoku-The Number Logic Puzzle 

Sudoku Generator

This class will generate the sudoku puzzle.

package com.vikesh.gamesudoku;

import java.util.ArrayList;
import java.util.Random;

import android.graphics.Color;

public class SudokuGenerator {

private ArrayList<ArrayList<Integer>> Available = new ArrayList<ArrayList<Integer>>();
private static SudokuGenerator instance;
private Random rand = new Random();
private SudokuGenerator()
{
}
public static SudokuGenerator getInstance()
{
if(instance==null)
{
instance = new SudokuGenerator();
}
return instance;
}
public int[][] generateGrid()
{
int[][] sudoku = new int[9][9];
int currentPos = 0;
while(currentPos < 81)
{
if( currentPos == 0 ){
clearGrid(sudoku);
}
if(Available.get(currentPos).size()!=0)
{
int i = rand.nextInt(Available.get(currentPos).size());
int number = Available.get(currentPos).get(i);
if(!checkConflict(sudoku, currentPos,number))
{
int xpos = currentPos%9;
int ypos = currentPos/9;
sudoku[xpos][ypos] = number;
Available.get(currentPos).remove(i);
currentPos++;
}
else
{
Available.get(currentPos).remove(i);
}
}
else
{
for(int i = 1; i<=9; i++)
{
Available.get(currentPos).add(i);
}
currentPos--;
}
}
return sudoku;
}
public int[][] removeElements(int[][] sudoku)
{
int i=0;
while(i<Game.Difficulty_Level)
{
int x = rand.nextInt(9);
int y = rand.nextInt(9);
if(sudoku[x][y]!=0)
{
sudoku[x][y] = 0;
}
i++;
}
return sudoku;
}
private void clearGrid(int[][] sudoku)
{
Available.clear();
for(int y =0; y<9; y++)
{
for(int x = 0; x<9; x++)
{
sudoku[x][y] = -1;
}
}
for(int x=0;x<81;x++)
{
Available.add(new ArrayList<Integer>());
for(int i=1;i<=9;i++)
{
Available.get(x).add(i);
}
}
}
private boolean checkConflict(int[][] sudoku,int currentPos,final int number)
{
int xpos = currentPos%9;
int ypos = currentPos/9;
if(checkHorizontalConflict(sudoku, xpos, ypos, number)||checkVerticalConflict(sudoku, xpos, ypos, number)||checkRegionConflict(sudoku, xpos, ypos, number))
{
return true;
}
return false;
}
private boolean checkHorizontalConflict(final int[][] sudoku,final int xpos,final int ypos,final int number)
{
for(int x = xpos-1;x>=0;x--)
{
if(number == sudoku[x][ypos])
{
return true;
}
}
return false;
}
private boolean checkVerticalConflict(final int[][] sudoku,final int xpos,final int ypos,final int number)
{
for(int y=ypos;y>=0;y--)
{
if(number==sudoku[xpos][y])
{
return true;
}
}
return false;
}
private boolean checkRegionConflict(final int[][] sudoku,final int xpos,final int ypos,final int number)
{
int xRegion = xpos/3;
int yRegion = ypos/3;
for(int x = xRegion*3;x<xRegion*3+3;x++)
{
for(int y = yRegion*3;y<yRegion*3+3;y++)
{
if((x!=xpos || y!=ypos) && number==sudoku[x][y])
{
return true;
}
}
}
return false;
}
}

No comments:

Post a Comment