Created
April 29, 2014 08:02
-
-
Save ifukazoo/11393549 to your computer and use it in GitHub Desktop.
spacetalky問題回答
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env node | |
var fs = require('fs'); | |
var readline = require('readline'); | |
if (process.argv.length !== 3) { | |
console.log("usage:command <file path>"); | |
process.exit(1); | |
} | |
var filePath = process.argv[2]; | |
var rl = readline.createInterface({ | |
input: fs.createReadStream(filePath, {encoding: 'utf8'}), | |
output: {}, | |
}); | |
rl.on('line', function(line) { | |
answer = answerString(line); | |
console.log(answer); | |
}); | |
function answerString(line) { | |
if (!canEncode(line)) { | |
return 'X:' + line; | |
} else { | |
return stretchString(line) + ':' + line; | |
} | |
} | |
function stretchString(str) { | |
if (str.length % 2 !== 0) throw "illegal argument"; | |
var array = str.splitN(2); | |
var arrayStretched = array.map(function (e) { | |
return stretchTwoChar(e); | |
}); | |
return arrayStretched.join(''); | |
} | |
function toDecimal(c) { | |
if (c === undefined) throw "argument error"; | |
var s = 'abcdefghijklmnopqrstuvwxyz'; | |
return s.indexOf(c) + 1; | |
} | |
function stretchTwoChar(str) { | |
var first = str[0]; | |
var repeat = toDecimal(str[1]); | |
var newStr = ''; | |
for (var i = 0; i < repeat; i++) { | |
newStr += first; | |
} | |
return newStr; | |
} | |
function canEncode(str) { | |
var last = ''; | |
if (str.length % 2 === 1) return false; | |
for (var i = 0; i < str.length; i += 2) { | |
if (last === str[i] && str[i - 1] !== 'z') return false; | |
last = str[i]; | |
} | |
return true; | |
} | |
String.prototype.splitN = function (n) { | |
var a = []; | |
var begin = 0; | |
var i = 0; | |
for (; i < this.length; i++) { | |
if (i !== 0 && i % n == 0) { | |
a.push(this.substring(begin, i)); | |
begin = i; | |
} | |
} | |
a.push(this.substring(begin)); | |
return a; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment