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 wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Easy randomize problem 1

Status
Not open for further replies.

TFfan

Programmer
Jan 18, 2002
192
CA
Hi. I know this is very simple for most of you, and should be for me, but I can't figure out what's wrong. All I want this script to do is access a list of names and randomize it, making sure no names are duplicated. Now, I am a beginner to JS so please excuse the simplicity of the coding.

As always, thanks for your time.

<script language=&quot;JavaScript&quot;>

var nameArr = &quot;Sally,Smith Jessica,Terris Mike,Broady Butch,Cassidy Hans,Clean Judy,Prune Susie,Bright&quot;

nameArr = nameArr.split(&quot; &quot;);

var nameArr2 = new Array();

var k=0;

for (var i=0; nameArr2.length!=nameArr.length; i++)
{
if (isNameused(nameArr))
{
nameArr2[k] = nameArr;
k++;
}
}


function isNameused(name)
{

for (var i=0; i < nameArr2.length; i++)
{
if (name == nameArr2)
{
return false;
}

}

return true;


}


for (var i=0; i < nameArr2.length; i++)
{
var rand=Math.floor(Math.random()*nameArr2.length);
document.write([i+1] + &quot;. &quot;);
document.write(nameArr2[rand] + &quot; &quot;);
document.write(&quot;<br>&quot;);
}

</script>
 
<script language=&quot;JavaScript&quot;>

var nameArr = &quot;Sally,Smith Jessica,Terris Mike,Broady Butch,Cassidy Hans,Clean Judy,Prune Susie,Bright&quot;

nameArr = nameArr.split(&quot; &quot;);

document.write(nameArr.length + &quot; is the length<br><br>&quot;);

function swapNames(arr, num1, num2) {
var tempStr;

tempStr = arr[num1];
arr[num1] = arr[num2];
arr[num2] = tempStr;
}


//this for loop mixes up the array
for (var i=0; i < nameArr.length; i++) {
var randNum1=Math.floor(Math.random()*nameArr.length);
var randNum2=Math.floor(Math.random()*nameArr.length);
swapNames(nameArr, randNum1, randNum2);
}

//this for loop just prints them out
for (var i=0; i < nameArr.length; i++) {
document.write([i+1] + &quot;. &quot;);
document.write(nameArr);
document.write(&quot;<br>&quot;);
}


</script>


I think that is what you were wanting it to do. Note that your original array order is destroyed, so if it's important just create a copy and perform the function on it.

-kaht
 
one quick note:

on the loop that mixes the array, I just copied/pasted the other loop, feasibly you could set the number of times the loop executes to a higher number to get more random results

-kaht
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top