Skip to content

Instantly share code, notes, and snippets.

@sethuster
Created May 16, 2019 15:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sethuster/e328817743a707a860ddef2ced083d1a to your computer and use it in GitHub Desktop.
Save sethuster/e328817743a707a860ddef2ced083d1a to your computer and use it in GitHub Desktop.
Pizza Topping Combination Rank
// Assuming you have a json file named pizzas.json in the same directory as this script
// and the JSON file is a list of objects { "toppings" : ["topping1", "topping2"] }
// Determine the 20 most popular pizza topping combinations.
// Output the Combinations, the number of times the combination has been ordered,
// and the number of times the topping has been used
const fs = require('fs');
const pizzaFile = JSON.parse(fs.readFileSync('./pizzas.json', 'utf8'))
let search = '';
let uniqToppings = []
function findTopping(element) {
return element.name === search;
}
function rankToppings(){
pizzaFile.forEach((toppings) => {
toppings.toppings.forEach(topping => {
search = topping;
let found = uniqToppings.findIndex(findTopping);
found == -1 ? uniqToppings.push({name: topping, rank: 1}) : uniqToppings[found].rank += 1;
})
});
}
function findCombo(element){
if(
(element.toppings.length == search.length)
&& element.toppings.every((e, i) => { return search.includes(e); })
) {
return true;
} else {
return false;
}
}
function rankCombinations() {
rankToppings();
let combos = []
pizzaFile.forEach(combo => {
search = combo.toppings.filter((e, i) => {
return combo.toppings.indexOf(e) == i;
});
let found = combos.findIndex(findCombo);
found == -1 ? combos.push({toppings: combo.toppings, rank: 1}) : combos[found].rank += 1;
});
combos.sort((a, b) => {
return b.rank - a.rank;
});
for(let i = 0; i < 20; i += 1){
let toppings = '';
combos[i].toppings.forEach(topper => {
search = topper;
let t = uniqToppings.findIndex(findTopping);
toppings += `['${topper}' Used: ${uniqToppings[t].rank}]`
})
console.log(`Topping Combo: ${toppings} Rank: ${combos[i].rank}`);
}
}
rankCombinations()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment