Skip to content

Instantly share code, notes, and snippets.

@sonichandni
Last active December 22, 2023 10:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sonichandni/4493e1284ef7bfa274c54b6d95174cae to your computer and use it in GitHub Desktop.
Save sonichandni/4493e1284ef7bfa274c54b6d95174cae to your computer and use it in GitHub Desktop.
get unique pairs which have sum of targeted values
<?php
class UniquePairs {
public function getdata($elements, $target) {
$i = 0;
$response = [];
foreach($elements as $element1) {
$j = 0;
foreach($elements as $element2) {
$result = [];
if($j > $i) {
if(($element1 + $element2) == $target) {
$result[] = $element1;
$result[] = $element2;
}
}
if(!empty($result)) {
$response[] = $result;
}
$j++;
}
$i++;
}
$uniqueArray = [];
foreach ($response as $subArray) {
$reversedSubArray = array_reverse($subArray);
if (!in_array($subArray, $uniqueArray) && !in_array($reversedSubArray, $uniqueArray)) {
$uniqueArray[] = $subArray;
}
}
echo "Total Pairs: ". count($uniqueArray);
echo "<pre>Pairs: <br>";
print_r($uniqueArray); exit();
}
}
$data = new UniquePairs();
$data->getData([1, 2, 5, 46, 1, 6, 9], 47);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment