Sum Of All Fears

I'm A. Jackson Hol|

Background

The Sum of all fears coding challenge is intended to assess a candidate’s ability to work with Arrays. This challenge or a slight variation has been used by technology companies such as Amazon and Google and was also featured as a Daily Coding Problem in dev.to.

Description

Given a list of numbers and a number K, return whether any two numbers from the list add up to K.

Example: given [10, 15, 3, 7] and K of 17, return true since 10 + 7 is 17.

The basic challenge is to write a program that uses a hard-coded array of [10, 15, 3, 7] and allows the user to enter a value for K before running the algorithm and returning true or false.

Solve

Note: Each button press will run code for each click, for each click a randomly generated array of numbers will run. Default result will be false until a solution is found.

Enter your Number:


Results:


Code

The following is my JavaScript code used for this exercise. Read over if your interested.


// Event listener to call for my formula
document.getElementById("btnSubmit").addEventListener("click", superScary);

function superScary() {
    // Step 1: Get user Input

    let k = Number(document.getElementById("userInput").value);
    // Get the user Input
    let searchLen = Math.floor(Math.random() * (20 - 5 + 1)) + 5;
    // Gathering Numbers to search thru (Min of 5 elements with max of 20). Determines ele. to put thru array
    let arr = [];
    // Array creation to search thru with loop

    //Result Variables
    let result = false;
    // default of false to fall back on if no numbers match up
    let resultText = "";
    let randoResults = "[";

    //Step 2: Generating random array 
    // i stars at 0; I < var searchLen; i + 1
    // returns a random integer from 0 to 100 
    for (let i = 0; i < searchLen; i++) {                        
        arr.push(Math.floor(Math.random() * 101))               
    }
    // Step 3: Check if 2 nums add up
    // Outer loop - checks first element
    // inner loop - checks every other element against 1st
    // true if numbers match up
    for (let i = 0; i < arr.length - 1; i++) {                  
        for (let j = i + 1; j < arr.length - 1; j++) {                 
            if (arr[i] + arr[j] == k) {
                result = true                                  
                resultText += arr[i] + " + " + arr[j] + "<br>";
            }
        }
        if (arr.length - 2 != i) {
            randoResults += arr[i] + ",";
        } else {
            randoResults += arr[i];
        }
    }
    randoResults += "]";
    //Step 4: Result Output
    document.getElementById("result").innerHTML = "<br>" + result + "<br>" + resultText + "<br>" + randoResults;
};

Technologies

Technologies Used: HTML, CSS, JavaScript, jQuery and Bootstrap. Made in VS Studio 2019 with code on GitHub.