Created
September 20, 2014 01:41
-
-
Save v2keener/0450bcfe7e5a72df8c1c to your computer and use it in GitHub Desktop.
SumDigits, only more meta.
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
| object SumDigits { | |
| def maxInt = 2147483647 | |
| def printResult(arg: Int){ | |
| printResult(arg, sumDigits(arg)); | |
| } | |
| def printResult(arg: Int, result: Int){ | |
| printf("Sum of %d is %d\n", arg, result); | |
| } | |
| def main(args: Array[String]) { | |
| println("heelo [sic] world"); | |
| printResult(maxInt); //46 (Int [31 bit + 1 bit for sign] max value) | |
| printSumDigitsGivenInitialAsMaxSum(323523) | |
| // printSumDigitsGivenInitialAsMaxSum(99999999); | |
| } | |
| def sumDigits(arg: Int): Int = { | |
| def absArg = scala.math.abs(arg); //As a precondition, I *could* say I only accept natural numbers. I could. | |
| var power: Long = 1; // All Int values accepted, power must go to 100000000000 (exceeds max Int value) | |
| var sizeArg = absArg % power; // 0 | |
| // Accumulate our modulus operand [power] by measuring the results of increasing modulo ops | |
| while (sizeArg != absArg) { | |
| power = power * 10; | |
| sizeArg = absArg % power; | |
| } | |
| var digitSum: Int = 0; | |
| var argVar: Int = absArg; | |
| // Accumulate sum of digits | |
| while (power > 1) { | |
| // Get single-digit value from integer at [tens] place | |
| var digit = ((argVar - (argVar % power)) / power).toInt; | |
| digitSum = digitSum + digit; | |
| // Remove digit we just added to digitSum | |
| argVar = (argVar % power).toInt; | |
| // Go to next lower power of 10s | |
| power = power / 10; | |
| } | |
| // Add the last digit | |
| digitSum = digitSum + (arg % 10); | |
| return digitSum; | |
| } : Int | |
| // Note that for large numbers, this goes Big-O(x*x) (or something like that) | |
| def printSumDigitsGivenInitialAsMaxSum(arg: Int){ | |
| def max = sumDigits(arg) | |
| printResult(arg, max); | |
| var foundValues = Seq[Int](); | |
| var current = max - 1; | |
| for(i <- (1 until arg).reverse){ | |
| def result = sumDigits(i); | |
| while(foundValues.contains(current)){ | |
| current = current - 1; | |
| } | |
| if(result <= current && foundValues.contains(result) == false){ | |
| printResult(i, result); | |
| foundValues = foundValues.+:(result); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment