Skip to content

Instantly share code, notes, and snippets.

@caasi
Last active April 24, 2020 06:37
Show Gist options
  • Save caasi/e5309215793cf93c43b99081488124cc to your computer and use it in GitHub Desktop.
Save caasi/e5309215793cf93c43b99081488124cc to your computer and use it in GitHub Desktop.
const ZERO = 'a'.charCodeAt(0);
const WIDTH = 5;
const f = Math.floor;
function vPath(n: number): string {
if (n === 0) return '';
if (n > 0) return 'D'.repeat(n);
if (n < 0) return 'U'.repeat(-n);
return '' as never;
}
function hPath(n: number): string {
if (n === 0) return '';
if (n > 0) return 'R'.repeat(n);
if (n < 0) return 'L'.repeat(-n);
return '' as never;
}
function findPath([a, b]: [string, string]): string {
if (b === 'z') return findPath([a, 'u']) + 'D';
const x = a.charCodeAt(0) - ZERO;
const y = b.charCodeAt(0) - ZERO;
if (x === y) return '';
return vPath(f(y / WIDTH) - f(x / WIDTH)) + hPath(y % WIDTH - x % WIDTH);
}
function main(input: string) {
const cs: string[] = Array.prototype.slice.call(input);
const [xs] = cs.reduce(
([acc, last], curr) => [acc.concat([[last, curr]]), curr],
[[] as [string, string][], 'a'],
);
return xs.reduce((acc, curr) => acc + findPath(curr) + '!', '');
}
console.log(main('leet'), main('code'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment