Sunday, April 2, 2023

Coding Challenge #39 Random Draw From Bag (Unique & Non-Unique)

 // when passed an array, it will get [howMany] random indices from it. If uniqueIndices is true, each index could only be selected once.
function getRands(ary, howMany, uniqueIndices){
    if(ary.length == 0) return [];
    var a = []; // buffer array, copy of ary
    var output = []; // the output array containing the values at our randomly selected indices
    for(var xint = 0, len = ary.length;xint < len;xint++)
        a.push(ary[xint]);
    
    for(var xint = 0;xint < howMany;xint++){
        var randomIndex = Math.round(Math.random() * (a.length-1));
        output.push(a[randomIndex]);
        if(uniqueIndices){ // only select each index once
            a.splice(randomIndex,1); // remove the index so we can't select it again
            if(a.length == 0) for(var yint = 0,ylen=ary.length;yint<ylen;yint++) a.push(ary[yint]); // if howMany is more than ary.length, rack 'em up so we can keep adding up to howMany.
        }
    }
    return output;
}

function test(ary, howMany, uniqueIndices){
    console.log("\nSelect " +  howMany + " indices (" + (uniqueIndices?"unique":"not unique") + ") from " + ary.toString() + " => " + getRands(ary, howMany, uniqueIndices));
}

test([1,2,3,4,5], 1, false);
test([1,2,3,4,5], 3, false);
test([1,2,3,4,5], 5, false);
test([1,2,3,4,5], 10, false);
test([1,2,3,4,5], 1, true);
test([1,2,3,4,5], 3, true);
test([1,2,3,4,5], 5, true);
test([1,2,3,4,5], 10, true);
test([], 3, true);

No comments:

Post a Comment

Coding Challenge #54 C++ int to std::string (no stringstream or to_string())

Gets a string from an integer (ejemplo gratis: 123 -> "123") Wanted to come up with my own function for this like 10 years ago ...