Skip to content

Commit

Permalink
Fix remove bug
Browse files Browse the repository at this point in the history
  • Loading branch information
darshanparajuli committed Jul 13, 2020
1 parent 7b99a36 commit 9ad70be
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 12 deletions.
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
package com.logcat.collections

import kotlin.math.min

class FixedCircularArray<E>(val capacity: Int, initialSize: Int = INITIAL_SIZE) : Iterable<E> {

companion object {
private const val INITIAL_SIZE = 16
}

private var array = arrayOfNulls<Any>(Math.min(capacity, initialSize))
private var head = -1
private var array = arrayOfNulls<Any>(min(capacity, initialSize))
private var head = 0
private var next = 0

init {
resetHead()
if (capacity <= 0) {
throw IllegalStateException("capacity (= $capacity) must be > 0")
}
Expand Down Expand Up @@ -65,16 +68,10 @@ class FixedCircularArray<E>(val capacity: Int, initialSize: Int = INITIAL_SIZE)
}
array[(head + size - 1) % capacity] = null

if (next == 0) {
next = size - 1
} else {
next--
}

next = (head + size - 1) % capacity
if (next == head) {
if (head >= 0) {
head--
}
// empty array, reset
resetHead()
}

return result
Expand Down Expand Up @@ -111,7 +108,7 @@ class FixedCircularArray<E>(val capacity: Int, initialSize: Int = INITIAL_SIZE)
return
}

val newSize = Math.min(array.size * 2, capacity)
val newSize = min(array.size * 2, capacity)
val newArray = arrayOfNulls<Any>(newSize)
System.arraycopy(array, 0, newArray, 0, array.size)
array = newArray
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,29 @@ class FixedCircularArrayTest {
array.add(i)
}

println("================================")
assertEquals(10, array.size)
var index = 0
while (array.isNotEmpty()) {
assertEquals(91 + index++, array.removeAt(0))
}
assertTrue(array.isEmpty())

for (i in 0 until 5) {
array.add(i)
}
assertEquals(5, array.size)

for (i in 0 until 20) {
array.add(i)
}
assertEquals(10, array.size)

index = 0
while (array.isNotEmpty()) {
assertEquals(10 + index++, array.removeAt(0))
}
assertTrue(array.isEmpty())
}

@Test
Expand Down

0 comments on commit 9ad70be

Please sign in to comment.