r/dailyprogrammer • u/Cosmologicon 2 3 • Oct 12 '16
[2016-10-12] Challenge #287 [Intermediate] Mathagrams
Description
A mathagram is a puzzle where you have to fill in missing digits (x's) in a formula such that (1) the formula is true, and (2) every digit 1-9 is used exactly once. The formulas have the form:
xxx + xxx = xxx
Write a program that lets you find solutions to mathagram puzzles. You can load the puzzle into your program using whatever format you want. You don't have to parse it as program input, and you don't need to format your output in any particular way. (You can do these things if you want to, of course.)
There are generally multiple possible solutions for a mathagram puzzle. You only need to find any one solution that fits the constraints.
Example problem
1xx + xxx = 468
Example solution
193 + 275 = 468
Challenge problems
xxx + x81 = 9x4
xxx + 5x1 = 86x
xxx + 39x = x75
Bonus 1
Extend your solution so that you can efficiently solve double mathagrams puzzles. In double puzzles, every digit from 1 through 9 is used twice, and the formulas have the form:
xxx + xxx + xxx + xxx = xxx + xxx
Example problem for bonus 1:
xxx + xxx + 5x3 + 123 = xxx + 795
Example solution for bonus 1:
241 + 646 + 583 + 123 = 798 + 795
A solution to the bonus is only valid if it completes in a reasonable amount of time! Solve all of these challenge inputs before posting your code:
xxx + xxx + 23x + 571 = xxx + x82
xxx + xxx + xx7 + 212 = xxx + 889
xxx + xxx + 1x6 + 142 = xxx + 553
Bonus 2
Efficiently solve triple mathagrams puzzles. Every digit from 1 through 9 is used three times, and the formulas have the form:
xxx + xxx + xxx + xxx + xxx = xxx + xxx + xxx + xxx
Example problem and solution for bonus 2:
xxx + xxx + xxx + x29 + 821 = xxx + xxx + 8xx + 867
943 + 541 + 541 + 529 + 821 = 972 + 673 + 863 + 867
Again, your solution must be efficient! Solve all of these challenge inputs before posting your code:
xxx + xxx + xxx + 4x1 + 689 = xxx + xxx + x5x + 957
xxx + xxx + xxx + 64x + 581 = xxx + xxx + xx2 + 623
xxx + xxx + xxx + x81 + 759 = xxx + xxx + 8xx + 462
xxx + xxx + xxx + 6x3 + 299 = xxx + xxx + x8x + 423
xxx + xxx + xxx + 58x + 561 = xxx + xxx + xx7 + 993
EDIT: two more test cases from u/kalmakka:
xxx + xxx + xxx + xxx + xxx = 987 + 944 + 921 + 8xx
987 + 978 + 111 + 222 + 33x = xxx + xxx + xxx + xxx
Thanks to u/jnazario for posting the idea behind today's challenge on r/dailyprogrammer_ideas!
4
u/kalmakka Oct 13 '16
You might want to add some more test cases for bonus 2. Just these two are breaking a lot of the posted solutions:
xxx + xxx + xxx + xxx + xxx = 987 + 944 + 921 + 8xx
987 + 978 + 111 + 222 + 33x = xxx + xxx + xxx + xxx
3
u/fulgen8 Oct 13 '16
Javascript, the method I used is:
xxx + xxx + xxx + x29 + 821 = xxx + xxx + 8xx + 867
is:
(xxx + xxx + xxx + x29 + 821) - (xxx + xxx + 8xx + 867)
2. create an array with the numbers that can be used to fill the x's.
3. make random permutations of that array., for each permutation substitute the x's with the corresponding numbers according to the order of the permutation.
5. give each permutation the score absoluteValue(eval(expression)), if the score is 0, it means that the permutation is a solution. The closer the score is to 0 the closer the solution is.
6. keep the top x% of permutations and discard the rest for the next generation of random permutations.
this method solves all the bonus challenges in around half a second on my computer.
3
u/random_runner Oct 13 '16
Here's my solution in C#
It's a bit... different than most, as it's a completely unmaintainable mess of code. Type conversions, LINQ abuse and overly complex single line statements, it's all there! The end result worked in a suprisingly accetable manner. I then optimised the code to make a second version that ran a lot quicker.
Here's the naive solution:
And here's the optimised version:
Here's the test method I used to calculate how well it worked:
And these where the results:
2
u/Daanvdk 1 0 Oct 13 '16 edited Oct 13 '16
With bonusses in Python 3
Bonus 2 outputs:
Takes about a minute for these so not very efficient but ah well.
2
u/schulzsebastian Oct 13 '16
Python 3
less than 20 secs on my weak laptop
2
u/gabyjunior 1 2 Oct 14 '16 edited Oct 14 '16
C, wanted to make the solution as generic as possible. The program takes 5 arguments on the command line:
Challenge/Bonus 1 solved instantly, Bonus 2 in 2.5 secs including the last test cases added.
Output for bonus 2
1
u/wadehn Oct 13 '16 edited Oct 13 '16
C++: Simple bruteforce. All challenges together in ~1s.
Challenges:
1
u/FlammableMarshmallow Oct 13 '16 edited Oct 13 '16
Haskell
All the bonuses, runs in around 100ms for me; I'd consider this "efficient".
I appreciate any criticisms :)
1
u/marchelzo Oct 13 '16
Ty
I just used a naive brute-force approach. It solves the few triple mathagrams that I tried in seconds, but that's because it gets lucky and finds a solution in the first <1% of the search space.
1
u/JSternum Oct 13 '16
Python! My code seems efficient enough for Bonus 1, but the permutation calculation takes few seconds for Bonus 2. Any feedback would be appreciated.
1
u/benjade Oct 13 '16 edited Oct 13 '16
C
Compile with
gcc -std=c11 -Wall -OFast: it parses and solves 106 iterations of the last one in 1.5s on my machine (Lenovo G500 laptop)
include <stdio.h>
include <string.h>
include <stdlib.h>
include <ctype.h>
define DIG_CNT 3
typedef unsigned char num_t[DIG_CNT]; typedef struct eq *equation_t;
struct eq{ size_t cnt; size_t rhidx; num_t term[]; };
void printEq(equation_t eq){ for(int i=0;i<eq->cnt;i++){ for(int j=0;j<DIG_CNT;j++) putchar(eq->term[i][j]+'0'); if(i==eq->rhidx) putchar('='); else if(i!=eq->cnt-1) putchar('+'); } putchar('\n'); }
define INCR 4
equation_t newEquation(const char *s){ int enc_eq=0; size_t cnt=0,idx=0,sz=0; num_t tmp=malloc(sizeof(num_t)(sz+=INCR)); if(!tmp){ perror("Error allocating memory "); return NULL; } for(size_t digit_pos=0;;s++){ if(!digit_pos || digit_pos>=DIG_CNT) while(isspace(*s)) s++; if(digit_pos>=DIG_CNT){ if(*s=='\0'){cnt++;break;} if(*s!='+' && *s!='='){ if(!enc_eq) fputs("Expected '+' or '='\n",stderr); else fputs("Expected '+'\n",stderr); free(tmp); return NULL; } if(s=='='){ if(!enc_eq){idx=cnt;enc_eq=1;} else fputs("Expected '+'\n",stderr); } if(cnt>=sz){ tmp=realloc(tmp,sizeof(num_t)(sz+=INCR)); if(!tmp){ perror("Error reallocating memory "); return NULL; } } cnt++; digit_pos=0; continue; } if(isdigit(*s) && s>'0') tmp[cnt][digit_pos++]=s-'0'; else if(*s=='x') tmp[cnt][digit_pos++]=0; else{ fputs("Expected digit in {1..9} or 'x'\n",stderr); free(tmp); return NULL; } } if(!enc_eq){ fputs("Bad format: no '='\n",stderr); free(tmp); return NULL; } equation_t res=malloc(sizeof(*res)+sizeof(num_t)*cnt); res->cnt=cnt; res->rhidx=idx; memcpy(res->term,tmp,sizeof(num_t)*cnt); free(tmp); return res; }
int solve_(equation_t eq,int used[],int i,int j,int total){ if(i>=eq->cnt){ if(!j) return !total; return total%10? 0 : solve_(eq,used,0,j-1,total/10); } int k=eq->term[i][j]; if(!k){ for(k=1;k<10;k++) if(used[k]<(eq->cnt/DIG_CNT)){ ++used[k]; eq->term[i][j]=k; if(solve_(eq,used,i+1,j,total+(i<=eq->rhidx?k:-k))) return 1; eq->term[i][j]=0; --used[k]; } return 0; } return solve_(eq,used,i+1,j,total+(i<=eq->rhidx?k:-k) ); }
int solve(equation_t eq){ int used[10]={0}; for(int i=0;i<eq->cnt;i++){ for(int j=0;j<DIG_CNT;j++) if(eq->term[i][j]) used[eq->term[i][j]]++; } return solve_(eq,used,0,DIG_CNT-1,0); }
int main(void){ equation_t eq; eq=newEquation("xxx + xxx + xxx + 58x + 561 = xxx + xxx + xx7 + 993"); if(!eq) return 1; if(solve(eq)) printEq(eq); else puts("No solution"); return 0; }
1
u/superancetre Oct 14 '16
Common Lisp
Using a library called SCREAMER. Quoting the documentation:
It's a library enabling constraint programming. Code is below, no bonus as of now. This gives ALL the solutions for the problem.
And it outputs:
Also note about screamer, it shadow DEFUN so be careful with it. See the documentation linked above.
If you have any suggestions or improvements, i'd more than happy to hear it!
1
u/[deleted] Oct 14 '16 edited Oct 16 '16
Clojure with bonus.
Solves triple mathagrams very very slowly.EDITED: Now completes in a few seconds.1
u/unfallenrain20 Oct 14 '16 edited Oct 15 '16
+/u/CompileBot Python 3
Came in thinking everyone was an idiot for brute forcing the answer, worked on it for a bit, brute forced in probably one of the messiest ways. Might try the bonuses later.
Edit: And as always, i'll would appreciate feedback on either this or my bonus post :)
1
u/abyssalheaven 0 1 Oct 14 '16 edited Oct 14 '16
Python 3 partial bonusesTM - it is capable of solving 3rd order grams but not efficiently
BRUTE FORCE TIME YOLO
mg_inputs.py (only one of the easier brute-force bonus 2 problems shown to prove it works)
mathagram.py
output:
1
u/[deleted] Oct 14 '16 edited Oct 15 '16
PYTHON3
My first intermediate challenge, please be nice.
My solution in almost immediate for all challenges.
1
u/CommanderViral Oct 16 '16
+/u/CompileBot Ruby
It's bruteforce, but I tried to do some selective pruning to cut down on the size of the problem space.
1
u/TheMuffinMan616 Oct 17 '16
Python 3 It solves most inputs. Has a hard time with those cases from kalmakka though. Tried to make it short and readable.
1
u/plus977 Oct 18 '16
Python
My first intermediate solution. Any suggestions are welcome.
1
u/smarzzz Oct 18 '16 edited Oct 18 '16
C
Only did for the base case. Is solves all cases xxx + xxx = xxx in under a tenth of a second (uses recursion)
1
u/mastokley Oct 19 '16
python
1
u/[deleted] Oct 20 '16
C++
1
u/KeoneShyGuy Oct 22 '16 edited Oct 22 '16
Python
My first intermediate. Bonus capable. The first one from /u/kalmakka tanks a really long time, so I'll be skipping it. Looking at other Python coders, I have a lot to learn, but not too bad for a newbie.
+/u/CompileBot Python
1
u/frederic777 Oct 24 '16
Python3 used lots of regex and bruteforced it
1
u/Charredxil Nov 26 '16
Java no bonus, used recursion. This is my first solution on this subreddit!
1
u/[deleted] Dec 17 '16 edited Dec 17 '16
Haskell. No bonuses. Brute Force.
Takes input via three triples. Such as "mathagram (1,x,x) (x,x,x) (4,6,8)". Returns a string such as "173 + 295 = 468".
1
u/TheStoneDawg Dec 28 '16
Javascript Brute Force, no bonus. Reads input from file, and outputs all possible solutions.
1
u/urFriendlyITGuy Jan 06 '17
Python 3. No bonus for now. includes inputs.
1
u/[deleted] Mar 05 '17
Python 3.6, brute force
0
u/[deleted] Oct 13 '16
[deleted] — view deleted comment
0
u/[deleted] Oct 16 '16
[deleted] — view deleted comment