View Full Version : randomly grabbing *different* elements from an array...

Coastal Web
05-06-2006, 08:40 PM
Hello everyone, l have a quick question that l'm sure one of you vets can help me out with.....

I've got an array that l want to randomly grab 3 values out of. However l don't want there to be any chance that the array grabs the same value more than once.

if anyone could help me out, l would greatly appreciate it!

Samantha Gram

05-06-2006, 08:52 PM

shuffle then take first three

05-07-2006, 07:36 AM
Or (which is merely the same ideea, but coded in a sigle function:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/javascript">
var a=[12,3,5,78,7,10,32,41,100,13];
var nr=3;//number of elements in new radom array
var r;
function ran(){
r = new Array();
for(var i=0;i<nr;i++){
r[i] = a[Math.floor(Math.random()*a.length)];
var comp = r[i];
for(var j=0;j<r.length-1;j++){


05-07-2006, 11:37 PM
Shorter still:

var a=[12,3,5,78,7,10,32,41,100,13];
var nr=3;
function randOrd(){return (Math.round(Math.random())-0.5); }
function ran(){
return a.splice(0,nr);

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum