By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,848 Members | 3,223 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,848 IT Pros & Developers. It's quick & easy.

FAQ Topic - How do I generate a random integer from 1 to N? (2008-11-02)

P: n/a
-----------------------------------------------------------------------
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 Random(j) {
return Math.floor(j * Math.random());
}

- gives an evenly distributed random integer in the range from
` 0 ` to ` x-1 ` inclusive; use ` Random(N)+1 ` for ` 1 ` to ` N `.

http://msdn2.microsoft.com/en-us/library/41336409.aspx

http://docs.sun.com/source/816-6408-10/math.htm

How to Deal and Shuffle, see in:

http://www.merlyn.demon.co.uk/js-randm.htm
--
Postings such as this are automatically sent once a day. Their
goal is to answer repeated questions, and to offer the content to
the community for continuous evaluation/improvement. The complete
comp.lang.javascript FAQ is at http://jibbering.com/faq/index.html.
The FAQ workers are a group of volunteers. The sendings of these
daily posts are proficiently hosted by http://www.pair.com.

Nov 2 '08 #1
Share this Question
Share on Google+
1 Reply


P: n/a
In comp.lang.javascript message <49***********************@news.sunsite.
dk>, Sun, 2 Nov 2008 00:00:02, FAQ server <ja********@dotinternet.be>
posted:
>
// positive integer expected
function Random(j) {
return Math.floor(j * Math.random());
}

- gives an evenly distributed random integer in the range from
` 0 ` to ` x-1 ` inclusive; use ` Random(N)+1 ` for ` 1 ` to ` N `.
Definitely, x-1 should be j-1 .
That would be nicer as

function Random(j) {
return Math.floor(j * Math.random());
}

With ` j ` a positive integer, that gives an evenly distributed random
integer in the range from ` 0 ` to ` j-1 ` inclusive; use ` Random(N)+1
` for ` 1 ` to ` N `.

--
(c) John Stockton, nr London UK. ?@merlyn.demon.co.uk IE7 FF2 Op9 Sf3
news:comp.lang.javascript FAQ <URL:http://www.jibbering.com/faq/index.html>.
<URL:http://www.merlyn.demon.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.
Nov 2 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.