Skip to content

Commit

Permalink
perf(02/2024): simplify item removal from vector and improve performance
Browse files Browse the repository at this point in the history
  • Loading branch information
manhunto committed Dec 2, 2024
1 parent 9a92130 commit ee2fac0
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 22 deletions.
2 changes: 1 addition & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
| Day | Solved | Part 1 time (ms) | Part 2 time (ms) |
|--------------------------------------------------------------|:------:|-----------------:|-----------------:|
| [Day 1: Historian Hysteria](src/solutions/year2024/day01.rs) | ⭐⭐ | 0.221 | 0.219 |
| [Day 2: Red-Nosed Reports](src/solutions/year2024/day02.rs) | ⭐⭐ | 0.508 | 1.228 |
| [Day 2: Red-Nosed Reports](src/solutions/year2024/day02.rs) | ⭐⭐ | 0.508 | 0.853 |

# 2023

Expand Down
37 changes: 16 additions & 21 deletions src/solutions/year2024/day02.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,15 @@ pub struct Day02;

impl Solution for Day02 {
fn part_one(&self, input: &str) -> String {
let input = self.parse(input);

input
self.parse(input)
.iter()
.filter(|report| self.is_report_safe(report))
.count()
.to_string()
}

fn part_two(&self, input: &str) -> String {
let input = self.parse(input);

input
self.parse(input)
.iter()
.filter(|report| {
let result = self.is_report_safe(report);
Expand All @@ -27,12 +23,10 @@ impl Solution for Day02 {

(0..report.len())
.map(|i| {
report
.iter()
.enumerate()
.filter(|&(index, _)| index != i)
.map(|(_, &value)| value)
.collect()
let mut new: Vec<i32> = report.to_vec();
let _ = new.remove(i);

new
})
.any(|report| self.is_report_safe(&report))
})
Expand All @@ -53,7 +47,7 @@ impl Day02 {
.collect()
}

fn is_report_safe(&self, report: &Vec<i32>) -> bool {
fn is_report_safe(&self, report: &[i32]) -> bool {
let mut state: Option<Ordering> = None;

for i in 0..report.len() - 1 {
Expand All @@ -65,16 +59,17 @@ impl Day02 {
}

let current_state = first.cmp(second);
if let Some(inner_state) = state {
if inner_state == Ordering::Equal {
return false;
}
if inner_state != current_state {
return false;
}
} else {
if current_state == Ordering::Equal {
return false;
}

if state.is_none() {
state = Some(current_state);
}

if state.is_some_and(|inner| inner != current_state) {
return false;
}
}

true
Expand Down

0 comments on commit ee2fac0

Please sign in to comment.