Generate Ranking with combination of strings

Viewed 196

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?

3 Answers
Related