Message Boards Message Boards

0
|
1914 Views
|
4 Replies
|
0 Total Likes
View groups...
Share
Share this post:

Explanation needed of a code contains "For" and "RandomSample"

Posted 3 years ago

This is the code that I have been provided to work with for a draft lottery problem, where the user can input 7 numbers for the 'b' variable:

a = Range[45];

b = {1, 2, 3, 4, 5, 6, 7};

For[i = 1, i <= 200000000, i = i + 1,

 If[Sort[RandomSample[a, 7]] == b, Print[i]]]

It would be appreciated if someone could explain the last two lines, as I understand the penultimate to be a list of numbers from one to 200 million, but unsure of the last line. I am not sure of what the output is meant to be, as I have gotten 3 nine digit numbers and 1 eight digit number. Is there also any reason that RandomSample was used rather than RandomChoice? I had believed this to mean that the output would not contain the same number more than once, but my current output of 4 numbers does have the same number multiple times in each number. Any soltutions, explanations or advice on either or all issues are greatly appreciated. Thanks a lot :))

POSTED BY: John Cena
4 Replies

Randomchoice can repeat selected values (equivalent to selecting a ball and the returning it to the drum for selecting the next number). Lotteries don’t do that. (A number is used only once). RandomSample does not allow repeats.

POSTED BY: Neil Singer

Also, the actual probability is computed by multiplying the probability of selecting a good ball on each sample which is 7/45 * 6/44 * 5/43 ... 1/39 which is about 1/45,000,000 so you would expect slightly fewer than 4 hits in 200,000,000. You can compute this in mathematica using Binomial without having to simulate it.

POSTED BY: Neil Singer
Posted 3 years ago

Thank you so much for the help, any idea as to why RandomSample would be used in this sinulated lottery draw over RandomChoice?

POSTED BY: John Cena

Luke,

  1. RandomSample[a, 7] randomly pulls 7 elements from a list (a) without any repeats This models a lottery ball machine because once a ball drops out, it can’t be used again.
  2. The numbers you are getting are indexes (i) so they have no real meaning. I.e. if you get 34521 it means on the 34521 th sample you happened to draw the lottery (a list that exactly matches b). The fact that you got four hits in 200,000,000 gives you a rough estimate of the odds of hitting the lottery.
  3. The code draws 7 numbers , sorts them numerically so it can be easily compared with the ticket (which must be in sort order). It then prints the index when it pulls a match.

I hope this helps.

Regards

Neil

POSTED BY: Neil Singer
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract