If you've read the book Contact by Carl Sagan, this challenge may seem familiar to you.
Given an input of a set of mathematical equations consisting of a number, an unknown operator, another number, and a result, deduce which operators represent addition, subtraction, multiplication, or division.
Each input equation will always consist of
- a non-negative integer
- one of the letters
A
,B
,C
, orD
- another non-negative integer
- the character
=
- a final non-negative integer
concatenated together. For example, a possible input is 1A2=3
, from which you
can deduce that A
represents addition. Each of the integers will satisfy 0 ≤ x ≤ 1,000
.
However, it's not always as simple as that. It is possible for there to be ambiguity between:
5A0=5
: addition/subtraction1A1=1
: multiplication/division0A5=0
: multiplication/division2A2=4
: addition/multiplication4A2=2
: subtraction/division0A0=0
: addition/subtraction/multiplication
and so on. The challenge is to use this ability to narrow down choices, combined with process of elimination, to figure out what operator each letter represents. (There will always be at least one input equation, and it will always be possible to unambiguously, uniquely match each letter used in the input with a single operator.)
For example, let's say the input is the following equations:
0A0=0
: this narrows A down to addition, subtraction, or multiplication (can't divide by 0).10B0=10
: B has to be either addition or subtraction.5C5=10
: C is obviously addition, which makes B subtraction, which makes A multiplication.
Therefore, the output for these input equations should match A
with *
, B
with -
, and C
with +
.
Input may be given as either a single whitespace-/comma-delimited string or
an array of strings, each representing one equation. Output may be either a
single string ("A*B-C+"
), an array (["A*", "B-", "C+"]
), or a dictionary / dict-like 2D array ({"A": "*", ...}
or [["A", "*"], ...]
).
You may assume that a number will never be divided by another number it isn't divisible by (so, you don't need to worry about whether division should be floating point or truncated).
Since this is code-golf, the shortest code in bytes wins.
Test cases:
In Out
-------------------------------
0A0=0 10B0=10 5C5=10 A*B-C+
100D100=10000 D*
4A2=2 4B2=2 0A0=0 A-B/
15A0=15 4B2=2 2C2=0 A+B/C-
1A1=1 0A0=0 A*
0A0=0 2A2=4 5B0=5 2B2=4 A*B+
2A2=4 0C0=0 5B0=5 5A0=5 A+B-C*
0A1000=0 4A2=2 A/