- Home /
Get the two highest floats in a genericList without using .Sort()?
Hello, I am trying to get two highest floats in list without Sort(). Why on earth would omseone want to do that? Well, I need to maintain the order they entered the list, so I know which number pertains to which object. And since the number is a dynamic variable I cannot simply trace it back to the original gameobject. The gameObject is being used in a equation, in which I put that number into a list.
Now Im trying to figure out how to do this. I thought I had it figured out, and coded out the possibility manually, and it kind of works, and kind of doesn't. It's strange, maybe using too many layers of conditional math inside single if statements. But Im hoping maybe Im overlooking an easier way.
The highest value is easy enough, but to get the two highest is... a little more complicated. Since you have to compare to previous numbers and depends if the highest was first, then you cant simply check for the next highest as, " is higher than the previous", basically. So yeah.
Answer by robertbu · Oct 28, 2013 at 01:08 AM
I don't see any slick way but brute force:
void TwoHighest(out float highest, out float second, List<float> floats) {
highest = Mathf.NegativeInfinity;
second = Mathf.NegativeInfinity;
for (int i = 0; i < floats.Count; i++) {
if (floats[i] >= highest) {
second = highest;
highest = floats[i];
}
else if (floats[i] > second) {
second = floats[i];
}
}
}
This is C#. You'd have to fiddle more to get two values out of a function in Javascript.
I tried something like that, but it just wasnt working out for me. So, I did it the hard way, and it kind of works but it seems to not know how to compute at this level of, embedded-ness, I guess.
if(((float0>float1)||(float1>float0))&&(float1>float2)&&(float1>float3)){
I have several of those, but they dont seem to be working right. I have debugged all floats and they are correct. $$anonymous$$aybe Ill have to get even more down to the core... sigh.
im basically saying," I dont care which value is the highest out of the two highest, but if both of those, are indeed higher than the others, do something specific for that scenario". There are 4 floats, and 6 different versions of that code. but it just doesnt seem to be working correctly.
Hmmm.. I just debugged that code with just plain numbers and it computed fine. Strange.
turns out my code was perfect! I had 2 extra scenarios of outcome that in this case I didn't need, because they didn't apply to the use. Hard to explain without writing a book but basically I should have only had 4 varieties of my code in this situation. However your answer to this specific question is valid! so, correct! lol