Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.javascript > #15042

Re: FAQ Topic - How do I generate a random integer from 1 to n? (2012-07-12)

From Dr J R Stockton <reply1228@merlyn.demon.co.uk.not.invalid>
Newsgroups comp.lang.javascript
Subject Re: FAQ Topic - How do I generate a random integer from 1 to n? (2012-07-12)
Date 2012-07-13 21:06 +0100
Organization Home
Message-ID <fHPYItIE$HAQFwpf@invalid.uk.co.demon.merlyn.invalid> (permalink)
References <4ffe059f$0$287$14726298@news.sunsite.dk>

Show all headers | View raw


In comp.lang.javascript message <4ffe059f$0$287$14726298@news.sunsite.dk
>, Wed, 11 Jul 2012 23:00:02, FAQ server <javascript@dotinternet.be>
posted:

>-----------------------------------------------------------------------
>FAQ Topic - How do I generate a random integer from 1 to
>n?
>-----------------------------------------------------------------------
>
>`Math.random()` returns a value `R` such that `0 <= R < 1.0`; therefore:
>
>// positive integer expected
>function getRandomNumber(n) {
>return Math.floor(n * Math.random());
>}
>
>- gives an evenly distributed random integer in the range from
>`0` to `n - 1` inclusive; use `getRandomNumber(n)+1` for `1` to `n`.
>
><URL: http://msdn.microsoft.com/en-us/library/41336409%28VS.85%29.aspx>
><URL: http://docs.sun.com/source/816-6408-10/math.htm>
>How to Deal and Shuffle, see in: <URL: http://www.merlyn.demon.co.uk/js
>-randm.htm>


<FAQENTRY> There should be an added note to the effect that the quality
of Math-random is browser-dependent and may not be as good as expected.
Page js-randm.htm can do some tests on that, in your browser.  The link
should be to js-shufl.htm.

-- 
 (c) John Stockton, nr London UK  ?@merlyn.demon.co.uk  IE8 FF8 Op11 Sf5 Cr15
   news:comp.lang.javascript FAQ <http://www.jibbering.com/faq/index.html>.
   <http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
   <http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.

Back to comp.lang.javascript | Previous | Next — Previous in thread | Find similar | Unroll thread


Thread

FAQ Topic - How do I generate a random integer from 1 to n? (2012-07-12) "FAQ server" <javascript@dotinternet.be> - 2012-07-11 23:00 +0000
  Re: FAQ Topic - How do I generate a random integer from 1 to n? (2012-07-12) Dr J R Stockton <reply1228@merlyn.demon.co.uk.not.invalid> - 2012-07-13 21:06 +0100

csiph-web