| Bytes | Lang | Time | Link |
|---|---|---|---|
| 100 | Ruby n | 250521T233754Z | Value In |
| 055 | Perl 5 n | 250521T203123Z | Xcali |
| 058 | APLDyalog Unicode | 250521T190211Z | Mat_rdv |
| 088 | Zsh | 250322T075350Z | roblogic |
| 175 | C clang | 250323T163417Z | ceilingc |
| 091 | Python | 250323T132026Z | Mukundan |
| 031 | 05AB1E | 250324T091140Z | Kevin Cr |
| 073 | J | 250323T053208Z | Jonah |
| 028 | Jelly | 250323T165403Z | Jonathan |
| 112 | JavaScript V8 | 250322T040215Z | Steve Be |
| 045 | Charcoal | 250323T215844Z | Neil |
| 159 | Python 3 3.8 onwards | 250322T194830Z | 3RR0R404 |
| 109 | JavaScript V8 | 250322T052054Z | l4m2 |
| 161 | Maple | 250322T210556Z | dharr |
| 113 | Retina 0.8.2 | 250322T095709Z | Neil |
| 036 | Vyxal | 250322T015105Z | lyxal |
Ruby -n, 100 bytes
gsub(/\d/){b,e=$`,$'
s=(?0..?9).find{(q=b+_1+e)!~/\b0\d/&&eval(q.sub ?=,'==')}
s&&(puts b+s+e;exit)}
Perl 5 -n, 55 bytes
s,\d,map{$_="$`$_$'";/\b0\d/||eval s|=|-|r||say}0..9,ge
Input in a+b=c format. Outputs all valid solutions.
APL(Dyalog Unicode), 58 bytes SBCS
{⊃t/⍨{∧/((k≡⍕¨),+/=2×⊢/)⍎¨k←i⊆⍵}¨t←,⎕D∘.{⍺@⍵⊢w}⍸i←⎕D∊⍨w←⍵}
Explanation
solution ← {
w ← ⍵ ⍝ Save the right argument as w
replace ← {⍺@⍵⊢w} ⍝ Replace symbol of w with index ⍵ with ⍺
d ← w∊⎕D ⍝ Mask for digits in w
t ← , ⎕D ∘.replace ⍸d ⍝ All ways to switch one digit
correct ← { ⍝ Validate a possible answer
k ← d⊆⍵ ⍝ Split expression into numerical parts
numbers ← ⍎¨k ⍝ Decode them into numbers
correctSum ← (+/=2×⊢/)numbers ⍝ The sum of all numbers equals twice the last number ←→ the last number equals the sum of the previous ones
noLeadingZeros ← k ≡ ⍕¨numbers ⍝ Turn each number into strings again and check if nothing changed
∧/noLeadingZeros,correctSum ⍝ Whether all numbers are well formated and the equation is correct
}
answers ← t/⍨correct¨t ⍝ Check all variants and leave only correct ones
⊃answers ⍝ Return the first answer
}
Zsh, 136 92 88 bytes
s=$1+$2==$3
for i ({1..$#s})q=$s&&for j ({0..9})((1$q[i]))&&((q[i]=j,q))&&e=${q/=}
<<<$e
We put the whole equation into string $s then iteratively adjust its copy $q and evaluate it ((q)). If true, print $q in the required format.
C (clang), 204 195 188 183 179 175 bytes
#define S(a,x,y,z)if(g>1){for(i=g=!swprintf(a,99,L"%d+%d=%d\n",x,y,z);s[i]+d[i];)g+=s[i]!=d[i++];
d[99];g;i;f(*s,a,b,c){g=2;S(d,a,b,c)S(s,a,b,a+b)S(s,a,c-a,c)S(s,c-b,b,c)}}}}}
Port of @dharr's implementation.
Python, 97 93 91 bytes
-4 bytes thanks to @Albert.Lang
-2 bytes thanks to @Lucenaposition
f=lambda s,n=1,i=0:(t:=f"{i}+{n-i}={n}")*sum(map(str.find,s+t,t+s),3)or f(s,n+i//n,-~i%-~n)
Unlike the other answers which try to fix the given equation, this answer uses a different approach which is to check against all valid equation till one is found with atmost one differing character.
05AB1E, 33 31 bytes
9ÝISdƶ<δǝ˜.Δ„+=S¡Ð1ìsï1ìQs2ôOË*
I/O as a string equation.
Try it online or verify all test cases.
With less strict I/O rules (-4 bytes):
9ÝISdƶ<δǝ˜ʒð¡Ð1ìsï1ìQs2ôOË*
(.Δ„+=S has been replaced with ʒð)
Input as string with space-delimiter; output as a list of all possible results in that same format.
Try it online or verify all test cases.
Unfortunately, "09" equals 9 in 05AB1E, thus checking if there aren't any leading 0s (with the exception of 0 itself) is a bit long..
Explanation:
9Ý # Push a list in the range [0,9]
ISdƶ< # Get all (0-based) indices of digits in the input-string,
# or -1 for the indices of "+" and "=":
I # Push the input-string
S # Convert it to a list of characters
d # Check for each whether it's a digit
ƶ # Multiply each by its 1-based index
< # Decrease the 1-based indices by 1 to 0-based indices
δ # Apply double vectorized:
ǝ # Insert a digit from [0,9] at the index in the (implicit) input
# (the -1 indices result in the unmodified input)
˜ # Flatten this list of lists
.Δ # Find the first modified equation that's truthy for:
„+=S¡ # Split the string on "+"/"="
Ð # Triplicate this triplet of integers
1ìsï1ìQ # Check that there aren't any integers with leading 0s:
1ì # Prepend a 1 before each integer
s # Swap to get the list of triplets again
ï # Convert each to an integer, remove potential leading 0s
1ì # Prepend a 1 before each of those integers as well
Q # Check that both lists are the same
s # Swap to get the remaining triplet of integers
2ô # Split it into parts of size 2: [[a,b],[c]]
O # Sum each inner list
Ë # Check that both are the same
* # Check that both checks are truthy
# (after which the first valid result is output implicitly)
J, 73 bytes, conforming to output requirements
[:(cut@":;@,.<"+@'=+ ')](g{])`(g=.1 i.~1#.~:&": ::_"+)`[}1+/`(-/)`(-/)\.]
This strict output part could be golfed more but doesn't interest me.
J, 49 bytes, solving the actual problem
(g{])`(g=.1 i.~1#.~:&": ::_"+)`[}1+/`(-/)`(-/)\.]
1+/`(-/)`(-/)\.]Uses outfixes to find what each number in the equation would have to be to be consistent with the other two.1#.~:&": ::_"+For each candidate, counts how many digits differ from the existing number in that position.- Replaces the first one it find with only 1 differing digit with the correct number in that position.
Jelly, 31 30 28 bytes
JœP€jþØDẎv€`Ẉ’œpƊḌD$ƑƊƇVƇṀÞṪ
A monadic Link that accepts the errored equation as list of characters and yields a corrected equation as a list of characters.
Try it online! Or see the test-suite.
How?
JœP€jþØDẎ...ƇVƇṀÞṪ - Link: list of characters, Equation
J € - for each index of {Equation}:
œP - split-drop {Equation} at {that index}
ØD - "0123456789"
þ - table of:
j - join {a split-drop result} with {a digit character}
Ẏ - tighten
Ƈ - keep those for which:
... - (see link below)
Ƈ - keep those for which:
V - evaluate as Jelly code
ṀÞ - sort by maximum (i.e. contains an '=')
Ṫ - tail
v€`Ẉ’œpƊḌD$ƑƊ - link "...", above = NoLeadingZeros?: AlteredEquation
Ɗ - last three links as a monad - f(AlteredEquation):
v€ - evaluate each character of {AlteredEquation} as Jelly code
` - ...with {AlteredEquation} as its argument
Ɗ - last three links as a monad - f(AlteredEquation):
Ẉ - length of each
’ - decrement
œp - spit-drop {EvaluationResult} at truthy indices of {that}
Ƒ - is invariant under?:
ḌD$ - convert from, and then to decimal
JavaScript (V8), 112 bytes (fails some cases)
s=>{for(i=10;i--;)for(p=s.length;p--;)if(+s[p]+1&&eval((z=[...s],z[p]=i,t=z.join``).replace('=','==')))return t}
JavaScript (Node.js), 137 bytes
s=>[...Array(10)].flatMap((_,r)=>[...s].map((d,p)=>s.slice(0,p)+(9-r)+s.slice(p+1))).find(q=>q.match(/\+.+=/)&&eval(q.replace('=','==')))
Takes input in the string form a+b=c.
// loop through replacement digits from 9 to 0
s=>{for(i=10;i--;)
// loop over string backwards (helps avoid leading zero problem)
for(p=s.length;p--;)
// if the current character is a digit (ie, not + or =)
if(+s[p]+1&&
// check the mathematical sum is correct
eval(
// replace current char with the replacement digit - sigh, so verbose
(z=[...s],z[p]=i,t=z.join``)
// turn the mathematical equation into a javascript expression
.replace('=','==')))
// immediately return the new string if true
return t}
I'm not sure it correctly avoids leading zeroes in all cases.
Charcoal, 45 bytes
FχFEθ⭆θ⎇⁻νλμι«≔⪪κ+ηF⪪⊟η=⊞ηλ¿∧⬤η⁼λIIλ⁼I⊟ηΣIηPκ
Try it online! Link is to verbose version of code. Explanation:
Fχ
Loop through all potential replacement digits.
FEθ⭆θ⎇⁻νλμι«
Generate all strings resulting from replacing each character in turn with that digit. (Some of these won't contain the + or the =, but they will never be able to represent a valid equation.)
≔⪪κ+ηF⪪⊟η=⊞ηλ
Split the string into its separate numbers.
¿∧⬤η⁼λIIλ⁼I⊟ηΣIη
If each number is in canonical form and the first two sum to the last, then...
Pκ
Replace any previous output with the found equation.
Python 3 (3.8 onwards), 125 159 bytes
L=len(a:=input()+'+')-1
for i in range(10*L):i<L and a[i-1]in'+='and a[i+1]not in'+='or eval((c:=a[:i%L]+str(i//L)+a[i%L+1:L]).replace(*'=-'))or(d:=c)
print(d)
JavaScript (V8), 109 bytes
s=>{for(i=9;;--i)for(p in s)if(1/s[p-!i]&&!eval((z=[...s],z[p]=i+.5|0,t=z.join``).replace('=','-')))return t}
-2 bytes Steve Bennett
Steve Bennett's idea, much different implement
Cost much for 599+90=599 case
Maple, 161 bytes
proc(a,b,c)
u:=map(z->sprintf("%d+%d=%d",z[]),[[a,b,c],[a,b,a+b],[c-b,b,c],[a,c-a,c]]);
seq(`if`(nops({zip(`-`,[seq(u[1])],[seq(w)])[]})=2,w,NULL),w=u[2..])[1]
end;
The procedure accepts the three integers as arguments.
The three possible corrected sums are a+b=(a+b) (c wrong), (c-b)+b=c (a wrong), or a+(c-a)=c (b wrong). sprintf with format "%d+%d=%d" is used to make each of these into potential output strings. The %d format strips leading zeroes.
So for 135+246=341, u will be ["135+246=341", "135+246=381", "95+246=341", "135+206=341"], where the original has been also created as the first entry. Now each potential output string is converted to a list of characters and the list of characters for the original is subtracted from it, entrywise. For a correct string this gives a list of zeroes except in one place. (Using zip handles the case of different length strings, such as the third in the above list.) Converting to a set gives two distinct entries as the condition for a valid string. The valid ones are collected in a sequence and the first one is output.
Retina 0.8.2, 113 bytes
\d
$&$'¶$`0$'¶$`1$'¶$`2$'¶$`3$'¶$`4$'¶$`5$'¶$`6$'¶$`7$'¶$`8$'¶$`9
A`\b0\d
\d+
$*
1G`^(1*).(1*)=\1\2$
(?<!1)1*
$.&
Try it online! Link includes simplified test cases (code gets slow for more than three digits). Explanation:
\d
$&$'¶$`0$'¶$`1$'¶$`2$'¶$`3$'¶$`4$'¶$`5$'¶$`6$'¶$`7$'¶$`8$'¶$`9
Create copies of the equation but with each possible digit replaced with each possible digit. (There will be multiple copies of the original equation but this doesn't matter.)
A`\b0\d
Delete copies that contain a number with a leading zero.
\d+
$*
Convert to unary.
1G`^(1*).(1*)=\1\2$
Keep only the first correct equation. (Remove the 1 to output all possible equations.)
(?<!1)1*
$.&
Convert to decimal, taking care to convert zero correctly.
Vyxal, 36 bytes
`%+%=%`£ṫ₌∑-NWfṘ¨2?^Ȧ¥$%;'¥?%₌l꘍ṅ*;h
Shortest possible approach? Probably not. Aptly silly? Certainly.
Takes input as [a, b, c] and returns a+b=c.
Explained
`%+%=%`£ṫ₌∑-NWfṘ¨2?^Ȧ¥$%;'¥?%₌l꘍ṅ*;h
`%+%=%`£ # Store the string "%+%=%" in the register. This will be used for string formatting later.
ṫ # Push [a,b] and c to the stack
₌ # Pop both, and push:
∑ # Sum([a,b])
-N # [a, b] - c (vectorising)
Wf # Wrap and flatten so the top of stack is [a + b, a - c, b - c]
Ṙ # Reverse it so it's [b - c, a - c, a + b].
# This is a list of what each value would be if it were to be corrected in the sum.
¨2 ; # To each value, considering index:
?^ # Reorder the stack to be [input, index, value]
Ȧ # input[index] = value. This essentially tries each possible replacement
¥$% # Convert the list to form `_+_=_`
' ; # Keep equations where:
₌ * # Both of these are true:
'¥?% l # The length of the equation equals the input in the format `a+b=c`
¥?% ꘍ṅ # The Levenshtein Distance of the equation and formatted input is 1
# This is a long-winded way of saying "the Levenshtein Distance is 1, and the reason for that is a character change (not an addition or deletion)
h # Get the first remaining candidate
💎
Created with the help of Luminespire.