r/dailyprogrammer • u/Coder_d00d 1 3 • Dec 31 '14
[2014-12-31] Challenge #195 [Intermediate] Math Dice
Description:
Math Dice is a game where you use dice and number combinations to score. It's a neat way for kids to get mathematical dexterity. In the game, you first roll the 12-sided Target Die to get your target number, then roll the five 6-sided Scoring Dice. Using addition and/or subtraction, combine the Scoring Dice to match the target number. The number of dice you used to achieve the target number is your score for that round. For more information, see the product page for the game: (http://www.thinkfun.com/mathdice)
Input:
You'll be given the dimensions of the dice as NdX where N is the number of dice to roll and X is the size of the dice. In standard Math Dice Jr you have 1d12 and 5d6.
Output:
You should emit the dice you rolled and then the equation with the dice combined. E.g.
9, 1 3 1 3 5
3 + 3 + 5 - 1 - 1 = 9
Challenge Inputs:
1d12 5d6
1d20 10d6
1d100 50d6
Challenge Credit:
Thanks to /u/jnazario for his idea -- posted in /r/dailyprogrammer_ideas
New year:
Happy New Year to everyone!! Welcome to Y2k+15
2
u/threeifbywhiskey 0 1 Dec 31 '14
Is it not the goal, then, to use as many dice as possible to obtain the best score? It seems that should be so, in which case the output for the example ought to be
3+3+5-1-1=9.2
u/hutsboR 3 0 Dec 31 '14 edited Dec 31 '14
Dart, Brute force but does some checks.
Output:
I decided to do a big one, here's a solution for 1d1500 500d50:
2
u/Fuzzygrunt Dec 31 '14
I started this and quickly got flustered: is there an obvious non-brute force way to do this?
It seems related to the Subset Sum Problem, which has a DP solution, that I first thought might work. I can't see how you would back out the actual dice chosen with the extra complication of subtraction, though.
Am I overthinking this? Is it simpler somehow because you're trying to find the largest subset?
7
u/kirsybuu 0 1 Dec 31 '14
Prolog. Decided to try out the clpfd library (in SWI-Prolog).
Challenge Output Examples:
5
u/BayAreaChillin Jan 02 '15
Solved in Java!
4
u/wizao 1 0 Dec 31 '14
I've seen variations of this game where you could use multiplication and division. One variation had a restriction preventing the current value from ever going below zero. In another variation, you scored based on the number of different ways you reached the target number. Yet another variation allowed you to parenthesize any sub expression. It would be interesting to create an extended challenge using some of these ideas.
4
u/Quel Jan 01 '15 edited Jan 01 '15
Solved in R:
With output:
Edit: for fun, I ran it 1000 times and made a histogram of the number of possible solutions for each roll. Not having a solution is by far the most common outcome.
3
u/marchelzo Dec 31 '14
Haskell. Terrible time complexity, but I couldn't think of a more efficient way; plus this could easily be parallelized.
3
u/Tipaa Jan 01 '15
I've avoided using brute force, instead sorting the rolls into descending order and then simply seeing which operation brings me closer to the target. It's not optimal due to being naive and greedy, but it runs in O(n log n) (I think, due to the sort) instead of O( xn ) like brute forcing would. I'm using D.
Example inputs and outputs:
3
u/-Robbie Jan 04 '15
Haskell
Uses mwc-random for generating the dice throws.
2
u/jetRink Dec 31 '14 edited Dec 31 '14
Clojure
I wanted an excuse to use
tree-seq, which is a really fun function, so this program creates lazy tree of possibilities, then walks the tree looking for matches.Each node contains a set of numbers to be added and a set of numbers to be subtracted. In the root node, all the scoring dice values are in the addition set. A child node is created by dropping one of the numbers from the addition set or by moving one of the numbers from the addition set to the subtraction set. To prevent duplication of possibilities, each node also has an protected set of numbers that aren't to be moved or dropped. Nodes whose values are less than the target value and nodes whose protected sets are equal to their addition sets have no children. Keen observers will notice that the use of sets means that duplicate scoring dice will be dropped. This is an oversight on my part and unfortunately it's a bit too much work to fix at this point.
I got a kick out of seeing all the possibilities, so all the matches are printed, sorted by number of scoring dice used in the solution.
Sample output
Code
2
u/unruly_mattress Jan 03 '15 edited Jan 03 '15
Python3 at 3 AM. It's extra readable and uses O(number of dice) memory. Plus I've always wanted to use yield from. Maybe tomorrow I'll try to optimize it (You got 100 1's? Let me consider that as 2**100 possibilities...)
1
u/KeinBaum Jan 01 '15 edited Jan 01 '15
Scala, uses brute force to find a solution with an optimal score.
Sample output:
It's terribly slow. I aborted
1d100 50d6run after half an hour.Edit: Removed some unnecessary code to speed it up but it's still too slow for
1d100 50d6.Edit 2: Cleaned the code
1
u/Meshiest Jan 01 '15
Ruby moderately golfed
Output
Challenge input 1
Challenge input 2
1
u/[deleted] Jan 01 '15 edited Dec 22 '18
deleted 0.3568 What is ^^^this?
1
u/jnazario 2 0 Jan 01 '15
not quite what i was hoping. brute force guessing. F#.
1
u/ddsnowboard Jan 01 '15
Here's my Java. It's brute force, so it's really slow, but it works usually I think. Any criticism is appreciated.
EDIT: The Die class is exactly what you'd expect, and I know you could do it without it, but I was just feeling object-y today.
1
u/Godspiral 3 3 Jan 01 '15
in J,
from total and remaining list build boxes to add and subtract as first pass:
can quickly see remainder is 2, so can grab 4 from minuses and 3 ones from pluses and switch
execute string
95
1
u/ct075 Jan 01 '15 edited Jan 01 '15
mathdice.py
Whew, that took me way too long to write. Initially I wanted to use /u/zahlman 's approach, but while researching solutions for the subset sum problem, it occurred to me that we could just solve this problem directly in mostly the same way (by breaking it down into sub-problems).
Comments and improvements appreciated!
EDIT:
Since I forgot, sample outputs:
1d12 5d6
1d20 10d6
Unfortunately my computer is slow and can't compute 1d50 100d6 super quickly, but I feel like once I get around to making a dp solution it'll get a bit better
EDIT 2:
okay i also didn't make it greedy properly, that's easy enough to fix. i'll do that in the morning it's 4 AM here
EDIT 3:
after some sleep it also dawned on me that this isn't a lot better than brute force
1
u/NoobOfProgramming Jan 01 '15
I freaked out when i saw "Math Dice" at the top of this page because i just spent about two weeks making a math dice program. As you might assume from my username, any help/criticism is appreciated. The function that actually does the solving is at the top of MathDice.cpp. It uses brute force.
Language: messy C++
https://gist.github.com/NoobOfProgramming/cdee5ec55b310627f691
1
u/buckhenderson Jan 01 '15
i just started learning python. probably a better way to do this, but this works, to the best of my knowledge.
edit: wow, so much longer than everyone else's :/
1
u/[deleted] Jan 02 '15 edited May 04 '17
deleted 0.0251 What is ^^^this?
1
u/wizao 1 0 Jan 02 '15 edited Jan 30 '15
Haskell:
This solution uses applicative lists to apply all operations between attempted solutions 'at once'
1
u/_chebastian Jan 02 '15 edited Jan 02 '15
This is my very long answer in C++ havent coded in it for a while and now i sort of remember why. Much of the code is just parsing the input and or doing operations on the rolls. But i kind of like how it turned out. Cant say for sure that it is 100% correct but does give the right answer ( know bug that i dont care if A - B should actually be B - A to not get negative result)
1
u/gloridhel Jan 02 '15
In Java, finds the longest path using brute force. Quite expensive in the worst case.
1
u/[deleted] Jan 02 '15 edited Jan 02 '15
My solution is C#, its very clunky. But does the work
1
u/BearClawWednesda Jan 03 '15
Here's my solution in Python3 using recursion. I'm not completely sure of the complexity, but I do believe that my 'build_toward_target' function, which does the actual solving, might be close to O(n). Please let me know if I'm off. Anyway here's the code:
1
u/5900 Jan 04 '15 edited Jan 04 '15
I think that, as another poster suggested, the subset sum problem reduces to this one. Which I guess makes it NP-hard (disclaimer: I'm new to computational complexity theory).
My solution is a modified version of the naive subset sum algorithm described here: http://www.cs.dartmouth.edu/~ac/Teach/CS105-Winter05/Notes/nanda-scribe-3.pdf (also includes a polynomial time approximation algorithm which could possibly be transformed into a more efficient solution to math dice).
JavaScript:
1
u/apentlander 0 1 Jan 05 '15
Okay this took a bit longer but it's worth it. I used rust in as functional a manner as possible to make a genetic algorithm to solve it. It uses a population equal to the number of scoring dice and a hardcoded population of 100. I might make it more OO to clean it up a bit, as well as allow the number of populations to be entered by the user. I just wanted it to be done and take a break for a bit XD
If you want to test it, enter the code here and comment out 'input' and make a new input var. ex: let input = "1d12 5d6";
1
u/OutputStream Jan 06 '15
Ready to take on the daily challenges! Python 3:
Sample Output:
1
u/[deleted] Jan 08 '15
This was the best I could do. Python 2.7.
1
u/Iwishiknewwhatiknew Jan 11 '15 edited Jan 11 '15
Solution in java: import java.util.; import java.lang.; import java.io.*;
class diceChallenge {
}
Brute force. Runs O((2N) * N) where N is the number of die. Awfully slow. Theoretically can run any input without changing anything.
1
u/theKGS Jan 11 '15
My solver is based on constraint programming. Solver took 17 seconds to solve for 20000 dice. It took 0.15 seconds to solve for 2000 dice.
Language used: C++ Libraries used: GeCode
You specify a model inside the constructor for a class that inherits from another class called Script (belongs to GeCode library). When you launch the program you instantiate this class, then you start the solver. The solver will work on the given model until it has a solution, then it will output that solution. This is the model definition:
The above code defines the problem. I will explain how it works though I will skip the technicalities... :P
First we have an array of all the dice results we can work with. Line 1. This is currently not assigned to any values.
Then we have a matrix of the same width as the above array, but with two rows. Lines 2 and 3. The matrix is basically a "map" to values in the operations array.
It's on line 4 it starts to get interesting. Here we make use of the relation function in GeCode, which says basically that an output from the solver is only a valid solution if the statement inside the function is true! So within this loop we loop through an input vector of dice values and we do three things:
Line 5: We tell Gecode that the value at index i in dice must be equal to the value at index i in the input vector. Basically telling it which values it will work with.
The next part gets more complex without skipping ahead, so I ask you to look at line 9 briefly. Here we tell the solver that the sum of the top row in the operations matrix MINUS the sum of the values in the bottom row of the operations matrix is equal to targetSum. That is: The top row indicates dice we have chose to add, and the bottom are those we chose to subtract.
Now head back to line 6. Here I say that for every column in the matrix, at least one value has to be zero. On the next line (Line 6) I say that the sum of every column in the matrix is equal to the dice value at that index position. That is: I'm basically telling it to "place" the dice in EITHER the top or the bottom row but not both.
Now the model is done.
All we have to do is to tell the solver how to guess values, and where. We tell it to add values to the operations matrix (the second argument of the function). We also tell it INT_VAR_NONE() which basically means "try the first available variable in the array and go on from there". Finally we have INT_VAL_MAX() which tells Gecode to try with the largest value first. If that doesn't work, it will try lower values.
If it wasn't obvious already, I never specified an algorithm or an ORDER for these operations. I just tell Gecode what data I have, what variables I have and how these variables should relate to eachother. Gecode starts crunching and spits out a solution.
1
u/grim-grime Dec 31 '14 edited Dec 31 '14
Brute force O(3N ) solution in Python 3:
0
u/[deleted] Jan 05 '15
Java, object-oriented route. Feedback please since I do have my blindspots.
}
}