Skip to content

Instantly share code, notes, and snippets.

@musou1500
Last active January 23, 2018 11:01
Show Gist options
  • Save musou1500/7d3ed0d59c8cfd2b89d6d726fdf4739b to your computer and use it in GitHub Desktop.
Save musou1500/7d3ed0d59c8cfd2b89d6d726fdf4739b to your computer and use it in GitHub Desktop.
LZW圧縮
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.on('line', (input) => {
const findFirstUnregisteredIndex = (input, dict) =>
input
.split('')
.findIndex((val, i, arr) => !dict.includes(arr.slice(0, i + 1).join('')));
const dict = input.split('').filter((val, i) => input.indexOf(val) === i);
const encode = (input, dict) => {
const unregisteredIndex = findFirstUnregisteredIndex(input, dict);
if (unregisteredIndex < 0) return [dict.indexOf(input)];
const unregisteredWord = input.substr(0, unregisteredIndex + 1);
const wordToEncode = unregisteredWord.substr(0, unregisteredWord.length - 1);
dict.push(unregisteredWord);
return [
dict.indexOf(wordToEncode),
...encode(input.substr(unregisteredIndex), dict)
];
};
console.log({dict, encoded: encode(input, dict)});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment