본문 바로가기
Computer Science

[ Algorithm ] 빈도수 세기 패턴 Frequency Counters

by ウリ김영은 2023. 10. 29.
  • 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}