scala查找列表列表的所有组合
如何用列表替换项目并展平结果 例如: 将3替换为列表(a,b) 输入:scala查找列表列表的所有组合,scala,Scala,如何用列表替换项目并展平结果 例如: 将3替换为列表(a,b) 输入:列表(1,2,3,4) 输出: List(List(1, 2, a, 4) List(1, 2, b, 4)) List(List(1, 2, a, 4, a) List(1, 2, a, 4, b) List(1, 2, b, 4, a) List(1, 2, b, 4, b)) 输入:列表(1,2,3,4,3) 输出: List(List(1, 2, a, 4) List(1,
列表(1,2,3,4)
输出:
List(List(1, 2, a, 4)
List(1, 2, b, 4))
List(List(1, 2, a, 4, a)
List(1, 2, a, 4, b)
List(1, 2, b, 4, a)
List(1, 2, b, 4, b))
输入:列表(1,2,3,4,3)
输出:
List(List(1, 2, a, 4)
List(1, 2, b, 4))
List(List(1, 2, a, 4, a)
List(1, 2, a, 4, b)
List(1, 2, b, 4, a)
List(1, 2, b, 4, b))
这是:
def replacePermutations[A](l: Seq[A], replace: A, by: Seq[A]) = {
val byPermutationsWithRepetitions =
(by map (e => by.indices map (_ => e))) ++ by.permutations
byPermutationsWithRepetitions map { by =>
val i = Iterator.from(0)
l map { e =>
if (e == replace) by(i.next() % by.size)
else e
}
}
}
干杯到目前为止你都试了些什么?我们能帮你解决什么问题吗?顺便说一句,在你的例子中,结果不是平坦的,而在你的问题中,你是说你希望它平坦。用列表(a,b)替换3将导致列表(1,2,(a,b),4),而平坦将导致列表(1,2,a,b,4)。你写的东西完全不同。