|
| 1 | +fn count_arrangements(s: &str, damage_seqs: &[usize]) -> i32 { |
| 2 | + let s = s.trim_start_matches('.'); |
| 3 | + let count = s |
| 4 | + .strip_prefix('?') |
| 5 | + .map(|s| count_arrangements(s, damage_seqs)) |
| 6 | + .unwrap_or(0); |
| 7 | + if let Some((&d, damage_seqs)) = damage_seqs.split_first() { |
| 8 | + let mut d = d; |
| 9 | + let mut s = s; |
| 10 | + while d > 0 { |
| 11 | + if let Some(s_suffix) = s.strip_prefix(&['#', '?']) { |
| 12 | + s = s_suffix; |
| 13 | + d -= 1; |
| 14 | + } else { |
| 15 | + break; |
| 16 | + } |
| 17 | + } |
| 18 | + if d > 0 { |
| 19 | + // not enough damage to match |
| 20 | + count |
| 21 | + } else if !damage_seqs.is_empty() { |
| 22 | + if let Some(s_suffix) = s.strip_prefix(&['.', '?']) { |
| 23 | + count + count_arrangements(s_suffix, damage_seqs) |
| 24 | + } else { |
| 25 | + // a gap must exist between damage sequences |
| 26 | + count |
| 27 | + } |
| 28 | + } else { |
| 29 | + count + count_arrangements(s, damage_seqs) |
| 30 | + } |
| 31 | + } else if s.is_empty() { |
| 32 | + // good match: damage_seqs and s are both empty |
| 33 | + count + 1 |
| 34 | + } else { |
| 35 | + // no match: damage_seqs is empty, but s is not empty |
| 36 | + count |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +fn main() { |
| 41 | + let sum: i32 = std::io::stdin() |
| 42 | + .lines() |
| 43 | + .map(Result::unwrap) |
| 44 | + .map(|line| { |
| 45 | + let (row, line) = line.split_once(" ").unwrap(); |
| 46 | + let damage_seqs = line |
| 47 | + .split(",") |
| 48 | + .map(|d| d.parse::<usize>().expect("damage usize")) |
| 49 | + .collect::<Vec<usize>>(); |
| 50 | + count_arrangements(row, &damage_seqs[..]) |
| 51 | + }) |
| 52 | + .sum(); |
| 53 | + println!("{sum}"); |
| 54 | +} |
| 55 | + |
| 56 | +#[test] |
| 57 | +#[rustfmt::skip] |
| 58 | +fn test_count_arrangements() { |
| 59 | + assert_eq!(1, count_arrangements("???.###", &[1, 1, 3])); |
| 60 | + assert_eq!(4, count_arrangements(".??..??...?##", &[1, 1, 3])); |
| 61 | + assert_eq!(1, count_arrangements("?#?#?#?#?#?#?#?", &[1, 3, 1, 6])); |
| 62 | + assert_eq!(1, count_arrangements("????.#...#...", &[4, 1, 1])); |
| 63 | + assert_eq!(4, count_arrangements("????.######..#####.", &[1, 6, 5])); |
| 64 | + assert_eq!(10, count_arrangements("?###????????", &[3, 2, 1])); |
| 65 | +} |
0 commit comments