javascript
Php循环函数嵌套javascript,JS循环嵌套问题?
從arr中挑選出來需要保存的(arr.length - count)所有可能的組合,然后再從原數(shù)組中挑選出來所有可能的(count)補(bǔ)充組合,然后拼在一起去重就行了。
(async ()=>{
let vari = ['A','T','C','G'];
function change(arr, count = 1){
arr = arr.map(a=>vari.indexOf(a)).sort(); // convert to int array, for easier sorting in future
var prefix = combination(arr, arr.length - count);
var suffix = combination([0,1,2,3], count);
var res = prefix.length === 0 ? suffix : prefix.map(p=>suffix.map(s=>[...p, ...s])).reduce((a,b)=>[...a,...b], []);
var existing = arr.join(",");
res = res
.filter(r=>new Set(r).size === r.length) // filter out ones with duplicated items, like ["A","A","C"]
.map(r=>r.sort()) // order items, so ["C","A"] becomes ["A", "c"]
.sort() // sort, just make it looks prettier
.reduce((a,b)=>{ // remove duplicated combinations, keep only one
if(a[b.join(",")] === void 0){
a.arr.push(b);
a[b.join(",")] = 0;
}
return a;
}, {arr: []}).arr
.filter(r=>r.join(",") !== existing);
return res.map(r=>r.map((i)=>vari[i]));// convert back to letters
}
function combination(src, pick){
if(pick > src.length){
return [];
}
if(pick === 1){
return src.map(s=>[s]);
}
var res = [];
for(var i=0;i
for(var r of combination(src.slice(i+1), pick - 1)){
res.push([src[i], ...r]);
}
}
return res;
}
console.log(change(["G","A","C"], 2));
})();
output [A,T,C],[A,T,G],[T,C,G]
總結(jié)
以上是生活随笔為你收集整理的Php循环函数嵌套javascript,JS循环嵌套问题?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python网球比赛模拟_Python-
- 下一篇: 详细解释CNN卷积神经网络各层的参数和链