Skip to content

Instantly share code, notes, and snippets.

@m-sedl
Created September 10, 2021 18:56
Show Gist options
  • Save m-sedl/8efa705f0736b2da31e1da58ea6ea6ab to your computer and use it in GitHub Desktop.
Save m-sedl/8efa705f0736b2da31e1da58ea6ea6ab to your computer and use it in GitHub Desktop.
fun main() {
val list1 = ImmutableIntList(0)
println(list1)
val list2 = list1.add(1).add(2).add(4).add(5)
println(list2)
val list3 = list2.addAt(3,2)
println(list3)
val list4 = list3.deleteAt(list3.size - 1).deleteAt(0)
println(list4)
}
class ImmutableIntList(val size: Int) {
private val items = IntArray(size)
init {
if (size < 0) {
throw IllegalArgumentException("Size must be great or equals 0")
}
}
fun add(item: Int): ImmutableIntList {
return addAt(item, size)
}
fun addAt(item: Int, idx: Int): ImmutableIntList {
if (idx > size) {
throw IndexOutOfBoundsException("Index greater that size: $idx > $size")
}
val newList = ImmutableIntList(size + 1)
if (size == 0) {
newList.items[0] = item
return newList
}
for (i in 0 until idx) {
newList.items[i] = items[i]
}
newList.items[idx] = item
for (i in idx until items.size) {
newList.items[i + 1] = items[i]
}
return newList
}
fun deleteAt(idx: Int): ImmutableIntList {
if (size == 0) throw IllegalArgumentException("List is already clear")
assertIdxLessSize(idx)
val newList = ImmutableIntList(size - 1)
for (i in 0 until idx) {
newList.items[i] = items[i]
}
for (i in (idx + 1) until items.size) {
newList.items[i - 1] = items[i]
}
return newList
}
operator fun get(idx: Int): Int {
assertIdxLessSize(idx)
return items[idx]
}
private fun assertIdxLessSize(idx: Int) {
if (idx >= size) {
throw IndexOutOfBoundsException("Index greater or equals size: $idx >= $size")
}
}
override fun toString(): String {
return "[" + items.joinToString() + "]"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment