Skip to content

Instantly share code, notes, and snippets.

@keevitaja
Created July 26, 2016 05:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keevitaja/1c9acd837f4c0615b3c5bfd1ce54d0f0 to your computer and use it in GitHub Desktop.
Save keevitaja/1c9acd837f4c0615b3c5bfd1ce54d0f0 to your computer and use it in GitHub Desktop.
'use strict';
const Queue = require('./../libs/queue');
const def = (str)=> {
return /^[wesndu]$/.test(str);
};
const raw = (start, goal, rooms, level, portals)=> {
let que = new Queue();
let visited = {};
let path, num, exits, clone;
for (let num in rooms) visited[num] = false;
que.enqueue([[start]]);
visited[start] = true;
while ( ! que.isEmpty()) {
path = que.dequeue();
num = path[path.length - 1][0];
exits = rooms[num].exits;
if (num == goal) {
let result = [[], []];
for (let i = 0, len = path.length; i < len; i++) {
result[0].push(path[i][0]);
if (i != len - 1) result[1].push(path[i+1][1]);
}
return result;
};
if (num == start && portals) exits = exits.concat(portals);
for (let i = exits.length - 1; i >= 0; i--) {
let exit = exits[i];
if ( ! visited[exit.dst] && rooms[exit.dst]) {
visited[exit.dst] = true;
clone = path.slice(0);
clone.push([exit.dst, exit.cmd]);
que.enqueue(clone);
}
}
}
return false;
};
const speedwalk = (raw)=> {
let cnt = [];
let mlt = 1;
for (let i = 0, len = raw.length; i < len; i++) {
let c = raw[i];
let p = raw[i-1];
let n = raw[i+1];
if (def(c)) {
if (! def(p)) cnt.push('');
if (c == p) mlt++;
if (c != n) {
cnt[cnt.length - 1] += (mlt > 1 ? mlt : '') + c;
mlt = 1;
};
if ( ! def(n)) cnt[cnt.length - 1] = 'run ' + cnt[cnt.length - 1];
} else {
cnt.push(c);
}
}
return cnt;
};
const find = (start, goal, rooms, level, portals)=> {
let [path, commands] = raw(start, goal, rooms, level, portals);
return speedwalk(commands);
};
module.exports.raw = raw;
module.exports.speedwalk = speedwalk;
module.exports.find = find;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment