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
/// Implements [Digkstra's algorithm](https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm)
///
/// This searches for the cheapest path from one point to another, given a starting point (or
/// points) and a way to iteratively find next points. While this can be used for path-finding, it
/// can also be used to solve many other problems, assuming their state can be modeled as points,
/// the next steps can be iterated, and each step can be scored with some kind of priority.
///
/// # Example
///
/// Here's an example taken from the
/// [wikipedia page](https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm). We use strings for the
/// nodes instead of integers to make things a bit clearer.
///
/// In this example, we supply a hash map directly when constructing the [`PrioritySearch`]. This
/// works because the trait [`PrioritySearchVisitor`] is implemented directly in this case. It is
/// also implemented for functions, so you can pass a closure, plus the trait can be implemented
/// directly, of course.
///
/// ```
/// # use aoc_misc::prelude::*;
/// # use aoc_search::*;
/// // set up a data structure with a map of connected nodes and the distance between them
/// let mut nodes = HashMap::new ();
/// for (left, right, dist) in [
///    // list of connected nodes and the distance between them
///    ("one", "two", 7), ("one", "three", 9), ("one", "six", 14), ("two", "three", 10),
///    ("two", "four", 15), ("three", "four", 11), ("three", "six", 2), ("four", "five", 6),
///    ("five", "six", 8),
/// ] {
///    nodes.entry (left).or_insert (Vec::new ()).push ((right, dist));
///    nodes.entry (right).or_insert (Vec::new ()).push ((left, dist));
/// }
///
/// // create a PrioritySearch to traverse our nodes
/// let mut search = PrioritySearch::with_hash_map (nodes);
///
/// // add the starting point with a total distance of 0
/// search.push ("one", 0);
///
/// // verify the results
/// assert_eq! (search.next (), Some (("one", 0)));
/// assert_eq! (search.next (), Some (("two", 7)));
/// assert_eq! (search.next (), Some (("three", 9)));
/// assert_eq! (search.next (), Some (("six", 11)));
/// assert_eq! (search.next (), Some (("five", 19)));
/// assert_eq! (search.next (), Some (("four", 20)));
/// assert_eq! (search.next (), None);
/// ```

use super::*;

pub struct PrioritySearch <Node, Pri, Visitor, SeenImpl>
	where
		Node: Clone + Debug + Eq + Hash,
		Pri: Clone + Copy + Debug + Ord,
		SeenImpl: Seen <Node, Pri>,
		Visitor: PrioritySearchVisitor <Node, Pri, SeenImpl> {
	visitor: Visitor,
	inner: PrioritySearchInner <Node, Pri, SeenImpl>,
}

#[ allow (clippy::implicit_hasher) ]
impl <Node, Pri, Visitor>
	PrioritySearch <Node, Pri, Visitor, HashMap <Node, SeenState <Pri>>>
	where
		Node: Clone + Debug + Eq + Hash + Ord,
		Pri: Clone + Copy + Debug + Ord,
		Visitor: PrioritySearchVisitor <Node, Pri, HashMap <Node, SeenState <Pri>>> {

	#[ inline ]
	pub fn with_hash_map (visitor: Visitor) -> Self {
		Self {
			visitor,
			inner: PrioritySearchInner {
				seen: HashMap::new (),
				todo: BinaryHeap::new (),
			},
		}
	}

}

impl <Pos, Pri, Visitor, const DIMS: usize>
	PrioritySearch <GridCursor <Pos, DIMS>, Pri, Visitor, GridBuf <Vec <SeenState <Pri>>, Pos, DIMS>>
	where
		Pos: Clone + Debug + Eq + Hash + GridPos <DIMS>,
		Pri: Clone + Copy + Debug + Ord,
		Visitor: PrioritySearchVisitor <GridCursor <Pos, DIMS>, Pri, GridBuf <Vec <SeenState <Pri>>, Pos, DIMS>> {

	#[ inline ]
	pub fn with_grid_range (start: Pos, end: Pos, visitor: Visitor) -> NumResult <Self> {
		Ok (Self {
			visitor,
			inner: PrioritySearchInner {
				seen: GridBuf::new_range (start, end) ?,
				todo: BinaryHeap::new (),
			},
		})
	}

	#[ inline ]
	pub fn with_grid_size (size: Pos, visitor: Visitor) -> Self {
		Self {
			visitor,
			inner: PrioritySearchInner {
				seen: GridBuf::new_size (size),
				todo: BinaryHeap::new (),
			},
		}
	}

}

