How to replace numbers by letters in a special way?
lists.{"A", "B", "C"} /. 0 -> "1" /. Plus -> StringJoin
{"1", "C", "B", "BC", "A", "AC", "AB", "ABC"}
% // ToExpression
{1, C, B, BC, A, AC, AB, ABC}
One possibility is to use ReplaceAll
(the short form of which is /.
) with a list of rules. There are probably more concise ways of doing this that I'm not seeing.
{{0, 0, 0}, {0, 0, 1}, {0, 1, 0}, {0, 1, 1}, {1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}} /.
{{0, 0, 0} -> 1, {0, 0, 1} -> C, {0, 1, 0} -> B, {0, 1, 1} -> BC,
{1, 0, 0} -> A, {1, 0, 1} -> AC, {1, 1, 0} -> AB, {1, 1, 1} -> ABC}
(* {1,C,B,BC,A,AC,AB,ABC} *)
However, I would recommend surrounding each of those capital letters with quotation marks to make them strings, or else using lower case letters. All built-in functions in Mathematica begin with capital letters, and there are a number of single character capitals reserved by the system such as C, D, E, I, K, N, and O
.
Here's a way to do it (it's bad practice to put an involved answer in a comment so I'm moving it here):
lists = {{0, 0, 0}, {0, 0, 1}, {0, 1, 0}, {0, 1, 1}, {1, 0, 0}, {1, 0, 1}, {1,
1, 0}, {1, 1, 1}};
With[{a = ToUpperCase@Alphabet[]},
StringJoin /@ MapIndexed[If[# == 1, a[[#2[[-1]]]], ""] &, lists, {2}] /.
"" -> "1"
]
(* Out: {"1", "C", "B", "BC", "A", "AC", "AB", "ABC"} *)
Basically I directly translated what you said into code.
Here's a fun way that involves using the 0
/1
as a position, extracting that, then doing the string join:
With[{a = Prepend[ToUpperCase@Alphabet[], ""], sublen = Length@lists[[1]]},
Replace[
StringJoin /@
Partition[
a[[
Flatten[1 + ConstantArray[Range[sublen], Length@lists]*lists]
]],
sublen
],
"" -> "1",
1
]
]
Some tests show that it might be minimally faster than the former