'Writing Quickperm algorithm in Kotlin and having problem adding elements to a set
I am new to Kotlin and tried to write the Quickperm algorithm in Kotlin as a practice. My codes basically work when I use print to check the values. But when I created a set result to add all the permutations, the set remains unchanged. I then created an array check and added that to the set and that worked. So I am rather perturbed as to why this doesn't work down the line after I swapped the elements. Another issue I face is I have no idea how to pass the set to my main function. What I really want is to return result at the end of the permute function. What type is it? Thanks for any help on this.
fun permute(arr: Array<Char>): Array<Char>{
var n = arr.size
var indices = IntArray(n+1){ i -> i}
var elements = arr
var result = mutableSetOf(elements)
//val check = arrayOf('d','e','f')
//result.add(check)
var i = 1
var j:Int
while (i<n){
indices[i] = indices[i] - 1
if (i%2!=0){
j = indices[i]
} else {
j = 0
}
elements[i] = elements[j].also { elements[j] = elements[i]}
result.add(elements)
i = 1
while (indices[i]==0){
indices[i] = i
i+=1
}
}
for (e in result){
printArray(e)
}
return elements
}
fun printArray(array: Array<Char>) {
array.forEach { print("$it ")}
println()
}
fun main() {
var A = arrayOf('a','b','c')
printArray(permute(A))
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
