Created
September 29, 2016 10:08
-
-
Save trevorsibanda/117c05977eee489f9647038d3dbeaff6 to your computer and use it in GitHub Desktop.
Lucky numbers
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
//Lucky numbers challenge | |
//http://codegolf.stackexchange.com/questions/94695/unlucky-numbers | |
case class LuckyNumbers(val n: Double, seq: Seq[Double] ) | |
case class Test(val m: Int, val n: Int, val expected: Double) | |
object LuckyNumbers{ | |
def natural_numbers(max: Double) = { | |
def next(n: Double, seq: Seq[Double]): Seq[Double] = if(n >= max) seq ++ Seq(n) else next(n+1, seq ++ Seq(n) ) | |
next(1, Seq()) | |
} | |
//lucky numbers | |
def L(n: Int, seq: Seq[Double]) = { | |
require( n <= 100 , "Constraint: n <= 100") | |
def lucky(_n: Int, _seq: Seq[Double]) = _seq.grouped(_n).toList.map{_.take(_n-1)}.flatten | |
def filter(_n: Int, _seq: Seq[Double]): Seq[Double] ={ | |
if( _n == n ) | |
lucky(_n, _seq) | |
else | |
filter(_n+1, lucky(_n,_seq)) | |
} | |
if(n <= 1) seq else filter(2,seq) | |
} | |
//unlucky numbers | |
def U(n: Int, seq: Seq[Double]): Seq[Double] = { | |
L(n, seq).diff( L(n+1, seq) ) | |
} | |
} | |
object LuckyNumbersChallenge{ | |
def main(args: Array[String]){ | |
val max: Double = 1e3//should support up to 1e6 , using 1e3 to increase speed | |
val nat = LuckyNumbers.natural_numbers(100) | |
Seq( | |
Test(10,1,20), | |
Test(5,2,29) | |
).map{ | |
case Test(m,n,expected) => assert(LuckyNumbers.U(n, nat)(m-1) == expected, Test(m,n,expected)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment