useful in algorithms and challenges when you have multiple pieces of data, multiple inputs, and you need to compare them to see if they consist of similar values, if they are anagrams of one another, if a value is contained inside of another value, anytime you're comparing pieces of data to inputs or more than two and frequencies of certain things occurring,
usually use an object to construct a profile, sort of a way of breaking down the contents of an array or a string, usually some sort of linear structure like that.
문제
Write a function called same, which accepts two arrays. The function should return true if every value in the array has it's corresponding value squared in the second array. The frequency of values must be the same.
풀이
function same(arr1, arr2){
if(arr1.length !== arr2.length){
return false;
}
let frequencyCounter1 = {}
let frequencyCounter2 = {}
for(let val of arr1){
frequencyCounter1[val] = (frequencyCounter1[val] || 0) + 1
}
for(let val of arr2){
frequencyCounter2[val] = (frequencyCounter2[val] || 0) + 1
}
console.log(frequencyCounter1);
console.log(frequencyCounter2);
for(let key in frequencyCounter1){
if(!(key ** 2 in frequencyCounter2)){
return false
}
if(frequencyCounter2[key ** 2] !== frequencyCounter1[key]){
return false
}
}
return true
}
same([1,2,3,2,5], [9,1,4,4,11])
// {1:1, 2:2, 3:1, 5:1}
// {1:1, 4:2, 9:1, 11:1}
'Computer Science' 카테고리의 다른 글
[DB] 이상현상 Anomaly 란? (0) | 2024.01.21 |
---|---|
[ 자료구조 ] 배열 Array & 연결리스트 Linked List & 스택 Stack (0) | 2023.10.31 |
[ 자료구조 ] 해시테이블 Hash Table (0) | 2023.10.29 |
CLI , GUI 란? (1) | 2023.10.26 |
운영체제 Operating System란? (0) | 2023.10.26 |