Skip to content

Instantly share code, notes, and snippets.

@pinkmomo027
Created June 17, 2018 23:28
Show Gist options
  • Save pinkmomo027/f0c9c584153e395cf9affa4d6f79deed to your computer and use it in GitHub Desktop.
Save pinkmomo027/f0c9c584153e395cf9affa4d6f79deed to your computer and use it in GitHub Desktop.
count consecutive number
const arr = [-1, -1, 1, 1, 1, 1, 7, 11, 11];
// [ -1, 2, 1, 4, 7, 1, 11, 2];
class Stack {
constructor() {
this.values = [];
}
push(v) {
this.values.push(v);
}
pop() {
return this.values.pop();
}
peek() {
return this.values[this.values.length - 1];
}
isEmpty() {
return this.values.length == 0;
}
}
function countFrequency(arr) {
let stack = new Stack();
let answer = [], count, currentElementInStack, element;
for (let i = 0; i <= arr.length; i++) {
element = arr[i];
if ((stack.peek() != element) && !stack.isEmpty()) {
//start poping and clear the stack
count = 0;
currentElementInStack = stack.peek();
while(!stack.isEmpty()) {
stack.pop();
count++;
}
answer.push(currentElementInStack);
answer.push(count);
}
stack.push(element);
}
return answer;
}
@pinkmomo027
Copy link
Author

console.log( countFrequency(arr));

[ -1, 2, 1, 4, 7, 1, 11, 2 ]
[Finished in 0.1s]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment