Class: Namero::Board

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(n:, values: Array.new(n**2)) ⇒ Board

n: Integer values: Array<Integer>

Raises:

  • (ArgumentError)


7
8
9
10
11
# File 'lib/namero/board.rb', line 7

def initialize(n:, values: Array.new(n**2))
  raise ArgumentError if values.size != n**2
  @n = n
  @values = values
end

Instance Attribute Details

#nObject (readonly)

Returns the value of attribute n.



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

def n
  @n
end

Instance Method Details

#[](idx, type = :index) ⇒ Object



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
# File 'lib/namero/board.rb', line 48

def [](idx, type = :index)
  case type
  when :index
    @values[idx]
  when :row
    start = (idx / n ) * n
    @values[start...start+@n]
  when :column
    x = idx % n
    @values.each_slice(n).map{|row| row[x]}
  when :block
    x = idx % n
    y = idx / n
    start_x = x / root_n * root_n
    start_y = y / root_n * root_n

    [].tap do |res|
      root_n.times do |y_offset|
        root_n.times do |x_offset|
          
          res << self[start_x + x_offset + (start_y + y_offset) * n]
        end
      end
    end
  else
    raise "Unknown type: #{type}"
  end
end

#[]=(idx, type = :index, value) ⇒ Object

x, y: 0 based index type: :single, :row, :column, :block, :index



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
# File 'lib/namero/board.rb', line 15

def []=(idx, type = :index, value)
  case type
  when :index
    @values[idx] = value
  when :row
    start = (idx / n) * n
    n.times do |i|
      @values[start+i] = value[i]
    end
  when :column
    x = idx % n
    n.times do |i|
      @values[i * n + x] = value[i]
    end
  when :block
    x = idx % n
    y = idx / n
    start_x = x / root_n * root_n
    start_y = y / root_n * root_n

    value_idx = 0
    root_n.times do |y_offset|
      root_n.times do |x_offset|

        self[start_x + x_offset + (start_y + y_offset) * n] = value[value_idx]
        value_idx += 1
      end
    end
  else
    raise "Unknown type: #{type}"
  end
end

#complete?Boolean

Returns:

  • (Boolean)


89
90
91
92
93
# File 'lib/namero/board.rb', line 89

def complete?
  @values.all? do |v|
    v.value
  end
end

#dupObject



77
78
79
80
# File 'lib/namero/board.rb', line 77

def dup
  values = @values.map(&:dup)
  Board.new(n: @n, values: values)
end

#each_valuesObject



82
83
84
85
86
87
# File 'lib/namero/board.rb', line 82

def each_values
  return enum_for(__method__) unless block_given?
  @values.each do |value|
    yield value
  end
end