impl <Node, Pri, Visitor, SeenImpl> PrioritySearch <Node, Pri, Visitor, SeenImpl>
	where
		Node: Clone + Debug + Eq + Hash,
		Pri: Clone + Copy + Debug + Ord,
		SeenImpl: Seen <Node, Pri>,
		Visitor: PrioritySearchVisitor <Node, Pri, SeenImpl> {

	#[ inline ]
	pub fn len (& self) -> usize {
		self.inner.todo.len ()
	}

	#[ inline ]
	pub fn is_empty (& self) -> bool {
		self.len () == 0
	}

	#[ inline ]
	pub fn push (& mut self, node: Node, priority: Pri) -> & mut Self {
		self.inner.push (node, priority);
		self
	}

}

impl <Node, Pri, Visitor, SeenImpl> Iterator for PrioritySearch <Node, Pri, Visitor, SeenImpl>
	where
		Node: Clone + Debug + Eq + Hash,
		Pri: Clone + Copy + Debug + Ord,
		SeenImpl: Seen <Node, Pri>,
		Visitor: PrioritySearchVisitor <Node, Pri, SeenImpl> {

	type Item = Visitor::Item;

	#[ inline ]
	fn next (& mut self) -> Option <Self::Item> {
		if let Some (WithPriority { priority, value: node }) = self.inner.pop () {
			let adder = PrioritySearchAdder { inner: & mut self.inner };
			return Some (self.visitor.visit (node, priority, adder));
		}
		None
	}

}

struct WithPriority <Val, Pri> {
	priority: Pri,
	value: Val,
}

impl <Val, Pri> PartialEq for WithPriority <Val, Pri> where Pri: PartialEq {
	fn eq (& self, other: & Self) -> bool {
		self.priority.eq (& other.priority)
	}
}

impl <Val, Pri> Eq for WithPriority <Val, Pri> where Pri: Eq {
}

impl <Val, Pri> PartialOrd for WithPriority <Val, Pri> where Pri: PartialOrd {
	fn partial_cmp (& self, other: & Self) -> Option <Ordering> {
		other.priority.partial_cmp (& self.priority)
	}
}

impl <Val, Pri> Ord for WithPriority <Val, Pri> where Pri: Ord {
	fn cmp (& self, other: & Self) -> Ordering {
		other.priority.cmp (& self.priority)
	}
}

struct PrioritySearchInner <Node, Pri, Seen> {
	seen: Seen,
	todo: BinaryHeap <WithPriority <Node, Pri>>,
}

impl <Node, Pri, SeenImpl> PrioritySearchInner <Node, Pri, SeenImpl>
	where
		Node: Clone + Eq + Hash,
		Pri: Clone + Ord,
		SeenImpl: Seen <Node, Pri> {
	fn push (& mut self, node: Node, priority: Pri) {
		if self.seen.seen_push (node.clone (), priority.clone ()) {
			self.todo.push (WithPriority { priority, value: node });
		}
	}
	fn pop (& mut self) -> Option <WithPriority <Node, Pri>> {
		while let Some (WithPriority { value: node, priority }) = self.todo.pop () {
			if self.seen.seen_visited (& node) { continue }
			return Some (WithPriority { value: node, priority });
		}
		None
	}
}

pub struct PrioritySearchAdder <'inr, Node, Pri, Seen> {
	inner: & 'inr mut PrioritySearchInner <Node, Pri, Seen>,
}

impl <'inr, Node, Pri, SeenImpl> PrioritySearchAdder <'inr, Node, Pri, SeenImpl>
	where
		Node: Clone + Debug + Eq + Hash,
		Pri: Clone + Debug + Ord,
		SeenImpl: Seen <Node, Pri> {

	#[ inline ]
	pub fn add (& mut self, node: Node, priority: Pri) {
		self.inner.push (node, priority);
	}

}

pub trait PrioritySearchVisitor <Node, Pri, Seen> {

	type Item;

	fn visit (
		& mut self,
		node: Node,
		priority: Pri,
		adder: PrioritySearchAdder <Node, Pri, Seen>,
	) -> Self::Item;

}

