【问题标题】:All combinations of list elements, while each element keeps position列表元素的所有组合,同时每个元素保持位置
【发布时间】:2018-05-08 20:11:12
【问题描述】:

我是 Scala 的绝对初学者,我想生成列表元素的所有可能组合,但每个元素都保持其在列表中的位置。

例如,如果我有列表 List(1, 1),我想得到这样的东西:

List(1,1)

List(1,*)

List(*,1)

List(*,*)

其中 * 表示不参与当前组合的元素。

提前致谢。

【问题讨论】:

    标签: scala list combinations


    【解决方案1】:

    有定义

    def f(xs: List[Char]): List[List[Char]] = xs match {
      case Nil => List(Nil)
      case h :: t => for (y <- List(h, '*'); ys <- f(t)) yield y :: ys
    }
    

    这里是:

    f("1123".toList) foreach println
    

    给予:

    List(1, 1, 2, 3)
    List(1, 1, 2, *)
    List(1, 1, *, 3)
    List(1, 1, *, *)
    List(1, *, 2, 3)
    List(1, *, 2, *)
    List(1, *, *, 3)
    List(1, *, *, *)
    List(*, 1, 2, 3)
    List(*, 1, 2, *)
    List(*, 1, *, 3)
    List(*, 1, *, *)
    List(*, *, 2, 3)
    List(*, *, 2, *)
    List(*, *, *, 3)
    List(*, *, *, *)
    

    【讨论】:

    • 是的,这正是我想要的!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-22
    • 2010-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-13
    • 1970-01-01
    相关资源
    最近更新 更多