Last active
October 6, 2022 08:52
-
-
Save ppsdatta/f98f7515859f5b4ef6f704bd243ff0f5 to your computer and use it in GitHub Desktop.
Some scala functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def permutations(nums: Seq[Int]): Seq[Seq[Int]] = { | |
| if (nums.isEmpty) | |
| Array(Seq()) | |
| else { | |
| for ( | |
| n <- nums; | |
| perms <- permutations(nums.filter(_ != n)) | |
| ) yield n +: perms | |
| } | |
| } | |
| permutations(Array(1, 2, 3)) | |
| def combinations(nums: Seq[Int]): Seq[Seq[Int]] = { | |
| if (nums.isEmpty) | |
| Seq(nums) | |
| else if (nums.length == 1) | |
| Seq(nums) | |
| else { | |
| val combs = combinations(nums.tail) | |
| val combs1 = Seq(nums.head) +: combs | |
| val combs2 = combs.map(x => nums.head +: x) | |
| combs1 ++ combs2 | |
| } | |
| } | |
| combinations(Vector(1, 2, 3, 4)) | |
| def nQueens(n: Int): List[List[(Int, Int)]] = { | |
| def isSafe(queen: (Int, Int), queens: List[(Int, Int)]): Boolean = | |
| queens.forall(aQueen => | |
| aQueen._1 != queen._1 && | |
| aQueen._2 != queen._2 && | |
| Math.abs(aQueen._1 - queen._1) != Math.abs(aQueen._2 - queen._2) | |
| ) | |
| def placeQueen(k: Int): List[List[(Int, Int)]] = { | |
| if (k < 0) { | |
| List(List()) | |
| } | |
| else { | |
| for ( | |
| queens <- placeQueen(k - 1); | |
| column <- 0 until n; | |
| queen = (k, column) | |
| if isSafe(queen, queens) | |
| ) yield queen :: queens | |
| } | |
| } | |
| placeQueen(n - 1) | |
| } | |
| val solutions = nQueens(8) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment