wycy's recent activity

  1. Comment on Day 9: Smoke Basin in ~comp.advent_of_code

    wycy
    Link
    Rust Rust use std::env; use std::io::{self, prelude::*, BufReader}; use std::fs::File; use std::collections::{HashMap,HashSet}; use point2d::point2d::Point2D; fn neighbor_addresses(pt: &Point2D)...

    Rust

    Rust
    use std::env;
    use std::io::{self, prelude::*, BufReader};
    use std::fs::File;
    use std::collections::{HashMap,HashSet};
    
    use point2d::point2d::Point2D;
    
    fn neighbor_addresses(pt: &Point2D) -> Vec<Point2D> {
        vec![Point2D{ x: pt.x  , y: pt.y-1 },  // up
             Point2D{ x: pt.x+1, y: pt.y   },  // right
             Point2D{ x: pt.x  , y: pt.y+1 },  // down
             Point2D{ x: pt.x-1, y: pt.y   }]  // left
    }
    
    fn neighbor_values(pt: &Point2D, map: &HashMap<Point2D,i64>) -> Vec<i64> {
        let neighbors = neighbor_addresses(&pt);
        let mut values: Vec<i64> = Vec::new();
        for neighbor in neighbors {
            match map.get(&neighbor) {
                Some(value) => values.push(*value),
                None => {},
            }
        }
        values
    }
    
    fn is_low(pt: Point2D, map: &HashMap<Point2D,i64>) -> bool {
        let neighbor_values = neighbor_values(&pt, &map);
        map.get(&pt).unwrap() < neighbor_values.iter().min().unwrap()
    }
    
    fn uphill_neighbors(pt: Point2D, map: &HashMap<Point2D,i64>) -> Vec<Point2D> {
        let this_value = map.get(&pt).unwrap();
        let neighbors = neighbor_addresses(&pt);
        let mut uphill: Vec<Point2D> = Vec::new();
        for neighbor in neighbors {
            match map.get(&neighbor) {
                Some(value) => {
                    if value > this_value && value < &9 {
                        uphill.push(neighbor);
                        for n in uphill_neighbors(neighbor,&map) { uphill.push(n); }
                    }
                },
                None => {},
            }
        }
        uphill
    }
    
    fn risk_level(pt: Point2D, map: &HashMap<Point2D,i64>) -> i64 {
        map.get(&pt).unwrap() + 1
    }
    
    fn map_extents(map: &HashMap<Point2D,i64>) -> (i64,i64,i64,i64) {
        let xmin = &map.keys().map(|&pt| pt.x).min().unwrap();
        let ymin = &map.keys().map(|&pt| pt.y).min().unwrap();
        let xmax = &map.keys().map(|&pt| pt.x).max().unwrap();
        let ymax = &map.keys().map(|&pt| pt.y).max().unwrap();
        (*xmin,*ymin,*xmax,*ymax)
    }
    
    fn solve(input: &str) -> io::Result<()> {
        let file = File::open(input).expect("Input file not found.");
        let reader = BufReader::new(file);
    
        // Input
        let input: Vec<String> = match reader.lines().collect() {
            Err(err) => panic!("Unknown error reading input: {}", err),
            Ok(result) => result,
        };
    
        // Build smoke map
        let mut smoke_map: HashMap<Point2D,i64> = HashMap::new();
        for (y,line) in input.iter().enumerate() {
            for (x,ch) in line.chars().enumerate() {
                let (x,y,v) = (x as i64, y as i64, ch.to_digit(10).unwrap());
                smoke_map.insert(Point2D{x,y},v.into());
            }
        }
    
        // Part 1
        let mut part1: i64 = 0;
        let mut basins: Vec<Point2D> = Vec::new();
        let (xmin,ymin,xmax,ymax) = map_extents(&smoke_map);
        for y in ymin..=ymax {
            for x in xmin..=xmax {
                let pt = Point2D { x: x, y: y };
                if is_low(pt,&smoke_map) {
                    basins.push(pt);
                    part1 += risk_level(pt,&smoke_map);
                }
            }
        }
        println!("Part 1: {}", part1); // 575
    
        // Part 2
        let mut basin_sizes: Vec<usize> = Vec::new();
        for basin in basins {
            let basin = uphill_neighbors(basin,&smoke_map);
            let this_basin: HashSet<Point2D> = HashSet::from_iter(basin);
            let basin_size = this_basin.len() + 1;
            basin_sizes.push(basin_size);
        }
        basin_sizes.sort_by(|a,b| b.cmp(a)); // descending sort
        let part2 = basin_sizes[0] * basin_sizes[1] * basin_sizes[2];
        println!("Part 2: {}", part2); // 1019700
    
        Ok(())
    }
    
    fn main() {
        let args: Vec<String> = env::args().collect();
        let filename = &args[1];
        solve(&filename).unwrap();
    }
    
    1 vote
  2. Comment on Day 8: Seven Segment Search in ~comp.advent_of_code

    wycy
    (edited )
    Link
    Rust Brutal. SPOILERI spent so much time trying to figure out the individual wire mapping before realizing I didn't need to. Deleted 75% of my code in the end. Rust use std::env; use...

    Rust

    Brutal.

    SPOILERI spent so much time trying to figure out the individual wire mapping before realizing I didn't need to. Deleted 75% of my code in the end.

    Rust
    use std::env;
    use std::io::{self, prelude::*, BufReader};
    use std::fs::File;
    
    // Count number of matches second string has to characters in first string
    fn num_matches(first: &String, second: &String) -> usize {
        first.chars().filter(|c| second.contains(&c.to_string())).count()
    }
    
    struct PuzzleInput {
        signals: Vec<String>,
        outputs: Vec<String>,
    }
    impl PuzzleInput {
        pub fn output(&self) -> usize {
            let signal1 = self.signals.iter().filter(|s| s.len() == 2).map(|s| s.to_string()).next().unwrap();
            let signal4 = self.signals.iter().filter(|s| s.len() == 4).map(|s| s.to_string()).next().unwrap();
          //let signal7 = self.signals.iter().filter(|s| s.len() == 3).map(|s| s.to_string()).next().unwrap();
          //let signal8 = self.signals.iter().filter(|s| s.len() == 7).map(|s| s.to_string()).next().unwrap();
    
            let mut output = String::new();
            for o in &self.outputs {
                match (o.len(),num_matches(&o,&signal1),num_matches(&o,&signal4)) {
                    (6,2,3) => output.push_str("0"),
                    (2,_,_) => output.push_str("1"),
                    (5,1,2) => output.push_str("2"),
                    (5,2,3) => output.push_str("3"),
                    (4,_,_) => output.push_str("4"),
                    (5,1,3) => output.push_str("5"),
                    (6,1,3) => output.push_str("6"),
                    (3,_,_) => output.push_str("7"),
                    (7,_,_) => output.push_str("8"),
                    (6,_,4) => output.push_str("9"),
                    (_,_,_) => panic!("Unknown failure for signal: {}",&o),
                }
            }
            output.parse::<usize>().unwrap()
        }
    }
    impl From<&String> for PuzzleInput {
        fn from(s: &String) -> Self {
            let parts = s.split(" | ").collect::<Vec<_>>();
            let signals = parts[0].split_ascii_whitespace().map(|x| x.to_string()).collect();
            let outputs = parts[1].split_ascii_whitespace().map(|x| x.to_string()).collect();
            Self {
                signals: signals,
                outputs: outputs,
            }
        }
    }
    
    fn day08(input: &str) -> io::Result<()> {
        let file = File::open(input).expect("Input file not found.");
        let reader = BufReader::new(file);
    
        // Input
        let input: Vec<String> = match reader.lines().collect() {
            Err(err) => panic!("Unknown error reading input: {}", err),
            Ok(result) => result,
        };
        let inputs: Vec<_> = input.iter().map(PuzzleInput::from).collect();
    
        // Part 1
        let part1 = inputs
            .iter()
            .map(|x| {
                x.outputs
                    .iter()
                    .filter(|o| o.len() == 2 || o.len() == 4 || o.len() == 3 || o.len() == 7) // 1,4,7,8
                    .count()
            })
            .sum::<usize>();
        println!("Part 1: {}", part1); // 488
    
        // Part 2
        let part2 = inputs.iter().map(|x| x.output()).sum::<usize>();
        println!("Part 2: {}", part2); // 1040429
    
        Ok(())
    }
    
    fn main() {
        let args: Vec<String> = env::args().collect();
        let filename = &args[1];
        day08(&filename).unwrap();
    }
    
    5 votes
  3. Comment on Day 7: The Treachery of Whales in ~comp.advent_of_code

    wycy
    Link
    It turns out that the input to today's problem is also a valid Intcode program. If anyone wrote an Intcode VM for AOC 2019, it's worth running today's input through your VM.

    It turns out that the input to today's problem is also a valid Intcode program. If anyone wrote an Intcode VM for AOC 2019, it's worth running today's input through your VM.

    4 votes
  4. Comment on What games have you been playing, and what's your opinion on them? in ~games

    wycy
    Link
    I'm playing Pokemon Brilliant Diamond. I don't love it. I bought it somewhat by accident thinking it was the newest Pokemon game (apparently I was thinking of Arceus) and not just the newest...

    I'm playing Pokemon Brilliant Diamond. I don't love it. I bought it somewhat by accident thinking it was the newest Pokemon game (apparently I was thinking of Arceus) and not just the newest remake. The wild encounters are tedious. I can only stand to watch the dramatic battle animation to fight a Wooper so many times in a row before I lose it. That said, for now I'll keep playing.

    3 votes
  5. Comment on Day 7: The Treachery of Whales in ~comp.advent_of_code

    wycy
    Link Parent
    Side note: AoC really makes me appreciate Rust's ability to chain functions in the order that they're used, rather than having to nest them. To me, this is so clean: let input =...

    Side note: AoC really makes me appreciate Rust's ability to chain functions in the order that they're used, rather than having to nest them. To me, this is so clean:

        let input = std::fs::read_to_string(input)
            .unwrap()
            .trim()
            .split(",")
            .map(|x| x.parse::<isize>().unwrap())
            .collect();
    

    As opposed to languages where this would need to be nested and written in the opposite order:

    let input = collect(unwrap(parse::<i64>(split(trim(unwrap(std::fs::read_to_string(input))),","))))
    
    4 votes
  6. Comment on Day 7: The Treachery of Whales in ~comp.advent_of_code

    wycy
    (edited )
    Link
    Rust Rust use std::env; use std::io::{self}; fn part1(input: &Vec<isize>) -> isize { let min = input.iter().min().unwrap(); let max = input.iter().max().unwrap(); let mut min_fuel = isize::MAX;...

    Rust

    Rust
    use std::env;
    use std::io::{self};
    
    fn part1(input: &Vec<isize>) -> isize {
        let min = input.iter().min().unwrap();
        let max = input.iter().max().unwrap();
        let mut min_fuel = isize::MAX;
        for pos in *min..=*max {
            let mut fuel = 0;
            for crab in input {
                fuel += (pos - crab).abs();
            }
            min_fuel = std::cmp::min(min_fuel, fuel);
        }
        min_fuel
    }
    
    fn part2(input: &Vec<isize>) -> isize {
        let min = input.iter().min().unwrap();
        let max = input.iter().max().unwrap();
        let mut min_fuel = isize::MAX;
        for pos in *min..=*max {
            let mut fuel = 0;
            for crab in input {
                let x = (pos - crab).abs();
                fuel += (x.pow(2) + x) / 2;
            }
            min_fuel = std::cmp::min(min_fuel, fuel);
        }
        min_fuel
    }
    
    fn day07(input: &str) -> io::Result<()> {
        // Input
        let input = std::fs::read_to_string(input)
            .unwrap()
            .trim()
            .split(",")
            .map(|x| x.parse::<isize>().unwrap())
            .collect();
    
        // Answers
        println!("Part 1: {}", part1(&input)); // 349812
        println!("Part 2: {}", part2(&input)); // 99763899
    
        Ok(())
    }
    
    fn main() {
        let args: Vec<String> = env::args().collect();
        let filename = &args[1];
        day07(&filename).unwrap();
    }
    
    4 votes
  7. Comment on Day 6: Lanternfish in ~comp.advent_of_code

    wycy
    Link
    Rust Rust use std::env; use std::io::{self}; const INITIAL_SPAWN_DAYS: usize = 8; const RESPAWN_DAYS: usize = 6; const DAYS_P1: usize = 80; const DAYS_P2: usize = 256; fn day06(input: &str) ->...

    Rust

    Rust
    use std::env;
    use std::io::{self};
    const INITIAL_SPAWN_DAYS: usize = 8;
    const RESPAWN_DAYS: usize = 6;
    const DAYS_P1: usize = 80;
    const DAYS_P2: usize = 256;
    fn day06(input: &str) -> io::Result<()> {
        // Input
        let input_str = std::fs::read_to_string(input).unwrap();
        let input_str = input_str.trim();
        let fishes: Vec<_> = input_str.split(',').map(|x| x.parse::<isize>().unwrap()).collect();
        // Initialize
        let mut num_fishes = fishes.len() as isize;
        let mut spawns = vec![0; INITIAL_SPAWN_DAYS+1]; // index is number of days away
        for fish in fishes {
            spawns[fish as usize] += 1;
        }
        // Run
        for day in 0..DAYS_P2 {
            if day == DAYS_P1 { println!("Part 1: {}", num_fishes); } // 351188
            let new_fish = spawns[0];
            num_fishes += new_fish;
            spawns.rotate_left(1);
            spawns[INITIAL_SPAWN_DAYS] = new_fish;
            spawns[RESPAWN_DAYS] += new_fish;
        }
        println!("Part 2: {}", num_fishes); // 1595779846729
        Ok(())
    }
    fn main() {
        let args: Vec<String> = env::args().collect();
        let filename = &args[1];
        day06(&filename).unwrap();
    }
    
    2 votes
  8. Comment on Day 5: Hydrothermal Venture in ~comp.advent_of_code

    wycy
    Link Parent
    Our Rust implementations are pretty similar, except I ended up using a Vec to store the final vent map in the end rather than a HashMap. Kind of forgot about HashMaps despite using them for this...

    Our Rust implementations are pretty similar, except I ended up using a Vec to store the final vent map in the end rather than a HashMap. Kind of forgot about HashMaps despite using them for this very purpose in previous years. I think I'll refactor mine to use as HashMap like yours later.

    1 vote
  9. Comment on Day 5: Hydrothermal Venture in ~comp.advent_of_code

    wycy
    (edited )
    Link
    Rust Edit: Updated code to use a different approach for storing the map for part 2 just for the novelty. Rust use std::env; use std::io::{self, prelude::*, BufReader}; use std::fs::File; use...

    Rust

    Edit: Updated code to use a different approach for storing the map for part 2 just for the novelty.

    Rust
    use std::env;
    use std::io::{self, prelude::*, BufReader};
    use std::fs::File;
    use std::collections::HashMap;
    
    extern crate regex;
    use regex::Regex;
    
    #[derive(Clone,Hash,PartialEq,Eq)]
    struct Point {
        x: isize,
        y: isize,
    }
    
    #[derive(Clone)]
    struct Line {
        start: Point,
        end: Point,
    }
    impl From<&String> for Line {
        fn from(s: &String) -> Self {
            let re = Regex::new(r"(\d+),(\d+) -> (\d+),(\d+)").unwrap();
            let matches = re.captures(s).unwrap();
            Self {
                start: Point { x: matches[1].parse().unwrap(), y: matches[2].parse().unwrap() },
                end:   Point { x: matches[3].parse().unwrap(), y: matches[4].parse().unwrap() },
             }
        }
    }
    impl Line {
        pub fn points(&self, diagonals: bool) -> Vec<Point> {
            let mut points = Vec::new();
            let dx = self.end.x-self.start.x;
            let dy = self.end.y-self.start.y;
            let delta = if dx != 0 { dx } else { dy };
            if !diagonals && dx != 0 && dy != 0 { return points; } // part1: only vertical or horizontal lines
            let dx = dx.signum();
            let dy = dy.signum();
            for i in 0..delta.abs() + 1 {
                points.push(Point { x: self.start.x + i * dx, y: self.start.y + i * dy });
            }
            points
        }
    }
    
    fn day05(input: &str) -> io::Result<()> {
        let file = File::open(input).expect("Input file not found.");
        let reader = BufReader::new(file);
    
        // Input
        let input: Vec<String> = match reader.lines().collect() {
            Err(err) => panic!("Unknown error reading input: {}", err),
            Ok(result) => result,
        };
        let lines: Vec<_> = input.iter().map(Line::from).collect();
    
        // Part 1 (using nested Vecs)
        let mut vent_map = vec![vec![0; 1000]; 1000];
        for line in lines.clone() {
            for pt in line.points(false) {
                vent_map[pt.x as usize][pt.y as usize] += 1;
            }
        }
        let part1 = vent_map.iter().flat_map(|x| x.iter().filter(|&x| *x >= 2)).count();    
        println!("Part 1: {}", part1); // 6461
    
        // Part 2 (using HashMap)
        let mut vent_map: HashMap<Point,usize> = HashMap::new();
        for line in lines.clone() {
            for pt in line.points(true) {
                *vent_map.entry(pt).or_insert(0) += 1;
            }
        }
        let part2 = vent_map.iter().filter(|(_,&num)| num >= 2).count();
        println!("Part 2: {}", part2); // 18065
    
        Ok(())
    }
    
    fn main() {
        let args: Vec<String> = env::args().collect();
        let filename = &args[1];
        day05(&filename).unwrap();
    }
    
    3 votes
  10. Comment on Day 4: Giant Squid in ~comp.advent_of_code

    wycy
    (edited )
    Link Parent
    I swear I tried .all(|&x| x == true) before and it wasn't working, but now it clearly is so I don't know what I thought I was doing before. 😅 And I feel like a buffoon for actually writing x ==...

    I swear I tried .all(|&x| x == true) before and it wasn't working, but now it clearly is so I don't know what I thought I was doing before. 😅 And I feel like a buffoon for actually writing x == true--I'd certainly never do that in an if statement, so I don't know why I thought I had to do it in .all(). Thanks

    For whatever reason, though, with this change I now get the wrong answers. Puzzling. Maybe you really can’t slice Vecs this way.

    Rust
    impl BingoCard {
        pub fn validate(&mut self) -> bool {
            for i in 0..CARDSIZE {
                if self.marked[i][..].iter().all(|&x| x) { self.won = true; return true; }
                if self.marked[..][i].iter().all(|&x| x) { self.won = true; return true; }
            }
            return false;
        }
    }
    
    2 votes
  11. Comment on Day 4: Giant Squid in ~comp.advent_of_code

    wycy
    (edited )
    Link
    Rust Edit: Code fixed. Turns out the way I wanted to slice the cards wouldn't work. If anyone knows why the commented out portion of my validate function doesn't work, pls let me know. I was...

    Rust

    Edit: Code fixed. Turns out the way I wanted to slice the cards wouldn't work.

    If anyone knows why the commented out portion of my validate function doesn't work, pls let me know. I was getting an error that I couldn't compare &bool to bool, but no amount of referencing/dereferencing the bools would work, so I feel like there may be some other problem with what I was trying to do.

    Rust
    use std::env;
    use std::io::{self};
    
    const CARDSIZE: usize = 5;
    
    #[derive(Clone)]
    struct BingoCard {
        pub card: Vec<Vec<usize>>,
        pub marked: Vec<Vec<bool>>,
        pub won: bool,
    }
    impl From<&str> for BingoCard {
        fn from(s: &str) -> Self {
            let mut card: Vec<Vec<usize>> = Vec::new();
            for row in s.split("\n") {
                card.push(row.split_ascii_whitespace().map(|x| x.parse::<usize>().unwrap()).collect());
            }
            Self { card: card, marked: vec![vec![false;5];5], won: false }
        }
    }
    impl BingoCard {
        pub fn validate(&mut self) -> bool {
            /*for i in 0..CARDSIZE {
                if self.marked[i][..].iter().all(|&x| x) { self.won = true; return true; }
                if self.marked[..][i].iter().all(|&x| x) { self.won = true; return true; }
            }*/
            for row in 0..CARDSIZE {
                let mut bingo = true;
                for col in 0..CARDSIZE {
                    if !self.marked[row][col] { bingo = false; }
                }
                if bingo { self.won = true; }
            }
            for col in 0..CARDSIZE {
                let mut bingo = true;
                for row in 0..CARDSIZE {
                    if !self.marked[row][col] { bingo = false; }
                }
                if bingo { self.won = true; }
            }
            self.won
        }
        pub fn score(&self) -> usize {
            let mut score = 0;
            for row in 0..CARDSIZE {
                for col in 0..CARDSIZE {
                    if !self.marked[row][col] { score += self.card[row][col]; }
                }
            }
            if self.won { score } else { 0 }
        }
        pub fn mark_number(&mut self, number: usize) {
            'outer: for (i,row) in self.card.iter().enumerate() {
                for (j,col) in row.iter().enumerate() {
                    if col == &number {
                        self.marked[i][j] = true;
                        break 'outer;
                    }
                }
            }
    
        }
    }
    
    fn day04(input: &str) -> io::Result<()> {
        // Input
        let input_str = std::fs::read_to_string(input).unwrap();
        let input_str = input_str.trim();
        let input: Vec<_> = input_str.split("\n\n").collect();
        
        // Get Bingo numbers and cards
        let drawn: Vec<_> = input[0].split(",").map(|x| x.parse::<usize>().unwrap()).collect();
        let mut cards: Vec<_> = input[1..].into_iter().map(|x| BingoCard::from(*x)).collect();
        let num_bingo_cards = cards.len();
    
        // Play Bingo
        let mut bingos = 0;
        'bingo_loop: for number in drawn {
            //println!("Drawing: {}", number);
            for card in &mut cards {
                if card.won { continue; }
                card.mark_number(number);
                if card.validate() {
                    bingos += 1;
                    if bingos == 1 {
                        println!("Part 1: {}", number * card.score()); // 89001
                    } else if bingos == num_bingo_cards {
                        println!("Part 2: {}", number * card.score()); // 7296
                        break 'bingo_loop;
                    }
                }
            }
        }
        Ok(())
    }
    
    fn main() {
        let args: Vec<String> = env::args().collect();
        let filename = &args[1];
        day04(&filename).unwrap();
    }
    
    4 votes
  12. Comment on Day 3: Binary Diagnostic in ~comp.advent_of_code

    wycy
    Link
    Rust Kind of gross, but it works. Rust use std::env; use std::io::{self, prelude::*, BufReader}; use std::fs::File; fn main() { let args: Vec<String> = env::args().collect(); let filename =...

    Rust

    Kind of gross, but it works.

    Rust
    use std::env;
    use std::io::{self, prelude::*, BufReader};
    use std::fs::File;
    fn main() {
        let args: Vec<String> = env::args().collect();
        let filename = &args[1];
        day03(&filename).unwrap();
    }
    fn epsilon_from_gamma(gamma: &str) -> String {
        let mut epsilon = String::new();
        for ch in gamma.chars() {
            match ch {
                '0' => epsilon.push_str("1"),
                '1' => epsilon.push_str("0"),
                other => panic!("Unknown digit: {}", other),
            }
        }
        epsilon
    }
    fn binary_from_string(string: &str) -> isize {
        isize::from_str_radix(&string, 2).unwrap()
    }
    #[derive(Debug, Clone, Copy)]
    enum SystemType {
        OxygenGenerator,
        CO2Scrubber,
    }
    fn get_generator_scrubber(input: &Vec<String>, system: SystemType) -> isize {
        let mut inputs = input.clone();
        let len = inputs[0].len();
        for i in 0..len {
            if inputs.len() == 1 { break; }
            let mut num0 = 0;
            let mut num1 = 0;
            for number in &inputs {
                match number.chars().nth(i).unwrap() {
                    '0' => num0 += 1,
                    '1' => num1 += 1,
                    other => panic!("Unknown digit: {}", other),
                }
            }
            let keep = match system {
                SystemType::OxygenGenerator => {
                    if num0 > num1 { '0' }
                    else           { '1' }
                },
                SystemType::CO2Scrubber => {
                    if num0 > num1 { '1' }
                    else           { '0' }
                },
            };
            inputs.retain(|x| x.chars().nth(i).unwrap() == keep);
        }
        binary_from_string(inputs.iter().next().unwrap())
    }
    fn day03(input: &str) -> io::Result<()> {
        let file = File::open(input).expect("Input file not found.");
        let reader = BufReader::new(file);
        // Input
        let input: Vec<String> = match reader.lines().collect() {
            Err(err) => panic!("Unknown error reading input: {}", err),
            Ok(result) => result,
        };
        
        // Part 1
        let len = input[0].len();
        let mut gamma_rate = String::new();
        for i in 0..len {
            let mut num0 = 0;
            let mut num1 = 0;
            for number in &input {
                match number.chars().nth(i).unwrap() {
                    '0' => num0 += 1,
                    '1' => num1 += 1,
                    other => panic!("Unknown digit: {}", other),
                }
            }
            if num0 > num1 {
                gamma_rate.push_str("0");
            } else {
                gamma_rate.push_str("1");
            }
        }
        let epsilon_rate = epsilon_from_gamma(&gamma_rate);
        let gamma_rate   = binary_from_string(&gamma_rate);
        let epsilon_rate = binary_from_string(&epsilon_rate);
        println!("Part 1: {}", gamma_rate * epsilon_rate); // 3895776
        // Part 2
        let o2  = get_generator_scrubber(&input, SystemType::OxygenGenerator);
        let co2 = get_generator_scrubber(&input, SystemType::CO2Scrubber);
        println!("Part 2: {}", o2 * co2); // 7928162
        Ok(())
    }
    
    1 vote
  13. Comment on Day 2: Dive! in ~comp.advent_of_code

    wycy
    (edited )
    Link
    Rust My Rust skills are very rusty at the moment. I'll need to go back and see if I can make this code more idiomatically Rust. Solution use std::env; use std::io::{self, prelude::*, BufReader};...

    Rust

    My Rust skills are very rusty at the moment. I'll need to go back and see if I can make this code more idiomatically Rust.

    Solution
    use std::env;
    use std::io::{self, prelude::*, BufReader};
    use std::fs::File;
    
    fn main() {
        let args: Vec<String> = env::args().collect();
        let filename = &args[1];
        day02(&filename).unwrap();
    }
    
    #[derive(Debug, Clone)]
    enum SubmarineCommand {
        Forward(i64),
        Up(i64),
        Down(i64),
    }
    impl From<&String> for SubmarineCommand {
        fn from(input: &String) -> Self {
            use SubmarineCommand::*;
            let mut parts = input.split_ascii_whitespace();
            let direction = parts.next().unwrap();
            let magnitude = parts.next().unwrap().parse::<i64>().unwrap();
            match direction {
                "forward" => Forward(magnitude),
                "up"      => Up(magnitude),
                "down"    => Down(magnitude),
                other     => panic!("Unknown direction: {}", other),
            }
        }
    }
    
    fn day02(input: &str) -> io::Result<()> {
        let file = File::open(input).expect("Input file not found.");
        let reader = BufReader::new(file);
    
        // Input
        let input: Vec<String> = match reader.lines().collect() {
            Err(err) => panic!("Unknown error reading input: {}", err),
            Ok(result) => result,
        };
        
        let commands = input
            .iter()
            .map(SubmarineCommand::from)
            .collect::<Vec<SubmarineCommand>>();
    
        // Part 1
        let mut depth = 0;
        let mut pos = 0;
        for cmd in commands.clone() {
            match cmd {
                SubmarineCommand::Forward(mag) => { pos += mag },
                SubmarineCommand::Up(mag)      => { depth -= mag },
                SubmarineCommand::Down(mag)    => { depth += mag }, 
            }
        }
        println!("Part 1: {}", depth * pos); // 1893605
    
        // Part 2
        let mut depth = 0;
        let mut pos = 0;
        let mut aim = 0;
        for cmd in commands.clone() {
            match cmd {
                SubmarineCommand::Forward(mag) => { pos += mag; depth += aim * mag },
                SubmarineCommand::Up(mag)      => { aim -= mag },
                SubmarineCommand::Down(mag)    => { aim += mag },
            }
        }
        println!("Part 2: {}", depth * pos); // 2120734350
    
        Ok(())
    }
    
    2 votes
  14. Comment on Day 1: Sonar Sweep in ~comp.advent_of_code

    wycy
    Link
    Rust Solution use std::env; use std::io::{self, prelude::*, BufReader}; use std::fs::File; fn main() { let args: Vec<String> = env::args().collect(); let filename = &args[1];...

    Rust

    Solution
    use std::env;
    use std::io::{self, prelude::*, BufReader};
    use std::fs::File;
    
    fn main() {
        let args: Vec<String> = env::args().collect();
        let filename = &args[1];
        day01(&filename).unwrap();
    }
    
    fn day01(input: &str) -> io::Result<()> {
        let file = File::open(input).expect("Input file not found.");
        let reader = BufReader::new(file);
    
        // Input
        let input: Vec<String> = match reader.lines().collect() {
            Err(err) => panic!("Unknown error reading input: {}", err),
            Ok(result) => result,
        };
        let input: Vec<i64> = input
            .iter()
            .map(|x| x.parse::<i64>().unwrap())
            .collect();
    
        // Solutions
        println!("Part 1: {}", sonar(&input, 1)); // 1301
        println!("Part 2: {}", sonar(&input, 3)); // 1346
    
        Ok(())
    }
    
    fn sonar(input: &Vec<i64>, winsize: usize) -> usize {
        input
            .windows(winsize)
            .map(|x| x.iter().sum::<i64>())
            .collect::<Vec<_>>()
            .windows(2)
            .filter(|x| x[1] > x[0])
            .count()
    }
    
    5 votes
  15. Comment on COVID-19 myths in ~health.coronavirus

    wycy
    Link Parent
    Wait, what does this mean? To my knowledge, COVID doesn't linger inside your body to resurface later like some viruses (chickenpox) do.

    Even after recovering from COVID-19, it remains inside your body and can resurface.

    Wait, what does this mean? To my knowledge, COVID doesn't linger inside your body to resurface later like some viruses (chickenpox) do.

    5 votes
  16. Comment on Architect resigns in protest over UCSB mega-dorm in ~design

    wycy
    Link
    Just stumbled across this bit: Just 2 entrances for 4500 students. Sounds like an extreme fire hazard.

    Just stumbled across this bit:

    Currently, he said, the largest single dormitory in the world is Bancroft Hall at the U.S. Naval Academy, which houses 4,000 students and is composed of multiple wings wrapped around numerous courtyards with over 25 entrances. [...] “Munger Hall, in comparison, is a single block housing 4,500 students with two entrances,” McFadden said, and would qualify as the eighth densest neighborhood on the planet, falling just short of Dhaka, Bangladesh.

    Just 2 entrances for 4500 students. Sounds like an extreme fire hazard.

    11 votes
  17. Comment on Architect resigns in protest over UCSB mega-dorm in ~design

    wycy
    Link Parent
    This just sounds like a billionaire wanting to toy with people and have a little fun through subtle psychological torture. I can't believe anyone wants this to get built.

    The idea was conceived by 97-year-old billionaire-investor turned amateur-architect Charles Munger, who donated $200 million toward the project with the condition that his blueprints be followed exactly.

    This just sounds like a billionaire wanting to toy with people and have a little fun through subtle psychological torture. I can't believe anyone wants this to get built.

    5 votes
  18. Comment on The first thing we do, let's kill all the leaf blowers in ~enviro

    wycy
    Link Parent
    Can confirm. I have an battery-powered electric leaf blower and most of the time I'm using it at half-power anyway. It's fantastic. I used to have a corded electric leaf blower which was even more...

    Can confirm. I have an battery-powered electric leaf blower and most of the time I'm using it at half-power anyway. It's fantastic.

    I used to have a corded electric leaf blower which was even more powerful (unnecessary), but being tethered to a cord was pretty annoying. Modern battery-powered yard tools are pretty good.

    6 votes
  19. Comment on What delicious foods don't photograph well? in ~talk

    wycy
    (edited )
    Link
    I make scrambled eggs every morning that I find delicious. I took a picture of it one morning and was horrified to notice that it just looks like a plate of vomit in the photo despite looking...

    I make scrambled eggs every morning that I find delicious. I took a picture of it one morning and was horrified to notice that it just looks like a plate of vomit in the photo despite looking normal in real life. Better lighting probably would've gone a long way, but after the first picture I was demotivated from trying anything else.

    The photo: https://imgur.com/a/gAkN5bv I swear they were light, fluffy, brightly colored in real life.

    5 votes
  20. Comment on Shower thought ... Maybe everything else is mutating, too? in ~health

    wycy
    Link
    It's also possible it was covid, and the one test missed it. To me, a single test between three people doesn't sound conclusive.

    It's also possible it was covid, and the one test missed it. To me, a single test between three people doesn't sound conclusive.

    10 votes