2

I have a list of 3 elements. I want to create range from each of them and iterate through all possible combinations.

What I need to re-write to be able operate with different amount of elements in initial list:

val el = List(5, 4, 7)
(0 to el(0)).map { e0 => 
(0 to el(1)).map { e1 => 
(0 to el(2)).map { e2 => 
doSmth(List(e1,e2,e0))
}}}

It should be simple task. Just curious how to google it...

1
  • I'm not sure what you're asking for makes sense since you'd have to know at compile-time how many arguments doSmth takes, meaning that you'd have to know how low el is at compile-time too. Commented Mar 26, 2015 at 19:32

1 Answer 1

2

You can pretty easily get all combinations using recursion:

def combos(list: List[Int]): List[List[Int]] = list match {
   case hd::tl => combos(tl).flatMap{ combo => (0 to hd).map(_ :: combo) }
   case Nil => List(List())
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.