So we have a group project thats due at the end of the day and everyone has done their part except for one person. We dont have much time left and i havent heard from that person so i decided to just write that persons part myself incase they never upload it.
The problem is... i have no idea how to do this part.
there are three horses and i have to make it so that 1 horse wins the race randomly. Thats easy. just use
1 + rand()%(3-1+1);
The problem is that each horse should have a different probability
horse 1 has a 45% chance of winning
horse 2 has 30%
horse 3 25%
(notice this add up to 100)
Can somebody please help me figure out how to make a horse randomily win using probability?
Due to the circumstances I have until the end of the day to figure this out on my own :(
Pick a random number in the range 1 to 100, uniformly distributed. 1 to 45 is horse 1, 46 to 75 is horse 2, and 76 to 100 is horse 3.
Adjust algorithm to zero based indexing if you prefer.
Generate a U(0,1), call it
u <= 0.45 horse 1 wins, else
if u <= 0.75 (i.e., between 0.45 and 0.75) it's horse 2, else it's horse 3. This is conceptually like the integer-based solution proposed by David Heffernan, but can handle arbitrary probabilities that don't map nicely to integer sets, such as 1/pi or 1/e.
Split the range of numbers generated by the RNG into pieces with the respective sizes. Then figure out which piece a number lies in to decide which horse wins.
It sounds like the number of horses is small, so a simple
else chain will probably work fine. If you have many horses and speed is important, put the boundaries of the pieces in an array and find the correct one with binary search.
Try using the random number generator function. Import the header file #include Or #include Assign the function to a variable in which the value will be stored Eg r=rand();
Then you can have each horse as an element of an array. Sort this array using a sorting technique to find the largest value.