I have a list of vector2’s:
List playerSpiele = new List(4);
This is where the List is filled:
playerSpiele[playerNumber - 1] = new Vector2(game, suit);
I want to find the Vector2 with the highest value of the int “game” and return its index, if there are two of the same value, i want both of their indexes.
I can’t think of a way to do this, can anyone help me with it?
Thanks in advance!
Here is my take:
public class Data
{
public int game;
public int suit;
}
List<Data> games = new List<Data>();
private List<int> FindHighestGames(List<Data> input)
{
List<int> results = new List<int>(); // Better us HashSet<int> and cache/recycle it.
// Find the highest score.
int highestGame = -1; // some value, that should never appear in Data.game
for (int i = 0; i < input.Count; i++)
{
if (input*.game > highestGame)*
_ highestGame = input*.game;_
_ }*_
* // Now find all with the highest score and add them.*
* for (int i = 0; i < input.Count; i++)*
* {*
_ if (input*.game == highestGame)
results.Add(i); // store index.
}
return results;
}
Things to note:
- You shouldn’t represent score with floats. When you’re comparing values, better use ints. You can always convert them to the desired output format later. Comparing floats might cause subtle trouble, for example when checking if they are equals, because of floating-point imprecision.
- If I understood what you wanted correctly, the algorithm does this: Search for the highest score from a list of inputs. Then checks to see if there are other scores which are the same and returns the indices of them all in a collection.*_
You only need a loop to compare each value of your list.
List<Vector2> List = new List<Vector2>(4) { };
float x = 0;
float y = 0;
int indexX = 0;
int indexY = 0;
bool allValues0 = true;
for(int i = 0; i < List.Count; i++)
{
if(List*.x > x)*
{
x = List*.x;*
indexX = i;
allValues0 = false;
}
if (List*.y > y)*
{
y = List*.y;*
indexY = i;
allValues0 = false;
}
}
if(allValues0)
{
print(" All values are 0");
} else
{
print("the biggest X is = " + x + " on Index = " + indexX);
print("the biggest Y is = " + y + " on Index = " + indexY);
}