codebuddies / DailyAlgorithms

Do a problem. Create (or find) your problem in the issues. Paste a link to your solution. See others' solutions of the same problem.
12 stars 1 forks source link

[Practice] Grouping Dishes by Ingredient #37

Open lpatmo opened 5 years ago

lpatmo commented 5 years ago

//DISHES //Each element is a list of strings beginning with the name, followed by ingredients //Group by ingredient so you can find all the dishes that contain it. //Only ingredients that are in two or more dishes matter. //Return an array structured the same way, but with ingredients first and all the dishes after

/* dishes = [["Salad", "Tomato", "Cucumber", "Salad", "Sauce"], ["Pizza", "Tomato", "Sausage", "Sauce", "Dough"], ["Quesadilla", "Chicken", "Cheese", "Sauce"], ["Sandwich", "Salad", "Bread", "Tomato", "Cheese"]]

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

//EC: alphabetical order

lpatmo commented 5 years ago

function groupingDishes(dishes) {
    const ingredients = {};
    const results = [];
    for (let i = 0; i < dishes.length; i++) {
      for (let j = 1 ; j < dishes[i].length; j++) {
        if (!ingredients[dishes[i][j]]) {
          ingredients[dishes[i][j]] = [dishes[i][0]];
        } else {
          ingredients[dishes[i][j]].push(dishes[i][0]);
        }
      }
    }
    console.log('ingredients', ingredients)
    // const temp = [];
    for (let key in ingredients) {
      if (ingredients[key].length > 1) {
        //temp.push(key);
        results.push([key].concat(ingredients[key].sort()))
      }
    }
    //['cheese', 'salad', 'sauce','tomato']
    // for (let ingredient of temp) {
    //   results.push([ingredient].concat(ingredients[ingredient]));
    // }
    //['tomato'].concat(['salad', 'pizza', 'sandwich'])
    return results.sort();

}