Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

239
Visualizações
generate 2 different random numbers from an Array?

my only issue so far is when the ships have the same value, I get an error message if I'm using VSC. TypeError: Assignment to constant variable. I was trying to get to different values by using the condition but I think it doesn't work.

let grid = [[]];
const letters = "abc".toUpperCase();

// create the Grid


const createGrid = (size) => {
  let row;
  let col = 0;
  for (row = 0; row < size; row++) {
    grid[row] = [];
    for (col = 0; col < size; col++) {
    grid[row][col] = `${letters[row]}${col + 1}`;
    }
  }

};

createGrid(letters.length);
console.table(grid);

// Start the game


//create ships



const flatArray = grid.reduce((acc, curr) => {
  return [...acc, ...curr];
}, []);

function getRandomNumber(len) {
  return Math.floor(Math.random() * len);
}


const randomNumber1 = getRandomNumber(flatArray.length);
const randomNumber2 = getRandomNumber(flatArray.length);

while(randomNumber1 == randomNumber2) {
  getRandomNumber();
}

var shipOne = flatArray[randomNumber1];
var shipTwo = flatArray[randomNumber2];



console.log(shipOne);
console.log(shipTwo);

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Fix an infinite loop

I created a snippet from your example code and it runs forever in the error case you are describing.

A problem is that you have a while loop that will run forever:

while(randomNumber1 == randomNumber2) {
  getRandomNumber();
}

You run this code as long as randomNumber1 and randomNumber2 are the same but you update neither of them in the loop so it can never be false.

Try this:

while(randomNumber1 == randomNumber2) {
  randomNumber2 = getRandomNumber(flatArray.length);
}

You might also make your code a little smarter and remove elements from the flatArray array you have already chosen.

about 4 years ago · Juan Pablo Isaza Relatório

0

Inside of your while loop if the two random numbers were the same you would be stuck inside an infinite loop. Like Peter stated.

To fix this use the code Peter stated but don't forget you still need to pass in the array length into this function. Otherwise you will have an error:

while(randomNumber1 == randomNumber2) {
  randomNumber2 = getRandomNumber(flatArray.length);
}

Thanks!!

about 4 years ago · Juan Pablo Isaza Relatório

0

One other approach you could try is to create a function pickRandomEntries() that will pick N random entries from an array, without ever picking the same ones.

To do this, we shuffle a copy of your flatArray(), then pick the first two items.

This way we never have to check for the ships having the same value:

let grid = [[]];
const letters = "abc".toUpperCase();

const createGrid = (size) => {
  let row;
  let col = 0;
  for (row = 0; row < size; row++) {
    grid[row] = [];
    for (col = 0; col < size; col++) {
    grid[row][col] = `${letters[row]}${col + 1}`;
    }
  }
};

createGrid(letters.length);

const flatArray = grid.reduce((acc, curr) => {
  return [...acc, ...curr];
}, []);

// Shuffle an array into a random order (using Fisher-Yates)
function shuffle(arr) {
    for(let i = arr.length - 1; i > 0; i--) {
        let index = Math.floor(Math.random() * (i + 1));
        [arr[index], arr[i]] = [arr[i], arr[index]];
    }
    return arr;
}

// Pick count random items from the array
function pickRandomEntries(arr, count) {
    let shuffled = shuffle([...arr]);
    return shuffled.slice(0, count);
}

let [shipOne, shipTwo] = pickRandomEntries(flatArray, 2);
console.log( { shipOne, shipTwo });

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda