【问题标题】:Find unmatched unique pairs of an array from another array从另一个数组中查找不匹配的唯一数组对
【发布时间】:2021-07-18 17:22:12
【问题描述】:

我有一个用户列表,也有一对匹配用户的列表。即

const users = ["A", "B", "C", "D", "E", "F", "G"];
const alreadyMatchedUsers = [
    { user1: 'A', user2: 'B' },
    { user1: 'A', user2: 'C' },
  ]

我想查找唯一不匹配用户的列表。唯一性是指用户对 AB 和 BA 将被视为 1 对。

这是我想出的解决方案:

const alreadyMatchedUsers = [
    { user1: 'A', user2: 'B' },
    { user1: 'A', user2: 'C' },
  ]

  const unMatchedArrary = []

  // const users = ['A', 'B', 'C', 'D']

  const users = []

  for (let i = 0; i < 300; i++) users.push(i)

  const n = users.length
  const uniquePossiblePairs = []
  const uniquePossiblePairsCount = (n * (n - 1)) / 2

  for (let i = 0; i < n - 1; i++) {
    console.log('Main loop+++++++++++++++++', users[i])
    for (let j = i; j < n - 1; j++) {
      // uniquePossiblePairs.push({ user1: users[i], user2: users[j + 1] });
      const alreadyMatched = alreadyMatchedUsers.some(
        (mpair) => (users[i] === mpair.user1 || users[i] === mpair.user2)
          && (users[j + 1] === mpair.user1 || users[j + 1] === mpair.user2),
      )

      if (!alreadyMatched) {
        unMatchedArrary.push({ user1: users[i], user2: users[j + 1] })
      }

      console.log('Already Matched, ', users[i], users[j + 1], alreadyMatched)
    }
  }

  console.log('UNIQUE POSSIBLE PAIRS Count', uniquePossiblePairsCount)
  console.log('UNIQUE POSSIBLE PAIRS', uniquePossiblePairs)
  console.log('UNMATCHED ARRARY ', unMatchedArrary)
}

这个解决方案给出了预期的结果,但它的操作非常昂贵。尝试在 300 个用户的情况下运行此代码,如果已经匹配的用户变得更大,它将变得更加昂贵。

我怎样才能让它更快?

谢谢

【问题讨论】:

    标签: javascript arrays performance recursion


    【解决方案1】:
    const users = ["A", "B", "C", "D", "E", "F"];
    
    const combinations = [];
    while (users.length > 0) {
        const lastUser = users[users.length-1]; // start at last user of users list.
        
         // this loop gets all combinations involving the last user.
        for (let user of users) {
            if (user !== lastUser) {
                combinations.push({"user1": user, "user2": lastUser});
            }
        }
        
        // this gets rid of last user from the users list, as we have found all its combinations from this iteration of the while loop.
        users.pop()
    }
    
    console.log(combinations);
    

    此算法可确保迭代次数 == number of possible combinations

    【讨论】:

    • 他们已经这样做了:内部循环ji 开头(实际上应该是i+1)。但是,对于大 N 来说,“N 选择 2”仍然是一个巨大的数字。
    • 对。将保留它,因为它可能有助于清理代码。
    【解决方案2】:

    你可以这样实现:

    const users = ["A", "B", "C", "D", "E", "F", "G"];
    const alreadyMatchedUsers = [
      { user1: 'A', user2: 'B' },
      { user1: 'A', user2: 'C' },
    ]
      
    const pairs = alreadyMatchedUsers.map(x => `${x.user1}${x.user2},${x.user2}${x.user1}`);
    
    let allPairs = [];
    
    for (user of users) {
      allPairs.push(...users.map(x => `${user}${x},${x}${user}`))
    }
    
    // filter allPairs
    const uniquePairs = allPairs
       .filter(pair => !pairs.includes(pair) && pair.split(',')[0] != pair.split(',')[1])
       .map(pair => pair.split(',')[0].split('')); 
    
    console.log('pairs: ', pairs);
    console.log('allPairs: ', allPairs);
    console.log('uniquePairs', uniquePairs);

    【讨论】:

    • AFAG 等怎么样?
    【解决方案3】:

    这是我对这个问题的看法。我已将matchedPairs 从对象替换为数组以简化这一点。

     const users = ["A", "B", "C", "D", "E", "F", "G"];
    const alreadyMatchedUsers = [
      ["A", "B"],
      ["A", "C"],
    ];
    const unmatchedPairs = [...alreadyMatchedUsers];
    const unmatchedPairsFinal = [];
    for (let i = 0; i < users.length; i++) {
      users.forEach((user) => {
        if (user !== users[i]) {
          console.log("checking", user, " vs ", users[i]);
          const alreadyDetected = unmatchedPairs.filter((userCheck) => {
            return userCheck.includes(user) && userCheck.includes(users[i]);
          });
          console.log(alreadyDetected);
          if (!alreadyDetected.length > 0) {
            unmatchedPairs.push([user, users[i]]);
            unmatchedPairsFinal.push([user, users[i]]);
          }
        }
      });
    }
    console.log(unmatchedPairs);
    console.log(unmatchedPairsFinal);

    【讨论】:

      猜你喜欢
      • 2016-02-14
      • 2023-02-04
      • 2020-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-27
      相关资源
      最近更新 更多