Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (function (root, factory) {
- if (typeof exports === 'object') {
- module.exports = factory(root);
- } else if (typeof define === "function" && define.amd) {
- define([], factory);
- } else {
- root.IdiomSolitaire = factory(root);
- }
- })(typeof global !== 'undefined' ? global : this.window || this.global, function (root) {
- class IdiomSolitaire {
- constructor() {
- this.idioms = null;
- }
- load() {
- return this.idioms ? Promise.resolve(this) : fetch('https://cdn.jsdelivr.net/gh/pwxcoo/chinese-xinhua/data/idiom.json')
- .then(res => res.json())
- .then(res => {
- this.idioms = Object.freeze(res.map(e => {
- const pinyin = e.pinyin.replace(/[ ,?]/, '').split(' ');
- e.start = pinyin[0];
- e.end = pinyin[pinyin.length - 1];
- return Object.freeze(e);
- }));
- return this;
- });
- }
- solve(start, end) {
- if (!this.idioms) {
- throw new Error('Idioms not ready');
- }
- console.time('Solve');
- const startIdiom = this.idioms.find(e => e.word === start);
- const endIdiom = this.idioms.find(e => e.word === end);
- if (!startIdiom || !endIdiom) {
- throw new Error('Invalid idiom');
- }
- const set = new Set;
- const queue = [{
- parent: null,
- idiom: startIdiom,
- }];
- let found;
- let nodeCount = 0;
- while (queue.length) {
- const node = queue.shift();
- nodeCount++;
- const children = this.idioms
- .filter((e, i) => e.start === node.idiom.end && !set.has(i) && set.add(i))
- .map(e => ({
- parent: node,
- idiom: e,
- }));
- if (found = children.find(e => e.idiom.end === endIdiom.start)) {
- break;
- }
- children.forEach(e => queue.push(e));
- }
- console.info('Node count:', nodeCount);
- console.timeEnd('Solve');
- if (found) {
- const result = [endIdiom];
- while (found) {
- result.unshift(found.idiom);
- found = found.parent;
- }
- return result;
- } else {
- throw new Error('No solution');
- }
- }
- }
- return IdiomSolitaire;
- });
- // 使用例:
- const solitaire = new IdiomSolitaire;
- solitaire.load().then(solitaire => console.log(solitaire.solve('身经百战', '谈笑风生').map(e => e.word).join(' -> ')));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement