Skip to content

Instantly share code, notes, and snippets.

@amnn
Last active September 6, 2015 20:55
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 amnn/5e33418727549dfbb297 to your computer and use it in GitHub Desktop.
Save amnn/5e33418727549dfbb297 to your computer and use it in GitHub Desktop.
A class to print arbitrary Sudoku-style gride, given a list of numbers.
# A class to print arbitrary Sudoku-style grids, given a list of numbers
# Author: Ashok Menon, 01/09/2015
class Array
def surround(delim)
"#{delim}#{join delim}#{delim}"
end
end
class Grid
# Accepts a list of 81 numbers.
# The first 9 are treated as the first row, the 2nd 9 as the 2nd row etc.
# A value of 0 signifies an empty position in the grid.
def initialize(nums)
unless nums.length == NUM_ELEMS
raise ArgumentError, "#{NUM_ELEMS} numbers required, I was given #{nums.length}"
end
@grid = nums.each_slice(GRID_WIDTH).to_a
end
def to_s
@grid.each_slice(BOX_HEIGHT).map do |row_of_boxes|
row_of_boxes.map do |row|
row.each_slice(BOX_WIDTH).map do |box_row|
box_row.map do |digit|
digit == 0 ? '.' : digit.to_s
end.surround(" " * NUM_PAD)
end.surround("|")
end.surround("\n")
end.surround(H_BORDER)
end
BOX_WIDTH = 3
BOX_HEIGHT = 3
BOX_HCOUNT = 3
BOX_VCOUNT = 3
GRID_WIDTH = BOX_WIDTH * BOX_HCOUNT
GRID_HEIGHT = BOX_HEIGHT * BOX_VCOUNT
NUM_ELEMS = GRID_WIDTH * GRID_HEIGHT
private
NUM_PAD = 1
BOX_H_BORDER = "-" * (NUM_PAD + (1 + NUM_PAD) * BOX_WIDTH)
H_BORDER = ([BOX_H_BORDER] * BOX_HCOUNT).surround("+")
end
if ARGV.length != 1
puts "Usage: $ ruby #{__FILE__} [#{Grid::NUM_ELEMS} numbers, no spaces]"
exit
end
input = ARGV.first.split("").map(&:to_i)
puts Grid.new(input).to_s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment