Skip to content

Instantly share code, notes, and snippets.

@christopherwxyz
Created August 24, 2022 17:16
Show Gist options
  • Save christopherwxyz/d070a090d621010b21483da9040fabe6 to your computer and use it in GitHub Desktop.
Save christopherwxyz/d070a090d621010b21483da9040fabe6 to your computer and use it in GitHub Desktop.
groupingDishes
function solution(dishes) {
let dishMap = {};
let ingredientsMap = {};
dishes.forEach((_, i) => {
dishMap[dishes[i][0]] = new Set(dishes[i].slice(1));
});
[...new Set(dishes.map((x) => x.slice(1)).flatMap((x) => x))].map((x) => {
for (const key in dishMap) {
if (dishMap[key].has(x)) {
if (ingredientsMap[x] === undefined) ingredientsMap[x] = [];
ingredientsMap[x].push(key);
}
}
});
return Object.entries(ingredientsMap)
.filter(([key, value]) => {
if (value.length >= 2) {
return [key, value.sort()];
}
})
.sort((a, b) => {
if (a[0] < b[0]) return -1;
if (a[0] > b[0]) return 1;
return 0;
})
.map((x) => x.flat());
}
@christopherwxyz
Copy link
Author

My answer for CodeSignal where:

For

  dishes = [["Salad", "Tomato", "Cucumber", "Salad", "Sauce"],
            ["Pizza", "Tomato", "Sausage", "Sauce", "Dough"],
            ["Quesadilla", "Chicken", "Cheese", "Sauce"],
            ["Sandwich", "Salad", "Bread", "Tomato", "Cheese"]]
            
the output should be

  solution(dishes) = [["Cheese", "Quesadilla", "Sandwich"],
                      ["Salad", "Salad", "Sandwich"],
                      ["Sauce", "Pizza", "Quesadilla", "Salad"],
                      ["Tomato", "Pizza", "Salad", "Sandwich"]]
For

  dishes = [["Pasta", "Tomato Sauce", "Onions", "Garlic"],
            ["Chicken Curry", "Chicken", "Curry Sauce"],
            ["Fried Rice", "Rice", "Onions", "Nuts"],
            ["Salad", "Spinach", "Nuts"],
            ["Sandwich", "Cheese", "Bread"],
            ["Quesadilla", "Chicken", "Cheese"]]
            
the output should be

  solution(dishes) = [["Cheese", "Quesadilla", "Sandwich"],
                      ["Chicken", "Chicken Curry", "Quesadilla"],
                      ["Nuts", "Fried Rice", "Salad"],
                      ["Onions", "Fried Rice", "Pasta"]]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment