0

I want to generate a random number between 1 and 10 but it should not be equal to the current no or current value?

I looked at this below answer but having difficulty in making it as module since current no has to be retrieved from different file. I pretty much want something like this, but not exactly (if yo get what I mean).

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
steve
  • 49
  • 10
  • The answers to the question you've linked provide multiple ways of generating a random number, with the restriction that you've identified. Many of these could be split between multiple files, or be referenced from a single file. Is your question about how to write javascript split between multiple files? – Micheal Hill Dec 08 '18 at 07:25

2 Answers2

1

Simple - just use a function which takes the current number, and generate a random number from 1-10 and, if it's equal to the current number, recalculate and re-check:

function newRandomNumber(currentNumber) {
    var random = Math.floor(Math.random() * 10) + 1;
    while (random == currentNumber) {
        random = Math.floor(Math.random() * 10) + 1;
    }
    return random;
}
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
1

I have the below solution:

let previousValue = Math.floor(Math.random() * 10) + 1

for(let i = 0; i < 20 ; ++i) {
    previousValue = (previousValue + Math.floor(Math.random() * 9)) % 10 + 1
    console.log(new Date(), previousValue)
}

As you can see you create a previousValue to initiate the process. To generate another value between 1 and 10 but different than the previous one the solution is to generate a value between 0 and 9 and add it to the previous value. Using modulo operator you end up with a result in the correct range and different from the previous one.

Eponyme Web
  • 966
  • 5
  • 10