From c3adfe14a1ff7d5d85b3a16e961eafcc34da5807 Mon Sep 17 00:00:00 2001 From: Diego Leonardo Urban Date: Wed, 18 Nov 2026 21:24:22 +0100 Subject: [PATCH 1/3] Add IntDynamicArray stub with example and model-based tests The class is documented (growth policy, contract, exceptions) but every method throws UnsupportedOperationException, to be implemented by hand. - IntDynamicArrayTest: 11 examples, incl. doubling when full and halving at a quarter full, never below the initial capacity of 10 - IntDynamicArrayPropertyTest: jqwik model-based check that random add/insert/set/remove sequences keep it identical to an ArrayList The 12 new tests fail until the implementation lands. Co-Authored-By: Claude Opus 5.5 --- .../datastructure/array/IntDynamicArray.java | 134 +++++++++++++++ .../array/IntDynamicArrayPropertyTest.java | 92 +++++++++++ .../array/IntDynamicArrayTest.java | 153 ++++++++++++++++++ 3 files changed, 379 insertions(+) create mode 100644 src/main/java/io/github/diegourban/algorithms/datastructure/array/IntDynamicArray.java create mode 100644 src/test/java/io/github/diegourban/algorithms/datastructure/array/IntDynamicArrayPropertyTest.java create mode 100644 src/test/java/io/github/diegourban/algorithms/datastructure/array/IntDynamicArrayTest.java diff --git a/src/main/java/io/github/diegourban/algorithms/datastructure/array/IntDynamicArray.java b/src/main/java/io/github/diegourban/algorithms/datastructure/array/IntDynamicArray.java new file mode 100644 index 0000000..94b55a4 --- /dev/null +++ b/src/main/java/io/github/diegourban/algorithms/datastructure/array/IntDynamicArray.java @@ -0,0 +1,134 @@ +package io.github.diegourban.algorithms.datastructure.array; + +/** + * A growable list of {@code int} values backed by an {@code int[]}, so values are never boxed. + *

+ * 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 a quarter full, but never drops below {@value #INITIAL_CAPACITY}. + * Shrinking at a quarter (not a half) keeps alternating adds and removes from resizing every time, so every operation + * is amortised O(1) apart from the index shifts of {@link #add(int, int)} and {@link #remove(int)}. + */ +public class IntDynamicArray { + + /** The capacity of a new array, and the smallest capacity it ever shrinks to. */ + public static final int INITIAL_CAPACITY = 10; + + /** Creates an empty array with capacity {@value #INITIAL_CAPACITY}. */ + public IntDynamicArray() { + throw new UnsupportedOperationException("not implemented"); + } + + /** + * Appends a value at the end, doubling the capacity first if the array is full. + * + * @param value the value to append + */ + public void add(final int value) { + throw new UnsupportedOperationException("not implemented"); + } + + /** + * Inserts a value at the given index, shifting the value at that index and all later ones one position right. + * Index {@link #size()} appends. + * + * @param index the zero-based index, from {@code 0} to {@link #size()} + * @param value the value to insert + * @throws IndexOutOfBoundsException if {@code index} is negative or greater than {@link #size()} + */ + public void add(final int index, final int value) { + throw new UnsupportedOperationException("not implemented"); + } + + /** + * 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 int get(final int index) { + throw new UnsupportedOperationException("not implemented"); + } + + /** + * 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 + * @return the value previously at {@code index} + * @throws IndexOutOfBoundsException if {@code index} is negative or not less than {@link #size()} + */ + public int set(final int index, final int value) { + throw new UnsupportedOperationException("not implemented"); + } + + /** + * Removes the value at the given index, shifting all later values one position left, then halves the capacity if + * the array is left a quarter full (never below {@value #INITIAL_CAPACITY}). + * + * @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 int remove(final int index) { + throw new UnsupportedOperationException("not implemented"); + } + + /** + * Returns the number of stored values. + * + * @return the number of values + */ + public int size() { + throw new UnsupportedOperationException("not implemented"); + } + + /** + * Tells whether the array holds no values. + * + * @return {@code true} if {@link #size()} is {@code 0} + */ + public boolean isEmpty() { + throw new UnsupportedOperationException("not implemented"); + } + + /** + * Returns the length of the backing array, which is at least {@link #size()}. Exposed so the growth policy can + * be observed and tested. + * + * @return the current capacity + */ + public int capacity() { + throw new UnsupportedOperationException("not implemented"); + } + + /** + * Tells whether the array holds the given value. + * + * @param value the value to look for + * @return {@code true} if some index holds {@code value} + */ + public boolean contains(final int value) { + throw new UnsupportedOperationException("not implemented"); + } + + /** + * Returns the index of the first occurrence of the given value. + * + * @param value the value to look for + * @return the lowest index holding {@code value}, or {@code -1} if it is absent + */ + public int indexOf(final int value) { + throw new UnsupportedOperationException("not implemented"); + } + + /** + * Returns the stored values in order, as a new array of length {@link #size()}; changing it does not change this + * dynamic array. + * + * @return a copy of the stored values + */ + public int[] toArray() { + throw new UnsupportedOperationException("not implemented"); + } +} diff --git a/src/test/java/io/github/diegourban/algorithms/datastructure/array/IntDynamicArrayPropertyTest.java b/src/test/java/io/github/diegourban/algorithms/datastructure/array/IntDynamicArrayPropertyTest.java new file mode 100644 index 0000000..b9a1000 --- /dev/null +++ b/src/test/java/io/github/diegourban/algorithms/datastructure/array/IntDynamicArrayPropertyTest.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 IntDynamicArray} holding exactly what a + * {@link java.util.ArrayList} holds after the same operations, and the capacity always respects the growth policy. + * 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 IntDynamicArrayPropertyTest { + + sealed interface Operation permits Add, Insert, Set, Remove {} + + record Add(int value) implements Operation {} + + record Insert(int rawIndex, int value) implements Operation {} + + record Set(int rawIndex, int value) implements Operation {} + + record Remove(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(4, values.map(Add::new)), + Tuple.of(2, Combinators.combine(rawIndexes, values).as(Insert::new)), + Tuple.of(2, Combinators.combine(rawIndexes, values).as(Set::new)), + Tuple.of(3, rawIndexes.map(Remove::new))); + } + + @Property + void behavesLikeAnArrayList(@ForAll("operationSequences") final List operations) { + final IntDynamicArray array = new IntDynamicArray(); + final List model = new ArrayList<>(); + + for (final Operation operation : operations) { + apply(operation, array, model); + + assertThat(array.size()).isEqualTo(model.size()); + assertThat(array.toArray()).containsExactly(toInts(model)); + assertThat(array.capacity()) + .isGreaterThanOrEqualTo(Math.max(array.size(), IntDynamicArray.INITIAL_CAPACITY)); + } + } + + private static void apply(final Operation operation, final IntDynamicArray array, final List model) { + switch (operation) { + case Add(final int value) -> { + array.add(value); + model.add(value); + } + case Insert(final int rawIndex, final int value) -> { + final int index = rawIndex % (model.size() + 1); + array.add(index, value); + model.add(index, value); + } + case Set(final int rawIndex, final int value) -> { + if (!model.isEmpty()) { + final int index = rawIndex % model.size(); + assertThat(array.set(index, value)).isEqualTo(model.set(index, value)); + } + } + case Remove(final int rawIndex) -> { + if (!model.isEmpty()) { + final int index = rawIndex % model.size(); + assertThat(array.remove(index)).isEqualTo(model.remove(index)); + } + } + } + } + + private static int[] toInts(final List values) { + return values.stream().mapToInt(Integer::intValue).toArray(); + } +} diff --git a/src/test/java/io/github/diegourban/algorithms/datastructure/array/IntDynamicArrayTest.java b/src/test/java/io/github/diegourban/algorithms/datastructure/array/IntDynamicArrayTest.java new file mode 100644 index 0000000..a9ff564 --- /dev/null +++ b/src/test/java/io/github/diegourban/algorithms/datastructure/array/IntDynamicArrayTest.java @@ -0,0 +1,153 @@ +package io.github.diegourban.algorithms.datastructure.array; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +import org.junit.jupiter.api.Test; + +class IntDynamicArrayTest { + + private static IntDynamicArray of(final int... values) { + final IntDynamicArray array = new IntDynamicArray(); + for (final int value : values) { + array.add(value); + } + return array; + } + + @Test + void startsEmptyWithTheInitialCapacity() { + final IntDynamicArray array = new IntDynamicArray(); + + assertThat(array.isEmpty()).isTrue(); + assertThat(array.size()).isZero(); + assertThat(array.capacity()).isEqualTo(IntDynamicArray.INITIAL_CAPACITY); + assertThat(array.toArray()).isEmpty(); + } + + @Test + void appendsInOrder() { + final IntDynamicArray array = of(3, 1, 2); + + assertThat(array.size()).isEqualTo(3); + assertThat(array.isEmpty()).isFalse(); + assertThat(array.get(0)).isEqualTo(3); + assertThat(array.get(2)).isEqualTo(2); + assertThat(array.toArray()).containsExactly(3, 1, 2); + } + + @Test + void insertsAtTheStartMiddleAndEnd() { + final IntDynamicArray array = of(2, 4); + + array.add(0, 1); + array.add(2, 3); + array.add(4, 5); + + assertThat(array.toArray()).containsExactly(1, 2, 3, 4, 5); + } + + @Test + void setReplacesAndReturnsThePreviousValue() { + final IntDynamicArray array = of(1, 2, 3); + + assertThat(array.set(1, 20)).isEqualTo(2); + assertThat(array.toArray()).containsExactly(1, 20, 3); + } + + @Test + void removeShiftsLaterValuesAndReturnsTheRemovedOne() { + final IntDynamicArray array = of(1, 2, 3, 4); + + assertThat(array.remove(1)).isEqualTo(2); + assertThat(array.remove(2)).isEqualTo(4); + assertThat(array.remove(0)).isEqualTo(1); + assertThat(array.toArray()).containsExactly(3); + } + + @Test + void findsValues() { + final IntDynamicArray array = of(5, 7, 5); + + assertThat(array.contains(7)).isTrue(); + assertThat(array.contains(9)).isFalse(); + assertThat(array.indexOf(5)).isZero(); + assertThat(array.indexOf(9)).isEqualTo(-1); + } + + @Test + void toArrayReturnsACopy() { + final IntDynamicArray array = of(1, 2); + + array.toArray()[0] = 99; + + assertThat(array.get(0)).isEqualTo(1); + } + + @Test + void doublesTheCapacityWhenFull() { + final IntDynamicArray array = new IntDynamicArray(); + for (int i = 0; i < IntDynamicArray.INITIAL_CAPACITY; i++) { + array.add(i); + } + assertThat(array.capacity()).isEqualTo(10); + + array.add(10); + assertThat(array.capacity()).isEqualTo(20); + + for (int i = 11; i <= 20; i++) { + array.add(i); + } + assertThat(array.size()).isEqualTo(21); + assertThat(array.capacity()).isEqualTo(40); + } + + @Test + void halvesTheCapacityWhenAQuarterFullButNotBelowTheInitialCapacity() { + final IntDynamicArray array = new IntDynamicArray(); + for (int i = 0; i < 21; i++) { + array.add(i); + } + assertThat(array.capacity()).isEqualTo(40); + + while (array.size() > 11) { + array.remove(array.size() - 1); + } + assertThat(array.capacity()).as("11 of 40 is above a quarter").isEqualTo(40); + + array.remove(array.size() - 1); + assertThat(array.size()).isEqualTo(10); + assertThat(array.capacity()).as("10 of 40 is a quarter: halve").isEqualTo(20); + + while (array.size() > 5) { + array.remove(array.size() - 1); + } + assertThat(array.capacity()).as("5 of 20 is a quarter: halve").isEqualTo(10); + + while (!array.isEmpty()) { + array.remove(0); + } + assertThat(array.capacity()).as("never below the initial capacity").isEqualTo(10); + } + + @Test + void rejectsIndexesOutsideTheStoredValues() { + final IntDynamicArray 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.remove(2)); + assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> array.add(3, 0)); + assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> array.add(-1, 0)); + assertThat(array.toArray()).containsExactly(1, 2); + } + + @Test + void rejectsAccessToAnEmptyArray() { + final IntDynamicArray array = new IntDynamicArray(); + + assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> array.get(0)); + assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> array.remove(0)); + } +} From c76bae5acda8dc931c1000a26dbd97971f889660 Mon Sep 17 00:00:00 2001 From: Diego Leonardo Urban Date: Wed, 18 Nov 2026 22:00:00 +0100 Subject: [PATCH 2/3] dynamic array --- .../datastructure/array/DynamicArray.java | 130 +++++++++++++++ .../datastructure/array/IntDynamicArray.java | 134 --------------- .../array/DynamicArrayPropertyTest.java | 92 +++++++++++ .../datastructure/array/DynamicArrayTest.java | 147 +++++++++++++++++ .../array/IntDynamicArrayPropertyTest.java | 92 ----------- .../array/IntDynamicArrayTest.java | 153 ------------------ 6 files changed, 369 insertions(+), 379 deletions(-) create mode 100644 src/main/java/io/github/diegourban/algorithms/datastructure/array/DynamicArray.java delete mode 100644 src/main/java/io/github/diegourban/algorithms/datastructure/array/IntDynamicArray.java create mode 100644 src/test/java/io/github/diegourban/algorithms/datastructure/array/DynamicArrayPropertyTest.java create mode 100644 src/test/java/io/github/diegourban/algorithms/datastructure/array/DynamicArrayTest.java delete mode 100644 src/test/java/io/github/diegourban/algorithms/datastructure/array/IntDynamicArrayPropertyTest.java delete mode 100644 src/test/java/io/github/diegourban/algorithms/datastructure/array/IntDynamicArrayTest.java 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..62c701f --- /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.fixedArray[this.size] = null; + this.size -= 1; + 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/main/java/io/github/diegourban/algorithms/datastructure/array/IntDynamicArray.java b/src/main/java/io/github/diegourban/algorithms/datastructure/array/IntDynamicArray.java deleted file mode 100644 index 94b55a4..0000000 --- a/src/main/java/io/github/diegourban/algorithms/datastructure/array/IntDynamicArray.java +++ /dev/null @@ -1,134 +0,0 @@ -package io.github.diegourban.algorithms.datastructure.array; - -/** - * A growable list of {@code int} values backed by an {@code int[]}, so values are never boxed. - *

- * 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 a quarter full, but never drops below {@value #INITIAL_CAPACITY}. - * Shrinking at a quarter (not a half) keeps alternating adds and removes from resizing every time, so every operation - * is amortised O(1) apart from the index shifts of {@link #add(int, int)} and {@link #remove(int)}. - */ -public class IntDynamicArray { - - /** The capacity of a new array, and the smallest capacity it ever shrinks to. */ - public static final int INITIAL_CAPACITY = 10; - - /** Creates an empty array with capacity {@value #INITIAL_CAPACITY}. */ - public IntDynamicArray() { - throw new UnsupportedOperationException("not implemented"); - } - - /** - * Appends a value at the end, doubling the capacity first if the array is full. - * - * @param value the value to append - */ - public void add(final int value) { - throw new UnsupportedOperationException("not implemented"); - } - - /** - * Inserts a value at the given index, shifting the value at that index and all later ones one position right. - * Index {@link #size()} appends. - * - * @param index the zero-based index, from {@code 0} to {@link #size()} - * @param value the value to insert - * @throws IndexOutOfBoundsException if {@code index} is negative or greater than {@link #size()} - */ - public void add(final int index, final int value) { - throw new UnsupportedOperationException("not implemented"); - } - - /** - * 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 int get(final int index) { - throw new UnsupportedOperationException("not implemented"); - } - - /** - * 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 - * @return the value previously at {@code index} - * @throws IndexOutOfBoundsException if {@code index} is negative or not less than {@link #size()} - */ - public int set(final int index, final int value) { - throw new UnsupportedOperationException("not implemented"); - } - - /** - * Removes the value at the given index, shifting all later values one position left, then halves the capacity if - * the array is left a quarter full (never below {@value #INITIAL_CAPACITY}). - * - * @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 int remove(final int index) { - throw new UnsupportedOperationException("not implemented"); - } - - /** - * Returns the number of stored values. - * - * @return the number of values - */ - public int size() { - throw new UnsupportedOperationException("not implemented"); - } - - /** - * Tells whether the array holds no values. - * - * @return {@code true} if {@link #size()} is {@code 0} - */ - public boolean isEmpty() { - throw new UnsupportedOperationException("not implemented"); - } - - /** - * Returns the length of the backing array, which is at least {@link #size()}. Exposed so the growth policy can - * be observed and tested. - * - * @return the current capacity - */ - public int capacity() { - throw new UnsupportedOperationException("not implemented"); - } - - /** - * Tells whether the array holds the given value. - * - * @param value the value to look for - * @return {@code true} if some index holds {@code value} - */ - public boolean contains(final int value) { - throw new UnsupportedOperationException("not implemented"); - } - - /** - * Returns the index of the first occurrence of the given value. - * - * @param value the value to look for - * @return the lowest index holding {@code value}, or {@code -1} if it is absent - */ - public int indexOf(final int value) { - throw new UnsupportedOperationException("not implemented"); - } - - /** - * Returns the stored values in order, as a new array of length {@link #size()}; changing it does not change this - * dynamic array. - * - * @return a copy of the stored values - */ - public int[] toArray() { - throw new UnsupportedOperationException("not implemented"); - } -} 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..24a1d12 --- /dev/null +++ b/src/test/java/io/github/diegourban/algorithms/datastructure/array/DynamicArrayTest.java @@ -0,0 +1,147 @@ +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)); + } +} diff --git a/src/test/java/io/github/diegourban/algorithms/datastructure/array/IntDynamicArrayPropertyTest.java b/src/test/java/io/github/diegourban/algorithms/datastructure/array/IntDynamicArrayPropertyTest.java deleted file mode 100644 index b9a1000..0000000 --- a/src/test/java/io/github/diegourban/algorithms/datastructure/array/IntDynamicArrayPropertyTest.java +++ /dev/null @@ -1,92 +0,0 @@ -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 IntDynamicArray} holding exactly what a - * {@link java.util.ArrayList} holds after the same operations, and the capacity always respects the growth policy. - * 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 IntDynamicArrayPropertyTest { - - sealed interface Operation permits Add, Insert, Set, Remove {} - - record Add(int value) implements Operation {} - - record Insert(int rawIndex, int value) implements Operation {} - - record Set(int rawIndex, int value) implements Operation {} - - record Remove(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(4, values.map(Add::new)), - Tuple.of(2, Combinators.combine(rawIndexes, values).as(Insert::new)), - Tuple.of(2, Combinators.combine(rawIndexes, values).as(Set::new)), - Tuple.of(3, rawIndexes.map(Remove::new))); - } - - @Property - void behavesLikeAnArrayList(@ForAll("operationSequences") final List operations) { - final IntDynamicArray array = new IntDynamicArray(); - final List model = new ArrayList<>(); - - for (final Operation operation : operations) { - apply(operation, array, model); - - assertThat(array.size()).isEqualTo(model.size()); - assertThat(array.toArray()).containsExactly(toInts(model)); - assertThat(array.capacity()) - .isGreaterThanOrEqualTo(Math.max(array.size(), IntDynamicArray.INITIAL_CAPACITY)); - } - } - - private static void apply(final Operation operation, final IntDynamicArray array, final List model) { - switch (operation) { - case Add(final int value) -> { - array.add(value); - model.add(value); - } - case Insert(final int rawIndex, final int value) -> { - final int index = rawIndex % (model.size() + 1); - array.add(index, value); - model.add(index, value); - } - case Set(final int rawIndex, final int value) -> { - if (!model.isEmpty()) { - final int index = rawIndex % model.size(); - assertThat(array.set(index, value)).isEqualTo(model.set(index, value)); - } - } - case Remove(final int rawIndex) -> { - if (!model.isEmpty()) { - final int index = rawIndex % model.size(); - assertThat(array.remove(index)).isEqualTo(model.remove(index)); - } - } - } - } - - private static int[] toInts(final List values) { - return values.stream().mapToInt(Integer::intValue).toArray(); - } -} diff --git a/src/test/java/io/github/diegourban/algorithms/datastructure/array/IntDynamicArrayTest.java b/src/test/java/io/github/diegourban/algorithms/datastructure/array/IntDynamicArrayTest.java deleted file mode 100644 index a9ff564..0000000 --- a/src/test/java/io/github/diegourban/algorithms/datastructure/array/IntDynamicArrayTest.java +++ /dev/null @@ -1,153 +0,0 @@ -package io.github.diegourban.algorithms.datastructure.array; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; - -import org.junit.jupiter.api.Test; - -class IntDynamicArrayTest { - - private static IntDynamicArray of(final int... values) { - final IntDynamicArray array = new IntDynamicArray(); - for (final int value : values) { - array.add(value); - } - return array; - } - - @Test - void startsEmptyWithTheInitialCapacity() { - final IntDynamicArray array = new IntDynamicArray(); - - assertThat(array.isEmpty()).isTrue(); - assertThat(array.size()).isZero(); - assertThat(array.capacity()).isEqualTo(IntDynamicArray.INITIAL_CAPACITY); - assertThat(array.toArray()).isEmpty(); - } - - @Test - void appendsInOrder() { - final IntDynamicArray array = of(3, 1, 2); - - assertThat(array.size()).isEqualTo(3); - assertThat(array.isEmpty()).isFalse(); - assertThat(array.get(0)).isEqualTo(3); - assertThat(array.get(2)).isEqualTo(2); - assertThat(array.toArray()).containsExactly(3, 1, 2); - } - - @Test - void insertsAtTheStartMiddleAndEnd() { - final IntDynamicArray array = of(2, 4); - - array.add(0, 1); - array.add(2, 3); - array.add(4, 5); - - assertThat(array.toArray()).containsExactly(1, 2, 3, 4, 5); - } - - @Test - void setReplacesAndReturnsThePreviousValue() { - final IntDynamicArray array = of(1, 2, 3); - - assertThat(array.set(1, 20)).isEqualTo(2); - assertThat(array.toArray()).containsExactly(1, 20, 3); - } - - @Test - void removeShiftsLaterValuesAndReturnsTheRemovedOne() { - final IntDynamicArray array = of(1, 2, 3, 4); - - assertThat(array.remove(1)).isEqualTo(2); - assertThat(array.remove(2)).isEqualTo(4); - assertThat(array.remove(0)).isEqualTo(1); - assertThat(array.toArray()).containsExactly(3); - } - - @Test - void findsValues() { - final IntDynamicArray array = of(5, 7, 5); - - assertThat(array.contains(7)).isTrue(); - assertThat(array.contains(9)).isFalse(); - assertThat(array.indexOf(5)).isZero(); - assertThat(array.indexOf(9)).isEqualTo(-1); - } - - @Test - void toArrayReturnsACopy() { - final IntDynamicArray array = of(1, 2); - - array.toArray()[0] = 99; - - assertThat(array.get(0)).isEqualTo(1); - } - - @Test - void doublesTheCapacityWhenFull() { - final IntDynamicArray array = new IntDynamicArray(); - for (int i = 0; i < IntDynamicArray.INITIAL_CAPACITY; i++) { - array.add(i); - } - assertThat(array.capacity()).isEqualTo(10); - - array.add(10); - assertThat(array.capacity()).isEqualTo(20); - - for (int i = 11; i <= 20; i++) { - array.add(i); - } - assertThat(array.size()).isEqualTo(21); - assertThat(array.capacity()).isEqualTo(40); - } - - @Test - void halvesTheCapacityWhenAQuarterFullButNotBelowTheInitialCapacity() { - final IntDynamicArray array = new IntDynamicArray(); - for (int i = 0; i < 21; i++) { - array.add(i); - } - assertThat(array.capacity()).isEqualTo(40); - - while (array.size() > 11) { - array.remove(array.size() - 1); - } - assertThat(array.capacity()).as("11 of 40 is above a quarter").isEqualTo(40); - - array.remove(array.size() - 1); - assertThat(array.size()).isEqualTo(10); - assertThat(array.capacity()).as("10 of 40 is a quarter: halve").isEqualTo(20); - - while (array.size() > 5) { - array.remove(array.size() - 1); - } - assertThat(array.capacity()).as("5 of 20 is a quarter: halve").isEqualTo(10); - - while (!array.isEmpty()) { - array.remove(0); - } - assertThat(array.capacity()).as("never below the initial capacity").isEqualTo(10); - } - - @Test - void rejectsIndexesOutsideTheStoredValues() { - final IntDynamicArray 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.remove(2)); - assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> array.add(3, 0)); - assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> array.add(-1, 0)); - assertThat(array.toArray()).containsExactly(1, 2); - } - - @Test - void rejectsAccessToAnEmptyArray() { - final IntDynamicArray array = new IntDynamicArray(); - - assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> array.get(0)); - assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> array.remove(0)); - } -} From bd7564282aa079b4178eb3e5908a6de119749266 Mon Sep 17 00:00:00 2001 From: Diego Leonardo Urban Date: Wed, 18 Nov 2026 22:02:55 +0100 Subject: [PATCH 3/3] Fix popBack clearing the slot before decrementing the size popBack nulled fixedArray[size] before size -= 1, so on a full array it wrote one past the end (ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10, found by DynamicArrayPropertyTest in CI), and on other arrays it cleared the empty slot after the last value instead of releasing the removed one. Decrement first, then clear. New example test popBackFromAFullArray failed before the fix. Co-Authored-By: Claude Opus 5.5 --- .../datastructure/array/DynamicArray.java | 2 +- .../datastructure/array/DynamicArrayTest.java | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) 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 index 62c701f..27defcf 100644 --- a/src/main/java/io/github/diegourban/algorithms/datastructure/array/DynamicArray.java +++ b/src/main/java/io/github/diegourban/algorithms/datastructure/array/DynamicArray.java @@ -94,8 +94,8 @@ public void popBack() { if (this.size == 0) { throw new ArrayIndexOutOfBoundsException("Index: 0, Size: " + this.size); } - this.fixedArray[this.size] = null; 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); } 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 index 24a1d12..4e78c62 100644 --- a/src/test/java/io/github/diegourban/algorithms/datastructure/array/DynamicArrayTest.java +++ b/src/test/java/io/github/diegourban/algorithms/datastructure/array/DynamicArrayTest.java @@ -144,4 +144,17 @@ void rejectsPoppingFromAnEmptyArray() { 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); + } }