Reputation: 1
I have a project which involves simulating a horse race and reporting who comes first, second and third. I have gone all of the way up to making a random number for each measure of distance and whichever horse has the highest total number wins. I am having trouble putting the first, second and third place down right. I have the total in an array and I'm not quite sure where to go with it now.
Console.Write ("Type 'Begin' to start the race. ");
string startRace = Console.ReadLine ();
if (startRace == "Begin")
{
Console.Clear ();
Console.WriteLine ("You may now begin the race.");
Console.Clear ();
int[] tot = new int[numberOfHorses];
for (int i = 0; i < numberOfHorses; i++)
{
Console.Write (string.Format("{0, 10}: ", horseName[i]));
int total = 0;
for (int n = 1; n <= furlongs; n++)
{
int randomNum = rnd.Next (0, 10);
Console.Write (" " + randomNum + " ");
total = total + randomNum;
}
tot[i] = total;
Console.Write (" | " + total);
Console.WriteLine (" ");
} //This is where I start to get unsure of myself.
int firstPlace = Int32.MinValue
for (int place = 0; place < numberOfHorses; place++)
{
if (tot[place] > firstPlace)
{
firstPlace = tot[place];
}
}
}
'numberOfHorses' is how many horses the user has decided to race and 'horseName' is what the user has named each horse. Thanks. :)
Upvotes: 0
Views: 1879
Reputation: 1
Emerald King should already know how to find the highest number in a list. Take the top number out (set it to 0) then repeat the process to find second, and again to find third.
Upvotes: 0
Reputation: 1616
You need a sorting function. Instead of:
int firstPlace = Int32.MinValue
for (int place = 0; place < numberOfHorses; place++)
{
if (tot[place] > firstPlace)
{
firstPlace = tot[place];
}
}
try this:
int[] horseIndexes = new int[numberOfHorses];
for (int place = 0; place < numberOfHorses; place++)
{
horseIndexes[place] = place ;
}
// this is the sorting function here
// (a,b) => tot[b] - tot[a]
// it will sort in descending order
Array.Sort(horseIndexes, (a,b) => tot[b] - tot[a]);
for (int place = 0; place < horseIndexes.Length && place < 3; place++)
{
Console.WriteLine("place: " + (place+1));
Console.WriteLine("horse: " + horseName[horseIndexes[place]);
Console.WriteLine("total: " + tot[horseIndexes[place]);
}
There are better ways of doing this using LINQ expressions, but hopefully this example is the most understandable.
Upvotes: 1