[mv-0-to-end-array] move zeros to the end

This commit is contained in:
Kai.Yuan 2024-02-02 17:06:31 +01:00
parent 5eae4e7df8
commit e8b27416d7
1 changed files with 40 additions and 0 deletions

View File

@ -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);
}
}