【问题标题】:Check if there is a duplicate product between 3 arrays using hash使用哈希检查 3 个数组之间是否存在重复产品
【发布时间】:2022-01-23 23:05:56
【问题描述】:

我有一个列表 pf 产品,其数据已分成 3 个数组,其中包含产品的名称、价格和重量。如何创建一个使用哈希映射查找重复产品的函数?

//Inputs:
name = ["ball", "bat", "glove", "glove", "glove"]
price = [2, 3, 1, 2, 1]
weight = [2, 5, 1, 1, 1]
//Output: true

//Inputs: 
name = ["ball", "bat", "glove", "glove", "glove"]
price = [2, 3, 1, 2, 2]
weight = [2, 5, 1, 1, 2]
//Output: false

【问题讨论】:

标签: javascript hash functional-programming hashmap hashtable


【解决方案1】:

Javascript 没有HashSet,但有一个Set 可以存储您喜欢的任何内容。因此,要测试重复项:

  • 创建一个空的Set

  • 遍历i = 0..items.length

  • 对于每个i,从name[i]price[i]weight[i] 创建一个散列。注意:不管你怎么做,只要满足以下条件(注意 3x ===):

    hash(name[i], price[i], weight[i]) === hash(name[i], price[i], weight[i])

  • 创建哈希后,检查它是否已经存在于您的Set

    • 如果存在,则存在重复,您可以立即返回
    • 如果没有,则将哈希添加到您的集合中并继续循环
  • 在没有提前返回的情况下到达循环的末尾意味着没有重复

let name, price, weight;

const makeHash = (name, price, weight) => 
  `${name}__${price}__${weight}`;
  
const duplicateTest = () => {
  const seen = new Set();
  
  for (let i = 0; i < name.length; i += 1) {
    const hash = makeHash(name[i], price[i], weight[i]);
    if (seen.has(hash)) return true;
    
    seen.add(hash);
  }
  
  return false;
}


name = ["ball", "bat", "glove", "glove", "glove"]
price = [2, 3, 1, 2, 1]
weight = [2, 5, 1, 1, 1]
console.log(duplicateTest()); // Output: true

name = ["ball", "bat", "glove", "glove", "glove"]
price = [2, 3, 1, 2, 2]
weight = [2, 5, 1, 1, 2]
console.log(duplicateTest()); // Output: false

【讨论】:

    【解决方案2】:

    我会首先挑战将数据拆分为三个数组的需求,然后如果无法重塑数据结构,则最终以这种方式解决问题。

    const findDupes = (
      [name, ...names], 
      [price, ...prices], 
      [weight, ...weights], 
      res = {},
    ) => {
      const next = ($res) => findDupes(names, prices, weights, $res);
      const hash = `${name}\/${price}\/${weight}`;
      
      const dupe = res[hash] ? { name, price, weight } : [];
      
      return [].concat(dupe).concat(
        names.length ? next({ ...res, [hash]: true }) : [],
      );
    };
    
    const name = ["ball", "bat", "glove", "glove", "glove"];
    const price = [2, 3, 1, 2, 1];
    const weight = [2, 5, 1, 1, 1];
    
    console.log(
      findDupes(name, price, weight),
    );

    【讨论】:

      猜你喜欢
      • 2015-04-18
      • 1970-01-01
      • 2018-03-31
      • 2017-04-28
      • 1970-01-01
      • 2011-12-28
      • 2011-05-19
      • 1970-01-01
      相关资源
      最近更新 更多