Created
March 7, 2015 22:47
-
-
Save paralax/6aa458b94a124ab3597f to your computer and use it in GitHub Desktop.
addition chain in scala - failing and flailing
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
import scala.annotation.tailrec | |
object AdditionChain { | |
def chain(len:Int, target:Int):List[List[Int]]= { | |
def inner(len:Int, target:Int, sofar:List[Int]):List[Int] = { | |
sofar.length == len match { | |
case true => | |
println(sofar) | |
sofar.head == target match { | |
case true => sofar | |
case false => inner(len, target, List(1)) | |
} | |
case false => sofar. | |
map(x => x + sofar.head). | |
map(x => (x::sofar).sorted.reverse). | |
map(x => inner(len, target, x)). | |
flatten | |
} | |
} | |
inner(len, target, List(1)).grouped(len)toList | |
} | |
def main(args:Array[String]) = { | |
println(chain(args(1).toInt, args(2).toInt)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment