-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathDynamicArraySimplified.kt
More file actions
38 lines (33 loc) · 1.22 KB
/
DynamicArraySimplified.kt
File metadata and controls
38 lines (33 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package day4
import kotlinx.atomicfu.*
// This implementation never stores `null` values.
class DynamicArraySimplified<E : Any>(
private val capacity: Int
) {
private val array = atomicArrayOfNulls<Any?>(capacity)
private val size = atomic(0) // never decreases
fun addLast(element: E): Boolean {
val curSize = size.value
if (curSize == capacity) return false
// TODO: you need to install the element and
// TODO: increment the size atomically.
// TODO: You are NOT allowed to use CAS2,
// TODO: there is a more efficient and smarter solution!
array[curSize].value = element
size.value = size.value + 1
return true
}
fun set(index: Int, element: E) {
val curSize = size.value
require(index < curSize) { "index must be lower than the array size" }
// As the size never decreases, this update is safe.
array[index].value = element
}
@Suppress("UNCHECKED_CAST")
fun get(index: Int): E {
val curSize = size.value
require(index < curSize) { "index must be lower than the array size" }
// As the size never decreases, this read is safe.
return array[index].value as E
}
}