## Code Challenge: Day 3

It’s that time again where i try and solve a problem posed by Daily Coding Problem. This problem has been identified as hard, so lets see what I can do.

## The Problem

This problem was asked by Stripe.
Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
For example, the input `[3, 4, -1, 1]` should give `2`. The input `[1, 2, 0]` should give `3`.
You can modify the input array in-place.

Daily Coding Problem

## Our Approach

My solution to this is going to go through a few stages, lets list these out.

1. We will create a function/method that takes in a single argument and returns an integer, I’ll call this `lowestInt`. I thought about that name for a while…
2. The desired return value is going to be a positive integer, so we will remove the values that are less or equal than 0, and sort the remaining values in ascending order.
3. Starting with the value 1, we will iterate through the array/list until we find a missing value, and return that value.

We will just be tackling this challenge in javaScript, but will explain the steps we are taking in a bit more depth than previous challenges

## The Solution

#### Step 1

Our first step was a nice easy one to get us started, create the function. We will also assign the given test cases to variables for testing later.

```// Supplied test arrays
const testCases = [
[[3, 4, -1, 1],2],
[[1, 2, 0],3]
]

//The alogrithm
function lowestInt(array) {
}
```

#### step 2

Next we will remove the negative and zero integers from the list. We are using the filter() function to remove the values that are less than 1.

```// The alogrithm
function lowestInt(array) {
let positives = array.filter(int => int>0);
}
```

Our next task, according to our plan is to sort the array into ascending order.

```// The alogrithm
function lowestInt(array) {
let positives = array.filter(int => int>0);
let sorted = positives.sort()
}
```

Nothing too complicated so far.

#### Step 3

The next step is to iterate through the sorted array until there is a missing integer. We will do this with an `if statement` within a `for loop.`

```// The alogrithm
function lowestInt(array) {
let positives = array.filter(int => int>0);
let sorted = positives.sort()

for (let i =0;i<=sorted.length; i++ ) {
if(sorted[i] != i+1){
return i+1
}
}
}
```

And that should be that. I have written a quick test function so that we can load a list of tests and expected answers.

```// Test function
function runTest(array) {
if(lowestInt(array) == array){
return `expected \${array}, received \${lowestInt(array)}: Test Passed`
} else {
return `expected \${array}, received \${lowestInt(array)}: Test Failed`
}
}

// Run tests
for (let test = 0; test < testCases.length; test++) {
console.log(`Test \${test}: \${runTest(testCases[test])}`)
}
```

Just to be sure, let’s add some other tests into the `testCases `array.

```// Supplied test arrays
const testCases = [
[[3, 4, -1, 1],2],
[[1, 2, 0],3],
[[3,-88,100,2,6],1],
[,2],
[[],1]
]

// Logged:
Test 0: expected 2, received 2: Test Passed
Test 1: expected 3, received 3: Test Passed
Test 2: expected 1, received 1: Test Passed
Test 3: expected 2, received 2: Test Passed
Test 4: expected 1, received 1: Test Passed
```

And on that note we are done, I am sure there are more elegant solutions but this seems to work.

Complete code below:

```// Supplied test arrays
const testCases = [
[[3, 4, -1, 1],2],
[[1, 2, 0],3],
[[3,-88,100,2,6],1],
[,2],
[[],1]
]

//The alogrithm
function lowestInt(array) {
let positives = array.filter(int => int>0);
let sorted = positives.sort()

for (let i =0;i<=sorted.length; i++ ) {
if(sorted[i] != i+1){
return i+1
}
}
}

// Test function
function runTest(array) {
if(lowestInt(array) == array){
return `expected \${array}, received \${lowestInt(array)}: Test Passed`
} else {
return `expected \${array}, received \${lowestInt(array)}: Test Failed`
}
}

// Run tests
for (let test = 0; test < testCases.length; test++) {
console.log(`Test \${test}: \${runTest(testCases[test])}`)
}
```

## Conclusion

This algorithm could probably be refactored with some form of function chaining, but other than that I am happy with the efficiency of our solution.

For tomorrows challenge we use either PHP or Python

## 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) // 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[i]) {
result = false // If any value doesn't match change result to false
}
}
//print test results
if(result){
console.log(`Test passed!, expected \${e}, recieved \${testReturn}`)
} else {
console.log(`Test FAILED!, expected \${e}, 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);
// 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[\$i]) {
\$result = false; // If any value doesn't match change result to false
}
}

print_r(\$testReturn);
echo '<br />';
print_r(\$e);
//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)  # 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[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

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, 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, false]
]

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

let result = checkSum(testList, k);

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, false]
];

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

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

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, False]]

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

result = checkSum(testList, k)

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.