/    Sign up×
Community /Pin to ProfileBookmark

Randomizing a list of numbers

Say i have a list of numbers –

50
100
250
300
400
500
1000
1500
2500

how would i randomize these and generate one random number from the list?
im not asking for a whole script but if you could point me in the right direction that would be appreciated.

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@nap0leonApr 13.2012 — 1- place them in an array

2- pick a random number between 0 and the number of numbers

3- the position chosen in #2 is the value

There are more efficient ways of creating arrays, etc., but I went kinda long-hand to make it easy to follow.

e.g.,
<i>
</i>&lt;script&gt;
var strNumbers = "50,100,250,300,400,500,1000,1500,2500"
var arrNumbers = strNumbers.split(",")
var numberOfNumbers = arrNumbers.length
var rndNumber = Math.floor((Math.random()*nmbOfNumbers));
alert(arrNumbers[rndNumber])
&lt;/script&gt;
Copy linkTweet thisAlerts:
@mrhooApr 13.2012 — you can handle a list in javascript as an array-

[CODE]var numberarray=[50,100,250,300,400,500,1000,1500,2500];[/CODE]

and you can get a random integer between 0 and the array's length with Math.random

[CODE]var i= Math.floor(Math.random()*numberarray.length);
alert(numberarray[i]);[/CODE]


or you can 'shuffle' the array by randomly sorting it-

[CODE]numberarray.sort(function(){return Math.random()-.5});[/CODE]

and shift or pop one at a time

[CODE]while(numberarray.length)alert(numberarray.pop())[/CODE]
Copy linkTweet thisAlerts:
@Ay__351_eApr 14.2012 —  <br/>
&lt;script type="text/javascript"&gt;

var A = [ 500, 100, 400, 2500, 300, 50, 1000, 1500, 250 ]

var d = new Date().getTime();

//alert(d);

//alert(typeof(d)); // number

var kalan = d &amp;#37; 10;

alert(kalan);

var random = A[kalan % A.length ]

alert( random ) ;


// alert( A[( new Date().getTime() %10 ) % A.length ] );

&lt;/script&gt;
×

Success!

Help @garethsmall spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...