+shiffle
+List.binarySearch
This commit is contained in:
1 parent
0ec0ed96ee
commit
dc837e2095
10 files changed
+110
-9
No files matched your search
@@ -324,10 +324,8 @@ open class Obj {
|
||||
addFn("apply") {
|
||||
val body = args.firstAndOnly()
|
||||
(thisObj as? ObjInstance)?.let {
|
||||
println("apply in ${thisObj is ObjInstance}, ${it.instanceScope}")
|
||||
body.callOn(ApplyScope(this, it.instanceScope))
|
||||
} ?: run {
|
||||
println("apply on non-instance $thisObj")
|
||||
body.callOn(this)
|
||||
}
|
||||
thisObj
|
||||
|
||||
@@ -50,5 +50,26 @@ val ObjArray by lazy {
|
||||
addFn("indices") {
|
||||
ObjRange(0.toObj(), thisObj.invokeInstanceMethod(this, "size"), false)
|
||||
}
|
||||
|
||||
addFn("binarySearch") {
|
||||
val target = args.firstAndOnly()
|
||||
var low = 0
|
||||
var high = thisObj.invokeInstanceMethod(this, "size").toInt() - 1
|
||||
|
||||
while (low <= high) {
|
||||
val mid = (low + high) / 2
|
||||
val midVal = thisObj.getAt(this, ObjInt(mid.toLong()))
|
||||
|
||||
val cmp = midVal.compareTo(this, target)
|
||||
when {
|
||||
cmp == 0 -> return@addFn (mid).toObj()
|
||||
cmp > 0 -> high = mid - 1
|
||||
else -> low = mid + 1
|
||||
}
|
||||
}
|
||||
|
||||
// Элемент не найден, возвращаем -(точка вставки) - 1
|
||||
(-low - 1).toObj()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -141,6 +141,5 @@ val ObjIterable by lazy {
|
||||
list.list.reverse()
|
||||
list
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -269,6 +269,10 @@ class ObjList(val list: MutableList<Obj> = mutableListOf()) : Obj() {
|
||||
thisAs<ObjList>().quicksort { a, b -> comparator.call(this, a, b).toInt() }
|
||||
ObjVoid
|
||||
}
|
||||
addFn("shuffle") {
|
||||
thisAs<ObjList>().list.shuffle()
|
||||
ObjVoid
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -131,6 +131,10 @@ fun Iterable.sortedBy(predicate) {
|
||||
sortedWith { a, b -> predicate(a) <=> predicate(b) }
|
||||
}
|
||||
|
||||
fun Iterable.shuffled() {
|
||||
toList().apply { shuffle() }
|
||||
}
|
||||
|
||||
fun List.toString() {
|
||||
"[" + joinToString(",") + "]"
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user