Math random to find Names in an Array while not du

2019-08-11 02:20发布

问题:

So I want to find three names out of an array of names which I then want to write to a new array (not gotten this far yet though), but the problem I have is that it keeps randomizing the same names I already found.

Check out the jsfiddle script.

Code:

findStudentBtn.onclick = findStudent;

function findStudent() {
    var studArray = ["John","Daniel","Hans","Lars","Tom","Amanda","Jane","Sarah"] //1-8
    for (i=0; i<3; i++) {
        if (i=1) {
            var randomStud1 = studArray[Math.floor(studArray.length * Math.random())];
            msg8.innerHTML += randomStud1 + ", ";
        }
        if (i=2) {
            var randomStud2 = studArray[Math.floor(studArray.length * Math.random())];
            msg8.innerHTML += randomStud2 + ", ";
        }
        if (i=3) {
            var randomStud3 = studArray[Math.floor(studArray.length * Math.random())];
            msg8.innerHTML += randomStud3 + ", ";
        }

        if (randomStud1 == randomStud2 || randomStud2 == randomStud3 || randomStud1 == randomStud3){
            ms8.innerHTML = "";
            findStudent();
        } 
    }
}  

回答1:

For anyone interested in the solution, but not willing to go to the jsfidle, here's is the script I used.

findStudentBtn.onclick = function(){
    findStudent();
};

var r_stud = ["John","Daniel","Hans","Lars","Tom","Amanda","Jane","Sarah"];
var r_rndm = [];
var r_newr = [];

function getStudent(){

    //if the amount of available people, is to small to reach 3.
    if(r_rndm.length == r_stud.length){
        //reset the random selected array
        r_rndm = [];
        return r_newr;
    }

    //select a student
    var i_randomStudent = Math.floor(r_stud.length * Math.random());
    var s_randomStudent = r_stud[i_randomStudent];

    if(r_rndm.indexOf(s_randomStudent) >= 0){
        //if it's allready been selected, try again.
        getStudent();
    }else{
        //add students to new selection and to alltime selection
        r_rndm.push(s_randomStudent);
        r_newr.push(s_randomStudent);

        //return the new array
        return r_newr;
    }

};

function findStudent(){

    //reset new array.
    r_newr = [];
    for(i = 0; i < 3; i++){
        getStudent();
    };

    //print contents of new array to console.
    console.log(r_newr);

    for(i = 0; i < r_newr.length; i++){
        separator = (i == r_newr.length - 1 && r_rndm.length == 0 ) ? '' : ', ';
        msg8.innerHTML += r_newr[i] + separator;
    }

};