Last active
December 11, 2015 19:09
-
-
Save shibukawa/4646834 to your computer and use it in GitHub Desktop.
Burrows-Wheeler Transform by JSX
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
class _BWEntry { | |
static var LAST_CHAR = String.fromCharCode(1); | |
var last: string; | |
var key: string; | |
var _index: number; | |
function constructor(str: string, index: number) { | |
this.key = str.slice(index); | |
this._index = index; | |
if (index == 0) | |
{ | |
this.last = _BWEntry.LAST_CHAR; | |
} | |
else | |
{ | |
this.last = str.slice(index - 1, index); | |
} | |
} | |
} | |
class _BWDecodeEntry { | |
var ch: string; | |
var index: number; | |
function constructor(input: string, index: number) { | |
this.index = index; | |
this.ch = input.slice(index, index + 1); | |
} | |
} | |
class BurrowsWheeler { | |
static var LAST_CHAR = String.fromCharCode(1); | |
static function encode(input : string) : string | |
{ | |
var S : string = input + BurrowsWheeler.LAST_CHAR; | |
var Si = [] : _BWEntry[]; | |
for (var i = 0; i < S.length; i++) | |
{ | |
Si.push(new _BWEntry(S, i)); | |
} | |
//log Si; | |
Si.sort(function (a : _BWEntry, b : _BWEntry) : number { | |
if (a.key < b.key) | |
{ | |
return -1; | |
} | |
else if (a.key > b.key) | |
{ | |
return 1; | |
} | |
return 0; | |
}); | |
//log Si; | |
var temp = [] : string[]; | |
Si.forEach(function (entry : _BWEntry) { | |
temp.push(entry.last); | |
}); | |
return temp.join(""); | |
} | |
static function decode(input : string) : string | |
{ | |
var Si = [] : _BWDecodeEntry[]; | |
for (var i = 0; i < input.length; i++) | |
{ | |
Si.push(new _BWDecodeEntry(input, i)); | |
} | |
//log Si; | |
Si.sort(function (a : _BWDecodeEntry, b : _BWDecodeEntry) : number { | |
if (a.ch < b.ch) | |
{ | |
return -1; | |
} | |
else if (a.ch > b.ch) | |
{ | |
return 1; | |
} | |
return a.index - b.index; | |
}); | |
//log Si; | |
var result = [] : string[]; | |
var nextIndex = 0; | |
for (var j in Si) | |
{ | |
var nextEntry = Si[nextIndex]; | |
//log nextEntry; | |
result.push(nextEntry.ch); | |
nextIndex = nextEntry.index; | |
} | |
return result.slice(1).join(''); | |
} | |
static function escape(input: string) : string | |
{ | |
return input.replace(BurrowsWheeler.LAST_CHAR, "$"); | |
} | |
} | |
class _Main { | |
static function main (args: string[]) : void { | |
var teststr : string = "abracadabra"; | |
var encoded_string = BurrowsWheeler.encode(teststr); | |
log "encoded: ", BurrowsWheeler.escape(encoded_string); | |
var decoded_string = BurrowsWheeler.decode(encoded_string); | |
log "decoded: ", decoded_string; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment