5
$\begingroup$

I'm trying to code a text. I created the code and I put the code to each individual unique character in the text. My map now looks like this:

{{"l", {1, 0}}, {"a", {1, 1}}, {"j", {0, 1, 0}}, {"u", {0, 1, 1}}, {"e", {0, 0}}}

How do I take these code words and apply them to a text, then put the final text in the output? Example with this map:

text="lea"

Output: {100011}

$\endgroup$

4 Answers 4

4
$\begingroup$

This looks like a case where an Association[] is more appropriate:

as = AssociationThread @@ Transpose[{{"l", {1, 0}}, {"a", {1, 1}}, {"j", {0, 1, 0}},
                                     {"u", {0, 1, 1}}, {"e", {0, 0}}}]

Then you can do this:

StringJoin[Map[IntegerString, Lookup[as, Characters["lea"]], {2}]]
   "100011"
$\endgroup$
4
$\begingroup$
ClearAll[code] 
code = StringReplace[# -> StringRiffle[#2, ""] & @@@ #]&;

Example:

list = {{"l", {1, 0}}, {"a", {1, 1}}, {"j", {0, 1, 0}}, {"u", {0, 1, 1}}, {"e", {0, 0}}};

code[list]["lea"]
"100011"
$\endgroup$
2
$\begingroup$

I like J.M.'s solution. But since there is in Mathematica at least 10 ways to do the same thing, I thought to have a go at it

code = {{"l", {1, 0}}, {"a", {1, 1}}, {"j", {0, 1, 0}}, {"u", {0, 1, 1}}, {"e", {0, 0}}};
word = "ltea";
let = Characters[word];

StringJoin@Flatten[Cases[code, {x_, y__} /; 
       StringMatchQ[x, #] :> (ToString /@ y)] & /@ let]

Mathematica graphics

$\endgroup$
2
$\begingroup$
   decode[s_] := Module[{xs, dict, decodeString},
     xs = {{"l", {1, 0}}, {"a", {1, 1}}, {"j", {0, 1, 0}}, {"u", {0, 1, 
      1}}, {"e", {0, 0}}};
     dict = AssociationThread @@ Transpose@xs;
     decodeString[x_] := StringSplit[x, ""] // Map[dict[#] &] // Flatten;
     decodeString[s]
   ]
   decode["lea"]

{1, 0, 0, 0, 1, 1}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.