1use alloc::vec::Vec;
21
22use crate::graph::{Graph, ReverseGraph};
23
24#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct BenchmarkGraph<const N: usize> {
28 out: Vec<Vec<(u32, [u32; N])>>,
30 into: Vec<Vec<(u32, [u32; N])>>,
32}
33
34pub type Query = (u32, u32);
36
37impl<const N: usize> BenchmarkGraph<N> {
38 #[must_use]
44 pub fn from_arcs(nodes: u32, arcs: &[(u32, u32, [u32; N])]) -> Self {
45 let n = usize::try_from(nodes).expect("node counts fit in usize");
46 let mut graph = Self {
47 out: alloc::vec![Vec::new(); n],
48 into: alloc::vec![Vec::new(); n],
49 };
50 for &(from, to, cost) in arcs {
51 graph.out[index(from)].push((to, cost));
52 graph.into[index(to)].push((from, cost));
53 }
54
55 graph
56 }
57
58 #[must_use]
64 pub fn node_count(&self) -> u32 {
65 u32::try_from(self.out.len()).expect("built from a u32 count")
66 }
67
68 #[must_use]
70 pub fn arc_count(&self) -> usize {
71 self.out.iter().map(Vec::len).sum()
72 }
73
74 pub fn arcs(&self) -> impl Iterator<Item = (u32, u32, [u32; N])> + '_ {
80 self.out.iter().enumerate().flat_map(|(u, edges)| {
81 let u = u32::try_from(u).expect("built from a u32 count");
82 edges.iter().map(move |&(v, c)| (u, v, c))
83 })
84 }
85
86 #[must_use]
94 pub fn project<const M: usize>(&self, objectives: [usize; M]) -> BenchmarkGraph<M> {
95 let pick = |c: [u32; N]| objectives.map(|i| c[i]);
96 let arcs: Vec<_> = self.arcs().map(|(u, v, c)| (u, v, pick(c))).collect();
97 BenchmarkGraph::from_arcs(self.node_count(), &arcs)
98 }
99}
100
101impl<const N: usize> Graph for BenchmarkGraph<N> {
102 type State = u32;
103 type Weight = [u32; N];
104
105 fn successors(&self, state: &u32, out: &mut Vec<(u32, [u32; N])>) {
106 out.extend_from_slice(&self.out[index(*state)]);
107 }
108}
109
110impl<const N: usize> ReverseGraph for BenchmarkGraph<N> {
111 fn predecessors(&self, state: &u32, out: &mut Vec<(u32, [u32; N])>) {
112 out.extend_from_slice(&self.into[index(*state)]);
113 }
114}
115
116fn index(state: u32) -> usize {
118 usize::try_from(state).expect("u32 fits in usize")
119}
120
121#[derive(Debug, Clone)]
123struct Rng(u64);
124
125impl Rng {
126 fn next(&mut self) -> u64 {
128 self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15);
129 let mut z = self.0;
130 z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
131 z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
132 z ^ (z >> 31)
133 }
134
135 fn range(&mut self, low: u32, high: u32) -> u32 {
137 let span = u64::from(high - low) + 1;
138 low + u32::try_from(self.next() % span).expect("below the span")
139 }
140}
141
142#[must_use]
155pub fn random_grid<const N: usize>(
156 width: u32,
157 height: u32,
158 seed: u64,
159) -> (BenchmarkGraph<N>, Query) {
160 assert!(width > 0 && height > 0, "a grid needs at least one cell");
161 let cells = width.checked_mul(height).expect("the grid fits u32 states");
162 let (source, target) = (cells, cells + 1);
163 let mut rng = Rng(seed);
164 let mut cost = || core::array::from_fn(|_| rng.range(1, 10));
165 let mut arcs = Vec::new();
166
167 for y in 0..height {
168 for x in 0..width {
169 let cell = y * width + x;
170 if x + 1 < width {
171 arcs.push((cell, cell + 1, cost()));
172 arcs.push((cell + 1, cell, cost()));
173 }
174
175 if y + 1 < height {
176 arcs.push((cell, cell + width, cost()));
177 arcs.push((cell + width, cell, cost()));
178 }
179 }
180
181 arcs.push((source, y * width, cost()));
182 arcs.push((y * width + width - 1, target, cost()));
183 }
184
185 (
186 BenchmarkGraph::from_arcs(cells + 2, &arcs),
187 (source, target),
188 )
189}
190
191#[must_use]
205pub fn netmaker(
206 nodes: u32,
207 out_min: u32,
208 out_max: u32,
209 locality: u32,
210 seed: u64,
211) -> BenchmarkGraph<3> {
212 assert!(
213 nodes >= 2 && out_min < out_max,
214 "`NetMaker` needs two states and out_min < out_max"
215 );
216 let mut rng = Rng(seed);
217
218 let mut order: Vec<u32> = (0..nodes).collect();
220 for i in (1..order.len()).rev() {
221 let j = index(rng.range(0, u32::try_from(i).expect("below nodes")));
222 order.swap(i, j);
223 }
224
225 let mut out: Vec<Vec<(u32, [u32; 3])>> = alloc::vec![Vec::new(); index(nodes)];
226 for k in 0..order.len() {
227 let (u, v) = (order[k], order[(k + 1) % order.len()]);
228 let mut bands = [(1, 333), (334, 666), (667, 1000)];
229 for i in (1..3).rev() {
230 let j = index(rng.range(0, u32::try_from(i).expect("below 3")));
231 bands.swap(i, j);
232 }
233
234 out[index(u)].push((v, bands.map(|(low, high)| rng.range(low, high))));
235 }
236
237 for u in 0..nodes {
238 let degree = rng.range(out_min + 1, out_max);
239 let low = u.saturating_sub(locality / 2);
240 let high = (u + locality / 2).min(nodes - 1);
241 let mut free: Vec<u32> = (low..=high)
242 .filter(|&v| v != u && out[index(u)].iter().all(|e| e.0 != v))
243 .collect();
244
245 while out[index(u)].len() < index(degree) && !free.is_empty() {
246 let pick = index(rng.range(0, u32::try_from(free.len() - 1).expect("small")));
247 let v = free.swap_remove(pick);
248 out[index(u)].push((v, core::array::from_fn(|_| rng.range(1, 99))));
249 }
250 }
251
252 let arcs: Vec<_> = out
253 .iter()
254 .enumerate()
255 .flat_map(|(u, edges)| {
256 edges
257 .iter()
258 .map(move |&(v, c)| (u32::try_from(u).expect("below nodes"), v, c))
259 })
260 .collect();
261 BenchmarkGraph::from_arcs(nodes, &arcs)
262}
263
264#[must_use]
271pub fn netmaker_queries(nodes: u32, count: usize, seed: u64) -> Vec<Query> {
272 assert!(nodes >= 10, "queries need at least ten states");
273 let tenth = nodes / 10;
274 let mut rng = Rng(seed);
275 (0..count)
276 .map(|_| (rng.range(0, tenth - 1), rng.range(nodes - tenth, nodes - 1)))
277 .collect()
278}
279
280#[must_use]
300pub fn guards_grid(map: &str, guards: &[(u32, u32)]) -> Option<BenchmarkGraph<2>> {
301 let (width, height, open) = parse_map(map)?;
302 let passable = |x: i64, y: i64| {
303 x >= 0 && y >= 0 && x < i64::from(width) && y < i64::from(height) && open[cell(width, x, y)]
304 };
305 let exposure: Vec<u32> = (0..height)
306 .flat_map(|y| (0..width).map(move |x| (x, y)))
307 .map(|(x, y)| {
308 let seen = guards
309 .iter()
310 .filter(|&&(gx, gy)| {
311 sees(
312 &passable,
313 (i64::from(gx), i64::from(gy)),
314 (i64::from(x), i64::from(y)),
315 )
316 })
317 .count();
318 u32::try_from(seen).expect("guard counts fit")
319 })
320 .collect();
321
322 let mut arcs = Vec::new();
323 for y in 0..i64::from(height) {
324 for x in 0..i64::from(width) {
325 if !passable(x, y) {
326 continue;
327 }
328
329 for (dx, dy) in [
330 (1, 0),
331 (-1, 0),
332 (0, 1),
333 (0, -1),
334 (1, 1),
335 (1, -1),
336 (-1, 1),
337 (-1, -1),
338 ] {
339 let (tx, ty) = (x + dx, y + dy);
340 if !passable(tx, ty) {
341 continue;
342 }
343
344 let diagonal = dx != 0 && dy != 0;
345 let risk = if diagonal {
346 if !passable(x + dx, y) || !passable(x, y + dy) {
347 continue;
348 }
349
350 exposure[cell(width, tx, ty)]
351 .max(exposure[cell(width, x + dx, y)])
352 .max(exposure[cell(width, x, y + dy)])
353 } else {
354 exposure[cell(width, tx, ty)]
355 };
356
357 let id = |x: i64, y: i64| u32::try_from(cell(width, x, y)).expect("cells fit u32");
358 arcs.push((id(x, y), id(tx, ty), [if diagonal { 14 } else { 10 }, risk]));
359 }
360 }
361 }
362
363 Some(BenchmarkGraph::from_arcs(width.checked_mul(height)?, &arcs))
364}
365
366fn cell(width: u32, x: i64, y: i64) -> usize {
368 usize::try_from(y * i64::from(width) + x).expect("a cell on the map")
369}
370
371fn parse_map(map: &str) -> Option<(u32, u32, Vec<bool>)> {
373 let mut lines = map.lines();
374 let (mut width, mut height) = (None, None);
375 for line in lines.by_ref() {
376 let mut words = line.split_whitespace();
377 match (words.next(), words.next()) {
378 (Some("height"), Some(h)) => height = h.parse().ok(),
379 (Some("width"), Some(w)) => width = w.parse().ok(),
380 (Some("map"), None) => break,
381 _ => {}
382 }
383 }
384
385 let (width, height): (u32, u32) = (width?, height?);
386 let mut open = Vec::new();
387 for _ in 0..height {
388 let row = lines.next()?;
389 if row.chars().count() != index(width) {
390 return None;
391 }
392
393 open.extend(row.chars().map(|c| matches!(c, '.' | 'G' | 'S')));
394 }
395
396 Some((width, height, open))
397}
398
399fn sees(passable: &impl Fn(i64, i64) -> bool, from: (i64, i64), to: (i64, i64)) -> bool {
402 let (mut x, mut y) = from;
403 let (dx, dy) = ((to.0 - x).abs(), -(to.1 - y).abs());
404 let (sx, sy) = (if x < to.0 { 1 } else { -1 }, if y < to.1 { 1 } else { -1 });
405 let mut err = dx + dy;
406
407 loop {
408 if !passable(x, y) {
409 return false;
410 }
411
412 if (x, y) == to {
413 return true;
414 }
415
416 let e2 = 2 * err;
417 if e2 >= dy {
418 err += dy;
419 x += sx;
420 }
421
422 if e2 <= dx {
423 err += dx;
424 y += sy;
425 }
426 }
427}
428
429#[must_use]
441pub fn road_extended(
442 nodes: u32,
443 arcs: &[(u32, u32, [u32; 2])],
444 elevation: &[i32],
445) -> BenchmarkGraph<5> {
446 let mut degree = alloc::vec![0_u32; index(nodes)];
447 for &(u, _, _) in arcs {
448 degree[index(u)] += 1;
449 }
450
451 let extended: Vec<_> = arcs
452 .iter()
453 .map(|&(u, v, [d, t])| {
454 let rise = elevation[index(u)].abs_diff(elevation[index(v)]);
455 (u, v, [d, t, rise, degree[index(u)] + degree[index(v)], 1])
456 })
457 .collect();
458
459 BenchmarkGraph::from_arcs(nodes, &extended)
460}