Interview question: XQuery y Z is an array of integers with three different elements. Find all the combinations of x = y + z.

title: XQuery ypenz is three different elements of an array of integers. Find all the combinations of x = y + z and use a better algorithm as much as possible on the basis of realizing the requirements of the topic.

my implementation code:

$arr = [1, 2, 5, 6, 7];
foreach ($arr as $value) {
    foreach ($arr as $val) {
        if ($val == $value) {
            continue;
        }
        $sum = $value + $val;
        if ($sum != $value && $sum != $val && in_array($sum, $arr)) {
            echo "$sum = $value + $val <br>";
        }
    }
}
Is there a better way to implement

?


is optimized a little bit. According to your algorithm, an array of n elements should be looped

.
n * n * in_arrayin_array
var arr = [1, 2, 5, 6, 7];//
var len =arr.length

let result=[]
let count=0

for(let a=0;a<len;aPP){
let max = arr.pop()
let newlen = arr.length
for(let i=0;i<newlen-1;iPP){
   if(arr[i]+arr[i+1]> max){
    break;
  }
  for(let j=i;j<newlen-1;jPP){
    let plus = arr[i]+arr[j+1]
    countPP
    if(plus>max){
      break;
    }
    if(plus==max){
      result.push([max,arr[i],arr[j+1]])
    }
  }
}
}
console.log(result)//
console.log(count)//
As stated in the

reply, I did not consider the case of negative numbers. If you want to consider negative numbers, which maximum number pop will not work, you can only re-maintain a new array to enumerate all values. Modify as follows

var arr = [-8, -1, 1, 2, 5, 6, 7];//
var len =arr.length
var arr1 = [...arr] //
let result=[]
let count=0

for(let a=0;a<len;aPP){
let max = arr1.pop()// 
let newlen = arr.length
for(let i=0;i<newlen-1;iPP){
   if(arr[i]+arr[i+1]> max){
    break;
  }
  for(let j=i;j<newlen-1;jPP){
    let plus = arr[i]+arr[j+1]
    countPP
    if(plus>max){
      break;
    }
    if(plus==max){
      result.push([max,arr[i],arr[j+1]])
    }
  }
}
}
console.log(result)//
console.log(count)//

[[7, 1, 6], [7, 2, 5], [6, -1, 7], [6, 1, 5], [5, -1, 6], [1, -1, 2], [-1, -8, 7]]
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b32ebb-2be44.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b32ebb-2be44.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?