Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

238
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!