The task
Given an integer array, move all elements that are equal to 0 to the left while maintaining the order of other elements in the array. Let's look at the following integer array.
After moving all zero elements to the left, the array should look like this. We need to maintain the order of non-zero elements.
0 0 0 1 10 20 59 63 88
My approach, I used TDD and hoped my solution would become just as good as the sample solution.
test('contains no element', () => {
expect(moveZeroToLeft([])).toStrictEqual(undefined);
});
test('contains only a 0 element', () => {
expect(moveZeroToLeft([0])).toStrictEqual([0]);
});
test('contains only a non 0 element', () => {
expect(moveZeroToLeft([1])).toStrictEqual([1]);
});
test('contains more than one element with a 0', () => {
expect(moveZeroToLeft([1, 0])).toStrictEqual([0, 1]);
});
test('contains more than one element without 0', () => {
expect(moveZeroToLeft([1, 3])).toStrictEqual([1, 3]);
});
test('contains more than one element with a 0 somewhere in the middle', () => {
expect(moveZeroToLeft([1, 0, 3])).toStrictEqual([0, 1, 3]);
});
test('contains random number of zeros and non-zero elements', () => {
expect(moveZeroToLeft([1, 0, 3, 0, 0, 44, 1, 0, 2])).toStrictEqual([0, 0, 0, 0, 1, 3, 44, 1, 2]);
});
My solution
function moveZeroToLeft(arr) {
if (arr.length < 2) {
return arr;
}
if (arr.some(x => x === 0)) {
let zeroCounter = 0;
const res = arr.filter(el => {
if (el !== 0) {
return true;
}
zeroCounter++;
});
const leadingZeros = Array(zeroCounter).fill(0);
return leadingZeros.concat(res);
}
return arr;
}
But the sample solution is much more elegant than mine:
let move_zeros_to_left = function(A) {
if (A.length < 1) {
return;
}
let lengthA = A.length;
let write_index = lengthA - 1;
let read_index = lengthA - 1;
while (read_index >= 0) {
if (A[read_index] != 0) {
A[write_index] = A[read_index];
write_index--;
}
read_index--;
}
while (write_index >= 0) {
A[write_index] = 0;
write_index--;
}
};
How could I have come to the sample solution with a TDD approach?
moveZeroToLeft([])
should result in[]
, notundefined
. If your test is incorrect in the first place, TDD would be a hindrance to you instead. \$\endgroup\$