I have inputs like :
var a = [23, 45, 21], b = [45, 23], c = [21, 32], d = [23], e= [32], f= [50, 54];
These all are separate entities and can be passed only one array at a time. i.e generateRanks(a). sometimes later, generateRanks(b)
Result is stored in global variable. For each time, i make a call with input, the result is updated.
And the result should includes the ranking of all combination of values from the array.
The output should be like :
{
"21": 2,
"23": 3,
"32": 2,
"45": 2,
"52": 1,
"54": 1,
"23, 45": 2,
"23, 45, 21": 1,
"21, 32": 1,
"50 : 54": 1,
"50" : 1
}
This is what I'm tried
var result;
function generateRank(abc) {
if(!result) {
result = {};
}
var spl = getCombinations(abc);
spl.forEach(function(st, index) {
var fArrayKey = st.split(":");
var noMatch = true;
Object.keys(result).forEach(function(key) {
console.log(key);
var matchedKey = containsAllStrings(key, fArrayKey);
if(matchedKey) {
console.log("macthed true ");
result[key] = result[key] + 1;
noMatch = false;
}
else {
console.log("macthed false ");
noMatch = true;
}
});
if(noMatch) {
result[fArrayKey] = 1;
}
});
}
function containsAllStrings(word, array) {
for(var k=0; k<array.length; k++) {
if(word.indexOf(array[k]) == -1) {
return false;
}
}
return true;
}
function getCombinations(chars) {
var result = [];
var f = function(prefix, chars) {
for (var i = 0; i < chars.length; i++) {
result.push(prefix + chars[i]);
f(prefix + chars[i] + ":", chars.slice(i + 1));
}
}
f('', chars);
return result;
}
Any help?
You could sort the arrays and take all combinations and count the occurence of the combinations.
function getCombinations(array) {
function fork(i, t) {
if (i === array.length) {
t.length && result.push(t);
return;
}
fork(i + 1, t.concat(array[i]));
fork(i + 1, t);
}
var result = [];
fork(0, []);
return result;
}
function addCombination(array, object) {
getCombinations(array.sort((a, b) => a - b))
.forEach(a => object[a.join(', ')] = (object[a.join(', ')] || 0) + 1);
}
var a = [23, 45, 21],
b = [45, 23],
c = [21, 32],
d = [23],
e = [32],
f = [50, 54],
result = Object.create(null);
addCombination(a, result);
addCombination(b, result);
addCombination(c, result);
addCombination(d, result);
addCombination(e, result);
addCombination(f, result);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }