【发布时间】:2020-05-09 23:18:00
【问题描述】:
我正在尝试创建一个脚本来生成二进制开关的所有各种排列,其中应该有 5 个1 和 4 个0。并且数组的大小应该是9。
我尝试了以下代码。排列的条件是:
1.数组集应该是唯一的。
2. 相邻的1不超过3个
const row = [1, 1, 1, 1, 1, 0, 0, 0, 0];
const list = [];
const fullList = [];
// To make sure that no more than 3 `1` are next to each other
const isRowValid = (row) => {
let isValid = true;
for(let i = 0; i+2 < row.length; i++) {
if(row[i] === 1 && row[i+1] === 1 && row[i+2] === 1) {
isValid = false;
break;
}
}
return isValid;
}
const combinations = (row, baseIndex, currentIndex, iterationLevel, list) => {
if(currentIndex > row.length - iterationLevel) {
baseIndex++;
currentIndex = 0;
}
if(baseIndex + iterationLevel > row.length) {
baseIndex = 0;
iterationLevel++;
}
if(iterationLevel === 5) {
return;
}
let rowCopy = [...row]
if(baseIndex > currentIndex ) {
let first = [...row.slice(0, currentIndex)];
let second = [...row.slice(currentIndex)];
let value = second.splice(baseIndex - currentIndex, iterationLevel);
rowCopy = [...first, ...value, ...second]
} else if(baseIndex < currentIndex) {
let first = [...row.slice(0, currentIndex + iterationLevel)];
let second = [...row.slice(currentIndex + iterationLevel)];
let value = first.splice(baseIndex, iterationLevel);
rowCopy = [...first, ...value, ...second];
}
if(isRowValid(rowCopy)) {
list.push(rowCopy);
}
console.log(rowCopy);
combinations(row, baseIndex, currentIndex + 1, iterationLevel, list);
}
combinations(row, 0, 0, 1, list);
list.forEach(l => combinations(l, 0, 0, 1, fullList));
// To remove duplicates
for(let i = 0; i < fullList.length; i++) {
const base = fullList[i]
for(let j = i + 1; j < fullList.length; j++) {
const isSame = fullList[j].every((l, m) => base[m] === l);
if(isSame) {
fullList[j] = [];
}
}
}
let filtered = fullList.filter(l => l.length !== 0);
console.log(filtered.length);
filtered.slice(0, 100).map(i => console.log(i));
console.log(fullList.length);
【问题讨论】:
-
不清楚你在问什么。
-
预期输出是什么?
-
你的意思是排列而不是组合?
标签: javascript arrays typescript combinations