Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS do ... while

It seems to me that i misunderstand the behavior of the do ... while loop in JS. Let's say we have a code like:

var a = [1,2,3,4,5];
var b = [];
var c;
do {c = a[Math.floor(Math.random()*a.length)];
    b.push(c);}
while(c===4);
console.log(b);

Which is intended to roll out random item from array a if that item is not 4. But if we roll several times we'll see that it doesn't actually prevent 4 from getting to array b. Why? I thought that it would work like this:

  1. Roll random item from array a, store it to c and push c to b;
  2. Check if (c===4) is true;
  3. If it is — go to paragraph 1;
  4. If it's not — log b to console.

Where am I mistaking and why does this code work in such a way? What are others way to 'ban' some item from array from being rolled randomly (except filtering the array) if this approach can't help me?

like image 533
Tristan Tzara Avatar asked Apr 14 '26 19:04

Tristan Tzara


2 Answers

Do while runs and THEN checks. So it will get a random number from A, store that in C and push that to B, and THEN if C is 4, it will do another loop.

So if C is 4, it will still push it to B, it just won't continue after that.

You could do it like this:

var a = [1,2,3,4,5];
var b = [];
var c = a[Math.floor(Math.random()*a.length)];
while (c !== 4) {
  b.push(c);
  c = a[Math.floor(Math.random()*a.length)];
}
console.log(b);

I think this is what you're trying to do? Continuously push a random item from A into B unless you get the result 4, in which case, quit and go to console.log?

like image 94
WakeskaterX Avatar answered Apr 17 '26 08:04

WakeskaterX


As explained by the commenters, you're still pushing 4. You can avoid it by make it very explicit what happens when.

var a = [1,2,3,4,5];
var b = [];
var c;
var keep_going = true;
while (keep_going) {
    c = a[Math.floor(Math.random()*a.length)];
    if (c === 4) {
        keep_going = false;
    } else {
        b.push(c);
    }
}
console.log(b);
like image 42
Halcyon Avatar answered Apr 17 '26 10:04

Halcyon