Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::collections::{HashMap, HashSet, VecDeque};
- use std::iter::once;
- use std::str;
- fn main() {
- let mut state: Vec<_> = INITIAL_STATE.bytes().collect();
- let mut idx_min = 0i64;
- let mut idx_max = state.len() as i64;
- let rules: HashMap<&[u8], u8> = RULES
- .split('\n')
- .map(|r| (&r.as_bytes()[0..5], r.bytes().nth(9).unwrap()))
- .collect();
- let mut visited = HashMap::new();
- visited.insert(state.clone(), (0, idx_min, idx_max));
- //println!("{:3} | {} | {}", idx_min, str::from_utf8(&state[..]).unwrap(), idx_max);
- let mut i = 0;
- loop {
- i += 1;
- let l = state.len();
- idx_min -= 2;
- idx_max += 2;
- state = once(&[b'.', b'.', b'.', b'.', state[0]][..])
- .chain(once(&[b'.', b'.', b'.', state[0], state[1]][..]))
- .chain(once(&[b'.', b'.', state[0], state[1], state[2]][..]))
- .chain(once(&[b'.', state[0], state[1], state[2], state[3]][..]))
- .chain(state.windows(5))
- .chain(once(
- &[state[l - 4], state[l - 3], state[l - 2], state[l - 1], b'.'][..],
- ))
- .chain(once(
- &[state[l - 3], state[l - 2], state[l - 1], b'.', b'.'][..],
- ))
- .chain(once(&[state[l - 2], state[l - 1], b'.', b'.', b'.'][..]))
- .chain(once(&[state[l - 1], b'.', b'.', b'.', b'.'][..]))
- .map(|x| rules[x])
- .skip_while(|&x| {
- if x == b'.' {
- idx_min += 1;
- true
- } else {
- false
- }
- })
- //.inspect(|x| println!("{:?}", x))
- .collect();
- while let Some(b'.') = state.last() {
- state.pop();
- idx_max -= 1;
- }
- assert_eq!(idx_max - idx_min, state.len() as i64);
- if visited.contains_key(&state) {
- let (a, b, c) = visited[&state];
- println!("steady state detected {} : {} ... {} --> {} : {} ... {}", a, b, c, i, idx_min, idx_max);
- break
- } else {
- visited.insert(state.clone(), (i, idx_min, idx_max));
- }
- //println!("{:3} | {} | {}", idx_min, str::from_utf8(&state[..]).unwrap(), idx_max);
- if i == 20 {
- println!("solution A: {}", state.iter().zip(idx_min..idx_max).filter_map(|(&x, i)| if x == b'#' {Some(i)} else {None}).sum::<i64>())
- }
- }
- idx_min += 50000000000 - i;
- idx_max += 50000000000 - i;
- println!("solution B: {}", state.iter().zip(idx_min..idx_max).filter_map(|(&x, i)| if x == b'#' {Some(i)} else {None}).sum::<i64>())
- }
- const INITIAL_STATE: &str = "#...#..##.......####.#..###..#.##..########.#.#...#.#...###.#..###.###.#.#..#...#.#..##..#######.##";
- const RULES: &str = "#..#. => #
- #.#.. => #
- ###.. => #
- ##..# => .
- .#.## => #
- ..... => .
- ...#. => #
- ##.#. => #
- #.#.# => .
- ###.# => #
- ....# => .
- ####. => #
- .##.. => #
- #.##. => #
- #..## => #
- ##... => #
- #...# => .
- ##.## => #
- .#... => .
- .#..# => #
- ..#.# => #
- ##### => .
- .#### => #
- ..#.. => #
- #.### => .
- ..##. => .
- .##.# => #
- .#.#. => .
- ..### => .
- .###. => .
- ...## => .
- #.... => .";
Add Comment
Please, Sign In to add comment