Skip to content

Instantly share code, notes, and snippets.

@embarq
Created June 22, 2016 00:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save embarq/1a4242c02f626ba70eb9eaca7126a77f to your computer and use it in GitHub Desktop.
Save embarq/1a4242c02f626ba70eb9eaca7126a77f to your computer and use it in GitHub Desktop.
Encode/Decode Gray-code
// Грея => Дополнительный
"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