diff --git a/src/test/java/linkedlist/_02_04_PartitionTest.java b/src/test/java/linkedlist/_02_04_PartitionTest.java index 56a0b93..32f4829 100644 --- a/src/test/java/linkedlist/_02_04_PartitionTest.java +++ b/src/test/java/linkedlist/_02_04_PartitionTest.java @@ -2,6 +2,11 @@ import org.junit.Test; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import static junit.framework.TestCase.fail; import static org.junit.Assert.assertEquals; public class _02_04_PartitionTest { @@ -15,27 +20,59 @@ public void withEmptyList() { @Test public void withSortedList() { - assertEquals(LinkedListNode.of(1, 2, 3), s.partition(LinkedListNode.of(1, 2, 3), 2)); + assertPartition(LinkedListNode.of(1, 2, 3), s.partition(LinkedListNode.of(1, 2, 3), 2), 2); } @Test public void withSortedList_AndOutOfListX() { - assertEquals(LinkedListNode.of(3, 2, 1), s.partition(LinkedListNode.of(1, 2, 3), 4)); + assertPartition(LinkedListNode.of(3, 2, 1), s.partition(LinkedListNode.of(1, 2, 3), 4), 4); } @Test public void withSortedList_AndOutOfListX_Smaller() { - assertEquals(LinkedListNode.of(1, 2, 3), s.partition(LinkedListNode.of(1, 2, 3), 0)); + assertPartition(LinkedListNode.of(1, 2, 3), s.partition(LinkedListNode.of(1, 2, 3), 0), 0); } @Test public void withUnSortedList() { - assertEquals(LinkedListNode.of(1, 2, 4, 3, 5), s.partition(LinkedListNode.of(4, 3, 2, 5, 1), 3)); + assertPartition(LinkedListNode.of(1, 2, 4, 3, 5), s.partition(LinkedListNode.of(4, 3, 2, 5, 1), 3), 3); } @Test public void withUnSortedList_AndOutOfScopeX() { - assertEquals(LinkedListNode.of(1, 2, 4, 3, 6), s.partition(LinkedListNode.of(3, 4, 2, 6, 1), 5)); + assertPartition(LinkedListNode.of(1, 2, 4, 3, 6), s.partition(LinkedListNode.of(3, 4, 2, 6, 1), 5), 5); + } + + private void assertPartition(LinkedListNode input, LinkedListNode actual, int x) { + List original = toList(input); + List result = toList(actual); + + // Check that elements are the same (ignoring order) + List originalSorted = new ArrayList<>(original); + List resultSorted = new ArrayList<>(result); + Collections.sort(originalSorted); + Collections.sort(resultSorted); + assertEquals("Partitioned list must contain the same elements", originalSorted, resultSorted); + + // Check partition order + boolean seenRightPartition = false; + for (int value : result) { + if (value < x) { + if (seenRightPartition) { + fail("Elements less than x appeared after elements greater than or equal to x"); + } + } else { + seenRightPartition = true; + } + } } -} \ No newline at end of file + private List toList(LinkedListNode node) { + List list = new ArrayList<>(); + while (node != null) { + list.add(node.val); + node = node.next; + } + return list; + } +}