Class: Sudoku

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/sudoku.rb

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ Sudoku

Returns a new instance of Sudoku.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/sudoku.rb', line 9

def initialize data
  # set up data container (9x9 array)
  @data = Array.new(9) { Array.new(9) }

  # convert insert data into one-dimensional array
  data = data.scan(/\d| /)

  if data.size == 81
    # split array into 9-elements arrays
    data.each_index do |i|
      @data[i/9][i%9] = SudokuItem.new(self, data.at(i))
    end
  end
end

Instance Method Details

#at(x, y) ⇒ Object



28
29
30
# File 'lib/sudoku.rb', line 28

def at x, y
  @data.at(y).at(x)
end

#boxesObject



44
45
46
# File 'lib/sudoku.rb', line 44

def boxes
  (group_by {|item| (item.x / 3).to_s + (item.y / 3).to_s }).values
end

#cloneObject



24
25
26
# File 'lib/sudoku.rb', line 24

def clone
  Sudoku.new self.to_s
end

#count_setObject



36
37
38
# File 'lib/sudoku.rb', line 36

def count_set
  count {|item| item.set?}
end

#eachObject



60
61
62
# File 'lib/sudoku.rb', line 60

def each
  each_with_position {|item, x, y| yield item}
end

#each_with_positionObject



64
65
66
# File 'lib/sudoku.rb', line 64

def each_with_position
  @data.each_with_index {|row, y| row.each_with_index {|item, x| yield item, x, y}}
end

#groupsObject



40
41
42
# File 'lib/sudoku.rb', line 40

def groups
  boxes + horizontals + verticals
end

#horizontalsObject



48
49
50
# File 'lib/sudoku.rb', line 48

def horizontals
  @data
end

#set(x, y, value) ⇒ Object



32
33
34
# File 'lib/sudoku.rb', line 32

def set x, y, value
  at(x, y).set(value) unless at(x, y).related.any? {|item| item.to_i == value }
end

#solved?Boolean

Returns:

  • (Boolean)


56
57
58
# File 'lib/sudoku.rb', line 56

def solved?
  all? {|item| item.set?}
end

#to_sObject



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/sudoku.rb', line 68

def to_s
  # output schemas
  break_line = '+---+---+---+'
  data_line = "|%s%s%s|%s%s%s|%s%s%s|"

  # initialize the output variable as an array
  result = [break_line]

  @data.each_with_index do |row, i|
    # add formated data line to output variable
    result.push sprintf(data_line, *row)

    # add a break line to the output variable if nedded
    result.push break_line if (i.succ % 3).zero?
  end

  # return output variable with EOL symbol between each element
  result.join("\n")
end

#verticalsObject



52
53
54
# File 'lib/sudoku.rb', line 52

def verticals
  @data.transpose
end