skip to Main Content

I have the following problem:

Given is an 8-column grid. Now I want to place an item randomly inside it with a random span-width. I figured it out, how to place it randomly and give it a random width.
But I can’t figure out, how to adjust the width based on parameters.

So for example:
columnStart and columnSpan should be less or equal than 8 but still number 2 should be at least 2.

So columnStart can max only be 6.

Thank you for the help!

I tried it with this:
let columnStart = Math.floor(Math.random() * 8) + 1; let columnSpan = Math.floor(Math.random() * 7) + 2;

Which resulted in objects, starting at columnStart 6 and span over 6 more columns. Which shouldn’t be due it’s only a 8-column grid.

I also tried a do-while loop:
do { let columnStart = Math.floor(Math.random() * 8) + 1; let columnSpan = Math.floor(Math.random() * 7) + 2; } while (columnStart + columnSpan === 8)

But this also didn’t brought the result I tried to achieve

2

Answers


  1. // 1 to 6.
    const columnStart = Math.floor(Math.random() * 6) + 1;
    // 2 to 8
    const columnSpan = 2 + Math.floor(Math.random() * (8 - columnStart));
    console.log("Start:", columnStart, "Span:", columnSpan);
    Login or Signup to reply.
  2. function getRandomNumber(min, max) {
      // Generate a random number between 0 and 1 (exclusive)
      const randomFraction = Math.random();
      
      // Scale the random number to the desired range (max - min) and shift it by min
      const randomNumberInRange = randomFraction * (max - min) + min;
    
      // Use Math.floor or Math.round to get an integer result, if needed
      return Math.floor(randomNumberInRange); // Change to Math.round for rounding
    }
    
    // Example usage:
    const minNumber = 1;
    const maxNumber = 100;
    const randomNum = getRandomNumber(minNumber, maxNumber);
    console.log(randomNum);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search