r/projecteuler • u/Nimitz14 • Aug 19 '15
Help with problem 265 (Binary Circles)
So I came across Project Euler and after finding the first problem too easy decided to jump ahead and randomly pick a (for me) hard one out.
Now I've managed to write what I think is a solution by simply brute forcing the problem (solves it for n=3), but it uses too much memory to do n=5...
I'm thinking I could rewrite it and split things up or maybe even switch to C++ (takes quite a while until I get an error atm in Python). But at the same time I can't help but feel there's probably a clever analytical way to solving the problem. Which is basically my question, does one exist and if yes could you give me a hint. :D
Here's my code, with n=5 it seems like already my very first list become way too large. Note I'm new to Python so there are doubtless a lot of things that could be done in a better way, feel free to point out whatever you think deserves a mention.
1
u/devacoen Aug 21 '15 edited Aug 21 '15
This is pretty much what I was getting at, but done pretty much on paper alone. As of iterating vs storing: why not use both? This is Yet Another Project Euler Problem where dynamic programming can change it from impossible to 'I got it in under 600KB!' ;).
EDIT: Maybe not to leave someone interesting hanging, I meant this:
Crappy rationale
We have a limited set of building-blocks 2n and all of them are of same length n.
Putting any two blocks next to each-other can be done in 22n ways if you don't place any conditions.
Putting any two blocks will generate other blocks when you are going from one side to the other. Save them as possible rules.
Use the resulting sub-blocks to eliminate them from possible next steps.
Example
A =
001, B =101, AB =001101.Sub-blocks:
AB1 =
011, AB2 =110So any time you will place them next to each-other you can eliminate from your next selections AB1 and AB2 to make another number.
Where does it break?
Nowhere, as long as you will generate the rules for placing any block to the left of
000and check their respective sub-blocks.Efficiency
Much better then iteration. This look-up table is pretty much the same as precalculating all digit factorials for problem 34, just a bit fancier. You know from the start that there is a finite number of possible placements, why not save them?
How to improve it?
Save results of placing any three blocks and mind the rules for the left side.
If your language can manage that, use bits and Boolean type to hold the data where you can.
Don't waste time on conversions. Blocks in binary work like digits in decimal, placing
0101(dec 5) to the left of0011(dec 3) is going to be smaller then01011010. Use that to build solutions that are already close to minimal instead of doing conversions back and forth.Because you are constantly doing the exact same thing, why not do it in much larger chunks :]?