0

I can't wrap my head around a piece of code using loops and functions in javascript. I have a function which generates random numbers (between a min and max), see below:

const getRandomNumber = (min, max) => {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min; 
}

Below a simple Function which returns true if 2 random numbers add up to 10, else it returns false:

const Function1 = (n1, n2) => (n1 + n2 === 10) ? true : false

Below i will use Function1 to return n1 and n2:

const Function1Check= () => {
    const n1 = getRandomNumber(-10, 10);
    const n2 = getRandomNumber(-10, 10);
    if(Function1(n1, n2)) {
     return [n1, n2]
    } else {
     return {false}
   }
}


const LoopFunction = () => {
    while(Function1Check === false) {
       Function1Check();
     if(Function1Check) {break;}
  }
}

My while loop does not work correctly, what am i missing? Hope you guys can help me out and point me in the right direction using vanilla javascript. Thanks in advance.

Greetings.

6
  • 3
    "I have tried different things with while loops..." That's the kind of thing you'd want to do, show us that. Commented Jun 23, 2021 at 9:33
  • while loop doesn't return anything, please show your loop, and be specific when describing the problem. Commented Jun 23, 2021 at 9:35
  • Please show us what you have tried. It will help us understand the problem better and help you. Commented Jun 23, 2021 at 9:36
  • notice how low probable is that you get the right numbers,maybe your freezing is because of that Commented Jun 23, 2021 at 9:48
  • 1
    before your last edit, you wanted a loop with 5 results. Now you only want one. But that's still roughly 0.22% probable. You should expect to wait for a while (pun not intended) Commented Jun 23, 2021 at 9:55

3 Answers 3

3

You can use a do.. while loop and quit after a maximum number of attempts to avoid an infinite loop.

The loop will also terminate once the target length of the array is reached:

const getRandomNumber = (min, max) => {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min; // max & min both included 
}

const Function1 = (n1, n2) => (n1 + n2 === 10) ? true : false

const Function1Check = () => {
    const n1 = getRandomNumber(-10, 10);
    const n2 = getRandomNumber(-10, 10);
    if(Function1(n1, n2)) {
        return [n1, n2]
    } else {
        return false;
    }
}


let rightNumbers = [];
let attempts = 0;
let maxAttempts = 1000;
let target = 5;

do {
   let numbers = Function1Check();
   if (numbers) {
       rightNumbers.push(numbers);
   }
} while (rightNumbers.length < target && (attempts++) < maxAttempts)

console.log(`Found ${target} number(s) after ${attempts} attempts`);
console.log(`Numbers:`, rightNumbers)

Sign up to request clarification or add additional context in comments.

5 Comments

nice addition of maxAttempts
perfect, this is what i was looking for!!
(after your edit) please notice that is not the same generating two random numbers and checking if they fulfill a given constraint than generating one random number and forcing the other to comply with the constraint
Oh, yes I agree I'm probably missing something. It's just a possible approach, perhaps suitable for a similar issue. I'll delete the second snippet if you feel it adds nothing!
I hadn't see the update at that point.. I've updated again.
2

If your program freezes that's a clear sign that your while loop doesn't stop.

I'd approach it the following way:

const AMOUNT_OF_RESULTS = 5;
const results = [];

// This would be the correct predicate to stop your while loop. 
// You want to stop looping once you have 5 correct results.
while (results.length < AMOUNT_OF_RESULTS ) {
    const result = checkRightNumbers();

    // If result is not false(an array in your case)
    if(!result) {
        // Then add the result to the array of results:
        results.push(result);
    }
}

The loop will continue generating results until it filled the quota(AMOUNT_OF_RESULTS).

Comments

1

A method which achieves what you are trying to do looks something like this:

const getSolutionSet = () => {
  let answers = [];

  while(answers.length < 5){
    let check = checkRightNumbers(); 
    if(check){
      answers.push(check);
    }
  }

  return answers;
}

You could make it a bit more advanced, by passing the amount of results as a parameter

const getSolutionSet = (numResults) => {
  let answers = [];

  while(answers.length < numResults){
    let check = checkRightNumbers(); 
    if(check){
      answers.push(check);
    }
  }

  return answers;
}

You should keep in mind, that the probability is pretty low to find an exact match, so adding a max number of tries would also be a good idea

1 Comment

using maxAttempts stopped my screen from freezing. THanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.