Created
June 20, 2022 14:56
-
-
Save VizGhar/6d7a7fcc16fd095bdc33838233e14e3c to your computer and use it in GitHub Desktop.
N-queens problem solved using TabuSearch Algorithm
This file contains 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
import kotlin.math.pow | |
const val boardSize = 10 | |
fun cost(solution: Array<Int>): Int { | |
var cost = 0 | |
for (i in 0 until boardSize) { | |
for (j in (i + 1) until boardSize) { | |
if (solution[i] == solution[j]) cost++ | |
if (solution[i] == solution[j] + (j - i)) cost++ | |
if (solution[i] == solution[j] - (j - i)) cost++ | |
} | |
} | |
return cost | |
} | |
fun bruteforce() { | |
for (i in 0 until boardSize.toDouble().pow(boardSize).toInt()) { | |
val solution = i.toString(boardSize).padStart(boardSize, '0').map { it.digitToInt() }.toTypedArray() | |
if (cost(solution) == 0) { | |
println("${solution.joinToString("-")}") | |
return | |
} | |
} | |
} | |
fun tabuSearch() { | |
var solution = Array(boardSize) { (0 until boardSize).random() } | |
val tabu = mutableListOf<Array<Int>>() | |
while (cost(solution) != 0) { | |
val neighbors = (0 until boardSize).map { column -> | |
solution.copyOf().apply { this[column] = (this[column] + 1) % boardSize } | |
} | |
solution = neighbors.filter { neighbor -> tabu.none { it.joinToString() == neighbor.joinToString() } }.minByOrNull { cost(it) }!! | |
tabu.add(solution) | |
} | |
println("${solution.joinToString("-")}") | |
} | |
fun main() { | |
val start = System.currentTimeMillis() | |
print("tabu search - ") | |
tabuSearch() | |
println(System.currentTimeMillis() - start) | |
val start2 = System.currentTimeMillis() | |
print("bruteforce - ") | |
bruteforce() | |
println(System.currentTimeMillis() - start2) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment