use std::fs::read_to_string; use std::time::Instant; fn get_hash(data: &[u8]) -> u8 { let mut state: u16 = 0; for &c in data { state += c as u16; state *= 17; state &= 255; } state as u8 } fn main() { let time_start = Instant::now(); let input_str = read_to_string("input.txt").unwrap(); let input_line = input_str.lines().next().unwrap(); let time_start_no_io = Instant::now(); // Task 1 let mut sum1: u32 = 0; // Task 2 let mut sum2: u32 = 0; // Rust is annoying const NEW_VEC: Vec<(&[u8], u8)> = vec![]; let mut boxes: [Vec<(&[u8], u8)>; 256] = [NEW_VEC; 256]; // Processing the input for str in input_line.split(',') { let bytes = str.as_bytes(); // Task 1 sum1 += get_hash(bytes) as u32; // Task 2 if *bytes.last().unwrap() == b'-' { // Remove let label = &bytes[..bytes.len()-1]; let hash = get_hash(label); let target_box = &mut boxes[hash as usize]; if let Some(index) = target_box.iter().position(|(str, _)| *str == label ) { target_box.remove(index); } } else { // Insert / modify let focal = bytes.last().unwrap() - b'0'; let label = &bytes[..bytes.len()-2]; let hash = get_hash(label); let target_box = &mut boxes[hash as usize]; if let Some(index) = target_box.iter().position(|(str, _)| *str == label ) { target_box[index] = (label, focal); } else { target_box.push((label, focal)); } } } for (i, current_box) in boxes.iter().enumerate() { let box_value = i + 1; for (i, (_, focal)) in current_box.iter().enumerate() { sum2 += (box_value * (i + 1) * *focal as usize) as u32; } } let elapsed = time_start.elapsed().as_micros(); let elapsed_no_io = time_start_no_io.elapsed().as_micros(); println!("Time: {}us", elapsed); println!("Time without file i/o: {}us", elapsed_no_io); println!("Sum1: {}", sum1); println!("Sum2: {}", sum2); }