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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
use super::CapStone;
#[derive(Debug, Clone)]
pub struct CapStoneGroup(
pub CapStone,
pub CapStone,
pub CapStone
);
#[derive(Clone, Copy, Debug, PartialEq)]
struct Neighbor {
index: usize,
distance: f64,
}
pub fn find_groupings(mut capstones: Vec<CapStone>) -> Vec<CapStoneGroup> {
let mut idx = 0;
let mut groups = Vec::new();
while idx < capstones.len() {
let (hlist, vlist) = find_possible_neighbors(&capstones, idx);
match test_neighbours(&hlist, &vlist) {
None => {
idx += 1
}
Some((h_idx, v_idx)) => {
let group = remove_capstones_in_order(&mut capstones,
h_idx,
idx,
v_idx);
groups.push(group);
let sub = [h_idx, v_idx].iter()
.filter(|&&i| i < idx)
.count();
idx -= sub;
}
}
}
groups
}
fn remove_capstones_in_order(caps: &mut Vec<CapStone>,
first: usize,
second: usize,
third: usize) -> CapStoneGroup {
assert_ne!(first, second);
assert_ne!(first, third);
assert_ne!(second, third);
let idx0 = first;
let mut idx1 = second;
let mut idx2 = third;
if second > first {
idx1 -= 1;
}
if third > first {
idx2 -= 1;
}
if third > second {
idx2 -= 1;
}
let first_cap = caps.remove(idx0);
let second_cap = caps.remove(idx1);
let third_cap = caps.remove(idx2);
CapStoneGroup(first_cap, second_cap, third_cap)
}
fn find_possible_neighbors(capstones: &[CapStone], idx: usize) -> (Vec<Neighbor>, Vec<Neighbor>) {
let cap = &capstones[idx];
let mut hlist = Vec::new();
let mut vlist = Vec::new();
for others_idx in 0..capstones.len() {
if others_idx == idx {
continue;
}
let cmp_cap = &capstones[others_idx];
let (mut u, mut v) = cap.c.unmap(&cmp_cap.center);
u = (u - 3.5f64).abs();
v = (v - 3.5f64).abs();
if u < 0.2f64 * v {
hlist.push(Neighbor {
index: others_idx,
distance: v,
});
}
if v < 0.2f64 * u {
vlist.push(Neighbor {
index: others_idx,
distance: u,
});
}
}
(hlist, vlist)
}
fn test_neighbours(
hlist: &[Neighbor],
vlist: &[Neighbor],
) -> Option<(usize, usize)> {
let mut best_score = 2.5;
let mut best_h = None;
let mut best_v = None;
for hn in hlist {
for vn in vlist {
let score = (1.0f64 - hn.distance / vn.distance).abs();
if score > 2.5 {
continue;
}
let new = match (best_h, score) {
(None, _) => {
(Some(hn.index), Some(vn.index), score)
}
(Some(_), b) if b < best_score => {
(Some(hn.index), Some(vn.index), b)
}
_ => (best_h, best_v, best_score)
};
best_h = new.0;
best_v = new.1;
best_score = new.2;
}
}
match (best_h, best_v) {
(None, _)
| (_, None) => None,
(Some(h), Some(v)) => Some((h, v))
}
}