Created
June 22, 2016 00:18
-
-
Save embarq/1a4242c02f626ba70eb9eaca7126a77f to your computer and use it in GitHub Desktop.
Encode/Decode Gray-code
This file contains 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
// Грея => Дополнительный | |
"use strict"; | |
let rand = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; | |
let toDecimal = (value, notation) => | |
value.split('').map((char, i, arr) => | |
parseInt(char) * Math.pow(notation, arr.length - (i + 1))) | |
.reduce((sum, current) => sum + current); | |
let toNotation = (int, notation) => { | |
let convert = (int, buffer) => { | |
buffer.push(int % notation); | |
let current = Math.floor(int / notation); | |
return current ? convert(current, buffer) : buffer.reverse(); | |
}; | |
return convert(int, []).join(''); | |
}; | |
let grayEncode = decimal => decimal ^ (decimal >> 1); | |
let grayDecode = gray => { | |
let binary = 0; | |
while (gray) { | |
binary ^= gray; | |
gray >>= 1; | |
} | |
return binary; | |
} | |
console.log("origin\tencoded\tdecoded\n"); | |
let i = 20; | |
while (i--) { | |
let origin = (rand(10, 100)).toString(2); | |
let encoded = grayEncode(toDecimal(origin, 2)); | |
console.log("%s\t%s\t%s", | |
/*origin */ origin, | |
/*gray-encoded*/ toNotation(encoded, 2), | |
/*gray-decoded*/ toNotation(grayDecode(encoded), 2)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment