...

View Full Version : Two small randomizing functions



Lerura
05-16-2012, 03:17 AM
function chooseVal(){var list=[];for each (arg in arguments){list=list.concat(arg);}return list[Math.floor(Math.random()*list.length)];}

and


function chooseSet(){var list=[];for each (arg in arguments){(arg[0].constructor==Array?list=list.concat(arg):list.push(arg))}return list[Math.floor(Math.random()*list.length)];}

quite similar, except for the way the treat 1-dimensional arrays.

Usage:

String="I am a single value"
Array1D=['I am the first element from an 1D array','I am the second element from a 1D array','I am the third element from a 1D array'];
Array2D=[['We','are','elements','of','the','first','subarray','in','a','2D','array'],['We','are','values','of','the','second','subarray','in','a','2D','array']];
Chosen=chooseVal(String,Array1D,Array2D);

SingleValue="I am a single value"
Array1D=['We','are','elements','from','a','1D','array'];
Array2D=[['We','are','elements','from','the','first','subarray','in','a','2D','array'],['We','are','values','of','the','second','subarray','in','a','2D','array']];
Chosen=chooseSet(SingleValue,Array1D,Array2D);

Red = not recommended

Intensions:

ChooseVal is for selecting a value from the combination of single values and values stored in 1D arrays.
example:

<html>
<head>
<title></title>
<script>
var MyFamily=['MyFather.png','MyMother.png','MySister.png','MyBrother.png'];
var MyFriend='MyFriend.png';
function displayPicture(){
Chosen=chooseVal(MyFamily,MyFriend);
document.getElementById('Pic').src=Chosen;
}
/* or:
function displayPicture(){
document.getElementById('Pic').src=chooseVal(MyFamily,MyFriend);
}
*/
</script>
<head>
<body onload="displayPicture()">
<img id="Pic" src="blank.gif">
</body>
</html>
ChooseSet is for selecting a array from the combination of 1D arrays and subarrays of 2D arrays.
example:

<html>
<head>
<title></title>
<script>
var MyFamily=[['MyFather.png','My Father'],['MyMother.png','My Mother'],['MySister.png','My Sister'],['MyBrother.png','My Brother']];
var MyFriend=['MyFriend.png','My Friend'];
function displayPicture(){
Chosen=chooseSet(MyFamily,MyFriend);
document.getElementById('Pic').src=Chosen[0];
document.getElementById('Text').innerHTML=Chosen[1];
}
</script>
<head>
<body onload="displayPicture()">
<img id="Pic" src="blank.gif">
<span id="Text"></span>
</body>
</html>

Notes:
Though it is possible, it is not recommended that 2D arrays and single values are passed to the same run, as the output then could either be a single value or an array.

If you are dealing with only single values, or only with 2D arrays, you can use either function, as both function will output a subarray if 2D arrays are passed, and a single value if single values are passed.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum