Skip to content

Instantly share code, notes, and snippets.

@dcbriccetti
Created December 16, 2020 00:29
Show Gist options
  • Save dcbriccetti/2e1b58c28a6d3d780805287905a2d055 to your computer and use it in GitHub Desktop.
Save dcbriccetti/2e1b58c28a6d3d780805287905a2d055 to your computer and use it in GitHub Desktop.
Advent of Code 2020 Day 14 Part 1 Solution in Rust
use std::collections::HashMap;
use regex::Regex;
use std::fs::File;
use std::io::{BufRead, BufReader};
fn main() {
let mut memory: HashMap<u64, u64> = HashMap::new();
let mut or_mask: u64 = 0;
let mut and_mask: u64 = 0;
let rx_mask = Regex::new(r"mask = ([X10]{36})").unwrap();
let rx_mem = Regex::new(r"mem\[(\d+)\] = (\d+)").unwrap();
let file = File::open("test_data.txt").unwrap();
for result in BufReader::new(file).lines() {
let line = result.unwrap();
for captures in rx_mask.captures(&line) {
let mask_string = &captures[1];
let mut two_power = 36;
let mut off_bits: u64 = 0;
let mut on_bits: u64 = 0;
for mask_char in mask_string.chars() {
two_power -= 1;
let bit_position: u64 = 1 << two_power;
if mask_char == '0' {
off_bits |= bit_position
}
if mask_char == '1' {
on_bits |= bit_position
}
}
or_mask = on_bits;
and_mask = !off_bits;
println!("{} {:b} {:b}", mask_string, or_mask, and_mask);
}
for captures in rx_mem.captures(&line) {
let addr: u64 = captures[1].parse().unwrap();
let unmasked_val: u64 = captures[2].parse().unwrap();
let masked_val: u64 = {
let bits_off_val: u64 = unmasked_val & and_mask;
let bits_on_val: u64 = bits_off_val | or_mask;
println!("{} <- val: {}, off: {}, on: {}", addr, unmasked_val, bits_off_val, bits_on_val);
bits_on_val
};
memory.insert(addr, masked_val);
}
}
println!("Memory: {:?}", memory);
let sum = memory.values().fold(0, |acc, v| acc + v);
println!("Sum of all values: {}", sum)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment