30
\$\begingroup\$

You are provided with a function Rand5(). This function returns perfectly random (equal distribution) integers between 1 and 5.

Provide the function Rand7(), which uses Rand5() to produce perfectly random integers between 1 and 7.

\$\endgroup\$
  • 3
    \$\begingroup\$ Duplicate question \$\endgroup\$ – Mateen Ulhaq Jun 17 '11 at 5:23
  • 8
    \$\begingroup\$ Obligatory xkcd: xkcd.com/221 \$\endgroup\$ – Steven Rumbalski Sep 28 '11 at 14:39
  • \$\begingroup\$ 1 and 5 inclusive? i.e. from the set {1,2,3,4,5} ? \$\endgroup\$ – Aaron McDaid Dec 8 '11 at 22:54
  • 1
    \$\begingroup\$ What criteria determines a single winner? \$\endgroup\$ – kojiro Jan 26 '13 at 20:51
  • \$\begingroup\$ That moment when you realize this is actually an old question. \$\endgroup\$ – nyuszika7h Dec 20 '14 at 12:33

31 Answers 31

1
2
-4
\$\begingroup\$

JavaScript (53 characters):

function Rand7(){return Math.abs(Rand5()-3)+Rand5()}

JSFiddle Example: here

Same algorithm on PHP (49 characters):

function Rand7(){return abs(Rand5()-3)+Rand5();}
|improve this answer|||||
\$\endgroup\$
  • 3
    \$\begingroup\$ The resulting distribution is not uniform. For instance the chance of pulling a seven is P(7) = 0.4 * 0.2 = 0.08 != 1/7. \$\endgroup\$ – dmckee --- ex-moderator kitten Apr 29 '11 at 20:20
1
2

Not the answer you're looking for?Browse other questions tagged or ask your own question.