Skip to content

Instantly share code, notes, and snippets.

@techsin
Created November 26, 2017 02:09
Show Gist options
  • Save techsin/7c805fe2249653b13107d4057c184847 to your computer and use it in GitHub Desktop.
Save techsin/7c805fe2249653b13107d4057c184847 to your computer and use it in GitHub Desktop.
var arr = ["apple", ["apple","fix","apple"],["Apple", "apple"]];
function recurCount([...arr]) {
const WORD = 'apple';
if (arr.length === 0) {
return 0;
} else {
let tmp = arr.pop();
if (Array.isArray(tmp)) {
return recurCount(tmp) + recurCount(arr);
} else if (tmp === WORD) {
return 1 + recurCount(arr);
} else {
return 0 + recurCount(arr);
}
}
}
//https://stackoverflow.com/questions/5278580/non-recursive-depth-first-search-algorithm
function loopCount(arr) {
let n = 0;
let stack = [];
const WORD = 'apple';
stack.push(arr);
while(stack.length) {
let current = stack.pop();
if (Array.isArray(current)) {
current.forEach(n => stack.push(n));
} else if (current === WORD) {
n++;
}
}
return n;
}
console.log(recurCount(arr));
console.log(loopCount(arr));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment