Code Challenge: Day 2

Another day brings another challenge from Daily Coding Problem, so let’s see what we have facing us today. As per last time, I will attempt to solve the problem in three languages; JavaScript, PHP, and Python.

Problem 2

The Problem


Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].

Daily Coding Problem

My Approach

The way I am going to tackle this is:

  1. Create a method/function that takes one argument ,array
  2. Create a new empty result array within the method/function to store the result
  3. Iterate through the array, calulating the product of all values exluding the current index, store the product in the result array with the same index
  4. Once all indexes have been processed, return the result array

Sounds simple, right? Let’s jump in.

My Solution

JAVASCRIPT

// Supplied test cases
// Format: array[test array, expected result]
const tests = [
  [[1, 2, 3, 4, 5],[120, 60, 40, 30, 24]],
  [[3, 2, 1], [2, 3, 6]]
]

// The Algorithm
function product(array){
  let result = [] // To be filled and then returned
  for (let i = 0 ; i < array.length ; i++) { // iterate through array
    let product = 1 // Running product total to be added to the result array
    for (let j = 0; j < array.length; j++) {
      if ( j != i) { // calculate product for all values exluding current index
        product *= array[j]
      }      
    }
    result[i] = product
  }

  return result
}

// Test algorithm
function test(array) {
  array.forEach(e => {
    let testReturn = product(e[0]) // Run function on test array
    let result = true //default value, will change if test fails
    //Iterate through both testReturn and the expected result to compare
    for (i=0; i<array.length; i++) { 
      if ( testReturn[i] != e[1][i]) {
        result = false // If any value doesn't match change result to false
      }
    }
    //print test results
    if(result){
      console.log(`Test passed!, expected ${e[1]}, recieved ${testReturn}`)
    } else {
      console.log(`Test FAILED!, expected ${e[1]}, recieved ${testReturn}`)
    }
  });
}


//Call tests
test(tests)

PHP

// Supplied test cases
// Format: array[test array, expected result]
$tests = [
  [[1, 2, 3, 4, 5],[120, 60, 40, 30, 24]],
  [[3, 2, 1], [2, 3, 6]]
];

// The Algorithm
function product($array){
  $result = []; // To be filled and then returned
  for ($i = 0 ; $i < count($array); $i++) { // iterate through array
    $product = 1; // Running product total to be added to the result array
    for ($j = 0; $j < count($array); $j++) {
      if ( $j != $i) { // calculate product for all values exluding current index
        $product = $product * $array[$j];
      }      
    }
    $result[$i] = $product;
  }

  return $result;
}

// Test algorithm
function test($array) {
  foreach ($array as $e) {
    $testReturn = product($e[0]);
     // Run function on test array
    $result = true; //default value, will change if test fails
    //Iterate through both testReturn and the expected result to compare
    for ($i=0; $i<count($array); $i++) { 
      if ( $testReturn[$i] != $e[1][$i]) {
        $result = false; // If any value doesn't match change result to false
      }
    }

    print_r($testReturn);
    echo '<br />';
    print_r($e[1]);
    //print test results
    if($result){
      echo "Test passed!";
    } else {
      echo "Test FAILED!";
    }
  };
}


//Call tests
test($tests);

Python

# Supplied test cases
# Format: array[test array, expected result]
print("working")
tests = [[[1, 2, 3, 4, 5], [120, 60, 40, 30, 24]], [[3, 2, 1], [2, 3, 6]]]


# The Algorithm
def product(array):
    result = []  # To be filled and then returned
    i = 0
    while i < len(array):
        product = 1
        j = 0
        while j < len(array):
            if j != i:
                product *= array[j]
            j += 1
        result.append(product)
        i += 1
    return result


# Test algorithm
def test(array):
    for e in array:
        testReturn = product(e[0])  # Run function on test array
        result = True  # Default value

        # iterate through test and expected results and compare
        i = 0
        while i < len(array):
            if testReturn[i] != e[1][i]:
                result = False
            i += 1

        # print test results
        if result is True:
            print("Test passed!")
        else:
            print("Test FAILED!")


# Call tests
test(tests)

Conclusions

This problem and solution don’t really differ too much from the last challenge, and to be honest i found the test script harder to get working properly than the alogrithm itself, I was passing the wrong array to the test function and it took an embarassing amount of time to identify.

If you would like to give these challenges and ones like it a try, I suggest heading to Daily Coding Problem and sign up.

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.