Improve error handling by not panicking in helper function

This commit is contained in:
George Thomas 2025-12-19 15:34:13 +00:00
parent 83e957d5f9
commit 73ea25236f

View File

@ -52,20 +52,24 @@ fn max_batteries(n: usize, v: &[u8]) -> Option<Vec<u8>> {
let mut remaining = n; let mut remaining = n;
let mut slice = v; let mut slice = v;
while remaining > 0 { while remaining > 0 {
if slice.len() - remaining + 1 == 0 { match find_max(&slice[..slice.len() - remaining + 1]) {
return None; Some((b, i)) => {
result.push(b);
remaining -= 1;
slice = &slice[i + 1..];
}
None => return None,
} }
let (b, i) = find_max(&slice[..slice.len() - remaining + 1]);
result.push(b);
remaining -= 1;
slice = &slice[i + 1..];
} }
Some(result) Some(result)
} }
fn find_max<A: Ord + Copy>(v: &[A]) -> (A, usize) { fn find_max<A: Ord + Copy>(v: &[A]) -> Option<(A, usize)> {
let (n, x) = v.iter().enumerate().rev().max_by_key(|x| x.1).unwrap(); v.iter()
(*x, n) .enumerate()
.rev()
.max_by_key(|x| x.1)
.map(|(n, x)| (*x, n))
} }
fn digits_to_int(digits: &[u8]) -> usize { fn digits_to_int(digits: &[u8]) -> usize {