r/dailyprogrammer • u/jnazario 2 0 • Jan 26 '18
[2018-01-26] Challenge #348 [Hard] Square Sum Chains
Description
For this challenge your task is, given a number N, rearrange the numbers 1 to N so that all adjacent pairs of numbers sum up to square numbers.
There might not actually be a solution. There also might be multiple solution. You are only required to find one, if possible.
For example, the smallest number for which this is possbile is 15:
8 1 15 10 6 3 13 12 4 5 11 14 2 7 9
8 + 1 = 9 = 3^2
1 + 15 = 16 = 4^2
15 + 10 = 25 = 5^2
10 + 6 = 16 = 4^2
...
Example Input
15
8
Example Output
8 1 15 10 6 3 13 12 4 5 11 14 2 7 9
Not possible
Challenge Input
23
24
25
256
Credit
This challenge was suggested by user /u/KeinBaum, many thanks. If you have an idea for a challenge, please share it in /r/dailyprogrammer_ideas and there's a good chance we'll use it.
5
u/skeeto -9 8 Jan 26 '18
C using a brute force search with pruning. I used a bit array to test for square numbers. It can solve all the challenge inputs except 256 instantly. It takes 4.0 seconds to find a solution for 64. I have it working on 256 but I don't expect to see it finish.
3
u/[deleted] Jan 26 '18 edited Jan 28 '18
Ruby
It works, but it's not incredibly fast. It solves the first few challenges about instantly. It takes 2 seconds to solve for 40, 0.5 seconds for 41, almost 5 seconds for 43. I waited over a minute for 50 before giving up. I have no hope that 128 would ever finish.
edit again: I stole the idea given by /u/i3aizey here and sorted both my starting numbers and my available edge set by occurrences (in other words, edges), and now it finishes for all challenge input! It solves 40 in 0.02 seconds now instead of 2 seconds. 256 takes just over 6 seconds to solve. Some things like 128 and 64 still take a very long time to solve (64 takes almost 5 minutes. 128 takes 40 seconds). I'm wondering how I can better optimize it.
Edit: Pre-solution post: Hmm. There's probably a solution here where you pre-scan the numbers to set up a set of valid pairs, and use that set to build a solution. I'll take a crack at this tonight.
Edit: I'm pretty sure I've got it. Build the set of valid pairs, and choose all numbers that appear only once. If these exist, one must be at the beginning or end of the list. If none exist, try with all pairs. If more than two exist, there is no solution. Recursively choose the set of next valid pairs, and try each one, removing pairs in the remaining list containing the just-covered number until no more are left. If all numbers have been used, a valid sequence has been found, and early-exit. This should be far faster than brute-force.
2
u/TheMsDosNerd Jan 26 '18
Backtracking in Python 3.
2
u/[deleted] Jan 27 '18 edited Jan 28 '18
Python
Back Tracking Recursion.
OutPut:
Code:
from pprint import pprint import copy import sys
Here's a #Haskell solution. It's much faster than python.
2
u/zqvt Jan 27 '18 edited Jan 28 '18
Python3, method: generate all square pairs, build a graph (with networkx, I'm lazy), find paths of correct length
2
u/octolanceae Jan 30 '18 edited Jan 30 '18
C++11
Originally used a recursive pre-order DFS, but it took 59 seconds to do 256. Reworked it to use an iterative DFS instead.
256 in 0.233s 500 in 0.805s
Output:
3
u/Godspiral 3 3 Jan 26 '18 edited Jan 26 '18
incomplete but generating smaller substrings, in J
1
u/[deleted] Jan 26 '18 edited Apr 25 '18
Python 3.6
EDIT: Removed recursion. Sped the program up considerably.
1
u/DEN0MINAT0R Jan 27 '18
I remember seeing this on Numberphile recently, and thinking, "Dang, that would be a good /r/DailyProgrammer challenge!"
1
u/Picklegunner Jan 27 '18
Java
Brute force
1
u/bionikspoon Jan 27 '18
python brute force, super slow, but I got it. Won't be putting this code in my portfolio :D.
I modeled this after how I might do it by hand. Got the array combinations -> filtered combinations if their sum was square-able -> draw a node diagram connecting each combination pair -> if each pair was used, find the longest route.
1
u/tomekanco Jan 28 '18 edited Jan 28 '18
Python LKH wrapper, 0.6 second for 256, 9.5 seconds for 1024, 55 s for 2048.
Example
1
u/Scroph 0 0 Jan 28 '18
C++ backtracker. The last input is still running as I'm typing this :
1
u/gabyjunior 1 2 Jan 28 '18 edited Jan 28 '18
C, inspired by /u/i3aizey 's solution, difference is sort by low edge count is done at every node in the search tree.
Instant for n = 256, takes 1.6 secs for n = 40000. Starting from n = 42000, the program halts due to segmentation fault in the qsort function, if I have some time I will try to find a workaround.
EDIT I think that the program halts because of a stack overflow, would need to implement a version using an explicit stack to fix it.
1
u/gabyjunior 1 2 Jan 28 '18
To confirm my solutions were valid, I wrote a quick solution checker in C, takes the order as argument and reads the solution on standard input.
1
u/dzhou8 Jan 29 '18
C++
Basically DFS, each number has certain neighbors it can go to, and you make sure that you haven't already visited that neighbor.
Can do input 64 but not input 256
Output:
Any feedback is welcome!
1
u/popillol Jan 30 '18 edited Jan 31 '18
Go / Golang Playground Link. Uses Hamilton path method that I stole from other submissions. Can solve 256 instantly, but playground times out on values higher than that.
EDIT: Takes 311ms for n=256, 27s for n=512 on my RasPi 3.
1
u/[deleted] Feb 04 '18
Rust
I recreated my algorithm from below in Rust (with some differences for performance and readability). This may not be as fast or clean as it could be, as it's my first real running program in the language, but it appears to perform well-enough. It still takes a very long time to finish for some inputs (as is expected), but there isn't an easy way to compensate for that.
Interestingly, it's far shorter and more readable than my Ruby code. I'm sure this is somehow my fault, as there's no reason that should be the case.
1
u/ComputerChopstick Feb 07 '18
C++
first time trying a challenge, I get stack overflow errors past 24, but I still get the correct solutions before that!
1
u/typhyr Feb 08 '18
In C++.
https://repl.it/@typhirz/Daily-Programmer-348-Hard
My first real stab at C++, I'm usually a Lua person. I brute forced it with pruning by creating a list of all possible pairs (2 unique integers that add to a square, with neither element being above the input). Then I iterate through the list itself similar to a linked list, where the second element is used to find the first element next, recursively. I've watched the numberphile video using graph theory and I want to try it, but this was an attempt a few hours in the making so I'm a bit tuckered out. Definitely cannot do 256. 50 took like 15 seconds or so, so I'm hesitant to try higher than that.
1
u/kaakans 0 0 Feb 10 '18
Erlang
Brute force with backtracking.
0
u/[deleted] Jan 26 '18
[deleted] — view deleted comment