gpt4 book ai didi

javascript - 频率计数器未定义/2 的幂不等于

转载 作者:行者123 更新时间:2023-12-02 21:29:24 24 4
gpt4 key购买 nike

所以问题是 2 个数组:

[1,2,2,4];
[1,4,4,16];

检查第一个数组中的项目在第二个数组中是否有重复项。

const counterNumber = (arr1,arr2) => {
if(arr1.length !== arr2.length) return false

let counter1 = {}
let counter2 = {}

for (let val of arr1){
counter1[val] = ( counter1[val] || 0 )+ 1
}

for (let val of arr2){
counter2[val] = ( counter2[val] || 0 )+ 1
}

for(let key in counter1){
if(!(key ** 2 in counter2)) return false
if(counter2[key ** 2] !== counter1[key]) return false
}

return true
}

现在可以工作了,但我不明白这一行

if(counter2[key ** 2] !== counter1[key]) return false

这怎么不返回 false?第一个数组有 1,2,2,4,第二个数组有 1,4,4,16。

对于第一个数组,将值存储在一个对象中后,该对象将具有键 1,2,3。在 for in 循环中

counter2[key **2] is  counter[1 ** 2] / counter[1]  // counter1[1] 
counter2[key ** 2] is counter[ 2 ** 2] / counter[4] // counter1[2]
counte2[key ** 3] is counter{ 3 ** 2] / counter[9] // counter1[3]


these are not === so therefore it should return false but instead if i console.log it gives me undefined and the return true appears.

最佳答案

最后一个 for 循环之前

counter1

const counter1 = {
1: 1,
2: 2,
4: 1
}

counter2

const counter2 = {
1: 1,
4: 2,
16: 1
}

这是一个根据arr1中的值描述不同变量的表格

+----+----------------+---+---+---+
| #1 | value in arr1 | 1 | 2 | 4 |
+----+----------------+---+---+---+
| #2 | counter1 key | 1 | 2 | 4 |
+----+----------------+---+---+---+
| #3 | counter2 key | 1 | 4 |16 |
+----+----------------+---+---+---+
| #4 | counter1 value | 1 | 2 | 1 |
+----+----------------+---+---+---+
| #5 | counter2 value | 1 | 2 | 1 |
+----+----------------+---+---+---+

下面的行检查两个数组中值的频率。

if(counter2[key ** 2] !== counter1[key]) return false

如果您查看表格,它会比较第 4 行和第 5 行;

代码可以像这样重构得更清晰

const counterNumber = (arr1,arr2) => {
if(arr1.length !== arr2.length) return false

let counter1 = {}
let counter2 = {}

for (let val of arr1){
counter1[val] = ( counter1[val] || 0 )+ 1
}

for (let val of arr2){
counter2[val] = ( counter2[val] || 0 )+ 1
}

for(let key in counter1){
if(!hasMatchingSquareNumber(key, counter2)) return false
if(!hasMatchingSquareNumberCount(key, counter1, counter2)) return false
}

return true
}

const hasMatchingSquareNumber = (value, counter2) => {
const valueToSquare = value ** 2;
return valueToSquare in counter2;
}

const hasMatchingSquareNumberCount = (value, counter1, counter2) => {
const valueToSquare = value ** 2;
return counter2[valueToSquare] === counter1[value];
}

关于javascript - 频率计数器未定义/2 的幂不等于,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60659581/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com