Skip to content

Instantly share code, notes, and snippets.

@LMnet
Last active June 7, 2018 01:40
Show Gist options
  • Save LMnet/7451deea9a36b09b3bb1aa5ffe7d04d5 to your computer and use it in GitHub Desktop.
Save LMnet/7451deea9a36b09b3bb1aa5ffe7d04d5 to your computer and use it in GitHub Desktop.
Находит все перестановки в матрице
object MatrixPermutations {
def main(args: Array[String]): Unit = {
val in = List(
List(1,2),
List(3,4),
List(5,6),
)
def findAllPermutations[T](matrix: List[List[T]]): List[List[T]] = {
matrix match {
case Nil => Nil
case head :: tail =>
findAllPermutations(tail) match {
case Nil =>
head.map { elem =>
elem :: Nil
}
case tailPermutations =>
tailPermutations.flatMap { tailPermutation =>
head.map { elem =>
elem +: tailPermutation
}
}
}
}
}
val res = findAllPermutations(in)
println(res) // List(List(1, 3, 5), List(2, 3, 5), List(1, 4, 5), List(2, 4, 5), List(1, 3, 6), List(2, 3, 6), List(1, 4, 6), List(2, 4, 6))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment