General Coding Assessment Problem - Javascript w/ solution (medium)
Anonymous User
1649

I recently took a general coding assessment for a company and had a question I wasn't able to finish in time. Recalling it from memory, I would love to hear other people's approach and/or get some feedback on what I came up with after-the-fact.

Problem

Write a function that accepts a string of numbers and a positive integer as an argument. The function should reduce the string in the following way:

EXAMPLE:
reduceTheNumber(numberString, k)

Input:
"1111123212", 3

Output:
"132"

Reduce the numbers in the following way:
Step 1
Split the numberString into as many groups of size k as possible, the remaining number(s) should placed in their own grouping.

So for our example, there will be 3 full groupings and 1 leftover grouping.*

"1111123212"  
[111]  [112]  [321]  [2]

Step 2
Sum each grouping

[1+1+1]  [1+1+2]  [3+2+1]  [2]
[3] [4] [6] [2]

Step 3
Repeat Steps 1 and 2, grouping and summing until you are left with only k numbers

[3 ] [4] [6] [2]
[3 4 6] [2]
[3 + 4 + 6] [2]
[13][2]

Step Four
When you are left with only k digits, return the numbers as a string.

[13][2]
=> "132"

Unfortunately, I don't remember all of the constraints, just that k was a positive integer. Apologies if I'm leaving any relevant information out of the description.

My Solution:

function reduceTheNumber(numberString, k){
    const splitNums = numberString.split('')
    let numArray = splitNums.map(num => {return num * 1})


    if (numArray.length <= k){
        return numberString
    }

    let len = numArray.length

    while (len >= k) {
        const sumArray = groupAndSum(numArray, k)
        len = sumArray.length
        numArray = sumArray
    }

    return numArray.join('')
    
//Helper Function     
    function groupAndSum(array, n){
        const groupArray = []
        
        for (let i = 0; i<array.length; i++){
            let grouping = array.slice(i, i+n)
            groupArray.push(grouping)
            i += (n-1)
        }

        const summed = groupArray.map(group => {
            if (group.length > 1){
                return group.reduce((a,b)=> a+b)
            } else {
                return group[0]
            }
        })

        return summed
    }
}

Thanks for taking a look.

Comments (4)