-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray.zero.move.js
More file actions
53 lines (47 loc) · 1.37 KB
/
array.zero.move.js
File metadata and controls
53 lines (47 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
* @title: move zeros
* @description: move all zeros to end of array
* @author: Thorsten Kober
* @email: [email protected]
*/
// sliding window - dynamic size
function moveZeros(arr) {
let lastNonZeroFoundAt = 0;
// Traverse the array. If element encountered is non-
// zero, then replace the element at index 'count'
// with this element
for (let i = 0; i < arr.length; i++) {
if (arr[i] !== 0) arr[lastNonZeroFoundAt++] = arr[i];
}
// Now all non-zero elements have been shifted to
// front and 'count' is set as index of first 0.
// Make all elements 0 from count to end.
while (lastNonZeroFoundAt < arr.length) {
arr[lastNonZeroFoundAt++] = 0;
}
return arr;
}
// sliding window - dynamic size
function moveZeros2(arr) {
let lastNonZeroFoundAt = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] !== 0) {
const temp = arr[lastNonZeroFoundAt];
arr[lastNonZeroFoundAt] = arr[i];
arr[i] = temp;
lastNonZeroFoundAt++;
}
}
return arr;
}
// npx jest algorithms/array/array.zero.move.js
describe('move all zeros to the end', () => {
it('moveZeros()', () => {
const nums = [1, 2, 0, 3, 0, 1, 2];
expect(moveZeros(nums)).toEqual([1, 2, 3, 1, 2, 0, 0]);
});
it('moveZeros2()', () => {
const nums = [1, 2, 0, 3, 0, 1, 2];
expect(moveZeros2(nums)).toEqual([1, 2, 3, 1, 2, 0, 0]);
});
});