vendredi 17 février 2023

Check if my array has consecutive similar letters randomly generated

I have to generate 200 random numbers (function has to do it) separated by commas. It doesn't matter if they are repeated but it must not be consecutively. If they are consecutive, I have to replace it with a new letter generated randomly by my function. I am new to programming. I also cannot modify my function as a constraint.

For the sake of the output, I am generating 10 numbers instead of 200.

This is my working code. I just can't manage to add a new random letter where I deleted a duplicate.

const characters = 'abcdefghijklmnopqrstuvwxyz';

function getRandomLetter() { return characters.charAt(Math.floor(Math.random() * characters.length)).toUpperCase(); }

var randomLetters = [];

for (let j = 0; j < 10; j++) { randomLetters [j] = getRandomLetter(); }

document.write("10 random letters: ", randomLetters );


let uniqueArr = [];

for(let i of randomLetters) {
    if(uniqueArr.indexOf(i) === -1) {
        uniqueArr.push(i);
    }
}
document.write("10 random letters without duplicates: ", uniqueArr);



Aucun commentaire:

Enregistrer un commentaire