fork download
  1. <?php
  2.  
  3. $input = array (3, 6, -3, 5, -10, 3, 10, 1, 7, -1, -9, -8, 7, 7, -7, -2, -7);
  4. function pairs($array=[]){
  5. $pairs = [];
  6. // counting the positive and negative of each number in the set
  7. foreach($array as $v){
  8. $av = abs($v);
  9. if(!isset($pairs[$av]))
  10. $pairs[$av] = [
  11. 'pos' => 0,
  12. 'neg' => 0
  13. ];
  14.  
  15. ($v > 0) ? $pairs[$av]['pos']++ : $pairs[$av]['neg']++;
  16. }
  17.  
  18. $pair_count = 0;
  19. // getting the number of pairs for each number, based on those counts
  20. foreach($pairs as $pair){
  21. $pair_count += min($pair['pos'],$pair['neg']);
  22. }
  23. return $pair_count;
  24. }
  25. echo pairs($input);
Success #stdin #stdout 0.03s 52480KB
stdin
Standard input is empty
stdout
5