mardi 17 décembre 2019

Selecting a random amount of elements from array in javascript

I have 2 arrays with 4 x-coordinates in each. In total I want to select 3 random values from both arrays. So array1+array2 =3 elements. In the end i just done it a bad way to make it do what i wanted. Just wondering if anyone can see a more efficient way to produce nicer code. This is how i ended up getting it to work. I cant show what i have tried as it has been so modified i ended up just deleting it and doing this.

enemyCars = [100, 200, 300, 400];    //not actual values

newCarArray = [];    //global
newWallArray = [];    //global

function randomNumber(a, b){
    return Math.round(random(a,b));
}

function chooseCars(){
    let carAmount = randomNumber(0,3);
    let wallAmount = 3 - carAmount;
    print('carAmount ' + carAmount);

    if(carAmount == 0){
        newCarArray = [];
    }
    if(carAmount == 1){
        let a = randomNumber(0,3);
        newCarArray.push(enemyCars[a]);
    }
    if(carAmount == 2){
        let a = randomNumber(0,3);
        newCarArray.push(enemyCars[a]);
        let b = randomNumber(0,3);
        newCarArray.push(enemyCars[b]);
    }
    if(carAmount == 3){
        let a = randomNumber(0,3);
        newCarArray.push(enemyCars[a]);
        let b = randomNumber(0,3);
        newCarArray.push(enemyCars[b]);
        let c = randomNumber(0,3);
        newCarArray.push(enemyCars[c]);
    }

    if(wallAmount == 0){
        newWallArray = [];
    }
    if(wallAmount == 1){
        let a = randomNumber(0,3);
        newWallArray.push(enemyWalls[a]);
    }
    if(wallAmount == 2){
        let a = randomNumber(0,3);
        newWallArray.push(enemyWalls[a]);
        let b = randomNumber(0,3);
        newWallArray.push(enemyWalls[b]);
    }
    if(wallAmount == 3){
        let a = randomNumber(0,3);
        newWallArray.push(enemyWalls[a]);
        let b = randomNumber(0,3);
        newWallArray.push(enemyWalls[b]);
        let c = randomNumber(0,3);
        newWallArray.push(enemyWalls[c]);
    }
}

thanks for the help




Aucun commentaire:

Enregistrer un commentaire