Last active
October 9, 2018 10:47
-
-
Save generic-github-user/ad4a686451ab8e026e8a26469128237d to your computer and use it in GitHub Desktop.
Converting a string to and from a one-hot encoded binary vector
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
// Converting a string to and from a one-hot encoded binary vector | |
// Accepts a string and returns an array of 1s and 0s | |
function encodeString(input, charset) { | |
// Define output as a variable containing an empty array | |
var output = []; | |
// Convert input string to array of all characters in input | |
input = input.split(""); | |
// Loop through each character of the input string | |
input.forEach( | |
// Loop through each possible character | |
str => charset.forEach( | |
char => { | |
// Check for a match between the current input character and the current character from the list; if there is a match, add a 1 to the output array | |
if (str == char) { | |
output.push(1); | |
} | |
// If there is no match, add a 0 to the output array | |
else { | |
output.push(0); | |
} | |
} | |
) | |
); | |
// Return output array | |
return output; | |
} | |
// Accepts an array of 1s and 0s as an input and returns a string | |
function decodeString(input, charset) { | |
// Define output as a variable containing an empty string | |
var output = ""; | |
// Loop through each character of the input string | |
for (var i = 0; i < input.length; i ++) { | |
// Check value of current element of input array | |
if (input[i] == 1) { | |
output += charset[i % charset.length]; | |
} | |
} | |
// Return output string | |
return output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment