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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
use directions::{Direction, DIRECTIONS};
use format::{self, Table};
use grid::{Elem, Grid, Pt, DirVector};
use path::{Closed, Path};
use std::borrow::Cow;
use std::cell::Cell;
struct FindPaths<'a> {
announce: Cell<fn (String)>,
format: Cow<'a, Table>,
grid: &'a Grid,
steps: Vec<Pt>,
}
#[derive(Debug)]
struct FindClosedPaths<'a> {
find: FindPaths<'a>
}
#[derive(Debug)]
struct FindUnclosedPaths<'a> {
prefix_rev: Vec<Pt>,
find: FindPaths<'a>
}
use std;
impl<'a> std::fmt::Debug for FindPaths<'a> {
fn fmt(&self, w: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(w, "FindPaths {{ grid, steps: {:?} }}", self.steps)
}
}
#[derive(Debug)]
struct FindContext {
prev: Option<Pt>,
curr: Pt,
}
#[derive(Debug)]
struct FindLoopContext<'a> {
prev: Pt,
curr: Pt,
corner_dirs: &'a [((char, Direction), (Direction, char))]
}
impl FindContext {
fn curr(&self) -> Pt { self.curr }
}
impl<'a> FindPaths<'a> {
#[cfg(test)]
fn new(grid: &Grid) -> FindPaths {
FindPaths {
announce: Cell::new(silent),
format: Default::default(),
grid: grid,
steps: vec![],
}
}
fn with_grid_format(grid: &'a Grid, format: &'a Table) -> Self {
FindPaths {
announce: Cell::new(silent),
format: Cow::Borrowed(format),
grid: grid,
steps: vec![],
}
}
fn start(&self) -> Pt { self.steps[0] }
fn to_path(&self, closed: Closed) -> Path {
Path {
steps: self.steps.iter().map(|&pt| (pt, self.grid[pt].to_char())).collect(),
closed: closed,
id: None,
attrs: None,
}
}
}
fn silent(_: String) { }
fn announce_fup(x: String) { println!("find_unclosed_path {}", x); }
fn announce_fupfe(x: String) { println!("find_unclosed_path fwd_ext {}", x); }
fn announce_fupre(x: String) { println!("find_unclosed_path rev_ext {}", x); }
fn announce_fuptre(x: String) { println!("find_unclosed_path try_rev_ext {}", x); }
fn announce_fcp(x: String) { println!("find_closed_path {}", x); }
fn announce_fcpf(x: String) { println!("find_closed_path_from {}", x); }
impl<'a> FindUnclosedPaths<'a> {
fn find_unclosed_path(mut self, curr: Pt) -> Result<Path, (Signal, Self)> {
if let Err(s @ Signal::CancelPath(_)) = self.find.check_neighbors(curr, announce_fup) {
return Err((s, self));
}
self.find.steps.push(curr);
for (j, &dir) in DIRECTIONS.iter().enumerate() {
debug!("find_unclosed_path {} dir: {:?}", j, dir);
let next = DirVector(curr, dir).steps(1);
debug!("find_unclosed_path {} dir: {:?} next: {:?}",
j, dir, next);
if !self.find.grid.holds(next.0) {
continue;
}
if !self.find.matches_start(curr, Some(next.0)) {
continue;
}
match self.fwd_ext(next, FindContext { prev: Some(curr), curr: next.0 })
{
Ok(p) => return Ok(p),
Err(s @ (Signal::CancelPath(_), _)) => {
return Err(s);
}
Err((Signal::SearchFailure, s)) => {
self = s;
}
}
}
debug!("find_unclosed_path self: {:?} exhausted directions; giving up.", self);
return Err((Signal::SearchFailure, self));
}
fn fwd_ext(mut self, dv: DirVector, fc: FindContext) -> Result<Path, (Signal, Self)> {
debug!("fwd_ext self: {:?} dv: {:?} {:?}", self, dv, fc);
assert!(self.find.grid.holds(dv.0));
assert!(!self.find.steps.contains(&dv.0));
assert_eq!(dv.0, fc.curr());
if let Err(s @ Signal::CancelPath(_)) = self.find.check_neighbors(fc.curr(), announce_fupfe) {
return Err((s, self));
}
let elem: Elem = self.find.grid[dv.0];
debug!("fwd_ext elem: {:?}", elem);
let _c: char = match elem {
Elem::Pad | Elem::Clear => return Err((Signal::SearchFailure, self)),
Elem::C(c) | Elem::Used(c) => c,
};
let dir = dv.dir();
let mut dirs_to_try: Vec<_> = DIRECTIONS.iter().map(|&d|d).filter(|&d| d != dir && d != dir.reverse()).collect();
dirs_to_try.push(dir);
self.find.steps.push(dv.0);
while let Some(dir) = dirs_to_try.pop() {
debug!("fwd_ext trying dir: {:?}", dir);
let next = dv.towards(dir).step();
if !self.find.grid.holds(next.0) { continue; }
if self.find.steps.contains(&next.0) { continue; }
if !self.find.matches(fc.prev, fc.curr, next.0) {
debug!("no format rule found for ({:?},{:?},{:?})",
fc.prev, fc.curr, next.0);
continue;
}
match self.fwd_ext(next, FindContext { prev: Some(dv.0), curr: next.0 }) {
p @ Ok(_) => return p,
Err(s @ (Signal::CancelPath(_), _)) => {
debug!("recursive search cancelled path for ({:?},{:?},{:?})",
fc.prev, fc.curr, next.0);
return Err(s)
}
Err((Signal::SearchFailure, s)) => {
debug!("recursive search failed for ({:?},{:?},{:?})",
fc.prev, fc.curr, next.0);
self = s;
continue;
}
}
}
assert_eq!(self.find.steps.last(), Some(&dv.0));
if self.find.matches_end(fc.prev, fc.curr) {
debug!("fwd_ext self: {:?} exhausted turns; finished.", self);
self.rev_ext()
} else {
debug!("fwd_ext self: {:?} cannot end here; aborting.", self);
assert_eq!(self.find.steps.last(), Some(&dv.0));
self.find.steps.pop();
Err((Signal::SearchFailure, self))
}
}
}
impl<'a> FindUnclosedPaths<'a> {
fn rev_ext(mut self) -> Result<Path, (Signal, Self)> {
let (curr, next) = self.first_two();
if let Err(s @ Signal::CancelPath(_)) = self.find.check_neighbors(curr, announce_fupre) {
return Err((s, self));
}
for (_j, &dir) in DIRECTIONS.iter().enumerate() {
let prev = DirVector(curr, dir).steps(1);
match self.try_rev_ext(next, curr, prev) {
Ok(p) => return Ok(p),
Err(s @ (Signal::CancelPath(_), _)) => return Err(s),
Err((Signal::SearchFailure, s)) => self = s,
}
}
Ok(self.to_path())
}
fn to_path(self) -> Path {
let grid = self.find.grid;
let mut steps = Vec::new();
for pt in self.prefix_rev.into_iter().rev() {
steps.push((pt, grid[pt].to_char()))
}
let mut p = self.find.to_path(Closed::Open);
for step in p.steps {
steps.push(step)
}
p.steps = steps;
p
}
fn first_two(&self) -> (Pt, Pt) {
match self.prefix_rev.len() {
0 => (self.find.steps[0], self.find.steps[1]),
n @ 1 => (self.prefix_rev[n-1], self.find.steps[0]),
n => (self.prefix_rev[n-1], self.prefix_rev[n-2]),
}
}
fn search_failure<T>(self) -> Result<T, (Signal, Self)> {
Err((Signal::SearchFailure, self))
}
fn try_rev_ext(mut self, next: Pt, curr: Pt, prev: DirVector) -> Result<Path, (Signal, Self)> {
if let Err(s @ Signal::CancelPath(_)) = self.find.check_neighbors(curr, announce_fuptre) {
return Err((s, self));
}
if !self.find.grid.holds(prev.0) {
return self.search_failure();
}
if self.find.grid[prev.0].is_blank() {
return self.search_failure();
}
if self.prefix_rev.contains(&prev.0) {
return self.search_failure();
}
if self.find.steps.contains(&prev.0) {
return self.search_failure();
}
if !self.find.matches(Some(prev.0), curr, next) {
return self.search_failure();
}
self.prefix_rev.push(prev.0);
if self.is_start(prev.0, curr) {
return self.rev_ext();
}
let (curr, next) = (prev.0, curr);
for (_j, &dir) in DIRECTIONS.iter().enumerate() {
let prev = DirVector(curr, dir).steps(1);
match self.try_rev_ext(next, curr, prev) {
ret @ Ok(_) => return ret,
Err(s @ (Signal::CancelPath(_), _)) => return Err(s),
Err((Signal::SearchFailure, s)) => self = s,
}
}
assert_eq!(self.prefix_rev.last(), Some(&prev.0));
self.prefix_rev.pop();
return Err((Signal::SearchFailure, self));
}
fn is_start(&self, curr: Pt, next: Pt) -> bool {
self.find.matches_start(curr, Some(next))
}
}
impl<'a> FindClosedPaths<'a> {
fn is_corner(&self, curr: Pt) -> Option<Vec<((char, Direction), (Direction, char))>> {
let grid = &self.find.grid;
let c = match grid[curr] {
Elem::C(c) | Elem::Used(c) => c,
Elem::Pad | Elem::Clear => return None,
};
let mut in_out = Vec::new();
for entry in &self.find.format.entries {
if !entry.loop_start { continue; }
if !entry.matches_curr(&self.find.announce.get(), c) { continue; }
let (in_match, in_dir) = entry.corner_incoming();
let (out_dir, out_match) = entry.corner_outgoing();
for in_dir in in_dir {
for &out_dir in &out_dir {
if in_dir == out_dir { continue; }
let i = curr.neighbor(in_dir.reverse());
let o = curr.neighbor(out_dir);
if !grid.holds(i) || !grid.holds(o) { continue; }
if let (Some(i), Some(o)) = (grid[i].opt_char(), grid[o].opt_char()) {
if in_match.matches(i) && out_match.matches(o) {
in_out.push(((i, in_dir), (out_dir, o)));
}
}
}
}
}
return if in_out.is_empty() {
debug!("no in_out found, is_corner returns None");
None
} else {
Some(in_out)
};
}
fn find_closed_path(mut self, curr: Pt) -> Result<Path, Self> {
if let Err(Signal::CancelPath(_)) = self.find.check_neighbors(curr, announce_fcp) {
return Err(self);
}
let elem = self.find.grid[curr];
let corner_dirs: Vec<((char, Direction),
(Direction, char))> = match self.is_corner(curr) {
None => return Err(self),
Some(v) => v,
};
self.find.steps.push(curr);
let mut out_dirs: Vec<Direction> = corner_dirs.iter().map(|t|(t.1).0).collect();
out_dirs.sort();
out_dirs.dedup();
debug!("find_closed_path self: {:?} curr: {:?} pt: {:?} corner_dirs: {:?} out_dirs: {:?}",
self, curr, elem, corner_dirs, out_dirs);
for (j, &dir) in out_dirs.iter().enumerate() {
let next = DirVector(curr, dir).steps(1);
debug!("find_closed_path {} dir: {:?} next: {:?}",
j, dir, next);
if !self.find.grid.holds(next.0) {
continue;
} else if next.0 == self.find.start() {
panic!("this cannot happen so soon.");
}
match self.find_closed_path_from(next, FindLoopContext { prev: curr,
curr: next.0,
corner_dirs: &corner_dirs })
{
ret @ Ok(_) => return ret,
Err(s) => self = s,
}
}
debug!("find_closed_path self: {:?} exhausted directions; giving up.", self);
return Err(self);
}
fn find_closed_path_from(mut self, dv: DirVector, fc: FindLoopContext) -> Result<Path, Self> {
use directions::Turn;
assert!(self.find.grid.holds(dv.0));
assert!(!self.find.steps.contains(&dv.0));
assert_eq!(dv.0, fc.curr);
if let Err(Signal::CancelPath(_)) = self.find.check_neighbors(fc.curr, announce_fcpf) {
return Err(self);
}
let elem: Elem = self.find.grid[dv.0];
let c = match elem {
Elem::Pad | Elem::Clear => return Err(self),
Elem::C(c) | Elem::Used(c) => c
};
debug!("find_closed_path_from self: {:?} dv: {:?} fc: {:?} c: {:?}", self, dv, fc, c);
self.find.steps.push(dv.0);
let mut dir = dv.dir().sharp_turn(Turn::CW);
while dir != dv.dir().reverse() {
let next = dv.towards(dir).step();
if !self.find.grid.holds(next.0) {
dir = dir.veer(Turn::CCW);
continue;
}
debug!("considering loop extension next: {:?} in {:?} fc: {:?}", next, self, fc);
if self.find.start() == next.0 {
if self.properly_closed_loop(&fc) {
debug!("properly closed loop in {:?} fc: {:?}", self, fc);
return Ok(self.find.to_path(Closed::Closed));
} else {
dir = dir.veer(Turn::CCW);
debug!("improperly closed in {:?} fc: {:?} veering to {:?}", self, fc, dir);
continue;
}
} else if self.find.steps.contains(&next.0) {
dir = dir.veer(Turn::CCW);
continue;
}
if !self.find.matches(Some(fc.prev), fc.curr, next.0) {
dir = dir.veer(Turn::CCW);
continue;
}
match self.find_closed_path_from(next, FindLoopContext { prev: dv.0,
curr: next.0,
..fc }) {
p @ Ok(_) => return p,
Err(s) => {
self = s;
dir = dir.veer(Turn::CCW);
continue;
}
}
}
assert_eq!(self.find.steps.last(), Some(&dv.0));
self.find.steps.pop();
debug!("find_closed_path self: {:?} exhausted turns; giving up.", self);
return Err(self);
}
}
impl<'a> FindClosedPaths<'a> {
#[cfg(test)]
fn new(grid: &'a Grid) -> Self {
FindClosedPaths { find: FindPaths::new(grid) }
}
fn properly_closed_loop(&self, fc: &FindLoopContext) -> bool {
let fst = self.find.steps[0];
let snd = self.find.steps[1];
let last = *self.find.steps.last().unwrap();
let s = self.find.grid[snd].opt_char().unwrap();
let l = self.find.grid[last].opt_char().unwrap();
let finis_arc = last.towards(fst);
let start_arc = fst.towards(snd);
fc.corner_dirs.contains(&((l, finis_arc), (start_arc, s)))
}
}
pub fn find_closed_path(grid: &Grid, format: &Table, pt: Pt) -> Option<Path> {
let pf = FindClosedPaths { find: FindPaths::with_grid_format(grid, format) };
let ret = pf.find_closed_path(pt).ok();
debug!("find_closed_path pt {:?} ret {:?}", pt, ret);
ret
}
pub fn find_unclosed_path_from(grid: &Grid, format: &Table, dir: DirVector) -> Option<Path> {
let pf = FindUnclosedPaths { prefix_rev: Vec::new(),
find: FindPaths::with_grid_format(grid, format) };
let ret = pf.fwd_ext(dir, FindContext {
prev: None,
curr: dir.0
}).ok();
debug!("find_unclosed_path_from dir {:?} ret {:?}", dir, ret);
ret
}
pub fn find_unclosed_path(grid: &Grid, format: &Table, pt: Pt) -> Option<Path> {
let pf = FindUnclosedPaths { prefix_rev: Vec::new(),
find: FindPaths::with_grid_format(grid, format) };
let ret = pf.find_unclosed_path(pt).ok();
debug!("find_unclosed_path pt {:?} ret {:?}", pt, ret);
ret
}
pub enum Signal {
CancelPath(Pt),
SearchFailure,
}
impl<'a> FindPaths<'a> {
fn check_inspection_start_at(&self, pt: Pt, a: fn (String)) {
if !self.grid.holds(pt) { return; }
if self.grid[pt].opt_char() == Some('%') {
println!("TURNING ON ANNOUCER at {:?}", pt);
self.announce.set(a);
}
}
fn check_inspection_finis_at(&self, pt: Pt) {
if !self.grid.holds(pt) { return; }
if self.grid[pt].opt_char() == Some('$') {
println!("TURNING OFF ANNOUCER at {:?}", pt);
self.announce.set(silent);
}
}
fn check_nonpath_xbones_at(&self, pt: Pt) -> Result<(), Signal> {
if !self.grid.holds(pt) { return Ok(()); }
if self.grid[pt].opt_char() == Some('☠') {
println!("CANCELLING PATH at {:?}", pt);
return Err(Signal::CancelPath(pt));
}
return Ok(());
}
fn check_inspection_start(&self, curr: Pt, a: fn (String)) {
self.check_inspection_start_at(curr, a);
for (_j, &dir) in DIRECTIONS.iter().enumerate() {
let nbor = DirVector(curr, dir).steps(1);
self.check_inspection_start_at(nbor.0, a);
}
}
fn check_inspection_finis(&self, curr: Pt) {
self.check_inspection_finis_at(curr);
for (_j, &dir) in DIRECTIONS.iter().enumerate() {
let nbor = DirVector(curr, dir).steps(1);
self.check_inspection_finis_at(nbor.0);
}
}
fn check_inspection(&self, curr: Pt, a: fn (String)) {
self.check_inspection_start(curr, a);
self.check_inspection_finis(curr);
}
fn check_nonpath(&self, curr: Pt) -> Result<(), Signal> {
try!(self.check_nonpath_xbones_at(curr));
for (_j, &dir) in DIRECTIONS.iter().enumerate() {
let nbor = DirVector(curr, dir).steps(1);
try!(self.check_nonpath_xbones_at(nbor.0));
}
return Ok(());
}
fn check_neighbors(&self, curr: Pt, a: fn (String)) -> Result<(), Signal> {
self.check_inspection(curr, a);
self.check_nonpath(curr)
}
fn find_entry(&self,
prev: Option<Pt>,
curr: Pt,
next: Pt) -> Option<&format::Entry> {
#![allow(unused_parens)]
let c = (if let Some(c) = self.grid[curr].opt_char() { c }
else { return None; });
let prev_arc = prev.and_then(|prev| {
self.grid[prev].opt_char().map(|p| (p, prev.towards(curr)))
});
let next_arc = self.grid[next].opt_char().map(|n| (curr.towards(next), n));
for entry in &self.format.entries {
if entry.matches(&self.announce.get(), prev_arc, c, next_arc) {
return Some(entry);
}
}
return None;
}
fn matches(&self, prev: Option<Pt>, curr: Pt, next: Pt) -> bool {
self.find_entry(prev, curr, next).is_some()
}
fn matches_start(&self, curr: Pt, next: Option<Pt>) -> bool {
let c = if let Some(c) = self.grid[curr].opt_char() { c } else { return false; };
let next_arc = next.and_then(|next| {
self.grid[next].opt_char().map(|n| (curr.towards(next), n))
});
for entry in &self.format.entries {
if entry.matches_start(&self.announce.get(), c, next_arc) {
return true;
}
}
return false;
}
fn matches_end(&self, prev: Option<Pt>, curr: Pt) -> bool {
let c = if let Some(c) = self.grid[curr].opt_char() { c } else { return false; };
let prev_arc = prev.and_then(|prev| {
self.grid[prev].opt_char().map(|p| (p, prev.towards(curr)))
});
for entry in &self.format.entries {
if entry.matches_end(&self.announce.get(), prev_arc, c) {
return true;
}
}
return false;
}
}
#[cfg(test)]
mod tests;