I have solved an algorithm but I’m looking for tips on how I might shorten the code up.
Here is the challenge(https://codefights.com/arcade/intro/level-5/ZMR5n7vJbexnLrgaM)
The basic problem is separate a given integer into its respective digits, add those digits together and subtract that sum from the initial integer.
Collect those sums into an array and determine the most frequent number within that array. (If several frequent numerals, then choose highest integer.)
Return that most frequent number.
Below is my code. If you can give me some tips on how it can be shrunk, then I would really appreciate it!
function mostFrequentDigitSum(n: number): number {
//create while loop that runs into initial integer is 0
while(n > 0){
//use container INT to hold integer in string form to split numeral of two digits
let int = n.toString().split('');
//break up double digit number into two variables
let digitOne = parseInt(int[0]);
let digitTwo = parseInt(int[1]);
//create container ONE for numbers generated with cycle of subtraction from initial integer
let arrOne: number[] = [];
//create container TWO for initial integers generated with each cycle of the loop
let arrTwo: number[] = [];
//create container NUM for addition of individual digits in double digit numbers
let num;
//if statement for double digits to add respective digits together&&push to ONE container
if(int.length>1){
num = digitOne+digitTwo
arrOne.push(num)
//when only single digit return
} else {
return digitOne
}
//create container RESULT for subtracting sum within NUM from initial integer N
let result = n - num;
//create container TWO for new digits at completion of loop cycle
arrTwo.push(result)
//change value of N to RESULT and begin new cycle
n = result;
}
}
console.log(mostFrequentDigitSum(88)); 9
console.log(mostFrequentDigitSum(8)); 8