diff --git a/src/main/java/io/github/diegourban/algorithms/datastructure/array/DynamicArray.java b/src/main/java/io/github/diegourban/algorithms/datastructure/array/DynamicArray.java new file mode 100644 index 0000000..27defcf --- /dev/null +++ b/src/main/java/io/github/diegourban/algorithms/datastructure/array/DynamicArray.java @@ -0,0 +1,130 @@ +package io.github.diegourban.algorithms.datastructure.array; + +/** + * A growable list of values of any type, backed by an array that is replaced by a larger or smaller copy as values + * are added and removed. + *

+ * Growth policy: the capacity starts at {@value #INITIAL_CAPACITY}, doubles when an element is added to a full array, + * and halves when a removal leaves the array less than a quarter full, but never drops below + * {@value #INITIAL_CAPACITY}. Shrinking at a quarter (not a half) keeps alternating appends and removals from resizing + * every time, so every operation is amortised O(1) apart from the index shifts of {@link #pop(int)}. + *

+ * The backing store is an {@code Object[]} cast to {@code T[]}, because Java cannot create an array of a type + * parameter; the cast is safe because only {@code T} values are ever stored in it. + * + * @param the type of the stored values + */ +public class DynamicArray { + + /** + * The capacity of a new array, and the smallest capacity it ever shrinks to. + */ + public static final int INITIAL_CAPACITY = 10; + + private int size; + private int capacity; + private T[] fixedArray; + + /** + * Creates an empty array with capacity {@value #INITIAL_CAPACITY}. + */ + public DynamicArray() { + this.capacity = INITIAL_CAPACITY; + this.size = 0; + this.fixedArray = (T[]) new Object[capacity]; + } + + /** + * Appends a value at the end, doubling the capacity first if the array is full. + * + * @param value the value to append + */ + public void append(final T value) { + if (this.size == this.capacity) { + this.resize(this.capacity * 2); + } + this.fixedArray[this.size] = value; + this.size += 1; + } + + /** + * Returns the value at the given index. + * + * @param index the zero-based index, from {@code 0} to {@code size() - 1} + * @return the value at {@code index} + * @throws IndexOutOfBoundsException if {@code index} is negative or not less than {@link #size()} + */ + public T get(final int index) { + if (index < 0 || index >= this.size) { + throw new ArrayIndexOutOfBoundsException("Index: " + index + ", Size: " + this.size); + } + return this.fixedArray[index]; + } + + /** + * Replaces the value at the given index. + * + * @param index the zero-based index, from {@code 0} to {@code size() - 1} + * @param value the new value + * @throws IndexOutOfBoundsException if {@code index} is negative or not less than {@link #size()} + */ + public void set(final int index, final T value) { + if (index < 0 || index >= this.size) { + throw new ArrayIndexOutOfBoundsException("Index: " + index + ", Size: " + this.size); + } + this.fixedArray[index] = value; + } + + /** + * Returns the number of stored values. + * + * @return the number of values + */ + public int size() { + return this.size; + } + + /** + * Removes the last value, then halves the capacity if the array is left less than a quarter full (never below + * {@value #INITIAL_CAPACITY}). + * + * @throws IndexOutOfBoundsException if the array is empty + */ + public void popBack() { + if (this.size == 0) { + throw new ArrayIndexOutOfBoundsException("Index: 0, Size: " + this.size); + } + this.size -= 1; + this.fixedArray[this.size] = null; // release the removed value so it can be garbage-collected + if ((double) this.size / this.capacity < 0.25 && this.capacity > INITIAL_CAPACITY) { + this.resize(this.capacity / 2); + } + } + + /** + * Removes the value at the given index, shifting all later values one position left, then shrinks like + * {@link #popBack()}. + * + * @param index the zero-based index, from {@code 0} to {@code size() - 1} + * @return the removed value + * @throws IndexOutOfBoundsException if {@code index} is negative or not less than {@link #size()} + */ + public T pop(final int index) { + if (index < 0 || index >= this.size) { + throw new ArrayIndexOutOfBoundsException("Index: " + index + ", Size: " + this.size); + } + final T value = this.fixedArray[index]; + for (int i = index; i < this.size - 1; i++) { + this.fixedArray[i] = this.fixedArray[i + 1]; + } + this.popBack(); + return value; + } + + private void resize(final int newCapacity) { + final T[] newArray = (T[]) new Object[newCapacity]; + System.arraycopy(this.fixedArray, 0, newArray, 0, this.size); + this.fixedArray = newArray; + this.capacity = newCapacity; + } +} diff --git a/src/test/java/io/github/diegourban/algorithms/datastructure/array/DynamicArrayPropertyTest.java b/src/test/java/io/github/diegourban/algorithms/datastructure/array/DynamicArrayPropertyTest.java new file mode 100644 index 0000000..1952780 --- /dev/null +++ b/src/test/java/io/github/diegourban/algorithms/datastructure/array/DynamicArrayPropertyTest.java @@ -0,0 +1,92 @@ +package io.github.diegourban.algorithms.datastructure.array; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.ArrayList; +import java.util.List; +import net.jqwik.api.Arbitraries; +import net.jqwik.api.Arbitrary; +import net.jqwik.api.Combinators; +import net.jqwik.api.ForAll; +import net.jqwik.api.Property; +import net.jqwik.api.Provide; +import net.jqwik.api.Tuple; + +/** + * Model-based check: any sequence of operations leaves {@link DynamicArray} holding exactly what a + * {@link java.util.ArrayList} holds after the same operations. Indexes are generated as raw numbers and wrapped into + * the valid range for the current size, so every operation is legal and long sequences grow and shrink the array + * across several resizes. + */ +class DynamicArrayPropertyTest { + + sealed interface Operation permits Append, Set, PopBack, Pop {} + + record Append(int value) implements Operation {} + + record Set(int rawIndex, int value) implements Operation {} + + record PopBack() implements Operation {} + + record Pop(int rawIndex) implements Operation {} + + @Provide + Arbitrary> operationSequences() { + return operations().list().ofMaxSize(200); + } + + private static Arbitrary operations() { + final Arbitrary values = Arbitraries.integers(); + final Arbitrary rawIndexes = Arbitraries.integers().greaterOrEqual(0); + return Arbitraries.frequencyOf( + Tuple.of(5, values.map(Append::new)), + Tuple.of(2, Combinators.combine(rawIndexes, values).as(Set::new)), + Tuple.of(2, Arbitraries.just(new PopBack())), + Tuple.of(2, rawIndexes.map(Pop::new))); + } + + @Property + void behavesLikeAnArrayList(@ForAll("operationSequences") final List operations) { + final DynamicArray array = new DynamicArray<>(); + final List model = new ArrayList<>(); + + for (final Operation operation : operations) { + apply(operation, array, model); + + assertThat(array.size()).isEqualTo(model.size()); + for (int i = 0; i < model.size(); i++) { + assertThat(array.get(i)) + .as("value at %d after %s", i, operation) + .isEqualTo(model.get(i)); + } + } + } + + private static void apply(final Operation operation, final DynamicArray array, final List model) { + switch (operation) { + case Append(final int value) -> { + array.append(value); + model.add(value); + } + case Set(final int rawIndex, final int value) -> { + if (!model.isEmpty()) { + final int index = rawIndex % model.size(); + array.set(index, value); + model.set(index, value); + } + } + case PopBack() -> { + if (!model.isEmpty()) { + array.popBack(); + model.removeLast(); + } + } + case Pop(final int rawIndex) -> { + if (!model.isEmpty()) { + final int index = rawIndex % model.size(); + assertThat(array.pop(index)).isEqualTo(model.remove(index)); + } + } + } + } +} diff --git a/src/test/java/io/github/diegourban/algorithms/datastructure/array/DynamicArrayTest.java b/src/test/java/io/github/diegourban/algorithms/datastructure/array/DynamicArrayTest.java new file mode 100644 index 0000000..4e78c62 --- /dev/null +++ b/src/test/java/io/github/diegourban/algorithms/datastructure/array/DynamicArrayTest.java @@ -0,0 +1,160 @@ +package io.github.diegourban.algorithms.datastructure.array; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; + +class DynamicArrayTest { + + @SafeVarargs + private static DynamicArray of(final T... values) { + final DynamicArray array = new DynamicArray<>(); + for (final T value : values) { + array.append(value); + } + return array; + } + + private static List contents(final DynamicArray array) { + final List values = new ArrayList<>(); + for (int i = 0; i < array.size(); i++) { + values.add(array.get(i)); + } + return values; + } + + @Test + void startsEmpty() { + final DynamicArray array = new DynamicArray<>(); + + assertThat(array.size()).isZero(); + assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> array.get(0)); + } + + @Test + void appendsInOrder() { + final DynamicArray array = of(3, 1, 2); + + assertThat(array.size()).isEqualTo(3); + assertThat(contents(array)).containsExactly(3, 1, 2); + } + + @Test + void holdsValuesOfAnyType() { + final DynamicArray array = of("a", "b"); + + array.set(0, "z"); + array.append(null); + + assertThat(contents(array)).containsExactly("z", "b", null); + assertThat(array.pop(1)).isEqualTo("b"); + } + + @Test + void setReplacesTheValueAtAnIndex() { + final DynamicArray array = of(1, 2, 3); + + array.set(1, 20); + + assertThat(contents(array)).containsExactly(1, 20, 3); + } + + @Test + void popBackRemovesTheLastValue() { + final DynamicArray array = of(1, 2, 3); + + array.popBack(); + + assertThat(contents(array)).containsExactly(1, 2); + } + + @Test + void popRemovesTheValueAtAnIndexShiftingLaterOnesAndReturnsIt() { + final DynamicArray array = of(1, 2, 3, 4); + + assertThat(array.pop(1)).isEqualTo(2); + assertThat(contents(array)).containsExactly(1, 3, 4); + + assertThat(array.pop(2)).isEqualTo(4); + assertThat(array.pop(0)).isEqualTo(1); + assertThat(contents(array)).containsExactly(3); + } + + @Test + void keepsEveryValueWhileGrowingPastTheInitialCapacity() { + final DynamicArray array = new DynamicArray<>(); + for (int i = 0; i < 1000; i++) { + array.append(i); + } + + assertThat(array.size()).isEqualTo(1000); + for (int i = 0; i < 1000; i++) { + assertThat(array.get(i)).isEqualTo(i); + } + } + + @Test + void keepsTheRemainingValuesWhileShrinking() { + final DynamicArray array = new DynamicArray<>(); + for (int i = 0; i < 1000; i++) { + array.append(i); + } + + while (array.size() > 3) { + array.popBack(); + } + + assertThat(contents(array)).containsExactly(0, 1, 2); + array.append(99); + assertThat(contents(array)).containsExactly(0, 1, 2, 99); + } + + @Test + void canBeEmptiedAndReused() { + final DynamicArray array = of(1, 2); + + array.popBack(); + array.pop(0); + assertThat(array.size()).isZero(); + + array.append(7); + assertThat(contents(array)).containsExactly(7); + } + + @Test + void rejectsIndexesOutsideTheStoredValues() { + final DynamicArray array = of(1, 2); + + assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> array.get(2)); + assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> array.get(-1)); + assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> array.set(2, 0)); + assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> array.set(-1, 0)); + assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> array.pop(2)); + assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> array.pop(-1)); + assertThat(contents(array)).containsExactly(1, 2); + } + + @Test + void rejectsPoppingFromAnEmptyArray() { + final DynamicArray array = new DynamicArray<>(); + + assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(array::popBack); + assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> array.pop(0)); + } + + @Test + void popBackFromAFullArray() { + final DynamicArray array = new DynamicArray<>(); + for (int i = 0; i < DynamicArray.INITIAL_CAPACITY; i++) { + array.append(i); + } + + array.popBack(); + + assertThat(array.size()).isEqualTo(DynamicArray.INITIAL_CAPACITY - 1); + assertThat(array.get(array.size() - 1)).isEqualTo(DynamicArray.INITIAL_CAPACITY - 2); + } +}