I found a solution for prioritize an items list accoding by user preference in javascript at link: http://jsfiddle.net/fq3sy/1/
I'm trying to pass it to kotlin , but the list items sometimes are coming with same values for user chooses
My Kotlin code currently:
var arr = arrayOf("finish homework", "finish chores", "go shopping")
insertionSort(arr)
fun promptInput(str1: String, str2: String): String{
println(str1+ " or " + str2 + "?");
return str1
}
fun insertionSort(arr: Array<String>){
println("arr size")
//alert(insertionSort("What needs to be done first", ["finish homework", "finish chores", "go shopping"]));
var len = arr.size
var i = -1
var j: Int? = null
var tmp: String?
while (len!=0) {
tmp = arr[++i];
j = i
while (j!=0 && (promptInput(arr[j], tmp) == arr[j])) {
arr[j + 1] = arr[j];
j--
}
arr[j + 1] = tmp;
len--
}
return arr.reverse();
}
It is printing in kotlin:
I/System.out: arr size
I/System.out: finish homework or finish homework?
I/System.out: finish homework or finish homework?
But it should print:
I/System.out: arr size
I/System.out: finish homework or finish chores?
I/System.out: finish homework or go shopping?
I/System.out: finish chores or go shopping?
with the following order: finish homework,finish chores,go shopping
What I'm doing wrong in this conversion?
Kotlin as of strict type-system would not allow Ints to be 0 or anything as false or true. If you want Boolean, you can use j-- != 0
.
You can do your work as follows:
fun main() {
val arr = arrayOf("finish homework", "finish chores", "go 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?");
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() }
}
With following ouput/input cases:
arr size: 3
What needs to be done first: finish homework or finish chores?
>> finish homework
What needs to be done first: finish homework or go shopping?
>> finish homework
What needs to be done first: finish chores or go shopping?
>> finish chores
[finish homework, finish chores, go shopping]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.