2024: clippies

This commit is contained in:
ktims committed 2026-12-02 14:09:23 -07:00
1 parent 966ac945ed
commit 2121d0dc55
7 files changed
+69 -41

No files matched your search

+1 -2
View File
@@ -1,7 +1,6 @@
use aoc_runner_derive::aoc;
use itertools::Itertools;
use rustc_hash::FxHashMap;
use std::iter::repeat;
type IntType = u64;
type CacheType = FxHashMap<Stone, IntType>;
@@ -66,7 +65,7 @@ fn count_blinks(stone: &Stone, blink: usize, cache: &mut Vec<CacheType>) -> IntT
}
fn blink_stones(stones: Stones, blinks: usize) -> IntType {
let mut cache = Vec::from_iter(repeat(CacheType::default()).take(blinks));
let mut cache = Vec::from_iter(std::iter::repeat_n(CacheType::default(), blinks));
stones
.0
.iter()
+37 -12
View File
@@ -55,8 +55,14 @@ impl NumberKeypadRobot {
// NOTE: no need to consider zig-zags since those paths will always require more button presses going back and forth
if (cur_pos.0 + x_ofs, cur_pos.1) != Self::pos_of(b'X') {
let mut x_first = Vec::new();
x_first.extend(repeat_n(if x_ofs > 0 { b'>' } else { b'<' }, x_ofs.abs() as usize));
x_first.extend(repeat_n(if y_ofs > 0 { b'v' } else { b'^' }, y_ofs.abs() as usize));
x_first.extend(repeat_n(
if x_ofs > 0 { b'>' } else { b'<' },
x_ofs.unsigned_abs() as usize,
));
x_first.extend(repeat_n(
if y_ofs > 0 { b'v' } else { b'^' },
y_ofs.unsigned_abs() as usize,
));
x_first.push(b'A');
paths.push({
let mut h = FxHashMap::default();
@@ -66,8 +72,14 @@ impl NumberKeypadRobot {
}
if (cur_pos.0, cur_pos.1 + y_ofs) != Self::pos_of(b'X') {
let mut y_first = Vec::new();
y_first.extend(repeat_n(if y_ofs > 0 { b'v' } else { b'^' }, y_ofs.abs() as usize));
y_first.extend(repeat_n(if x_ofs > 0 { b'>' } else { b'<' }, x_ofs.abs() as usize));
y_first.extend(repeat_n(
if y_ofs > 0 { b'v' } else { b'^' },
y_ofs.unsigned_abs() as usize,
));
y_first.extend(repeat_n(
if x_ofs > 0 { b'>' } else { b'<' },
x_ofs.unsigned_abs() as usize,
));
y_first.push(b'A');
paths.push({
let mut h = FxHashMap::default();
@@ -88,6 +100,7 @@ impl NumberKeypadRobot {
struct DirectionKeypadRobot {
pointing_at: u8,
child: Option<Box<KeypadRobot>>,
#[allow(unused)]
id: usize,
}
@@ -113,15 +126,27 @@ impl DirectionKeypadRobot {
if (cur_pos.0 + x_ofs, cur_pos.1) != Self::pos_of(b'X') {
let mut x_first = Vec::new();
x_first.extend(repeat_n(if x_ofs > 0 { b'>' } else { b'<' }, x_ofs.abs() as usize));
x_first.extend(repeat_n(if y_ofs > 0 { b'v' } else { b'^' }, y_ofs.abs() as usize));
x_first.extend(repeat_n(
if x_ofs > 0 { b'>' } else { b'<' },
x_ofs.unsigned_abs() as usize,
));
x_first.extend(repeat_n(
if y_ofs > 0 { b'v' } else { b'^' },
y_ofs.unsigned_abs() as usize,
));
x_first.push(b'A');
return x_first;
}
if (cur_pos.0, cur_pos.1 + y_ofs) != Self::pos_of(b'X') {
let mut y_first = Vec::new();
y_first.extend(repeat_n(if y_ofs > 0 { b'v' } else { b'^' }, y_ofs.abs() as usize));
y_first.extend(repeat_n(if x_ofs > 0 { b'>' } else { b'<' }, x_ofs.abs() as usize));
y_first.extend(repeat_n(
if y_ofs > 0 { b'v' } else { b'^' },
y_ofs.unsigned_abs() as usize,
));
y_first.extend(repeat_n(
if x_ofs > 0 { b'>' } else { b'<' },
x_ofs.unsigned_abs() as usize,
));
y_first.push(b'A');
return y_first;
}
@@ -155,7 +180,7 @@ impl DirectionKeypadRobot {
let path = self.path_to(&moves);
for path_move in path.split_inclusive(|m| *m == b'A') {
let entry = local_freqs.entry(path_move.to_vec()).or_insert(0);
*entry = *entry + count;
*entry += count;
}
}
my_frequencies.push(local_freqs);
@@ -200,20 +225,20 @@ fn run_robots(code: &Code, n: usize) -> i64 {
.unwrap();
sum += best;
}
return sum as i64 * code.num_val();
sum as i64 * code.num_val()
}
#[aoc(day21, part1)]
fn part1(input: &str) -> i64 {
let codes = parse(input);
codes.iter().map(|c| run_robots(c, 2)).sum::<i64>() as i64
codes.iter().map(|c| run_robots(c, 2)).sum::<i64>()
}
#[aoc(day21, part2)]
fn part2(input: &str) -> i64 {
let codes = parse(input);
for i in 0..26 {
let res = codes.iter().map(|c| run_robots(c, i)).sum::<i64>() as i64;
let res = codes.iter().map(|c| run_robots(c, i)).sum::<i64>();
println!("{i}: {res}");
}
0
+2 -2
View File
@@ -63,7 +63,7 @@ fn profit_for_sequence(changes: &[FxHashMap<[i8; 4], i8>], seq: &[i8]) -> i64 {
}
fn find_best_sequence(changes: &[FxHashMap<[i8; 4], i8>]) -> [i8; 4] {
let possible_seqs = (0..4).map(|_| (-9..=9i8)).multi_cartesian_product().collect_vec();
let possible_seqs = (0..4).map(|_| -9..=9i8).multi_cartesian_product().collect_vec();
let (best_seq, _best_profit) = possible_seqs
.par_iter()
.map_with(changes, |changes, seq| (seq, profit_for_sequence(changes, seq)))
@@ -131,7 +131,7 @@ mod tests {
#[test]
fn test_profit() {
assert_eq!(
profit_for_sequence(&vec![build_profit_map(&prices(123, 10))], &[-1, -1, 0, 2]),
profit_for_sequence(&[build_profit_map(&prices(123, 10))], &[-1, -1, 0, 2]),
6
);
let secrets = parse(EXAMPLE2);
+1 -1
View File
@@ -84,7 +84,7 @@ impl Network {
let new_p = FxHashSet::from_iter(p.intersection(&neighbours).copied());
let new_x = FxHashSet::from_iter(x.intersection(&neighbours).copied());
results.extend(self.bron_kerbosch(new_r, new_p, new_x).into_iter());
results.extend(self.bron_kerbosch(new_r, new_p, new_x));
p.remove(node);
x.insert(*node);
}
+19 -18
View File
@@ -1,9 +1,9 @@
use std::{borrow::BorrowMut, collections::VecDeque, fmt::Display, fs::File, io::Write, mem::swap};
use std::{fmt::Display, fs::File, io::Write};
use aoc_runner_derive::aoc;
use itertools::Itertools;
use regex::Regex;
use rustc_hash::{FxHashMap, FxHashSet};
use rustc_hash::FxHashMap;
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum Op {
@@ -78,13 +78,13 @@ impl GateMachine {
.keys()
.filter(|k| k.starts_with(reg))
.map(|s| (s, s.split_at(1).1.parse::<usize>().unwrap()));
let val = reg_gates
reg_gates
.map(|(name, bit)| if self.val_of(name) { 1 << bit } else { 0 })
.fold(0, |accum, val| accum | val);
val
.fold(0, |accum, val| accum | val)
}
fn expected_result(&self) -> u64 {
self.register('x') + self.register('y') & (1 << self.out_bits) - 1
(self.register('x') + self.register('y')) & ((1 << self.out_bits) - 1)
}
fn actual_result(&self) -> u64 {
self.register('z')
@@ -105,17 +105,18 @@ impl GateMachine {
self.gates.insert(b.to_string(), a_tmp);
}
// return the gates that this gate depends on
#[allow(unused)]
fn dependencies(&self, gate: &str) -> Vec<&str> {
if let Some((key, arg)) = self.gates.get_key_value(gate) {
let mut deps = vec![key.as_str()];
for dep in &arg.arguments {
if dep != "" && self.gates[dep].op != Op::Constant {
if !dep.is_empty() && self.gates[dep].op != Op::Constant {
deps.push(dep.as_str());
deps.extend(self.dependencies(&dep).iter().copied())
deps.extend(self.dependencies(dep).iter().copied())
}
}
deps
} else if gate != "" {
} else if !gate.is_empty() {
panic!("tried to look up invalid gate `{}`", gate);
} else {
Vec::new()
@@ -123,6 +124,7 @@ impl GateMachine {
}
// return the bits that this gate affects
// fn dependents(&self, gate: &str) -> Vec<&str> {}
#[allow(unused)]
fn reset(&mut self) {
for gate in self.gates.values_mut().filter(|g| g.op != Op::Constant) {
gate.value = None
@@ -132,10 +134,9 @@ impl GateMachine {
fn parse(input: &str) -> GateMachine {
let mut gates = FxHashMap::default();
let gate_re = Regex::new(r"^([a-z0-9]{3}) (AND|XOR|OR) ([a-z0-9]{3}) -> ([a-z0-9]{3})$").unwrap();
let const_re = Regex::new(r"^([xyz][0-9]{2}): ([01])$").unwrap();
for line in input.lines() {
let const_re = Regex::new(r"^([xyz][0-9]{2}): ([01])$").unwrap();
let gate_re = Regex::new(r"^([a-z0-9]{3}) (AND|XOR|OR) ([a-z0-9]{3}) -> ([a-z0-9]{3})$").unwrap();
if let Some(caps) = const_re.captures(line) {
gates.insert(
caps[1].to_string(),
@@ -182,7 +183,7 @@ pub fn part1(input: &str) -> u64 {
}
#[aoc(day24, part2)]
pub fn part2(input: &str) -> String {
pub fn part2(input: &str) -> Result<String, std::io::Error> {
let mut machine = parse(input);
let swaps = vec![("z06", "ksv"), ("nbd", "kbs"), ("z20", "tqq"), ("z39", "ckb")];
@@ -204,7 +205,7 @@ pub fn part2(input: &str) -> String {
let mut file = File::create("day24.dot").unwrap();
writeln!(file, "graph day24 {{").unwrap();
writeln!(file, " label=\"first error at bit {}\"", first_error);
writeln!(file, " label=\"first error at bit {}\"", first_error)?;
for (name, gate) in machine.gates {
if gate.op != Op::Constant {
@@ -215,11 +216,11 @@ pub fn part2(input: &str) -> String {
Op::Xor => " [color=red]",
_ => "",
};
writeln!(file, "{} -- {} {};", name, arg, color);
writeln!(file, "{} -- {} {};", name, arg, color)?;
}
}
}
writeln!(file, "}}");
writeln!(file, "}}")?;
// let mut test_machine = machine.clone();
// let mut swaps_left = 4;
@@ -239,7 +240,7 @@ pub fn part2(input: &str) -> String {
.collect_vec();
answer.sort();
answer.iter().join(",")
Ok(answer.iter().join(","))
}
#[cfg(test)]
@@ -332,6 +333,6 @@ x05 AND y05 -> z00";
#[ignore = "not solved"]
#[test]
fn part2_example() {
assert_eq!(part2(EXAMPLE3), "z00,z01,z02,z05");
assert_eq!(part2(EXAMPLE3).unwrap(), "z00,z01,z02,z05");
}
}
+7 -4
View File
@@ -12,11 +12,12 @@ struct LockPile {
locks: Vec<Vec<usize>>,
}
fn parse_grid(lines: &Vec<&str>) -> (LockKey, Vec<usize>) {
fn parse_grid(lines: &[&str]) -> (LockKey, Vec<usize>) {
assert_eq!(lines.len(), 7);
if lines[0].chars().all(|c| c == '#') {
// lock
let mut pins = vec![0; 5];
#[allow(clippy::needless_range_loop)]
for row in 1..lines.len() {
let row_s = lines[row];
for i in 0..row_s.len() {
@@ -29,8 +30,10 @@ fn parse_grid(lines: &Vec<&str>) -> (LockKey, Vec<usize>) {
} else if lines[6].chars().all(|c| c == '#') {
// key
let mut pins = vec![5; 5];
#[allow(clippy::needless_range_loop)]
for row in (1..lines.len()).rev() {
let row_s = lines[row];
#[allow(clippy::needless_range_loop)]
for i in 0..row_s.len() {
if row_s.chars().nth(i) == Some('#') {
pins[i] = 6 - row
@@ -48,7 +51,7 @@ fn parse(input: &str) -> LockPile {
let mut keys = Vec::new();
let mut accum: Vec<&str> = Vec::new();
for line in input.lines() {
if line == "" {
if line.is_empty() {
let (lk, pins) = parse_grid(&accum);
match lk {
LockKey::Lock => locks.push(pins),
@@ -59,7 +62,7 @@ fn parse(input: &str) -> LockPile {
accum.push(line);
}
}
if accum.len() != 0 {
if !accum.is_empty() {
let (lk, pins) = parse_grid(&accum);
match lk {
LockKey::Lock => locks.push(pins),
@@ -69,7 +72,7 @@ fn parse(input: &str) -> LockPile {
LockPile { keys, locks }
}
fn test_lock_key(lock: &Vec<usize>, key: &Vec<usize>) -> bool {
fn test_lock_key(lock: &[usize], key: &[usize]) -> bool {
!lock.iter().zip(key.iter()).any(|(lp, kp)| lp + kp > 5)
}