Swap findMax result tuple order

This commit is contained in:
George Thomas 2025-12-19 15:56:04 +00:00
parent 17f4b83fc0
commit 4a3506a58d
2 changed files with 6 additions and 10 deletions

View File

@ -32,9 +32,9 @@ maxBatteries :: Int -> Bank -> Maybe [Battery]
maxBatteries n0 (Bank bs0) = flip unfoldrM (n0, toList bs0) \case
(0, _) -> pure Nothing
(n, bs) -> do
(b, i) <- findMax <$> nonEmpty (dropEnd (n - 1) bs)
(i, b) <- findMax <$> nonEmpty (dropEnd (n - 1) bs)
pure $ Just (b, (n - 1, drop (i + 1) bs))
-- returns the leftmost element in case of a tie
findMax :: (Ord a) => NonEmpty a -> (a, Int)
findMax = foldl1' (\m x -> if fst x > fst m then x else m) . flip NE.zip (0 :| [1 ..])
findMax :: (Ord a) => NonEmpty a -> (Int, a)
findMax = foldl1' (\m x -> if snd x > snd m then x else m) . NE.zip (0 :| [1 ..])

View File

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