Listing combinations WITH repetitions in Scala

后端 未结 7 830
盖世英雄少女心
盖世英雄少女心 2021-01-12 01:18

Trying to learn a bit of Scala and ran into this problem. I found a solution for all combinations without repetions here and I somewhat understand the idea behind i

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-12 01:23

    Meanwhile, combinations have become integral part of the scala collections:

    scala> val li = List (1, 1, 0, 0) 
    li: List[Int] = List(1, 1, 0, 0)
    
    scala> li.combinations (2) .toList
    res210: List[List[Int]] = List(List(1, 1), List(1, 0), List(0, 0))
    

    As we see, it doesn't allow repetition, but to allow them is simple with combinations though: Enumerate every element of your collection (0 to li.size-1) and map to element in the list:

    scala> (0 to li.length-1).combinations (2).toList .map (v=>(li(v(0)), li(v(1))))
    res214: List[(Int, Int)] = List((1,1), (1,0), (1,0), (1,0), (1,0), (0,0))
    

提交回复
热议问题