Last active
December 22, 2023 10:53
-
-
Save sonichandni/4493e1284ef7bfa274c54b6d95174cae to your computer and use it in GitHub Desktop.
get unique pairs which have sum of targeted values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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