Created
September 27, 2018 08:40
-
-
Save kirikiriyamama/1ace0d3aac60a560c670766690b072ef to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Sudoku | |
def initialize(matrix) | |
@matrix = matrix.split("\n").map(&:chars) | |
end | |
def run | |
show | |
step while @matrix.flatten.include?(' ') | |
end | |
def step | |
@matrix.each_with_index do |l, i| | |
l.each_with_index do |c, j| | |
next if c != ' ' | |
candidates = ('1'..'9').to_a | |
candidates.reject! do |n| | |
l.include?(n) \ | |
|| @matrix.map { |l| l[j] }.include?(n) \ | |
|| @matrix.slice(i - (i - ((i / 3) * 3)), 3).map { |l| | |
l.slice(j - (j - ((j / 3) * 3)), 3) | |
}.flatten.include?(n) | |
end | |
if candidates.count == 1 | |
@matrix[i][j] = candidates.first | |
print "\n" | |
show([i, j]) | |
end | |
end | |
end | |
end | |
def show(changed = []) | |
# print "\e[2J\e[1;1H" | |
print "+---+---+---\e[1m+\e[0m---+---+---\e[1m+\e[0m---+---+---+\n" | |
@matrix.each_with_index do |l, i| | |
print "|" | |
l.each_with_index do |c, j| | |
if [i, j] == changed | |
print " \e[33m#{c}\e[0m " | |
else | |
print " #{c} " | |
end | |
print "\e[1m" if j == 2 || j == 5 | |
print "|" | |
print "\e[0m" if j == 2 || j == 5 | |
end | |
print "\n" | |
print "\e[1m" if i == 2 || i == 5 | |
if i == 2 || i == 5 | |
print "+---+---+---+---+---+---+---+---+---+" | |
else | |
print "+---+---+---\e[1m+\e[0m---+---+---\e[1m+\e[0m---+---+---+" | |
end | |
print "\e[0m" if i == 2 || i == 5 | |
print "\n" | |
end | |
end | |
end | |
# Sudoku.new(<<MATRIX).run | |
# 64 3 7 | |
# 5 1 7 9 | |
# 1 | |
# 49 8 6 | |
# 8 3 2 | |
# 4 | |
# 4 157 3 | |
# 2 83 4 | |
# 75 96 | |
# MATRIX | |
Sudoku.new(<<MATRIX).run | |
3549 6 | |
2 6819 | |
762 | |
427 315 | |
915 7 | |
6 5 7 | |
4 | |
5 2673 | |
6 5 19 | |
MATRIX |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment