Last active
December 10, 2015 11:58
-
-
Save seralf/4431015 to your computer and use it in GitHub Desktop.
small script to compute happy numbers with scala (useful as a funny benchmark for very big max numbers ;-) NOTE: try to replace numbers.map(x => x * x).sum
with: numbers.par.map(x => x * x).sum
This file contains 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
package happy | |
/** | |
* @author seralf | |
* | |
* small script to compute happy numbers with scala | |
* (useful as a funny benchmark for very big max numbers ;-) | |
* | |
* NOTE: try to replace | |
* numbers.map(x => x * x).sum | |
* with: | |
* numbers.par.map(x => x * x).sum | |
*/ | |
object Happy extends App { | |
def happyNumbers(numbers: List[Int]): List[Int] = | |
for (number <- numbers.filter(n => isHappy(n)).toList) yield number | |
def isHappy(n: Int): Boolean = { | |
def iterate(n: Int, sequence: List[Int]): Boolean = { | |
val next = (x: Int) => { | |
val numbers = for (x <- n.toString.toCharArray().toList) yield x.toString.toInt | |
numbers.map(x => x * x).sum | |
} | |
n match { | |
case 1 => true | |
case x if (sequence.contains(n)) => false | |
case x => iterate(next(x), x :: sequence) | |
} | |
} | |
iterate(n, Nil) | |
} | |
// TEST ------------------------------------------------------- | |
val max = 1111; | |
printf("List of firsts HAPPY numbers until %d:\n%s\n", max, happyNumbers((0 to max).toList)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment