Skip to content

Instantly share code, notes, and snippets.

@typester
Created December 6, 2023 15:48
Show Gist options
  • Save typester/b907b5bce1fac1ac84da8167a7f7e028 to your computer and use it in GitHub Desktop.
Save typester/b907b5bce1fac1ac84da8167a7f7e028 to your computer and use it in GitHub Desktop.
2023 Advent of Code Day 6
use lazy_static::lazy_static;
use regex::Regex;
const INPUT: &str = "..snip..";
fn main() {
let races = parse_input(INPUT);
let mut res: usize = 0;
for race in races.iter() {
let count =
(1..race.time)
.filter(|n| race.distance_by_press(*n) > race.distance)
.count();
if res == 0 {
res = count;
} else {
res *= count;
}
}
println!("part1: {}", res);
let race = parse_input2(INPUT);
// first true
let (mut l, mut h): (u64, u64) = (0, race.time);
while l < h {
let m = l + (h - l)/2;
if race.distance_by_press(m) > race.distance {
h = m;
} else {
l = m + 1;
}
}
let first = h;
let (mut l, mut h): (u64, u64) = (0, race.time);
while l < h {
let m = l + (h - l)/2;
if race.distance_by_press(m) > race.distance {
l = m + 1;
} else {
h = m
}
}
let last = l - 1;
println!("part2: {}", last - first + 1);
}
struct Race {
time: u64,
distance: u64,
}
impl Race {
fn distance_by_press(&self, msec: u64) -> u64 {
if msec == 0 || msec > self.time {
0
} else {
(self.time - msec) * msec
}
}
}
fn parse_input(input: &str) -> Vec<Race> {
let mut input_iter = input.lines();
let times = extract_numbers(input_iter.next().unwrap());
let distances = extract_numbers(input_iter.next().unwrap());
times.iter()
.zip(distances.iter())
.map(|(t, d)| Race { time: *t, distance: *d })
.collect()
}
fn parse_input2(input: &str) -> Race {
let mut input_iter = input.lines();
Race {
time: extract_numbers2(input_iter.next().unwrap()),
distance: extract_numbers2(input_iter.next().unwrap()),
}
}
lazy_static! {
static ref RE_NUM: Regex = Regex::new(r"(\d+)").unwrap();
}
fn extract_numbers(s: &str) -> Vec<u64> {
RE_NUM.captures_iter(s)
.map(|c| c.get(1).unwrap().as_str().parse::<u64>().unwrap())
.collect()
}
fn extract_numbers2(s: &str) -> u64 {
let mut num = String::new();
for c in RE_NUM.captures_iter(s) {
num.push_str(c.get(1).unwrap().as_str());
}
num.parse::<u64>().unwrap()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment