Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #################################
- ### Sudoku Generator ###
- #################################
- # #
- # Generates a 9x9 Sudoku puzzle.#
- # #
- #################################
- class Board
- def initialize()
- @grid = Array.new(81) { 0 }
- end
- # coordinates is a list [x,y]
- def toBoard(value,coordinates)
- index = (coordinates[0]*9)+(coordinates[1])
- @grid[index] = value
- end
- # get value at [x,y] coordinates
- def getVal(coordinates)
- index = (coordinates[0]*9)+(coordinates[1])
- return @grid[index]
- end
- # print full board
- def show
- (0..80).step(9) do |i|
- print @grid[i..i+8].to_s+"\n"
- end
- end
- # check for conflicts in grid
- def check
- end
- end
- # test if number at coordinate valid
- def validNumber(sudoku, num, coordinates)
- # create list of numbers in same column
- colNums = []
- (0..8).each do |i|
- colNums[i] = sudoku.getVal([i,coordinates[1]])
- end
- # create list of numbers in same row
- rowNums = []
- (0..8).each do |i|
- rowNums[i] = sudoku.getVal([coordinates[0],i])
- end
- if ! colNums.include?(num) and ! rowNums.include?(num)
- return true
- else
- return false
- end
- end
- # get random valid number
- def getNumber(sudoku, coordinates)
- numPool = [1,2,3,4,5,6,7,8,9]
- num = numPool.sample
- while true do
- if validNumber(sudoku, num, coordinates) == true
- return num
- else
- numPool.delete!(num)
- num = numPool.sample
- end
- end
- end
- def indexToCoord(index)
- y = index % 9
- x = (index - y)/9
- coordinates = [x,y]
- return coordinates
- end
- sudoku = Board.new()
- @grid.each_with_index do |cell, index|
- sudoku.toBoard(getNumber(sudoku,indexToCoord(index)))
- end
- print sudoku
Advertisement
Add Comment
Please, Sign In to add comment