This is the first in a series of code challenges that we will solve using PHP, let's jump straight in.
The Problem
This problem was asked by Google.
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.
- dailycodingproblem.com
Testing
Before starting the challenge I put together a few simple tests. We could use a library such as PHPUnit or PestPHP, but as we are only testing one simple method we will create the test case ourself.
// Test Data
$testData = [
['list' => [10, 15, 3, 7], 'key' => 17, 'expected' => true],
['list' => [2, 4, 6, 8, 10], 'key' => 16, 'expected'=> true],
['list' => [1, 3, 5, 7, 9, 11], 'key' => 24, 'expected' => false],
['list' => [0, 99, 158, 2000], 'key' => 865, 'expected' => false],
['list' => [23, 48, 76, 4, 25, 18, 32, 22, 67, 12], 'key' => 37, 'expected' => true],
['list' => [12], 'key' =>12, 'expected' => false],
['list' => [6,3,8], 'key' => 12, 'expected'=> false],
];
// Test Method
function testMethod(array $testData)
{
foreach($testData as $test) {
if($test['expected'] != checkSum($test['list'], $test['key'])) {
echo "Test " . implode(', ', $test['list']) . ": RESULT: *** FAIL ***".PHP_EOL;
continue;
}
echo "Test " . implode(', ', $test['list']) . ": RESULT: ----PASS----".PHP_EOL;
}
}
My Solution
First we will look at the code and then describe my thinking.
/* The Alogorithm */
function checkSum(array $list, int $k)
{
foreach($list as $key => $value) {
if(in_array($k - $value, $list) && array_search($k-$value, $list) != $key){
return true;
}
}
return false;
}
// Run the tests
testMethod($testData);
The solution I have chosen to take is a simple one.
- We iterate through the given list which gives us the $value variable. We then know that we are looking for the result of $k - $value in our array.
- We check that $value is in the array using the inbuilt in_array() method.
- We then do another check to make sure that we are not using the same value from the array twice using the inbuilt array_search() method.
When we run our script in the console we should get
Test 2, 4, 6, 8, 10: RESULT: ----PASS----
Test 1, 3, 5, 7, 9, 11: RESULT: ----PASS----
Test 0, 99, 158, 2000: RESULT: ----PASS----
Test 23, 48, 76, 4, 25, 18, 32, 22, 67, 12: RESULT: ----PASS----
Test 12: RESULT: ----PASS----
Test 6, 3, 8: RESULT: ----PASS----
Conclusion
There we have it, fairly straight forward using inbuilt array methods. How would you have done it?