|
| 1 | +/** |
| 2 | + * 1418. Display Table of Food Orders in a Restaurant |
| 3 | + * https://leetcode.com/problems/display-table-of-food-orders-in-a-restaurant/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given the array orders, which represents the orders that customers have done in a restaurant. |
| 7 | + * More specifically orders[i]=[customerNamei,tableNumberi,foodItemi] where customerNamei is the |
| 8 | + * name of the customer, tableNumberi is the table customer sit at, and foodItemi is the item |
| 9 | + * customer orders. |
| 10 | + * |
| 11 | + * Return the restaurant's “display table”. The “display table” is a table whose row entries |
| 12 | + * denote how many of each food item each table ordered. The first column is the table number |
| 13 | + * and the remaining columns correspond to each food item in alphabetical order. The first row |
| 14 | + * should be a header whose first column is “Table”, followed by the names of the food items. |
| 15 | + * Note that the customer names are not part of the table. Additionally, the rows should be |
| 16 | + * sorted in numerically increasing order. |
| 17 | + */ |
| 18 | + |
| 19 | +/** |
| 20 | + * @param {string[][]} orders |
| 21 | + * @return {string[][]} |
| 22 | + */ |
| 23 | +var displayTable = function(orders) { |
| 24 | + const foodItems = new Set(); |
| 25 | + const tableOrders = new Map(); |
| 26 | + |
| 27 | + for (const [, table, item] of orders) { |
| 28 | + foodItems.add(item); |
| 29 | + const tableMap = tableOrders.get(table) || new Map(); |
| 30 | + tableMap.set(item, (tableMap.get(item) || 0) + 1); |
| 31 | + tableOrders.set(table, tableMap); |
| 32 | + } |
| 33 | + |
| 34 | + const sortedItems = [...foodItems].sort(); |
| 35 | + const header = ['Table', ...sortedItems]; |
| 36 | + const result = [header]; |
| 37 | + |
| 38 | + for (const table of [...tableOrders.keys()].sort((a, b) => a - b)) { |
| 39 | + const row = [table]; |
| 40 | + const items = tableOrders.get(table); |
| 41 | + for (const item of sortedItems) { |
| 42 | + row.push(String(items.get(item) || 0)); |
| 43 | + } |
| 44 | + result.push(row); |
| 45 | + } |
| 46 | + |
| 47 | + return result; |
| 48 | +}; |
0 commit comments