-
Notifications
You must be signed in to change notification settings - Fork 3
/
DynamicArray.kt
52 lines (46 loc) · 1.56 KB
/
DynamicArray.kt
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package day4
import kotlinx.atomicfu.*
// This implementation never stores `null` values.
class DynamicArray<E: Any> {
private val core = atomic(Core(capacity = 1)) // Do not change the initial capacity
/**
* Adds the specified [element] to the end of this array.
*/
fun addLast(element: E) {
// TODO: Implement me!
// TODO: Yeah, this is a hard task, I know ...
}
/**
* Puts the specified [element] into the cell [index],
* or throws [IllegalArgumentException] if [index]
* exceeds the size of this array.
*/
fun set(index: Int, element: E) {
val curCore = core.value
val curSize = curCore.size.value
require(index < curSize) { "index must be lower than the array size" }
// TODO: check that the cell is not "frozen"
curCore.array[index].value = element
}
/**
* Returns the element located in the cell [index],
* or throws [IllegalArgumentException] if [index]
* exceeds the size of this array.
*/
@Suppress("UNCHECKED_CAST")
fun get(index: Int): E {
val curCore = core.value
val curSize = curCore.size.value
require(index < curSize) { "index must be lower than the array size" }
// TODO: check that the cell is not "frozen",
// TODO: unwrap the element in this case.
return curCore.array[index].value as E
}
private class Core(
val capacity: Int
) {
val array = atomicArrayOfNulls<Any?>(capacity)
val size = atomic(0)
val next = atomic<Core?>(null)
}
}