nQueensRandomized.kt
demonstrated in class uses backtracking for the n-queen puzzle in this way. It takes the basic algorithm for generating the permutations on \(\{0,1,\ldots, n-1\}\) and modifies it so that any branch of the permutation generation algorithm that will generate a mutually-attacking queen pair is abandoned.Here is an algorithm to generate all the permutations on the set \(\{ 0, 1, \dots, n-1 \}\).
fun main(args: Array<String>) {
val n = args[0].toInt()
val a = IntArray(n) { it }
fun swap(i: Int, k: Int) {
val temp = a[i]
a[i] = a[k]
a[k] = temp
}
fun perm(k: Int) {
if (k == n) println(a.joinToString(separator=" "))
else for (i in k until n) {
swap(i, k)
perm(k+1)
swap(i, k)
}
}
perm(0)
}
Note that order of symbols does not matter in the above listing: \(ab\) or \(ba\) means the same subset.
Here is an algorithm to generate all the \(k\)-combinations of the set \(\{ 0, 1, \dots, n-1 \}\).
fun main(args: Array<String>) {
val n = args[0].toInt()
val k = args[1].toInt()
val b = BooleanArray(n)
fun comb(start: Int, i: Int) {
if (i == k+1) {
for (j in b.indices)
if (b[j]) print(" $j")
println()
} else for (j in start until (n-k+i)) {
b[j] = true
comb(j+1, i+1)
b[j] = false
}
}
comb(0, 1)
}
where order does not matter in the above listing.
Here is an algorithm to generate all the subsets of the set \(\{ 0, 1, \dots, n-1 \}\).
fun main(args: Array<String>) {
val n = args[0].toInt()
val b = BooleanArray(n)
fun subsets(i: Int) {
if (i == n) {
for (j in b.indices)
if (b[j]) print(" $j")
println()
} else {
b[i] = false
subsets(i+1)
b[i] = true
subsets(i+1)
}
}
subsets(0)
}