The mission:
Zero Trim
Write a function which trims multiple zero's sequences to a single zero digit. The return value is the updated array. You are not allowed to use another array, and you need to implement it with one pass over the array. In other words, each element in the array should change its index only once during the program.
var w = [1,2,0,0,0,0,5,7,-6,0,0,0,8,0,0];
var n = zeroTrim(w);
console.log(n); //print [1,2,0,5,7,-6,0,8,0]
Best implementation should be in complexity of O(n), i.e., with one pass over the array.
I am allowed to use only: function,conditions (if), loops, --, ++, %, /, *, -, +, ==, !=, >=, >, <=, <, ||, &&, %=, /=, *=, +=, array.length, array.pop() and concat.
My code:
function zeroTrim(a){ var i,j,l,last,count,count1; count=0; count1=0; for( i = 0 ;i < a.length ;i++){ if(a[i] + a[i+1] === 0){ count++; j=i; while(a[j] === 0){ last=j; j++; count1++; } for(l=i ; l < a.length ;l++){ a[l] = a[last]; last++; } } } for(i = 0 ;i < count1-count ;i++ ){ a.pop(); } return a; } var a=[1,2,0,0,0,0,5,7,-6,0,0,0,8,0,0]; console.log(zeroTrim(a));
Any feedback would be appreciated, if you have other options please share it.
Thank you guys!
===
in your allowed list but you are using it?\$\endgroup\$