jeudi 19 janvier 2023

How do I generate pseudo random array?

I need to generate array from letters A,H,O,J and numbers 0-9. I want to generate letters into new array in order AHOJ. The individual characters can appear elsewhere in new array but always in AHOJ order and they dont need to follow each other. Remaining indexes of new array will be filled with digits. Examples - A123H85O2J3, AHOJ9854273, 012AH851OJ3 and so on. The order of AHOJ must not be randomized within new array. I have this code, but is probably completly wrong. It only works as expected when condition equal to 7 is met.

let letters = ['A','H','O','J'];
let newArray =new Array(11);
let lastIndex = 10;

for (let i = 0; i < letters.length; i++) {
    
    newIndex = Math.floor(Math.random() * lastIndex);
    console.log(newIndex);
    if (newIndex == 7) {
        for (let j = 0; j < letters.length; j++) {

            newArray.splice(j + 7,1,letters[j]);
        }
        for ( let k = 0; k < 7; k++) {
            newArray.splice(k,1,Math.floor(Math.random() * 10).toString());
        }
        break;
    }
    else if (newIndex > 7) {
        lastIndex = Math.floor(Math.random() * 6);
        newArray.splice(lastIndex,1,letters[i]);
    }
    else {
        newArray.splice(newIndex,1,letters[i]);
        
    }



    
    console.log(letters[i]);
}

console.log(newArray);



Aucun commentaire:

Enregistrer un commentaire