87 Zeilen
3,1 KiB
Rust
87 Zeilen
3,1 KiB
Rust
use advent_of_code::strings::{convert_to_array, parsenumber};
|
|
use advent_of_code_macros::include_aoc;
|
|
use log::*;
|
|
include_aoc!(DATA, 2024, 05, 2);
|
|
|
|
fn correct_sum(updates: Vec<Vec<u32>>, orders: Vec<(u32, u32)>) -> u32 {
|
|
let mut correct_numbers = 0;
|
|
'updateloop: for update in updates.clone().iter() {
|
|
for order in orders.clone() {
|
|
let (mut beforepos, mut afterpos) = (update.len(), update.len());
|
|
for i in 0..update.len() {
|
|
if update[i] == order.0 {
|
|
beforepos = i
|
|
} else if update[i] == order.1 {
|
|
afterpos = i
|
|
}
|
|
}
|
|
if beforepos != update.len() && afterpos != update.len() {
|
|
if beforepos > afterpos {
|
|
continue 'updateloop;
|
|
}
|
|
}
|
|
}
|
|
let centerpos = if update.len() % 2 == 1 {
|
|
(update.len() - 1) / 2
|
|
} else {
|
|
update.len() / 2
|
|
};
|
|
debug!("Adding {}: {:?}", update[centerpos], update);
|
|
correct_numbers += update[centerpos]
|
|
}
|
|
correct_numbers
|
|
}
|
|
|
|
fn incorrect_sum(updates: Vec<Vec<u32>>, orders: Vec<(u32, u32)>) -> u32 {
|
|
let mut numbers = 0;
|
|
'updateloop: for update in updates.clone().iter_mut() {
|
|
let mut broken;
|
|
let mut was_broken = false;
|
|
loop {
|
|
broken = false;
|
|
for order in orders.clone() {
|
|
let (mut beforepos, mut afterpos) = (update.len(), update.len());
|
|
for i in 0..update.len() {
|
|
if update[i] == order.0 {
|
|
beforepos = i
|
|
} else if update[i] == order.1 {
|
|
afterpos = i
|
|
}
|
|
}
|
|
if beforepos != update.len() && afterpos != update.len() {
|
|
if beforepos > afterpos {
|
|
(update[beforepos], update[afterpos]) = (update[afterpos], update[beforepos]);
|
|
debug!("switching {} with {} in {:?}", update[beforepos], update[afterpos], update);
|
|
broken = true;
|
|
was_broken = true;
|
|
}
|
|
}
|
|
}
|
|
if !was_broken {
|
|
continue 'updateloop;
|
|
}
|
|
if !broken {
|
|
break;
|
|
}
|
|
}
|
|
|
|
let centerpos = if update.len() % 2 == 1 {
|
|
(update.len() - 1) / 2
|
|
} else {
|
|
update.len() / 2
|
|
};
|
|
debug!("Adding {}: {:?}", update[centerpos], update);
|
|
numbers += update[centerpos]
|
|
}
|
|
numbers
|
|
}
|
|
|
|
fn main() {
|
|
let update_order = convert_to_array::<_, _, '\n'>(DATA_1, |l| {
|
|
let x = l.split_once('|').unwrap();
|
|
(parsenumber(x.0), parsenumber(x.1))
|
|
});
|
|
let updates: Vec<Vec<u32>> = convert_to_array::<_, _, '\n'>(DATA_2, |line| line.split(',').map(parsenumber).collect());
|
|
println!("The Sum of the center of the correct numbers are {}", correct_sum(updates.clone(), update_order.clone()));
|
|
println!("The Sum of the center of the incorrect numbers are {}", incorrect_sum(updates.clone(), update_order.clone()));
|
|
}
|