Check if arrays have the same values with the same frequencies

时间:2018-12-03 12:54:43

标签: php arrays

I have array with values, e.g.

$parameters = ['G', 'W', 'G'];

and now I need to check if another array has these values. $parameters can have duplicated values and can be in random order so if I'll check these values are in array

$array = ['W', 'G', 'G'];

it should return true but on check with

$array2 = ['W', 'G'];

should return false

How to best do this? I have idea for create $array with count for every letter, next count of every value in $parameters and compare it. Is it a good way?

2 个答案:

答案 0 :(得分:1)

如果我是对的,则需要比较两个数组的相同内容,而无需关心顺序。检查一下:

if (count(array_diff(array_merge($parameters, $array), array_intersect($parameters, $array))) === 0) { 
    /**... */ 
}

答案 1 :(得分:0)

您的想法很好:其算法复杂度为O(n + m),使用array_count_values()函数和equality operator的实现确实很容易:

function compareArrayFrequency(array $a, array $b): bool {
    return array_count_values($a) == array_count_values($b);
}