Skip to content

Commit

Permalink
Added test for MutableList.sortedAdd
Browse files Browse the repository at this point in the history
  • Loading branch information
AntonioNoack committed Sep 18, 2024
1 parent cb19124 commit 3b572e0
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/me/anno/utils/structures/lists/Lists.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package me.anno.utils.structures.lists

import me.anno.utils.callbacks.VtoD
import me.anno.utils.search.BinarySearch
import me.anno.utils.structures.Collections.filterIsInstance2
import me.anno.utils.structures.heap.Heap
import kotlin.math.max
Expand Down Expand Up @@ -568,7 +569,7 @@ object Lists {

@JvmStatic
fun <V> MutableList<V>.sortedAdd(instance: V, comparator: Comparator<V>, insertIfEquals: Boolean) {
var index = binarySearch(instance, comparator)
var index = BinarySearch.binarySearch(size) { comparator.compare(get(it), instance) }
if (index < 0) index = -1 - index
else if (!insertIfEquals && this[index] == instance) return
add(index, instance)
Expand Down
29 changes: 29 additions & 0 deletions test/src/me/anno/tests/structures/SortedAddTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package me.anno.tests.structures

import me.anno.utils.assertions.assertEquals
import me.anno.utils.structures.lists.Lists.sortedAdd
import org.junit.jupiter.api.Test

class SortedAddTest {

@Test
fun testSortedAdd() {
val numbers = listOf(0, 17, 4, 2, 5, 7, 1)
val mutable = ArrayList<Int>()
// insert unique numbers
for (i in numbers.indices) {
mutable.sortedAdd(numbers[i], false)
assertEquals(numbers.subList(0, i + 1).sorted(), mutable)
}
// try to add duplicates
for (i in numbers.indices) {
mutable.sortedAdd(numbers[i], false)
assertEquals(numbers.sorted(), mutable)
}
// add duplicates successfully
for (i in numbers.indices) {
mutable.sortedAdd(numbers[i], true)
assertEquals((numbers.subList(0, i + 1) + numbers).sorted(), mutable)
}
}
}

0 comments on commit 3b572e0

Please sign in to comment.