DEV Community

Discussion on: Daily Challenge #173 - Pandemia

Collapse
 
idanarye profile image
Idan Arye

Rust:

fn infected(map: &str) -> f64 {
    #[derive(Debug)]
    enum Cell {
        Uninfected,
        Infected,
        Ocean,
    }
    let mut map: Vec<_> = map.chars().map(|c| match c {
            '0' => Cell::Uninfected,
            '1' => Cell::Infected,
            'X' => Cell::Ocean,
            _ => panic!("Illegal cell type {}", c),
        }).collect();

    fn propagate<'a>(cells: impl Iterator<Item = &'a mut Cell>) {
        let mut infecting = false;
        for cell in cells {
            match cell {
                Cell::Uninfected => {
                    if infecting {
                        *cell = Cell::Infected;
                    }
                }
                Cell::Infected => {
                    infecting = true;
                }
                Cell::Ocean => {
                    infecting = false;
                }
            }
        }
    }
    propagate(map.iter_mut());
    propagate(map.iter_mut().rev());

    let mut infected = 0usize;
    let mut total = 0usize;
    for cell in map {
        match cell {
            Cell::Uninfected => {
                total += 1;
            }
            Cell::Infected => {
                total += 1;
                infected += 1;
            }
            Cell::Ocean => {}
        }
    }
    if total == 0 {
        0.0
    } else {
        100.0 * infected as f64 / total as f64
    }
}

fn main() {
    assert_eq!(infected("01000000X000X011X0X"), 73.33333333333333);
    assert_eq!(infected("01X000X010X011XX"), 72.72727272727273);
    assert_eq!(infected("XXXXX"), 0.0);
    assert_eq!(infected("00000000X00X0000"), 0.0);
    assert_eq!(infected("0000000010"), 100.0);
    assert_eq!(infected("000001XXXX0010X1X00010"), 100.0);
    assert_eq!(infected("X00X000000X10X0100"), 42.857142857142854);
}