Reputation: 11
flatMap takes integer input from command line.
A list must be generated with the input number of elements in the list starting from one.
Therefore, when input is 3, List(1,2,3)
must be generated.
Each number in the List generated numberList = List(1,2,3)
must be used to create separate lists with elements equal to the number starting from 1.
Therefore, when input is 3; List(1), List(1, 2), List(1,2,3)
must be created and joined together to give output resultList as List(1, 1, 2, 1, 2, 3)
Upvotes: 0
Views: 2051
Reputation: 51271
A 1-liner (just for fun).
def f(n :Int) = (n to 1 by -1).tails.flatten.toList.reverse
or
def f(n :Int) = List.tabulate(n)(x => 1 to (x+1)).flatten
Upvotes: 2
Reputation: 1940
If I understand correctly for input n=3 you expect the output (1, 1, 2, 1, 2, 3), and for input n=4, you expect the output (1, 1, 2, 1, 2, 3, 1, 2, 3, 4).
If that's the case, it is as simple as
def f(n: Int) = for {
i <- (1 to n)
j <- (1 to i)
} yield j
I tried this on ammonite and get
@ def f(n: Int) = for {
i <- (1 to n)
j <- (1 to i)
} yield j
defined function f
@ f(3)
res2: collection.immutable.IndexedSeq[Int] = Vector(1, 1, 2, 1, 2, 3)
@ f(4)
res3: collection.immutable.IndexedSeq[Int] = Vector(1, 1, 2, 1, 2, 3, 1, 2, 3, 4)
Upvotes: 1
Reputation: 22850
Here is the logic you need, you can adapt it to your precise use case.
Also, you would need to add all the other details like input and output.
def foo(n: Int): List[Int] = {
def listUntil(x: Int): List[Int] =
List.range(start = 1, end = (x + 1))
listUntil(n).flatMap(listUntil)
}
Upvotes: 1