VoyForums
[ Show ]
Support VoyForums
[ Shrink ]
VoyForums Announcement: Programming and providing support for this service has been a labor of love since 1997. We are one of the few services online who values our users' privacy, and have never sold your information. We have even fought hard to defend your privacy in legal cases; however, we've done it with almost no financial support -- paying out of pocket to continue providing the service. Due to the issues imposed on us by advertisers, we also stopped hosting most ads on the forums many years ago. We hope you appreciate our efforts.

Show your support by donating any amount. (Note: We are still technically a for-profit company, so your contribution is not tax-deductible.) PayPal Acct: Feedback:

Donate to VoyForums (PayPal):

Login ] [ Contact Forum Admin ] [ Main index ] [ Post a new message ] [ Search | Check update time | Archives: 12[3] ]


[ Next Thread | Previous Thread | Next Message | Previous Message ]

Date Posted: 09:29:42 05/18/00 Thu
Author: Webmaster
Subject: Re: Generate a series of unique random number
In reply to: Derek Chiu 's message, "Generate a series of unique random number" on 17:57:47 05/14/00 Sun

Hi Derek,

Sorry for my late reply since I am very busy with my exam. The followings is a solution:

---
function get_randoms(num, max) {
//returns an array of random numbers ranging from 1 to max
//num = no. of unique number
//max = upper bound of random numbers
var resultst = "";
var result = new Array();
n = 0;
while (n<num) {
var random = get_random(max);
if (resultst.indexOf(random) == -1) {
resultst += random;
if (n<num-1) resultst += " "; // if not the last draw, append a space as separator
n++;
}
}
result = resultst.split(" ");
return result;
}

function get_random(max) {
//return random number ranging from 1 to max
return Math.ceil(Math.random() * max);
}

alert(get_randoms(10, 20));

---

Procedure:
1. Draw a number
2. If it does not exist in "resultst", append the number to "resultst". Otherwise, draw again.
3. Repeat step 2 until n=20 (20 numbers have been drawn)
4. Split "resultst" into an array "result" with the space as a separator.

Hope this helps and thank you for your visit.



> I would like to generate a series of 10 unique random
> number from 1 to 20. Can you give me some suggestion?
> Thanks a lot!

[ Next Thread | Previous Thread | Next Message | Previous Message ]


Replies:

  • Re: Generate a series of unique random number -- Kent, 07:28:55 11/18/03 Tue
    [ Contact Forum Admin ]


    Forum timezone: GMT-8
    VF Version: 3.00b, ConfDB:
    Before posting please read our privacy policy.
    VoyForums(tm) is a Free Service from Voyager Info-Systems.
    Copyright © 1998-2019 Voyager Info-Systems. All Rights Reserved.