Finding index of maximum value

Hello,

I am creating a function to convert RGB values to HSL, which requires me to determine whether R, G, or B is the largest. I would prefer to avoid loops as much as possible, since this will need to run on every pixel and a loop would make it significantly slower.

I created the following snippet:

    let binding = rgb.0.clone();
    let max = binding
        .iter()
        .enumerate()
        .max()
        .unwrap();

    let min = rgb.0
        .iter()
        .enumerate()
        .min()
        .unwrap();

However, it always returns 0 as the min and 2 as the max, which I expected as a consequence of using .enumerate(). I just don't know how to make it actually work. What is the fastest way to properly find the index?

(Also, I'll probably get rid of the .unwrap() later since I know it's best avoided, I'm just trying to make it work in general first)

Thank you :3

Call .max_by_key(|(_idx, &val)| val).

How the hell did I not see that?? Thank you!

(Also, tiny correction to your answer, just in case a newbie comes along and is confused: _idx, &val needs to be wrapped in parentheses)

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.