在javascript中实现get array可能组合的最简单,无库的代码是什么?我想写
var preDefinedCombinations = [
['a', 'b', 'c'],
['a', 'c', 'd'],
['a'],
['b'],
['c']
];
var selectedvalues = ['a', 'b', 'd'];
getPossbileCombination(selectedvalues, preDefinedCombinations);
并获取
['a','b','c'],['a','c','d']
我尝试了下面的代码,但没有按预期工作,如果用户选择'a','b'而不是警报显示他选择'c'进行有效组合,它总是给我错过的术语。但如果用户选择'a','b'和amp; ['d']它不会为所选值提供可能的组合。
var preDefinedCombinations = [['a','b','c'], ['a','c','d'], ['a'], ['b'], ['c']];
var selectedvalues = ['a','b','d'];
function selectOption(value){
var checkIndex = selectedvalues.indexof(value);
if(checkIndex == -1){
selectedvalues.push(value);
}else{
selectedvalues.splice(checkIndex, -1);
}
}
function intersect_safe(a, b)
{
var ai=0, bi=0;
var result = new Array();
while( ai < a.length && bi < b.length )
{
if (a[ai] < b[bi] ){ ai++; }
else if (a[ai] > b[bi] ){ bi++; }
else /* they're equal */
{
result.push(a[ai]);
ai++;
bi++;
}
}
return result;
}
function checkVaildCombination(){
if(preDefinedCombinations.indexOf(selectedvalues) == -1){
var missing_bits = [];
for (var i = 0; i < preDefinedCombinations.length; i++) {
var missing_bit = intersect_safe(preDefinedCombinations[i], selectedvalues);
if (missing_bit.length == selectedvalues.length) { // candidate for valid answer
missing_bit = [];
for (var j = 0; j < preDefinedCombinations[i].length; j++) {
if (selectedvalues.indexOf(preDefinedCombinations[i][j]) == -1) { // actual missing bit
missing_bit.push(preDefinedCombinations[i][j]);
}
}
missing_bits.push(missing_bit);
}
}
alert('Invalid Combination, if you select any of these you`ll get a valid combination:\n' + missing_bits.toString());
}else{
alert('Valid Combination');
}
}