impl <VisitorFn, Node, Pri, Item, SeenImpl> PrioritySearchVisitor <Node, Pri, SeenImpl> for VisitorFn
	where
		Node: Clone,
		Pri: Clone + Ord,
		SeenImpl: Seen <Node, Pri>,
		VisitorFn: FnMut (Node, Pri, PrioritySearchAdder <Node, Pri, SeenImpl>) -> Item {

	type Item = Item;

	#[ inline ]
	fn visit (
		& mut self,
		node: Node,
		priority: Pri,
		adder: PrioritySearchAdder <Node, Pri, SeenImpl>,
	) -> Self::Item {
		self (node, priority, adder)
	}

}

impl <Node, Pri, SeenImpl, NextNodesIntoIter, Hshr> PrioritySearchVisitor <Node, Pri, SeenImpl>
	for HashMap <Node, NextNodesIntoIter, Hshr>
	where
		Hshr: BuildHasher,
		Node: Clone + Debug + Eq + Hash + Ord,
		Pri: Clone + Debug + Ord + Add <Output = Pri>,
		SeenImpl: Seen <Node, Pri>,
		for <'dat> & 'dat NextNodesIntoIter: IntoIterator <Item = & 'dat (Node, Pri)> {

	type Item = (Node, Pri);

	#[ inline ]
	fn visit (
		& mut self,
		node: Node,
		priority: Pri,
		mut adder: PrioritySearchAdder <Node, Pri, SeenImpl>,
	) -> Self::Item {
		if let Some (next_nodes) = self.get (& node) {
			for & (ref next_node, ref next_pri) in next_nodes {
				adder.add (next_node.clone (), priority.clone () + next_pri.clone ());
			}
		}
		(node, priority)
	}

}

pub trait Seen <Node, Pri> where Node: Clone, Pri: Clone + Ord {

	fn seen_get_mut (& mut self, node: Node) -> & mut SeenState <Pri>;

	#[ inline ]
	fn seen_push (& mut self, node: Node, priority: Pri) -> bool {
		let seen_state = self.seen_get_mut (node);
		match seen_state.clone () {
			SeenState::New => {
				* seen_state = SeenState::Unvisited (priority);
				true
			},
			SeenState::Unvisited (seen_priority) if priority < seen_priority => {
				* seen_state = SeenState::Unvisited (priority);
				true
			},
			SeenState::Unvisited (_) | SeenState::Visited => false,
		}
	}

	#[ inline ]
	fn seen_visited (& mut self, node: & Node) -> bool {
		let seen_state = self.seen_get_mut (node.clone ());
		if matches! (* seen_state, SeenState::Visited) {
			true
		} else {
			* seen_state = SeenState::Visited;
			false
		}
	}

}

impl <Node, Pri, Hshr> Seen <Node, Pri>
for HashMap <Node, SeenState <Pri>, Hshr>
	where
		Hshr: BuildHasher,
		Node: Clone + Eq + Hash + Ord,
		Pri: Clone + Ord {

	#[ inline ]
	fn seen_get_mut (& mut self, node: Node) -> & mut SeenState <Pri> {
		self.entry (node).or_insert (SeenState::New)
	}

}

impl <Node, Pri, const DIMS: usize> Seen <Node, Pri>
	for GridBuf <Vec <SeenState <Pri>>, Node, DIMS>
	where
		Node: GridPos <DIMS> + Clone + Eq + Hash,
		Pri: Clone + Ord {

	#[ inline ]
	fn seen_get_mut (& mut self, node: Node) -> & mut SeenState <Pri> {
		Self::get_mut (self, node).unwrap_or_else (
			|| panic! ("Position is not in grid: {node:?}"))
	}

}

impl <Pos, Pri, const DIMS: usize> Seen <GridCursor <Pos, DIMS>, Pri>
	for GridBuf <Vec <SeenState <Pri>>, Pos, DIMS>
	where
		Pos: GridPos <DIMS> + Clone + Eq + Hash,
		Pri: Clone + Ord {

	#[ inline ]
	fn seen_get_mut (& mut self, node: GridCursor <Pos, DIMS>) -> & mut SeenState <Pri> {
		Self::get_mut (self, node.native ()).unwrap_or_else (
			|| panic! ("Position is not in grid: {node:?}"))
	}

}

#[ derive (Clone) ]
pub enum SeenState <Pri: Clone> {
	New,
	Unvisited (Pri),
	Visited,
}

impl <Pri: Clone> Default for SeenState <Pri> {

	#[ inline ]
	fn default () -> Self {
		Self::New
	}

}