-3

I am trying to generate a random number that does NOT exist in a restricted number array.

js

var restricted = [3, 4, 7];

function getRand () {

    rand = Math.floor(Math.random() * 10);

    if ($.inArray(rand, restricted) === -1) {
        return rand;
    } else {
        try again
    }


}

rand = getRand ();
7
  • If it is being restricted, it is not very random. Also what is the issue with your current code? Commented May 14, 2013 at 16:11
  • 3
    And, what is your question ? Commented May 14, 2013 at 16:11
  • 2
    I guess he wants us to write the try again part? Commented May 14, 2013 at 16:12
  • Don't re-use rand in your function when you're already using it outside the function to hold the return value. Commented May 14, 2013 at 16:13
  • 1
    Get a random entry in [0,1,2,5,6,8,9]. Commented May 14, 2013 at 16:13

3 Answers 3

3

If your problem is about how to implement the "try again" part, just call getRand recursively:

var restricted = [3, 4, 7];

function getRand() {
    var rand = Math.floor(Math.random() * 10);
    if ($.inArray(rand, restricted) === -1) {
        return rand;
    } else {
        return getRand();
    }
}

var rand = getRand();

Also, if all you're using jQuery for is the $.inArray method, I suggest using Array.prototype.indexOf instead (for incompatible browsers, a shim is available here).

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

Comments

2

You need a while loop that tests if rand is in your restricted array and, if so, re-generate a new random number:

var rand;
do { 
    rand = Math.floor(Math.random() * 10); // re-randomize
} while ($.inArray(rand, restricted) > -1);
return rand;

http://jsfiddle.net/mblase75/dAN8R/

6 Comments

What is wrong with the OP's current code?
@Neal For starters, "try again" isn't valid code.
@AustinBrunkhorst no, not in this case.
@AustinBrunkhorst If rand is in the restricted array, the test will return some number greater than -1 and we need to generate a new random number.
May be a little cleaner with a do-while. Would prevent the need to seed rand with a restricted value.
|
1

Try this -

var restricted = [3, 4, 7];

function getRand () {
    var gotRand = false;
    var rand;
    while(!gotRand){  // loop until you got random number
       rand = Math.floor(Math.random() * 10);
       if ($.inArray(rand, restricted) === -1) {
          gotRand = true;
       }
    }
    return rand;
}

rand = getRand();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.