ultra-mega-enumerator
Version:
Ultra Mega Enumerator is a lightweight library designed to enumerate various combinatorial objects.
94 lines • 3.09 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DyckWordEnumeration = void 0;
const AbstractEnumeration_1 = require("./AbstractEnumeration");
class State {
// Main constructor
constructor(word, index, parent = null) {
this.parent = parent;
this.word = word;
this.index = index;
}
static create(word, index) {
return new State(word, index);
}
static createWithParent(parent, word, index) {
return new State(word, index, parent);
}
update(index) {
return new State(this.word, index, this.parent);
}
push(word, index) {
return new State(word, index, this);
}
pop() {
return this.parent;
}
equals(o) {
if (this === o)
return true;
if (o == null || this.constructor !== o.constructor)
return false;
const state = o;
return this.index === state.index &&
(this.parent ? this.parent.equals(state.parent) : state.parent == null) &&
this.word === state.word;
}
toString() {
return this.parent !== null ?
`State{word='${this.word}', index=${this.index}, parent=${this.parent}}` :
`State{word='${this.word}', index=${this.index}}`;
}
}
/**
* Adapted into an Enumeration from code by nl.dvberkel.
*/
class DyckWordEnumeration extends AbstractEnumeration_1.AbstractEnumeration {
constructor(nbOfPairs) {
super();
this.symbols = ["(", ")"];
this.target = this.symbols[1] + this.symbols[0];
this.replacement = this.symbols[0] + this.symbols[1];
this.currentState = this.initialStateOfLength(nbOfPairs * 2);
}
next(state) {
do {
if (state.index < state.word.length) {
let j = state.index;
while (j < (state.word.length - 1) && state.word.substring(j, j + 2) !== this.target) {
j++;
}
if (j < (state.word.length - 1)) {
const word = state.word;
const nextWord = word.substring(0, j) + this.replacement + word.substring(j + 2);
return state.update(j + 2).push(nextWord, j - 1);
}
}
state = state.pop();
} while (state !== null);
return null;
}
initialStateOfLength(n) {
return State.create(this.initialWordOfLength(n), 0);
}
initialWordOfLength(n) {
let builder = '';
for (let index = 0; index < n; index++) {
builder += this.symbols[index % 2];
}
return builder;
}
hasMoreElements() {
return this.currentState != null;
}
nextElement() {
if (this.currentState == null) {
throw new Error("No such element");
}
const o = this.currentState.word;
this.currentState = this.next(this.currentState);
return o;
}
}
exports.DyckWordEnumeration = DyckWordEnumeration;
//# sourceMappingURL=DyckWordEnumeration.js.map