Class: OPL::Sudoku

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input_matrix) ⇒ Sudoku

Returns a new instance of Sudoku.



7
8
9
10
# File 'lib/sudoku.rb', line 7

def initialize(input_matrix)
  @input_matrix = input_matrix
  ""
end

Instance Attribute Details

#input_matrixObject

Returns the value of attribute input_matrix.



3
4
5
# File 'lib/sudoku.rb', line 3

def input_matrix
  @input_matrix
end

#lpObject

Returns the value of attribute lp.



4
5
6
# File 'lib/sudoku.rb', line 4

def lp
  @lp
end

#solutionObject

Returns the value of attribute solution.



5
6
7
# File 'lib/sudoku.rb', line 5

def solution
  @solution
end

Instance Method Details

#format_solutionObject



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/sudoku.rb', line 40

def format_solution
  @lp.matrix_solution["x"]
  mat = @lp.matrix_solution["x"]
  sol = Array.new(mat[0][0].size) { Array.new(mat[0][0].size, 0) }
  mat.each_index do |i|
    mat[i].each_index do |j|
      mat[i][j].each_index do |k|
        if mat[i][j][k].to_f == 1.0
          sol[i][j] = k+1
        end
      end
    end
  end
  @solution = sol
  ""
end


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

def print_problem
  @input_matrix.each do |row|
    puts row.join(" ")
  end
  ""
end


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

def print_solution
  @solution.each do |row|
    puts row.join(" ")
  end
  ""
end

#solveObject



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
# File 'lib/sudoku.rb', line 12

def solve
  size = input_matrix.count
  rubysize = size-1

  constant_constraints = []
  input_matrix.each_index do |i|
    row = input_matrix[i]

    row.each_index do |j|
      element = input_matrix[i][j]

      if element != 0
        constant_constraints << "x[#{i}][#{j}][#{element-1}] = 1"
      end
    end
  end

  @lp = minimize("y", subject_to([
    "y = 2",# y is a dummy variable so I don't have to worry about the objective function
    "forall(i in (0..#{rubysize}), j in (0..#{rubysize}), sum(k in (0..#{rubysize}), x[i][j][k]) = 1)",# an element contains only one number
    "forall(i in (0..#{rubysize}), k in (0..#{rubysize}), sum(j in (0..#{rubysize}), x[i][j][k]) = 1)",# every row contains every number
    "forall(j in (0..#{rubysize}), k in (0..#{rubysize}), sum(i in (0..#{rubysize}), x[i][j][k]) = 1)",# every column contains every number
    "forall(u in [0,3,6], v in [0,3,6], k in (0..#{rubysize}), sum(i in ((0+u)..(#{(size/3)-1}+u)), j in ((0+v)..(#{(size/3)-1}+v)), x[i][j][k]) = 1)",# every 3x3 grid contains every number
    constant_constraints# some elements already have their values set
  ].flatten,["BOOLEAN: x"]))
  ""
end