Code Challenge: Day 1

In an attempt to improve my coding and problemsolving abilites, I decided to subscribe to Daily Coding Problem. Every day they send a coding challenge or problem for you to solve, many taken from interview situations.

I will be attempting to tackle these problems in multiple languages; JavaScript,PHP and Python.

Today was my first challenge.

Problem 1

The Problem


This problem was recently 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

This appeared to be a simple problem to start this journey, so confidently I dived in.

Planning

My approach would be the same for all languages, and I imagine this will be the case with the vast majority of the challenges.

  1. Create a function/method that takes 2 parameters; list and k
  2. Take the first number in the list and run through all numbers that follow it to see if there is a combination that equals k
  3. If no solution is found, restart step 2, but from the second number in the list. By only checking the numbers following our start point rather than all the numbers in the list, we only check each possible combination once.
  4. Repeat the above steps until either a solution is found or the list is exhausted.

Tests

I generated some test cases that included the samples given with the problem. These were formatted into an array that contained the list, k, and the expected result as a boolean.

testData = [
  [givenSampleList, givenK, true],
  [[2, 4, 6, 8, 10], 16, true],
  [[1, 3, 5, 7, 9, 11], 24, false],
  [[0, 99, 158, 2000], 865, false],
  [[23, 48, 76, 4, 25, 18, 32, 22, 67, 12], 37, true],
  [[12], 12, false]
]

My Solutions

JavaScript

// Supplied Variables
let givenSampleList = [10, 15, 3, 7]
let givenK = 17

// The Algorithm
function checkSum(list, k) {
  for (let n = 0; n < list.length; n++) {
    for (let v = n + 1; v < list.length; v++) {
      if (list[n] + list[v] == k) {
        return true;
      }
    }
  }
  return false;
}

// Test Data
// Format: array [ list, k, answer]
const testData = [
  [givenSampleList, givenK, true],
  [[2, 4, 6, 8, 10], 16, true],
  [[1, 3, 5, 7, 9, 11], 24, false],
  [[0, 99, 158, 2000], 865, false],
  [[23, 48, 76, 4, 25, 18, 32, 22, 67, 12], 37, true],
  [[12], 12, false]
]

// Test function
function testFunction(array) {
  for (let test = 0; test < array.length; test++) {
    const tests = array[test]
    const testList = tests[0]
    const k = tests[1]
    const answer = tests[2]

    let result = checkSum(testList, k);

    if (result == answer) {
      console.log(`Test ${test+1}: ${testList} with a k of ${k} should return ${answer}, returns ${result}. RESULT: ----PASS----`)
    } else {
      console.log(`Test ${test+1}: ${testList} with a k of ${k} should return ${answer}, returns ${result}. RESULT: *** FAIL ***`)
    }
  }
}

// Run test
testFunction(testData)

PHP

/* Supplied data */
$givenSampleList = [10, 15, 3, 7];
$givenK = 17;

/* The Alogorithm */
function checkSum($list, $k)
{
    for ($n = 0; $n < count($list); $n++) {
        for ($v = $n + 1; $v < count($list); $v++) {
            if ($list[$n] + $list[$v] == $k) {
                return true;
            }
        }
    }
    return false;
}

/*
Test data
Format: array [ list, k, answer]
 */

$testData = [
    [$givenSampleList, $givenK, true],
    [[2, 4, 6, 8, 10], 16, true],
    [[1, 3, 5, 7, 9, 11], 24, false],
    [[0, 99, 158, 2000], 865, false],
    [[23, 48, 76, 4, 25, 18, 32, 22, 67, 12], 37, true],
    [[12], 12, false]
];

/* Test function */
function testFunction($array)
{
    for ($test = 0; $test < count($array); $test++) {
        $tests = $array[$test];
        $testList = $tests[0];
        $k = $tests[1];
        $answer = $tests[2];

        $result = checkSum($testList, $k);

        if ($result == $answer) {
            echo ("Test " . $test . ":  RESULT: ----PASS----<br />");
        } else {
            echo ("Test " . $test . ":  RESULT: *** FAIL ***<br />");
        }
    }
}

/* Run tests */
testFunction($testData);

Python

# Supplied data
givenSampleList = [10, 15, 3, 7]
givenK = 17

# the alogrithm
def checkSum(list, k):
    n = 0
    while n < len(list):
        v = n + 1
        while v < len(list):
            if list[n] + list[v] == k:
                return True
            v += 1
        n += 1
    return False


# Test data
# FOrmat: array [ list, k, answer]
testData = [[givenSampleList, givenK, True], [[2, 4, 6, 8, 10], 16, True],
            [[1, 3, 5, 7, 9, 11], 24, False], [[0, 99, 158, 2000], 865, False],
            [[23, 48, 76, 4, 25, 18, 32, 22, 67, 12], 37, True],
            [[12], 12, False]]


# Test function
def testFunction(array):
    test = 0
    while test < len(array):
        tests = array[test]
        testList = tests[0]
        k = tests[1]
        answer = tests[2]

        result = checkSum(testList, k)

        if result == answer:
            print("Test " + str(test) + ": " + str(testList) +
                  " with a k of " + str(k) + " should return " + str(answer) +
                  ", returns " + str(result) + ". RESULT: ----PASS----")
        else:
            print("Test " + str(test) + ": " + str(testList) +
                  " with a k of " + str(k) + " should return " + str(answer) +
                  ", returns " + str(result) + ". RESULT: *** FAIL ***`")

        test += 1


# Run tests
testFunction(testData)

Conclusions

The code varies little except for syntax between the languages in my solution to this problem. I found this problem fairly straightforward and the only issues I ran into were due to my mixing of languages.

If this is something you would be interested in trying, visit Daily Coding Problem and sign up.

Leave a Reply