Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

random pick 2 1

Status
Not open for further replies.

tester321

Programmer
Mar 13, 2007
150
CA
Hi, thanks for reading this,
I have 4 vars like so:
var a1='a'
var a2='aa2'
var a3='a'
var a4='a'

the values of these for can be dynamic. I'm only interested in the vars that have a value length equal to 1.

I would like to randonly select 2 from the vars that length=1. There may be an instance when all four will have length=1 or that only 1 will have length=1. But i need to know which vars have a length=1, how can this be done?

this what i have tried:

var myarray = new Array()
myarray[0]=a1
myarray[1]=a2
myarray[2]=a3
myarray[3]=a4

for(var i=0; i < myarray.length; i++ ){

if (a.length=1) {myarray=i;}else{myarray=""};

};

myarray.sort(randOrd);

//myarray[0] might be from var a1 and equal to "a"
//myarray[1]; might be from var a4 and equal to "a
 
sry, i forgot the function:

function randOrd(){
return (Math.round(Math.random())-0.5); }
</script>
 
How about something like this:
Code:
var barray=['a','b','c','d','e','f','aa','a1',d'','v'];

var randarray = new Array(), numpicks = 4;
var ni = 0;
while (ni<numpicks)
  {
  var randnum = Math.floor(Math.random() * barray.length);
  var onepick = barray[randnum];
  if (onepick.length == 1)
    {
    randarray[ni] = onepick;
    ni++;

    //move last element of array into position just chosen
    //to prevent duplication of random selection choice
    barray[randnum] = basearray[barray.length - 1];
    barray.length--;
    }
  }

Lee
 
Hello Lee, and thanks! You’re awesome, did you write that from spontaneously? Caught a few issues in it: d'' and
basearray

but other than that it work amazingly well, especially under a stress test! kutos to you

Thanks Again!


 
Yeah, I wrote it in the box, then rewrote it a bit and missed changing a few things. It's a fairly common way to create an array of random selections from another array, though.

Lee
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top