From e8b27416d72a243c53cfe309dde5c23966c559b1 Mon Sep 17 00:00:00 2001 From: "Kai.Yuan" Date: Fri, 2 Feb 2024 17:06:31 +0100 Subject: [PATCH] [mv-0-to-end-array] move zeros to the end --- .../MoveZeroesToTheEndOfAnArrayUnitTest.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 core-java-modules/core-java-arrays-operations-advanced-2/src/test/java/com/baeldung/movezerototheend/MoveZeroesToTheEndOfAnArrayUnitTest.java diff --git a/core-java-modules/core-java-arrays-operations-advanced-2/src/test/java/com/baeldung/movezerototheend/MoveZeroesToTheEndOfAnArrayUnitTest.java b/core-java-modules/core-java-arrays-operations-advanced-2/src/test/java/com/baeldung/movezerototheend/MoveZeroesToTheEndOfAnArrayUnitTest.java new file mode 100644 index 0000000000..ae0152feca --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-advanced-2/src/test/java/com/baeldung/movezerototheend/MoveZeroesToTheEndOfAnArrayUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.movezerototheend; + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; + +public class MoveZeroesToTheEndOfAnArrayUnitTest { + static final int[] EXPECTED = new int[] { 1, 2, 3, 4, 0, 0 }; + + @Test + void whenCreatingANewArrayAndCopyingValues_thenGetTheExpectedResult() { + int[] array = new int[] { 1, 2, 0, 3, 4, 0 }; + int[] result = new int[array.length]; + int idx = 0; + for (int n : array) { + if (n != 0) { + result[idx++] = n; + } + } + assertArrayEquals(EXPECTED, result); + } + + @Test + void whenMovingZeroInTheOriginalArray_thenGetTheExpectedResult() { + int[] array = new int[] { 1, 2, 0, 3, 4, 0 }; + int idx = 0; + for (int n : array) { + if (n != 0) { + array[idx++] = n; + } + System.out.println(Arrays.toString(array)); + } + while (idx < array.length) { + array[idx++] = 0; + } + assertArrayEquals(EXPECTED, array); + } +} \ No newline at end of file