Searching for letters in an array created by random numbers

Asked

Viewed 89 times

2

I created an array with random values between 65 and 90 and turned it into an array of letters. So far so good. How do I find in this list (if it exists because it was created randomly) where the word DAD is formed when the loop is reading each index (letter) one by one.

let tabNombres = [];
let tabLettres = [];
let voyelles = 0;
let lettreE = 0;

//random numbers array
//Nombres aléatoires 65 à 90
for (let i = 0; i < 1000; i++) {
    tabNombres.push(Math.floor(Math.random() * ((90 - 65) + 1) + 65));
    }

// turning numbers into letters
// characters table
for (let j = 0; j <tabNombres.length; j++) {
    tabLettres.push(String.fromCharCode(tabNombres[j]));
}

// triying to find D, A, D sequence
for (let i = 0; i<tabLettres.length ; i++){
    for(let j=0; j<i; j++){
        for(let k=0; k<j; k++){
            if (tabLettres[k] === 'D' && tabLettres[j] === 'A' && tabLettres[i] === 'D'){

            }
        }
    }
    document.write(tabLettres.indexOf(i));
}
  • Welcome! Now read this how-to manual. https://pt.meta.Sstackoverflow.com/questions/1084/como-devemos-formatar-perguntas-e-respostas?cb=1

  • I believe the result is in the if: if (tabLettres[k] === 'D' && tabLettres[j] === 'A' && tabLettres[i] === 'D'){&#xA; //aqui certo, neste caso, vc tem que saber o índice de cada letra.&#xA; }

2 answers

2


Your code can be simplified using the ES6 syntax:

// Cria um array de 1000 caracteres pseudo-aletórios no intervalo [A-Z]
let tabLettres = [...Array(1000)].map(x => String.fromCharCode(~~(Math.random() * 26) + 65));

// Itera por tabLettres menos os seus dois últimos itens 
for (let i = 0; i < tabLettres.length - 3; i++) {
  // Compara apartir do item iterado com a sequencia DAD
  if (tabLettres[i] === 'D' &&
      tabLettres[i + 1] === 'A' &&
      tabLettres[i + 2] === 'D') console.log(`DAD encontrado no índice ${i}.`); // Se a sequencia for encontrada informa no console sua posição
}

The probability of occurrence of the combination DAD is not the highest so here goes the image of the result. inserir a descrição da imagem aqui

Another verification possibility of the algorithm is to apply the script in a more restricted range of letters. For example [A-F]:

// Cria um array de 1000 caracteres pseudo-aletórios no intervalo [A-F]
let tabLettres = [...Array(1000)].map(x => String.fromCharCode(~~(Math.random() * 6) + 65));

// Itera por tabLettres menos os seus dois últimos itens 
for (let i = 0; i < tabLettres.length - 3; i++) {
  // Compara apartir do item iterado com a sequencia DAD
  if (tabLettres[i] === 'D' &&
      tabLettres[i + 1] === 'A' &&
      tabLettres[i + 2] === 'D') console.log(`DAD encontrado no índice ${i}.`); // Se a sequencia for encontrada informa no console sua posição
}

References:

  • 1

    Thank you very much for your reply, I have learned a lot.

0

it is very unlikely that this test crash, when we have an algorithm with many conditions a good request would be to decrease these conditions in your test.

let tabNombres = [];
let tabLettres = [];

//random numbers array
//Nombres aléatoires 65 à 90
numeroAleatorio = function() {
for (let i = 0; i < 1000; i++) {
      tabNombres.push(Math.floor(Math.random() * ((90 - 65) + 1) + 65));
    }
}

// turning numbers into letters
// characters table
letraAleatorio = function() {
for (let j = 0; j <tabNombres.length; j++) {
    tabLettres.push(String.fromCharCode(tabNombres[j]));
}
}
const filtroDAD = (arr) => {
    let totalD = 0
    let posicao = 0
    for(i=0;i<arr.length;i++) {
        if(arr[i] == "D" && arr[i+1] == "A" && arr[i+2] == "D") {
            totalD +=1
            posicao =i
        }
        
    }

    return `Total DAD ${totalD} sua posição é ${posicao}`
}

numeroAleatorio()
letraAleatorio()
console.log(tabLettres)
console.log(filtroDAD(tabLettres))

in this code you can use less conditions in your comparison

const filtroDAD = (arr) => {
let totalD = 0
let posicao = 0
for(i=0;i<arr.length;i++) {
    // Deixar apenas duas condições para testar e obter mais probabilidade de acerto
    if(arr[i] == "D" && arr[i+1] == "A") {
        totalD +=1
        posicao =i
    }

}

return `Total DAD ${totalD} sua posição é ${posicao}`

}

in my tests only once got the expected output of the algorithm. inserir a descrição da imagem aqui

  • Thank you very much André for your reply, and instruction.

  • if you think the answer was correct you can mark it, thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.