Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,955 questions

51,897 answers

573 users

How to find elements that appear more than array_size/K times in an array with PHP

1 Answer

0 votes
function elements_that_appear_more_than_x_times($arr, $k) {
    $size = count($arr);
    $times = (int)($size / $k);
    
    echo "more than " . strval($times) . " times","\n";
    
    $freqency_map = array_count_values($arr);

    return $freqency_map;
}

$k = 4;
$arr = array(4, 8, 6, 5, 5, 8, 3, 2, 1, 2, 2, 5, 5, 5, 5, 8, 9, 8, 8);

$freqency_map = elements_that_appear_more_than_x_times($arr, $k);

$size = count($arr);
foreach(array_keys($freqency_map) as $key) {
    if ($freqency_map[$key] > (int)($size / $k)) {
        echo $key . " " . $freqency_map[$key] . " times\n";
    }
}




/*
run:

more than 4 times
8 5 times
5 6 times

*/

 



answered Feb 11, 2024 by avibootz
...