Distribute boolean values uniformly over array (Javascript)

Viewed 84

I have a boolean array with a fixed length. Values are defaulted to false.
I need to fill the array with N values of true, that are mostly evenly distributed and spreaded over the array.

For example: If length is 7 and N is 3, it would look something like this:
[false, true, false, true, false, true, false]

If length is 14 and N is 5, it would look something like this:
[false, false, true, false, false, true, false, false, true, false, true, false, true, false]

The thing is, there isn't a strict rule of how to spread it, only that it should be spreaded mostly in an even matter (perhaps with a rule that the first and last elements won't be true, but not necessary).

2 Answers

function createBoolArray(len, trues) {
  const arr = new Array(len).fill(false);
  
  let leftTrues = trues;
  let left = len;
  let divisor = 0;
  for(let i = 0; i < len && leftTrues > 0;) {
    left = len - i;
    divisor = Math.floor(left / leftTrues);
    
    if(Math.floor(left / divisor) > leftTrues) {
      i = i + divisor + 1;
      arr[i - 1] = true;
    } else {
      i = i + divisor;
      arr[i - 1] = true;
    }
    leftTrues--;
  }
  
  return arr;
}

console.log(createBoolArray(14, 5))

Ended up doing this (similar to what @ChrisG suggested):

function createBoolArray(len, trues) {
  const arr = new Array(len).fill(false);
  new Array(trues).fill(0).map((_, i) => 
  Math.floor((i+1) * (len-1) / trues))
 .forEach(e => arr[e] = true);

  return arr;
}

console.log(createBoolArray(14, 5))
Related