Skip to content

Instantly share code, notes, and snippets.

@sungchuni
Created January 29, 2021 09:09
Show Gist options
  • Save sungchuni/a304c9f6c73bafa23d921c713692a2e9 to your computer and use it in GitHub Desktop.
Save sungchuni/a304c9f6c73bafa23d921c713692a2e9 to your computer and use it in GitHub Desktop.
export default function createSubset(array) {
class Node {
constructor(level, antiparticle = false) {
this.level = level;
this.v = array[level];
this.l = array[level + 1] && new Node(level + 1);
this.r = array[level + 1] && new Node(level + 1, true);
this.antiparticle = antiparticle;
this.visited = false;
}
}
const root = new Node(-1);
const records = [];
const stack = [];
const record = stack => records.push(stack.map(({v, antiparticle}) => !antiparticle && v).filter(Boolean));
let cursor = root;
while (cursor) {
if (cursor.l && !cursor.l.visited) {
cursor.visited = true;
stack.push(cursor);
cursor = cursor.l;
} else if (cursor.r && !cursor.r.visited) {
stack.push(cursor);
cursor.visited = true;
cursor = cursor.r;
} else if (cursor.visited) {
cursor = stack.pop();
} else {
cursor.visited = true;
record(stack.concat(cursor));
}
}
return records;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment