简体   繁体   English

在数组上均匀分布 boolean 值(Javascript)

[英]Distribute boolean values uniformly over array (Javascript)

I have a boolean array with a fixed length.我有一个固定长度的 boolean 数组。 Values are defaulted to false .值默认为false
I need to fill the array with N values of true , that are mostly evenly distributed and spreaded over the array.我需要用 N 个true值填充数组,这些值大多均匀分布并分布在数组上。

For example: If length is 7 and N is 3, it would look something like this:例如:如果长度为 7,N 为 3,它看起来像这样:
[false, true, false, true, false, true, false]

If length is 14 and N is 5, it would look something like this:如果长度为 14,N 为 5,它看起来像这样:
[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).问题是,对于如何传播它并没有严格的规则,只是它应该主要以均匀的方式传播(也许有一个规则,即第一个和最后一个元素不会是真的,但不是必需的)。

 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):最终这样做了(类似于@ChrisG 的建议):

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM