I'm trying to generate a list in scala according to the formula:
for n > 1 f(n) = 4*n^2 - 6*n + 6 and for n == 1 f(n) = 1
currently I have:
def lGen(end: Int): List[Int] = {
for { n <- List.range(3 , end + 1 , 2) } yields { 4*n*n - 6*n - 6 }
}
For end = 5 this would give the list:
List(24 , 76)
Right now I'm stuck on trying to find a gracefull way to make this function give
List(1 , 24 , 74)
Any suggestions would be greatly appreciated.
-Lee
I'd separate out the "formula" from the list generation:
val f : Int => Int = {
case 1 => 1
case x if x > 1 => 4*x*x - 6*x + 6
}
def lGen(end: Int) = (1 to end by 2 map f).toList
or
def lGen(end: Int) = List.range(1, end + 1, 2) map f
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With