|
| 1 | +use common::sfy::Sfy; |
| 2 | +use fancy_regex::*; |
| 3 | + |
| 4 | +pub fn run(input: &str) { |
| 5 | + println!("pro-tip: compile with --release!"); |
| 6 | + |
| 7 | + let part1 = solve(input); |
| 8 | + println!("part 1: {}", part1); |
| 9 | + assert_eq!(part1, "vzbxxyzz"); |
| 10 | + |
| 11 | + let part2 = solve("vzbxxyzz"); |
| 12 | + println!("part 2: {}", part2); |
| 13 | + assert_eq!(part2, "vzcaabcc"); |
| 14 | +} |
| 15 | + |
| 16 | +fn solve(input: &str) -> String { |
| 17 | + // loop until we find a string which is valid |
| 18 | + let len = input.len(); |
| 19 | + let mut s = Vec::from(input.as_bytes()); |
| 20 | + next(&mut s, len - 1); |
| 21 | + |
| 22 | + let re = Regex::new(r"(.)\1.*(.)\2").unwrap(); |
| 23 | + |
| 24 | + while !valid(&s, &re) { |
| 25 | + next(&mut s, len - 1); |
| 26 | + } |
| 27 | + return s.sfy(); |
| 28 | +} |
| 29 | + |
| 30 | +// recursively increment the input |
| 31 | +fn next(input: &mut [u8], offset: usize) { |
| 32 | + if input[offset] == b'z' { |
| 33 | + input[offset] = b'a'; |
| 34 | + next(input, offset - 1); |
| 35 | + } else { |
| 36 | + input[offset] = input[offset] + 1; |
| 37 | + if (input[offset] == b'i') || (input[offset] == b'o') || (input[offset] == b'l') { |
| 38 | + // mini-optimization |
| 39 | + input[offset] = input[offset] + 1; |
| 40 | + for i in (offset + 1)..input.len() { |
| 41 | + input[i] = b'a'; |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +fn valid(input: &[u8], re: &Regex) -> bool { |
| 48 | + // use a helper function to find a straight of 3 letters |
| 49 | + if !has_straight(&input) { |
| 50 | + return false; |
| 51 | + } |
| 52 | + |
| 53 | + // use a a loop to check if input contains i, o or l. |
| 54 | + for i in input.iter() { |
| 55 | + if (*i == b'i') || (*i == b'o') || (*i == b'l') { |
| 56 | + return false; |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + // use regexp to check for non-overlapping pairs |
| 61 | + if !re.is_match(&input.sfy()).unwrap() { |
| 62 | + return false; |
| 63 | + } |
| 64 | + |
| 65 | + return true; |
| 66 | +} |
| 67 | + |
| 68 | +fn has_straight(input: &[u8]) -> bool { |
| 69 | + for i in 0..input.len() - 2 { |
| 70 | + if (input[i] == input[i + 1] - 1) && (input[i] == input[i + 2] - 2) { |
| 71 | + return true; |
| 72 | + } |
| 73 | + } |
| 74 | + return false; |
| 75 | +} |
0 commit comments