0
<div id='passarr'>1572 4528 3564 8921 4521</div>

I need to create a new random integer (4 digits), unique regarding the above content.

js

var content = $('#passarr').text();
var passarr = content.split(' ');
var pass = Math.floor(Math.random() * 9000) + 1000;
var i = 0;
while (i == 0) {
    if (jQuery.inArray(pass, passarr) > -1) {
        var pass = Math.floor(Math.random() * 9000) + 1000;
        i = 1;
    }
}

seems it works, but not sure this is the right and shortest way.
any suggestion?

7
  • Is #passarr the result? Commented Jul 28, 2017 at 17:36
  • 2
    It looks like the boolean expression in your if statement should actually be the boolean expression in the while statement. You don't need i. Commented Jul 28, 2017 at 17:37
  • @zer00ne, no, result is pass Commented Jul 28, 2017 at 17:40
  • 1
    I think what @4castle meant was while (jQuery.inArray(pass, passarr) === -1)) { ... } Commented Jul 28, 2017 at 17:41
  • 1
    This works by luck. In (5/9000)**2 cases, it wont work... ;0 Commented Jul 28, 2017 at 17:44

1 Answer 1

3

Your code is the way to go. However, you can eliminate a few smaller mistakes ( an unneccessary i and non working code in < 0.00001%) :

var content = $('#passarr').text();
var passarr = content.split(' ');
do {
  var pass = Math.floor(Math.random() * 9000) + 1000;
} while (jQuery.inArray(pass, passarr) > -1);

console.log(pass);
Sign up to request clarification or add additional context in comments.

3 Comments

This is exactly the algorithm they need. My only suggestion is to move the declaration of var pass to be outside of the loop, so that someone who isn't aware of hoisting won't be confused by the scope of pass.
@4castle thats actually a point for not changing it. Theyll wonder that this works, and will be more clever afterwards ;)
excellent, later I saw that my code in fact doesn't work. This works. thanks a lot.

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.