summaryrefslogtreecommitdiff
path: root/08/src/stuff.rs
blob: 7e886058bff342f3ed9beb3c1c10592e8975af30 (plain)
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
use std::collections::{HashMap};
use std::io::{BufRead};

pub fn ascii_to_u64(s: & [u8]) -> u64 {
    #[cfg(debug_assertions)]
    {
        assert!(s.into_iter().all(|& c| c.is_ascii_digit()), "Not an ASCII base-10 number");
    }

    // SAFETY: AoC is ASCII-only.
    unsafe { std::str::from_utf8_unchecked(s) }.parse().unwrap()
}

pub fn is_all_ascii_ws<'a, I: IntoIterator<Item = &'a u8>>(s: I) -> bool {
    s.into_iter().all(|& c| c.is_ascii_whitespace())
}

pub fn read_helper<'a, 'b, R: BufRead>(r: &'a mut R, buf: &'b mut Vec<u8>, token: u8) -> std::io::Result<usize> {
    buf.clear();
    let num_bytes = r.read_until(token, buf)?;
    if buf.last() == Some(& token) { buf.pop(); }
    Ok(num_bytes)
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Direction {
    L, R
}

impl TryFrom<u8> for Direction {
    type Error = &'static str;

    fn try_from(c: u8) -> Result<Self, Self::Error> {
        match c {
            b'L' => Ok(Self::L),
            b'R' => Ok(Self::R),
            _    => Err("ASCII character not a valid direction")
        }
    }
}

pub type Node = [u8; 3];

pub fn gcd(mut m: u64, mut n: u64) -> u64 {
    if m < n {
        std::mem::swap(&mut m, &mut n);
    }
    
    while n > 0 {
        let r: u64 = m % n;
        m = n;
        n = r;
    }
    m
}

pub fn lcm(m: u64, n: u64) -> u64 {
    m*(n/gcd(m, n))
}

pub fn walk<'a, I, F>(start: Node, is_finish: F, map: & HashMap<Node, (Node, Node)>, instructions: I) -> usize
where I: IntoIterator<Item = &'a Direction>,
<I as IntoIterator>::IntoIter: Clone,
F: Fn(Node) -> bool {
    let mut node: Node = start;
    for (i, instruction) in instructions.into_iter().cycle().enumerate() {
        if is_finish(node) {
            return i;
        }
        let (left, right) = map.get(& node).expect("Non-existent node");
        match instruction {
            Direction::L => { node = *left; },
            Direction::R => { node = *right; }
        }
    }
    unreachable!("Non-terminating map")
}


#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_gcd() {
        assert_eq!(gcd(1238124652, 22146), 2);
    }

    #[test]
    fn test_gcd_2() {
        assert_eq!(gcd(5025124, 1040), 52);
    }

    #[test]
    fn test_gcd_3() {
        assert_eq!(gcd(1040, 5025124), 52);
    }

    #[test]
    fn test_lcm() {
        assert_eq!(lcm(1040, 5025124), 100502480);
    }

}