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
|
2 answers
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 "ะะตั."; |
5and-5, that is, those @ Yaroslav, which together give0;) - Deonis