use std::collections::HashMap; fn find_left(instructions: &[u8], index: usize) -> usize { let mut result = index - 1; let mut count = 1; while count != 0 { if instructions[result] == ']' as u8 { count += 1; } else if instructions[result] == '[' as u8 { count -= 1; } result -= 1; } result + 1 } fn find_right(instructions: &[u8], index: usize) -> usize { let mut result = index + 1; let mut count = 1; while count != 0 { if instructions[result] == '[' as u8 { count += 1; } else if instructions[result] == ']' as u8 { count -= 1; } result += 1; } result - 1 } fn brain_luck(code: &str, input: Vec) -> Vec { let instructions = code.as_bytes(); let mut result = Vec::::new(); let mut tape = HashMap::::new(); let mut i = 0; let mut tape_i = 0; let mut input_i = 0; while i < instructions.len() { match instructions[i] as char { '>' => tape_i += 1, '<' => tape_i -= 1, '+' => { tape.insert(tape_i, (tape.get(&tape_i).unwrap_or(&0) + 1) % 256); () } '-' => { let new_value = tape.get(&tape_i).unwrap_or(&0) - 1; tape.insert(tape_i, if new_value < 0 { 255 } else { new_value }); () } '.' => { result.push(*tape.get(&tape_i).unwrap_or(&0) as u8); () } ',' => { tape.insert(tape_i, input[input_i] as i16); input_i += 1; () } '[' => { if *tape.get(&tape_i).unwrap_or(&0) == 0 { i = find_right(instructions, i); } () } ']' => { if *tape.get(&tape_i).unwrap_or(&0) != 0 { i = find_left(instructions, i); } () } _ => {} } i += 1; } result }