2

I want to create a function in Scala that given a List[Int] returns a List[List[Int]]. For example getCombs(List(1,2)) should returns List(List(1), List(2), List(1,2)).

I'm studying functional programming so I would like to accomplish my task using that paradigm.

I've created the following function and it works, but I think that there exist a better way to do the job in a functional programming style.

def getCombs(coins: List[Int]): List[List[Int]] = {

  var l = List(coins)
  var i = 0
  for (i <- 1 to coins.length - 1) {
    var it = coins.combinations(i)
    while (it.hasNext) {
      val el = it.next
      val newL = el :: l
      l = newL

    }

  }
  return l
}

2 Answers 2

2

I first create a range of all the lengths of combinations that I want to make, then I use flatMap to create all the combinations and make a list out of them:

def allCombinations(list: List[Int]): List[List[Int]] = {
    (1 to list.length).flatMap(list.combinations(_)).toList
}
Sign up to request clarification or add additional context in comments.

Comments

1
(1 to coins.length).flatMap { 
  coins.combinations(_)  
}.toList

3 Comments

This returns a List[Iterator[List[Int]]].
I changed the map to a flatMap...seems better to correct the code than give @Dima 's answer a down vote. :-)
Thanks, @KeithPinson. Some people just have to be like that ... :)

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.