Last active
December 6, 2018 22:20
-
-
Save harrisonmalone/0a1dd42ecd606df4a4589c92c83dabc8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Pick any four digit number and do the following: | |
// Rearrange the string of digits to form the largest and smallest 4-digit numbers possible. | |
// Take these two numbers and subtract the smaller number from the larger. | |
// Suppose we choose the number 8082. | |
// 8820−0288=8532 | |
// 8532−2358=6174 | |
// 7641−1467=6174 | |
// It hits 6174 and then stops. | |
// Count also how many iterations loops are required to get to this point. | |
// Bonus points for recognising what 6174 is. | |
function fourNumSort(num) { | |
const numStrArr = num.toString() | |
const numArr = numStrArr.split("").map(function(element) { | |
return parseInt(element) | |
}) | |
let result | |
let counter = 0 | |
let smallest = numArr.sort().join("") | |
console.log(smallest) | |
let smallestNum = parseInt(smallest) | |
let largest = numArr.sort().reverse().join("") | |
console.log(largest) | |
let largestNum = parseInt(largest) | |
while (result !== 6174) { | |
result = largestNum - smallestNum | |
largestNum = result.toString().split("").sort().reverse().join("") | |
smallestNum = result.toString().split("").sort().join("") | |
counter++ | |
} | |
return counter | |
} | |
console.log(fourNumSort(3087)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment