Skip to content

Instantly share code, notes, and snippets.

@elskwid
Created October 14, 2009 16:26
Show Gist options
  • Save elskwid/210200 to your computer and use it in GitHub Desktop.
Save elskwid/210200 to your computer and use it in GitHub Desktop.
sudoku mathy matrix
require 'pp'
# create an array of values for a sudoku grid
# and extract the grids as subarrays in the
# correct order.
#
# 4x4 = 4 grids of 4 cells
# 6x6 = 6 grids of 6 cells
# 9x9 = 9 grids of 9 cells
# etc
#
# 9x9 example:
#
# 1 2 3 | 4 5 6 | 7 8 9
# 10 11 12 | 13 14 15 | 16 17 18
# 19 20 21 | 22 23 24 | 25 26 27
# ------------------------------
# 28 29 30 | 31 32 33 | 34 35 36
# 37 38 39 | 40 41 42 | 43 44 45
# 46 47 48 | 49 50 51 | 52 53 54
# ------------------------------
# 55 56 57 | 58 59 60 | 61 62 63
# 64 65 66 | 67 68 69 | 70 71 72
# 73 74 75 | 76 77 78 | 79 80 81
#
# in the 9x9 case the result arrays would be:
#
# [[1, 2, 3, 10, 11, 12, 19, 20, 21]]
# [[4, 5, 6, 13, 14, 15, 22, 23, 24]]
# [[7, 8, 9, 16, 17, 18, 25, 26, 27]]
# [[28, 29, 30, 37, 38, 39, 46, 47, 48]]
# [[31, 32, 33, 40, 41, 42, 49, 50, 51]]
# [[34, 35, 36, 43, 44, 45, 52, 53, 54]]
# [[55, 56, 57, 64, 65, 66, 73, 74, 75]]
# [[58, 59, 60, 67, 68, 69, 76, 77, 78]]
# [[61, 62, 63, 70, 71, 72, 79, 80, 81]]
#
# for this exercise, break each grid array
# down into grid rows like:
#
# [[1, 2, 3], [10, 11, 12], [19, 20, 21]]
#
# setup
cols = 9
subcols = 3
rows = cols
grids = cols
rows_per_grid = (cols/subcols)
puts "#{cols}x#{rows} (#{subcols} column)"
# generate the matrix
matrix = []
(cols * rows).times{ |i| matrix << i+1 }
# create the grids
matrix_grids = []
grids.times{ matrix_grids << [] }
matrix.each_with_index do |cell, i|
row = i/cols
col = i-(row*cols)
grid_col = col/subcols
grid_row = row/rows_per_grid
grid = grid_col + ((grid_row)*rows_per_grid)
# puts "#{col}, #{row} = #{cell}"
matrix_grids[grid] << cell
end
# display them as subarrays of the grid
matrix_grids.each_with_index do |g,i|
puts "#{i}: #{g.each_slice(subcols).to_a.inspect}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment