I am working on solving this algorithmic challenge on CoderByte and need some help with the next steps…the question and my code is below:
Using the JavaScript language, have the function KaprekarsConstant( num ) take the num parameter being passed which will be a 4-digit number with at least two distinct digits. Your program should perform the following routine on the number: Arrange the digits in descending order and in ascending order (adding zeroes to fit it to a 4-digit number), and subtract the smaller number from the bigger number. Then repeat the previous step. Performing this routine will always cause you to reach a fixed number: 6174. Then performing the routine on 6174 will always give you 6174 (7641 - 1467 = 6174). Your program should return the number of times this routine must be performed until 6174 is reached. For example: if num is 3524 your program should return 3 because of the following steps: (1) 5432 - 2345 = 3087, (2) 8730 - 0378 = 8352, (3) 8532 - 2358 = 6174.
function KaprekarsConstant(num) {
function newNum(num){
num = num.toString()
num = num.split('')
if (num.length < 4){
num.push('0')
}
let numAsc = Number(num.sort().join(''))
let numDsc = Number(num.sort().reverse().join(''))
num = numDsc - numAsc
return num
}
}
As you can see from my code above, I have defined the function newNum(num) which will execute the first part of the challenge of taking in the ‘num’ argument and subtracting the larger number from the smaller after sorting it in ascending and descending order. The part I am stuck on is figuring out how to execute the function while incrementing a counter until the newNum(num) === 6174, and then returning the counter value. I am thinking I would need to use a While-loop but not sure how to increment the counter every time the newNum(num) function executes and doesn’t equal 6174. All I could think of was some psuedo-code :
let counter = 0
while(num < 6174){
num = newNum(num)
counter++}
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/debugging/use-the-javascript-console-to-check-the-value-of-a-variable
