Quick actions

cmd+k|ctrl+k

Navigation

Languages

Greedy Cake Thief

Snippet info

Language

JavaScript

Visibility

public

Author

horngyih

Created

2018-01-30T12:16:42Z

Updated

2018-01-30T12:16:42Z

var lines = [];

function parseInput(){
    var inputs = lines
    .map(item=>item.split(";"));
    inputs.forEach(item=>execute(item));
}

function readInput(){
    var buffer = process.stdin.read();
    if( buffer ){
        lines.push(buffer.toString());
    }
}

process.stdin.on("readable", readInput);
process.stdin.on("end", parseInput);

function execute( input ){
    var tuples = JSON.parse(input[0]);
    var capacity = parseInt(input[1]);
    console.log( optimize(tuples, capacity) );
}

function optimize( tuples, capacity ){
    var result = 0;
    console.log( "Tuples : ", tuples, " Capacity : ", capacity );
    if( tuples.length > 1 && capacity > 0 ){
        var weightedTuples = tuples
        .filter(item=>item[0]<=capacity) // Ignore cakes with higher weight than capacity
        .filter(item=>item[0]>0) // Ignore cakes with zero weight
        .filter(item=>item[1]>0) // Ignore cakes with zero value
        .map(item=>item.concat(Math.floor(capacity/item[0]))) // Determine the maximum number of cakes for each tuple can fit in duffel
        .map(item=>item.concat(capacity-(item[2]*item[0]))) // Determine the remaining capacity after the maximum number of cakes for each tuple
        .map(item=>item.concat(item[2]*item[1])) // Determine the value of the maximum number of cakes
        .sort((item1,item2)=>item2[4]-item1[4]); // Sort based on the maximum value
        var maxTuple = weightedTuples.shift(0,1); //Remove the Most lucrative tuple
        console.log(maxTuple);
        result = parseInt(maxTuple[4]) + optimize( weightedTuples.map(item=>[].concat(item[0]).concat(item[1])), maxTuple[3] ); //Optimize the remaining tuples with the remainder as capacity
    }
    return result;
}
INFO