forked from stokarenko/it-duel-2016
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnectivity.rb
74 lines (57 loc) · 2.13 KB
/
connectivity.rb
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
# Copyright (c) 2015 Sergey Tokarenko
module Tetris
module DiagonalStrategy
module Connectivity
#TODO cleanup..
DIAGONAL_INDEX_DELTA = 5
class << self
def check(size, board, cell)
min_diagonal_index = diagonal_index(size, cell)
diagonal_empty_cells = diagonal_empty_cells_count(size, board, cell, min_diagonal_index)
triangle_edge = min_diagonal_index + DIAGONAL_INDEX_DELTA
empty_cells = diagonal_empty_cells + if triangle_edge < size - 2
triangle_area = triangle_edge * (triangle_edge - 1) / 2
(size - 2)**2 - triangle_area
else
triangle_edge = 2 * (size - 2) - triangle_edge
triangle_edge > 0 ?
triangle_edge * (triangle_edge + 1) / 2 :
0
end
empty_cells % 4 == 0
end
private
def diagonal_empty_cells_count(size, board, cell, min_diagonal_index)
empty_cells = Array.new(size**2, false)
empty_cells[cell] = true
empty_cells_count = 1
queue = [cell]
while(center_cell = queue.shift)
nearby_cells(size, center_cell, min_diagonal_index) do |nearby_cell|
if !empty_cells[nearby_cell] && board[nearby_cell] == 0
empty_cells[nearby_cell] = true
queue.push(nearby_cell)
empty_cells_count += 1
end
end
end
empty_cells_count
end
def nearby_cells(size, center_cell, min_diagonal_index)
center_cell_diagonal_index = diagonal_index(size, center_cell)
if center_cell_diagonal_index > min_diagonal_index
yield(center_cell - 1)
yield(center_cell - size)
end
if center_cell_diagonal_index < min_diagonal_index + DIAGONAL_INDEX_DELTA
yield(center_cell + 1)
yield(center_cell + size)
end
end
def diagonal_index(size, cell)
cell % size + cell / size
end
end
end
end
end