Find prefix of list in Association
If you are willing to use a simple string representation, then StringReplace
might be adequate for your purpose:
decode[s_] := StringReplace[s, {"1" -> "a", "01" -> "b", "00" -> "c"}]
decode["110100"]
(* "aabc" *)
decode["101100101"]
(* "abacab" *)
This is probably not highly efficient but I think it does what you describe.
asc = <|{1} -> "a", {0, 1} -> "b", {0, 0} -> "c"|>;
code = {1, 1, 0, 1, 0, 0};
rls = KeyValueMap[Append[#, x___] :> (Sow[#2]; {x}) &, asc] // Dispatch;
Reap[code //. rls;][[2, 1]]
{"a", "a", "b", "c"}
- Note that I replaced string
"0"
and"1"
in the Association with integer0
and1
for consistency with the coded string (code
).
asc = <|{1} -> "a", {0, 1} -> "b", {0, 0} -> "c"|>;
func[assoc_Association, code : {(1 | 0) ..}] :=
Map[assoc[#] &][SequenceCases[code, Alternatives @@ Keys@assoc]];
func[asc,{1, 1, 0, 1, 0, 0}]
(* {"a", "a", "b", "c"} *)
code = {1, 0, 1, 1, 0, 0, 1, 0, 1};
func[asc,code]
(* {"a", "b", "a", "c", "a", "b"} *)