<?php

function findPairs($nums, $sum)
{
    $pairs = "";
    for ($i = 0; $i <= count($nums); $i++) {
        for ($j = $i + 1; $j < count($nums); $j++) {
            if ($nums[$i] + $nums[$j] == (int) $sum) {
                $pairs .= $nums[$i] . "," . $nums[$j] . ";";
            }
        }
    }
    return $pairs;
}
$fh = fopen($argv[1], "r");
while (!feof($fh)) {
    $pairs = "";
    $test = trim(fgets($fh));
    if ($test != "") {
        $args = explode(";", $test);
        $nums = explode(",", $args[0]);
        $pairs = findPairs($nums, $args[1]);
        if ($pairs != "") {
            echo substr($pairs, 0, strlen($pairs) - 1) . "\n";
        } else {
            echo "NULL\n";
        }
    }
}
fclose($fh);
Example #2
0
function findPreviouslyUsedInteger($array1, $i2)
{
    foreach ($array1 as $pair) {
        if ($pair[0] == $i2) {
            return true;
        }
    }
    return false;
}
function findPairs($x)
{
    $array1 = array();
    for ($i = -50; $i <= 50; $i++) {
        for ($i2 = -50; $i2 <= 50; $i2++) {
            if ($i + $i2 == $x && $i2 != $i && !findPreviouslyUsedInteger($array1, $i2)) {
                $array2 = array($i, $i2);
                array_push($array1, $array2);
            }
        }
    }
    return $array1;
}
foreach (findPairs(99) as $pair) {
    echo '(' . implode(',', $pair) . ')' . '<br>';
}
/*
This could be faster if iterations were reduced by 
removing previously used intergers from the list of candidates. 
The pairs are not evenly distributed, so eleminating some candidates based on this is also a possibility.
I understand that this can also be solved using Big-O
*/