Skip to content

Instantly share code, notes, and snippets.

@silalahi
Created July 25, 2018 10:51
Show Gist options
  • Save silalahi/8ebf91a45dbff510e05042edfae37d4e to your computer and use it in GitHub Desktop.
Save silalahi/8ebf91a45dbff510e05042edfae37d4e to your computer and use it in GitHub Desktop.
<?php
/**
* Daily Coding Problem:
*
* Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
* For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
*/
function possible($numbers = [], $k) {
// We don't have enough numbers to add (the minimum numbers are 2).
if(count($numbers) < 2) {
return false;
}
// We are going to sum the first number (first index) with the other numbers (second index to end) one by one.
// If the sum of these two numbers is equal to $k, then return true and stop the loop immediatelly.
for($i = 1; $i < count($numbers); $i++) {
if($numbers[0] + $numbers[$i] == $k) {
return true;
}
}
// At this point, the sum of first number (first index) with others numbers does not meet $k.
// We are going to remove the first number (first index) then start again to match second number (second index) with others index,
// until we got the $k or until the $numbers is not enough to sum.
return possible(array_slice($numbers, 1), $k);
}
$numbers = [15, 3, 7, 10];
$k = 17;
echo possible($numbers, $k) ? 'Yes!' . PHP_EOL : 'Nope...' . PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment