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.

Leave a Reply