Skip to content

Latest commit

 

History

History
47 lines (36 loc) · 1.45 KB

1418. 点菜展示表.md

File metadata and controls

47 lines (36 loc) · 1.45 KB

哈希表

function displayTable(orders: string[][]): string[][] {

    let heads: string[] = [], // 表格的标题
        orderNumbers: number[] = []; // 序号列表
    const tableData: Map<string, number> = new Map<string, number>(); // 表格数据

    for (const [, tableNumber, foodItem] of orders) {
        heads.push(foodItem);
        orderNumbers.push(+tableNumber);

        const key: string = hash(tableNumber, foodItem);
        tableData.set(key, (tableData.get(key) || 0) + 1);
    }

    // sort
    heads = [...new Set(heads)].sort();
    heads.unshift("Table");
    orderNumbers = [...new Set(orderNumbers)].sort((a, b) => a - b);

    const results: string[][] = new Array(orderNumbers.length + 1).fill(null).map((value) => []);

    for (let row = 0; row < results.length; ++row) {
        for (let col = 0; col < heads.length; ++col) {
            if (!row) {
                results[row][col] = heads[col];
            } else if (col) {
                const key: string = hash(orderNumbers[row - 1], heads[col]);
                results[row][col] = `${tableData.get(key) || 0}`;
            } else {
                results[row][col] = `${orderNumbers[row - 1]}`;
            }
        }
    }

    return results;
};

function hash(tableNumber: number | string, foodItem: string): string {
    return `${tableNumber}.${foodItem}`;
}