RustFmt on all the things

This commit is contained in:
Eryn Wells 2022-12-05 20:57:32 -08:00
parent 7bee28bdf6
commit 2251854f9c
7 changed files with 138 additions and 95 deletions

View file

@ -29,14 +29,18 @@ fn get_calorie_totals<R: Read + BufRead>(lines: Lines<R>) -> Result<Vec<u32>> {
pub fn main(input_filename: &str) -> Result<()> {
let line_reader = line_reader_for_file(input_filename)
.expect(format!("Unable to create line reader for file: {}", input_filename).as_str());
let elves = get_calorie_totals(line_reader)
.expect("Unable to get knapsack calorie totals");
let elves = get_calorie_totals(line_reader).expect("Unable to get knapsack calorie totals");
println!("Part 1: Elf with highest calorie count in knapsack: {}", elves[0]);
println!(
"Part 1: Elf with highest calorie count in knapsack: {}",
elves[0]
);
let sum_of_top_three = &elves[0] + &elves[1] + &elves[2];
println!("Part 2: Elves with top 3 highest calorie counts in their knapsacks: {}, {}, {} = {}",
&elves[0], &elves[1], &elves[2], sum_of_top_three);
println!(
"Part 2: Elves with top 3 highest calorie counts in their knapsacks: {}, {}, {} = {}",
&elves[0], &elves[1], &elves[2], sum_of_top_three
);
Ok(())
}

View file

@ -11,7 +11,11 @@ const SCORE_FOR_DRAW: i32 = 3;
const SCORE_FOR_LOSS: i32 = 0;
#[derive(Clone, Copy, PartialEq, PartialOrd)]
enum Shape { Rock, Paper, Scissors }
enum Shape {
Rock,
Paper,
Scissors,
}
impl Shape {
fn part1_from_string(s: &str) -> Option<Shape> {
@ -68,7 +72,11 @@ impl Shape {
}
#[derive(Clone, Copy, PartialEq, PartialOrd)]
enum Outcome { Win, Draw, Loss }
enum Outcome {
Win,
Draw,
Loss,
}
impl Outcome {
fn part2_from_string(s: &str) -> Option<Outcome> {
@ -76,7 +84,7 @@ impl Outcome {
"X" => Some(Outcome::Loss),
"Y" => Some(Outcome::Draw),
"Z" => Some(Outcome::Win),
_ => None
_ => None,
}
}
@ -103,27 +111,29 @@ struct Round {
impl Round {
fn part1_from_string(s: &str) -> Option<Round> {
let split: Vec<&str> = s.split(" ").collect();
match (Shape::part1_from_string(split[0]), Shape::part1_from_string(split[1])) {
(Some(opponents_shape), Some(my_shape)) => {
Some(Round {
match (
Shape::part1_from_string(split[0]),
Shape::part1_from_string(split[1]),
) {
(Some(opponents_shape), Some(my_shape)) => Some(Round {
me: my_shape,
outcome: Outcome::with_shapes(opponents_shape, my_shape)
})
},
_ => None
outcome: Outcome::with_shapes(opponents_shape, my_shape),
}),
_ => None,
}
}
fn part2_from_string(s: &str) -> Option<Round> {
let split: Vec<&str> = s.split(" ").collect();
match (Shape::part2_from_string(split[0]), Outcome::part2_from_string(split[1])) {
(Some(opponents_shape), Some(expected_outcome)) => {
Some(Round {
match (
Shape::part2_from_string(split[0]),
Outcome::part2_from_string(split[1]),
) {
(Some(opponents_shape), Some(expected_outcome)) => Some(Round {
me: Shape::part2_from_shape_and_outcome(opponents_shape, expected_outcome),
outcome: expected_outcome
})
},
_ => None
outcome: expected_outcome,
}),
_ => None,
}
}
@ -156,7 +166,8 @@ pub fn main(input_filename: &str) -> Result<()> {
let mut part2_total_score: i32 = 0;
for line in line_reader {
let line = line.expect(format!("Failed to read line after {} rounds!", number_of_rounds).as_str());
let line =
line.expect(format!("Failed to read line after {} rounds!", number_of_rounds).as_str());
if let Some(round) = Round::part1_from_string(&line) {
part1_total_score += round.score();
}
@ -168,7 +179,10 @@ pub fn main(input_filename: &str) -> Result<()> {
println!("Processed {} rounds", number_of_rounds);
println!("Part 1: total score two shapes: {}", part1_total_score);
println!("Part 2: total score with expected outcomes: {}", part2_total_score);
println!(
"Part 2: total score with expected outcomes: {}",
part2_total_score
);
Ok(())
}

View file

@ -13,7 +13,10 @@ fn priority_items_in_knapsack(knapsack: &str) -> Vec<char> {
let left_compartment_set: HashSet<char> = HashSet::from_iter(left_compartment.chars());
let right_compartment_set: HashSet<char> = HashSet::from_iter(right_compartment.chars());
left_compartment_set.intersection(&right_compartment_set).map(|c| *c).collect()
left_compartment_set
.intersection(&right_compartment_set)
.map(|c| *c)
.collect()
}
fn badge_for_group(group: (&str, &str, &str)) -> Vec<char> {
@ -21,14 +24,8 @@ fn badge_for_group(group: (&str, &str, &str)) -> Vec<char> {
let b_set: HashSet<char> = HashSet::from_iter(group.1.chars());
let c_set: HashSet<char> = HashSet::from_iter(group.2.chars());
let ab_intersection: HashSet<char> = a_set
.intersection(&b_set)
.map(|c| *c)
.collect();
ab_intersection
.intersection(&c_set)
.map(|c| *c)
.collect()
let ab_intersection: HashSet<char> = a_set.intersection(&b_set).map(|c| *c).collect();
ab_intersection.intersection(&c_set).map(|c| *c).collect()
}
pub fn main(filename: &str) -> Result<()> {
@ -52,8 +49,7 @@ pub fn main(filename: &str) -> Result<()> {
const LOWERCASE_A_SCORE: u32 = 'a' as u32;
const UPPERCASE_A_SCORE: u32 = 'A' as u32;
let sum_of_scored_priority_letters: u32 =
priority_letters
let sum_of_scored_priority_letters: u32 = priority_letters
.iter()
.map(|c| -> u32 {
let char_value: u32 = (*c).into();
@ -65,10 +61,12 @@ pub fn main(filename: &str) -> Result<()> {
})
.sum();
println!("Part 1: sum of scores of all priority items: {}", sum_of_scored_priority_letters);
println!(
"Part 1: sum of scores of all priority items: {}",
sum_of_scored_priority_letters
);
let sum_of_badges: u32 =
badges
let sum_of_badges: u32 = badges
.iter()
.map(|c| -> u32 {
let char_value: u32 = (*c).into();

View file

@ -7,7 +7,9 @@ use crate::file::line_reader_for_file;
struct RangeString(String);
impl From<&str> for RangeString {
fn from(s: &str) -> Self { RangeString(s.to_string()) }
fn from(s: &str) -> Self {
RangeString(s.to_string())
}
}
impl From<RangeString> for RangeInclusive<u32> {
@ -28,8 +30,8 @@ struct Assignment {
impl Assignment {
fn from_left_and_right_specifier(
left_specifier: RangeString,
right_specifier: RangeString) -> Assignment
{
right_specifier: RangeString,
) -> Assignment {
Assignment {
left: RangeInclusive::<u32>::from(left_specifier),
right: RangeInclusive::<u32>::from(right_specifier),
@ -37,10 +39,10 @@ impl Assignment {
}
fn has_range_contained_by_other(&self) -> bool {
let left_contains_right = self.left.contains(self.right.start())
&& self.left.contains(self.right.end());
let right_contains_left = self.right.contains(self.left.start())
&& self.right.contains(self.left.end());
let left_contains_right =
self.left.contains(self.right.start()) && self.left.contains(self.right.end());
let right_contains_left =
self.right.contains(self.left.start()) && self.right.contains(self.left.end());
left_contains_right || right_contains_left
}
@ -60,21 +62,33 @@ pub fn main(filename: &str) -> Result<()> {
let mut elves = line.split(",").map(|s| RangeString::from(s));
let assignment = Assignment::from_left_and_right_specifier(
elves.next().unwrap(),
elves.next().unwrap());
elves.next().unwrap(),
);
assert!(elves.next() == None);
assignment
})
.fold((0, 0, 0), |acc, a| {
let part1_counter = acc.1 + if a.has_range_contained_by_other() { 1 } else { 0 };
let part1_counter = acc.1
+ if a.has_range_contained_by_other() {
1
} else {
0
};
let part2_counter = acc.2 + if a.has_overlapping_range() { 1 } else { 0 };
(acc.0 + 1, part1_counter, part2_counter)
});
println!("Processed {} assignments", assignment_counts.0);
println!("Part 1: number of assignments with one range containing the other: {}", assignment_counts.1);
println!("Part 2: number of assignments with ranges at least partially overlapping: {}", assignment_counts.2);
println!(
"Part 1: number of assignments with one range containing the other: {}",
assignment_counts.1
);
println!(
"Part 2: number of assignments with ranges at least partially overlapping: {}",
assignment_counts.2
);
Ok(())
}

View file

@ -6,14 +6,17 @@ use crate::file::line_reader_for_file;
#[derive(PartialEq)]
enum State {
StartingState,
Instructions
Instructions,
}
#[derive(Debug)]
struct Stacks(Vec<Vec<String>>);
impl Stacks {
fn part1_perform(&mut self, instruction: &Instruction) -> std::result::Result<(), &'static str> {
fn part1_perform(
&mut self,
instruction: &Instruction,
) -> std::result::Result<(), &'static str> {
for _ in 0..instruction.quantity {
let item = self.0[instruction.from_stack].pop().unwrap();
self.0[instruction.to_stack].push(item);
@ -21,7 +24,10 @@ impl Stacks {
Ok(())
}
fn part2_perform(&mut self, instruction: &Instruction) -> std::result::Result<(), &'static str> {
fn part2_perform(
&mut self,
instruction: &Instruction,
) -> std::result::Result<(), &'static str> {
let from_stack_len: usize = self.0[instruction.from_stack].len();
let index_of_last_n = from_stack_len - instruction.quantity;
@ -40,10 +46,16 @@ impl Stacks {
impl fmt::Display for Stacks {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0.iter().enumerate()
write!(
f,
"{}",
self.0
.iter()
.enumerate()
.map(|(i, v)| format!("{}: {}", i, v.join(", ")))
.collect::<Vec<String>>()
.join("\n"))
.join("\n")
)
}
}
@ -51,7 +63,7 @@ impl fmt::Display for Stacks {
struct Instruction {
quantity: usize,
from_stack: usize,
to_stack: usize
to_stack: usize,
}
impl TryFrom<&str> for Instruction {
@ -132,19 +144,25 @@ pub fn main(filename: &str) -> Result<()> {
index_of_stack += 1;
}
},
}
State::Instructions => {
let instruction = Instruction::try_from(line.as_str()).unwrap();
let _ = part1_stacks.part1_perform(&instruction);
let _ = part2_stacks.part2_perform(&instruction);
},
}
}
}
println!("{}", part1_stacks);
println!("Part 1: tops of stacks: {}", part1_stacks.tops().collect::<Vec<&str>>().join(""));
println!(
"Part 1: tops of stacks: {}",
part1_stacks.tops().collect::<Vec<&str>>().join("")
);
println!("{}", part2_stacks);
println!("Part 2: tops of stacks: {}", part2_stacks.tops().collect::<Vec<&str>>().join(""));
println!(
"Part 2: tops of stacks: {}",
part2_stacks.tops().collect::<Vec<&str>>().join("")
);
Ok(())
}

View file

@ -14,26 +14,21 @@ fn main() {
println!("----- Day 1 -----");
let day1_datafile = &args[1];
day1::main(&day1_datafile)
.expect("Unable to process day1 data file");
day1::main(&day1_datafile).expect("Unable to process day1 data file");
println!("----- Day 2 -----");
let day2_datafile = &args[2];
day2::main(&day2_datafile)
.expect("Unable to process day2 data file");
day2::main(&day2_datafile).expect("Unable to process day2 data file");
println!("----- Day 3 -----");
let day3_datafile = &args[3];
day3::main(&day3_datafile)
.expect("Unable to process day3 data file");
day3::main(&day3_datafile).expect("Unable to process day3 data file");
println!("----- Day 4 -----");
let day4_datafile = &args[4];
day4::main(day4_datafile.as_str())
.expect("Unable to process day4 data file");
day4::main(day4_datafile.as_str()).expect("Unable to process day4 data file");
println!("----- Day 5 -----");
let day5_datafile = &args[5];
day5::main(day5_datafile.as_str())
.expect("Unable to process day5 data file");
day5::main(day5_datafile.as_str()).expect("Unable to process day5 data file");
}