From f4057a0cc79150d6e5a289a2ddde296e2a5e3060 Mon Sep 17 00:00:00 2001 From: Adam Wick Date: Sat, 14 Dec 2019 21:20:02 -0800 Subject: [PATCH] Day 4! --- src/args.rs | 23 +++++++++++++++++++++++ src/main.rs | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/src/args.rs b/src/args.rs index 8fca07e..01be7ee 100644 --- a/src/args.rs +++ b/src/args.rs @@ -10,6 +10,7 @@ pub enum Command { ComputeFuel(Vec), RunComputer(Computer), WireMap(Vec), + PasswordCrack(u32, u32), } fn is_number(s: String) -> Result<(), String> { @@ -62,6 +63,19 @@ impl Command { .required(true) .validator(is_file)) ) + .subcommand(SubCommand::with_name("crack") + .about("crack a code in the given range") + .arg(Arg::with_name("START") + .index(1) + .help("The starting number.") + .required(true) + .validator(is_number)) + .arg(Arg::with_name("END") + .index(2) + .help("The ending number") + .required(true) + .validator(is_number)) + ) .get_matches(); if let Some(problem1) = matches.subcommand_matches("fuel") { @@ -97,6 +111,15 @@ impl Command { return Command::WireMap(resvec); } + + if let Some(problem4) = matches.subcommand_matches("crack") { + let start_str = problem4.value_of("START").unwrap(); + let end_str = problem4.value_of("END").unwrap(); + let start = u32::from_str_radix(&start_str, 10).unwrap(); + let end = u32::from_str_radix(&end_str, 10).unwrap(); + + return Command::PasswordCrack(start, end); + } panic!("Failed to run a reasonable command."); } diff --git a/src/main.rs b/src/main.rs index 3ac4be1..ce859f8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,6 +6,7 @@ mod wiremap; use crate::args::Command; use crate::fuel::calculate_fuel; use crate::wiremap::WireMap; +use std::cmp::{max,min}; fn main() { match Command::get() { @@ -70,5 +71,41 @@ fn main() { println!("Total steps taken: {}", best_total_steps); } + + Command::PasswordCrack(start, end) => { + let mut count = 0; + let first = max(start, 100000); + let last = min(end, 999999); + + for cur in first..last { + let d0 = cur % 10; + let d1 = (cur / 10) % 10; + let d2 = (cur / 100) % 10; + let d3 = (cur / 1000) % 10; + let d4 = (cur / 10000) % 10; + let d5 = (cur / 100000) % 10; + + if d5 > d4 { continue; } + if d4 > d3 { continue; } + if d3 > d2 { continue; } + if d2 > d1 { continue; } + if d1 > d0 { continue; } + + let mut got_double = false; + if d0 == d1 { got_double |= !( d1 == d2 ); } + if d1 == d2 { got_double |= !((d0 == d1) || (d2 == d3)); } + if d2 == d3 { got_double |= !((d1 == d2) || (d3 == d4)); } + if d3 == d4 { got_double |= !((d2 == d3) || (d4 == d5)); } + if d4 == d5 { got_double |= !( d3 == d4 ); } + + if got_double { + count += 1; + println!("{} is a possibility [total {}]", cur, count); + } + } + + // 353 is wrong (low) + println!("Successful digits: {}", count); + } } }