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
use std::collections::HashSet;
use crate::{
board::{ColinearCheck, Dimensions},
ships::{ProjectIterState, ShapeProjection, ShipShape},
};
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct Line(usize);
impl Line {
pub fn new(len: usize) -> Self {
assert!(len > 0);
Line(len)
}
pub fn len(&self) -> usize {
self.0
}
}
impl<D: Dimensions + ColinearCheck + ?Sized> ShipShape<D> for Line {
type ProjectIterState = LineProjectIterState<D::Coordinate>;
fn is_valid_placement(&self, proj: &ShapeProjection<D::Coordinate>, dim: &D) -> bool {
if proj.len() != self.len() {
return false;
}
let mut proj = proj.iter();
let start = proj.next().unwrap();
let mut previous = start;
for coord in proj {
if dim.is_neighbor(coord, previous) && dim.is_colinear(start, previous, coord) {
previous = coord;
} else {
return false;
}
}
return true;
}
}
pub struct LineProjectIterState<C> {
start: C,
directions: Vec<C>,
next_dir: usize,
}
impl<D: Dimensions + ColinearCheck + ?Sized> ProjectIterState<D>
for LineProjectIterState<D::Coordinate>
{
type ShipShape = Line;
fn start(shape: &Self::ShipShape, dim: &D, coord: D::Coordinate) -> Self {
if shape.len() == 1 {
Self {
start: coord,
directions: Vec::new(),
next_dir: 0,
}
} else {
Self {
start: coord.clone(),
directions: dim.neighbors(coord).collect(),
next_dir: 0,
}
}
}
fn next(&mut self, shape: &Self::ShipShape, dim: &D) -> Option<ShapeProjection<D::Coordinate>> {
if shape.len() == 1 {
if self.next_dir == 0 {
self.next_dir = 1;
Some(vec![self.start.clone()])
} else {
None
}
} else {
loop {
if self.next_dir < self.directions.len() {
let dir = self.directions[self.next_dir].clone();
self.next_dir += 1;
if let Some(route) = try_build_route(dim, shape.0, self.start.clone(), dir) {
return Some(route);
}
} else {
return None;
}
}
}
}
}
fn try_build_route<D: Dimensions + ColinearCheck + ?Sized>(
dim: &D,
len: usize,
start: D::Coordinate,
dir: D::Coordinate,
) -> Option<ShapeProjection<D::Coordinate>> {
let mut route = Vec::with_capacity(len);
let mut visited = HashSet::with_capacity(len);
route.push(start.clone());
visited.insert(start.clone());
route.push(dir.clone());
visited.insert(dir.clone());
let mut last = dir.clone();
'outer: while route.len() < len {
for neighbor in dim.neighbors(last) {
if dim.is_colinear(&start, &dir, &neighbor) && visited.insert(neighbor.clone()) {
route.push(neighbor.clone());
last = neighbor;
continue 'outer;
}
}
return None;
}
return Some(route);
}