How To Pick Random Element In An Array AVOIDING (EXCEPT If It's) A Certain Value?
For example, when users are connecting to this application they are given a userid var, then it's inserted into the array. So, i'm using chosenUser = usersOnlineArray[Math.round((M
Solution 1:
You are on good way, just call again your method for example
public void Something(){ string user = GetUser(); }
public string GetUser(){
chosenUser = usersOnlineArray[Math.round((Math.random()*usersOnlineArray.length))];
if (chosenUser == userid)
{
return GetUser();
}
return chosenUser;
}
Solution 2:
using Math.round() can lead to returning "undefined" since you're allowing it to choose usersOnlineArray.length, which is not indexed. use Math.floor() instead.
you could move the item you don't want to match to the end of the array and then select at random an element from the array except for the last element:
//Users Array
var usersArray:Array = new Array("JoeID", "MaryID", "UserID", "JohnID", "SusanID");
//Find UserID And Push It To The End
usersArray.push(usersArray.splice(usersArray.indexOf("UserID"), 1));
//Randomly Select Companion From usersArray Except For UserID (Last Element)
var companion:String = usersArray[Math.floor(Math.random() * (usersArray.length - 1))];
trace(companion);
Solution 3:
Since Flash is same ECMA branch of languages as JavaScript and there is not a JS answer (and ActionScript is kind of extinct species) here is the answer (without recursion) in JS:
var getRandomExcept = function(elements, exceptElement){
if(elements.length <= 0){
return null;
}else if(typeof exceptElement !== 'undefined' && elements.length == 1){
if(elements[0] === exceptElement) return null;
}
var n = Math.floor(Math.random() * elements.length);
if(elements[n] === exceptElement){
// make one random trip around elements but stop (<elements.length) before the exceptElement
n = (n + Math.floor(Math.random() * elements.length)) % elements.length;
}
return elements[n];
};
Post a Comment for "How To Pick Random Element In An Array AVOIDING (EXCEPT If It's) A Certain Value?"