Do you need Main_Array to remain unchanged? It doesn't matter much, just determines whether we need to clone it. I'll assume you do. Why put "three" in Main_Array if it's not eligible to be selected?
I got a little fancy with the filter use, but it should work. There are other ways too. The most complicating part was that you want to pre-fill it partially.Code:/** * @param n int number of values to select from arr. * @param arr Array from which to select values * @return a new Array containing n values. **/ function selectUniqueValuesFrom(n:int, arr:Array, forbiddenValues:Array):Array{ if (n > arr.length){ //throw some error or return null or something. } var arrClone:Array = arr.filter(notIn(forbiddenValues)); var toreturn:Array = []; for (var i:int = 0; i < n; i++){ var k:int = Math.floor(Math.random()*arrClone.length); var elem:* = arrClone[k]; toreturn.push(elem); arrClone.splice(k, 1); } return toreturn; } /** * Builds a FUNCTION to use as a callback to filter * @param values Array of values to exclude via filter * @return Function */ function notIn(values:Array):Function{ return function(item:*, index:int, array:Array):Boolean{ return values.indexOf(item) == -1; } } Sub_Array = ["three"].concat(selectUniqueValuesFrom(4, Main_Array, ["three"]));




Reply With Quote
