ChildOfCode


Code, Maker, Robotic, Open Source. Knowledge Bases


Java Script - Possible Combinations with satisfy condition

Find the possible combinations and satisfy a condition

a very long time never update this blog.

last week start again to learning the CTF Jeopardy.

Since CTF Jeopardy have many different category, is just like problem solving . so my wife give me a first CTF Jeopardy challenge .

Find the Billing which group is satisfy with condition.

Our Task

//find possible combinations group total price equal at target Price 514.6.

var targetPrice = 514.6;  
var groupOfBill =[109.80, 59.90, 89.20, 30.00, 159.70, 128.00,  
 138.00, 163.00, 49.00, 45.07, 36.05, 39.90, 31.10];

Possible Combinations with satisfy condition Method

console.time("GetPossibleCombinations");

//Input target data    
var targetPrice = 799.50;  
var groupOfBill = [69.0, 216, 249, 35.8, 79.8, 40.14, 188.7, 143.1, 39.9, 74.90, 52.0, 129.50, 269.15, 86.30, 99.0];

var SatisfyGroup = 0;  
var PossibleGroup = [];  
var Util = function () { };

Util.getCombinations = function (array, size, start, initialStuff, PossibleGroup) {  
    if (initialStuff.length >= size) {
        PossibleGroup.push(initialStuff);
    } else {
        var i;

        for (i = start; i < array.length; ++i) {
            Util.getCombinations(array, size, i + 1, initialStuff.concat(array[i]), PossibleGroup);
        }
    }
}

Util.getAllPossibleCombinations = function (array, size, PossibleGroup) {  
    Util.getCombinations(array, size, 0, [], PossibleGroup);
}

function GetPossibleCombinations() {  
    for (indexGroup in groupOfBill) {
        Util.getAllPossibleCombinations(groupOfBill, indexGroup, PossibleGroup);
    }

    for (theGroup in PossibleGroup) {

        var theArray = PossibleGroup[theGroup]
        var sum = 0;

        for (var index = 0; index < theArray.length; index++) {
            sum += theArray[index]
        }

        if (sum.toFixed(2) == targetPrice) {
            SatisfyGroup++
            console.log("IndexGroup :: " + theArray.length);
            console.log("TargetGroup :: " + theArray);
            console.log("");
        }
    }
}

GetPossibleCombinations();  
console.log("total group :: " + PossibleGroup.length);  
console.log("Satisfy Group :: " + SatisfyGroup);  
console.timeEnd("GetPossibleCombinations");  

Note

  1. In our case we just need find the Possible Combinations with satisfy condition example [a, b, c] and [b, a, c] is same,
    since our satisfy condition is finding out the total amount on the group of bill any group is include same object we define is same group this will make the calculation more faster on performance.

  2. In JavaScript numbering calculation have decimal issue (will write another article for this).

refer:
https://rosettacode.org/wiki/Combinations#Functional

https://www.ibm.com/developerworks/community/blogs/hazem/entry/javascript_getting_all_possible_combinations?lang=en

https://rextester.com/OUC90847