use std::io::{self, BufRead}; use std::path::Path; use std::fs::File; fn main(){ // Submarine is breaking, do diagnostics by checking power consumption // Calculate gamma rate * epsilon rate // Diagnostics are encoded by series of binary numbers // Gamma rate is most common bit for each bit in the series // Epsilon rate is the opposite, i.e. least common bit // So when gamma rate would be 10011, epsilon rate automatically is 01100 println!("Advent of Code #3!\n"); let path = Path::new("./3.txt"); let display = path.display(); let file = match File::open(&path) { Err(why) => panic!("Couldn't open {}: {}", display, why), Ok(file) => file, }; let lines = io::BufReader::new(file).lines(); let mut diagnostics = Vec::>::new(); for line in lines{ let mut d_line = Vec::::new(); if let Ok(l) = line { for c in l.chars() { match c { '0' => d_line.push(false), '1' => d_line.push(true), _ => (), } } } diagnostics.push(d_line); } let mut line_numbers = 0; let b_len = diagnostics[0].len(); let mut ones = vec![0; b_len]; for line in &diagnostics { line_numbers += 1; for i in 0 .. b_len { match line[i] { true => ones[i] += 1, false => (), } } } let mut gamma_rate = Vec::new(); for n in ones { if n > line_numbers / 2 { gamma_rate.push(true); } else { gamma_rate.push(false); } } let mut gamma_rate_decimal = 0; let mut pow = 1; gamma_rate.reverse(); for b in gamma_rate { match b { true => gamma_rate_decimal += pow, false => (), } pow *= 2; } println!("Gamma rate in decimal is {}, epsilon rate in decimal is {}, yielding product of {}", gamma_rate_decimal, pow - gamma_rate_decimal - 1, gamma_rate_decimal * (pow - gamma_rate_decimal - 1)); }