I have an algorithm in javascript that works as a “prioritizer”, where I have an array with items to be priorized, and then, a javascript prompt appears for user choose one of the pair of items that appears and then, the algorithm makes the prioritization. It is here: http://jsfiddle.net/alexandre9865/bq3ey1pc/2/
I’m trying to adapt it to kotlin with an user interface, but I have one problem: the function promptInput called inside the second while in insertionSort function.
The function promptInput in javascript is asynchronous, has any approach in kotlin about that?
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.fragment_main, container, false)
pair1 = root!!.findViewById(R.id.pair1) as Button
pair2 = root!!.findViewById(R.id.pair2) as Button
pair1!!.setOnClickListener {
insertionSort(pair1!!.text.toString())
}
pair2!!.setOnClickListener {
insertionSort(pair2!!.text.toString())
}
fun main() {
val arr = arrayOf("homework", "chores", "shopping")
val result = insertionSort("What needs to be done first", arr)
println(result.toList())
}
fun promptInput(comparison: String, str1: String, str2: String): String {
println("$comparison: $str1 or $str2?");// i want to set the buttons pair1 and pair2 with texts of str1 and str2, and when the user click in one of them, the function returns to the while where it was called
return readLine()!!
}
fun insertionSort(comparison: String, arr: Array<String>): Array<String> {
println("arr size: ${arr.size}")
var len = arr.size
var i = -1
var j: Int
var tmp: String
while (len-- != 0) {
tmp = arr[++i];
j = i
while (j-- != 0 && (promptInput(comparison, arr[j], tmp) == arr[j])) {
arr[j + 1] = arr[j];
}
arr[j + 1] = tmp
}
return arr.apply { reverse() }
}