Skip to content Skip to sidebar Skip to footer

How Can I Generate A Random Sequence Of Numbers In Javascript With Conditions?

I'm trying to generate a sequence of numbers from 1-7. Completely random. A number cannot have a number in front of it or behind that separates it by 1. An example: [2, 4, 1, 6,

Solution 1:

Assuming a brute force approach:

var list = [ 1, 2, 3, 4, 5, 6, 7 ];

while(
  list.findIndex(function(v, i) {
    return v == i + 1 || (i && Math.abs(list[i - 1] - v) == 1);
  }) != -1
) {
  list.sort(function() { returnMath.random() - 0.5; });
}
document.write(list.join(' '));

Alternate version

Below is an attempt at the 'progressive filling' method.

It's more efficient overall, in the sense that it's actually trying to build a valid array rather than just observing that a given array is valid. It includes a test for inextricable situations, in which case it will abort immediately.

build() succeeds ~66% of the time (empirical results), so the average number of attempts is 1.5.

By comparison, my first method generates ~27 arrays in average before finding a valid one.

functionbuild() {
  var remaining = [ 1, 2, 3, 4, 5, 6, 7 ],
      res = [],
      candidate,
      n, sz, sel;

  for(n = 0; n < 7; n++) {
    candidate = remaining.filter(function(v) {
      return v != n + 1 && (!n || Math.abs(res[n - 1] - v) != 1);
    });
    if(!(sz = candidate.length)) {
      returnfalse;
    }
    res.push(sel = candidate[(Math.random() * sz) | 0]);
    remaining.splice(remaining.indexOf(sel), 1);
  }
  return res;
}

while((list = build()) === false) {};
document.write(list.join(' '));

Solution 2:

Outline of the approach I would consider:

For each position calculate the possible set of numbers at that position, and randomly select from that list.

Position 0 the set would be [2...7], at position 1 it would be [1, 3...7] minus those removed due to the selection at position 0.

If this fails restart from the beginning until it doesn't (it fails if the set of possibilities at a position is empty).

Solution 3:

I think the main issue was using && (AND) instead of || (OR).

var result = [], current, last = Infinity, i;
while (result.length < 7) {
  i = 0;
  while(++i < 1000 && (!current || result.includes(current) || (current === last - 1) || (current === last + 1) || (current === result.length))) {
    current = 1 + (Math.random() * 7) | 0; //use your floor of choice
  }
  if (i >= 1000) { result.length = 0; continue; }

  result.push(current);
  last = current;
}

Solution 4:

Your code has a missing ) in line 7. Here is a fixed version that loops correctly:

var randomOrder = [];

for (i = 0; i < 7; i++) {
    randomOrder[i] = Math.round(Math.random() * 6 + 1);
    if (i > 0) {
        while ((randomOrder.lastIndexOf(randomOrder[i], i - 1) != -1) && (((randomOrder[i - 1] - 1) != randomOrder[i]) && ((randomOrder[i - 1] + 1) != randomOrder[i]) && (randomOrder[i] != (i + 1)))) {
            randomOrder[i] = Math.round(Math.random() * 6 + 1);
        }
        alert(randomOrder.lastIndexOf(randomOrder[i], i - 1));
        alert(randomOrder);
    }
}

Post a Comment for "How Can I Generate A Random Sequence Of Numbers In Javascript With Conditions?"