Check whether there is at least one pair of opposite numbers in a one-dimensional numeric array. help me please

Closed due to the fact that off-topic participants Sergey Gornostaev , 0xdb , Vadizar , slippyk , Anton Shchyrov 20 Apr '18 at 8:21 .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • " Learning tasks are allowed as questions only on the condition that you tried to solve them yourself before asking a question . Please edit the question and indicate what caused you difficulties in solving the problem. For example, give the code you wrote, trying to solve the problem "- Sergey Gornostaev, 0xdb, Vadizar, slippyk, Anton Shchyrov
If the question can be reformulated according to the rules set out in the certificate , edit it .

  • one
    What have you tried? - Slavik
  • one
    And what is the "opposite numbers"? - MBo
  • @MBo, numbers that differ in characters. Eg, 5 and -5 , that is, those @ Yaroslav, which together give 0 ;) - Deonis
  • I can not understand what the search algorithm should be for this ( - Yaroslav
  • @ Yaroslav, I already gave a hint with the comment above. Although you can wait and someone will definitely do this simple operation for you. - Deonis

2 answers 2

You can use the bitwise ~ (NOT) operator along with the in_array () search and array_filter () filtering functions:

 $numbers = [1, 2, 3, 4, 5, 6, -7, 8, 9, -9]; $arr = array_filter($numbers, function($int)use($numbers){ return in_array(~--$int, $numbers); }); var_dump($arr); 

As a result, a pair of numbers 9 and -9 will be obtained (for the remaining pairs there is none)

  • buggy on [PHP_INT_MIN, PHP_INT_MAX] - rjhdby
  • @rjhdby what would you advise? - Edward
  • You can add a PHP_INT_MIN check with false returned. But I would just make a nested loop for(i=0;i<length-1;i++){for(j=i+1;j<length;j++){if($a+$b===0){ - rjhdby

Ok i'll do it for you

 $arr = [2, 4, 5, -3, -4]; foreach ($arr as $item) { if ($item && in_array(0 - $item, $arr) { die("ะ•ัั‚ัŒ!"); } } echo "ะะตั‚.";