...

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

Vladdy
05-06-2006, 08:52 PM
http://www.codingforums.com/showpost.php?p=101675&postcount=7

shuffle then take first three

Kor
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">
<html>
<head>
<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++){
if(comp==r[j]){i--;break}
}
}
}
onload=function(){ran();alert(r)}
</script>
</head>
<body>

</body>
</html>

felgall
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(){
a.sort(randOrd);
return a.splice(0,nr);
}
onload=function(){alert(ran())}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum