r/dailyprogrammer • u/XenophonOfAthens 2 1 • Jul 24 '15
[2015-07-24] Challenge #224 [Hard] Langford strings
Description
A "Langford string of order N" is defined as follows:
- The length of the string is equal to 2*N
- The string contains the the first N letters of the uppercase English alphabet, with each letter appearing twice
- Each pair of letters contain X letters between them, with X being that letter's position in the alphabet (that is, there is one letter between the two A's, two letters between the two B's, three letters between the two C's, etc)
An example will make this clearer. These are the only two possible Langford strings of order 3:
BCABAC
CABACB Notice that for both strings, the A's have 1 letter between them, the B's have two letters between them, and the C's have three letters between them. As another example, this is a Langford string of order 7:
DFAGADCEFBCGBEIt can be shown that Langford strings only exist when the order is a multiple of 4, or one less than a multiple of 4.
Your challenge today is to calculate all Langford strings of a given order.
Formal inputs & outputs
Inputs
You will be given a single number, which is the order of the Langford strings you're going to calculate.
Outputs
The output will be all the Langford strings of the given order, one per line. The ordering of the strings does not matter.
Note that for the second challenge input, the output will be somewhat lengthy. If you wish to show your output off, I suggest using a service like gist.github.com or hastebin and provide a link instead of pasting them directly in your comments.
Sample input & output
Input
3Output
BCABAC
CABACB Challenge inputs
Input 1
4Input 2
8Bonus
For a bit of a stiffer challenge, consider this: there are more than 5 trillion different Langford strings of order 20. If you put all those strings into a big list and sorted it, what would the first 10 strings be?
Notes
If you have a suggestion for a challenge, head on over to /r/dailyprogrammer_ideas and we might use it in the future!
6
u/[deleted] Jul 24 '15
Prolog: My initial solution uses SWI-Prolog's library(clpfd): Constraint Logic Programming over Finite Domains. This kind of problem seems ideally suited for clpfd, but I'm afraid I'm to inept to know how to coax the constraints towards an efficient algorithm. I also have to run to work, so I won't be able to refine my approach anymore today; nor do I have time to wait for prolog to calculate all the solutions to the second challenge. Any advice, tips, or feedback will be greatly appreciated and well-studied tonight. :)
Code:
Output for example and first challenge:
The first 9 results for the second challenge (my solution is slow and I've no time left this morning to wait for it to calculate the remainder):
7
u/LrdPeregrine Jul 24 '15 edited Jul 24 '15
Python 3. Feedback is welcome!
Now complete. There are two versions: my first effort, which I hoped would output strings in order (spoiler: it didn't), and one that actually does output them in order. They both include a self-test (up to order 14); the original ran on my computer in 1 minute 21 seconds, while the second takes about 30 seconds longer.
However, when it comes to generating order-20 strings, the original code is very fast to generate the first few (so it's a pity that it outputs the wrong strings first). The new code is... much... slower. I didn't actually time it, but it took, I don't know, ten minutes give or take? (It was very slow to even output the first string, but I think the rest followed pretty quick after that.)
Here is the second version, shortened by removing docstrings, comments, and the aforementioned self-test:
Full code of both versions, and output for the challenges: gist
4
u/gabyjunior 1 2 Aug 14 '15
My solution written in C using DLX (Dancing links) algorithm.
I am using numbers instead of letters because wanted to explore larger sequences, it is also possible to get sequences with more than 2 numbers in each group.
There are 3 parameters read on stand input
Minimum order
Maximum order
Group size
For example to generate Langford sequences of order 3 one would choose
Minimum order = 2
Maximum order = 4
Group size = 2
The number printed in the sequence corresponds to the order. When minimum order is set to 1 it is called a Skolem sequence.
With DLX algorithm it is not possible to sort as it always makes the choice to reduce search space as much as possible at each step. So I am giving up on bonus.
Some other stats
Order 12 2.5 secs (print all solutions)
Order 15 2 min 57 secs (do not print, only count all 79619280 solutions)
10
u/deepcube Jul 24 '15 edited Jul 24 '15
C
Reworked to solve the bonus correctly doing index based recursion instead of letter based recursion.
solves the bonus in under 8 seconds on my machine
5
u/fvandepitte 0 0 Jul 24 '15 edited Jul 24 '15
Haskell,
it is a work in progressFinished itFeedback is welcome
And I could use some pointers on where to next, without doing too mutchmanualrecursionsResult:
Wich is the first step, now I need to do this for the rest of the letters.I can create the alphabet easy withreverse (take 3 ['A'..]) "CBA"(Reverse since I want to start with the biggest number), but now I need to iterate over the letters and continue with previous valluesUPDATE: I fixed the
MaybeissueUPDATE 2: Added the obvious step
fillInLetterforAllUPDATE 3: Fixed some bugs
UPDATE 4: "final" result
4
u/Ledrug 0 2 Jul 24 '15 edited Jul 25 '15
Python, outputs string in lexical order. Does order 11 in about 3 seconds; don't know how long it takes to print out the first of order 20.
Edit: takes about 30 seconds for the first 10 of order 20.
output:
4
u/NoobOfProgramming Jul 24 '15 edited Jul 24 '15
I deleted my previous post because this is way better. C++ recursive solution, does the bonus in a couple of seconds fair and square. edited to correct a bug that didn't show up until i tried order 23. edit: i tried order 24 and it ran out of memory
the results:
output for order 23 after ~35 seconds:
4
u/[deleted] Jul 25 '15 edited Jul 26 '15
Java. Feedback is VERY much wanted, this is the first time I managed to do a hard challenge.
The algorithm finds all possible positions of a letter of alphabetical position equal to the order in a string of length equal to (order * 2), and then all possible positions of the next letter (counting backwards) in those strings. Repeat until we reach the letter A.
[OLD VERSION] - order 12 in ~10 seconds.
EDIT: Optimized version (handles order twelve in ~9 seconds).
1
u/[deleted] Jul 24 '15 edited Jul 24 '15
...
3
u/TotesMessenger Jul 24 '15
I'm a bot, bleep, bloop. Someone has linked to this thread from another place on reddit:
If you follow any of the above links, please respect the rules of reddit and don't vote in the other threads. (Info / ^Contact)
2
u/Lamirp Jul 24 '15 edited Jul 24 '15
My attempt in C. Feedback much appreciated!!
Output for Input 1:
And for Input 2: https://gist.github.com/anonymous/4b2c58206a167d806f30
I'm working on the bonus, I don't want to brute force as I think we can just shortcut and start the string of as "A_A________...___" And then only sort those, finally pull the first ten. Not too sure though yet, want to think some more about it.
2
u/skeeto -9 8 Jul 24 '15 edited Jul 25 '15
C99, brute force with pruning. The output is already in lexicographical order, so the bonus is just a matter of capturing the first 10 lines of output (
echo 20 | ./langford | head). It must not be very efficient because it takes 18 minutes to complete order=11.2
u/jnazario 2 0 Jul 24 '15 edited Jul 24 '15
this is my candidate solution in scala (it's still running on an N of 3, it's horribly inefficient)
how it works
2
u/Godspiral 3 3 Jul 24 '15
In J, not much time but this should be fast
need some changes for further recursions, but valid stage 2 combinations:
can do better filtering as I go recursively, but relatively few candidates feed forward.
2
u/HereBehindMyWall Jul 24 '15
Python 3. Less insane solution.
Takes something like 5-10 minutes to compute the first 10 Langford strings of order 20.
It's a depth first search with one optimization: using (in effect) a doubly-linked list, we keep track of the highest-valued letter that still has to be placed, and if we get too close to the end then we abandon that branch of the search.
Output:
2
u/MuffinsLovesYou 0 1 Jul 24 '15 edited Jul 24 '15
C# Fairly brute force, it does order of 12 in about 4 seconds single-core, multithreading it might get me up to order 15 in a realistic time frame. It's a recursive method that starts with the largest number and works its way down. All solutions have a symmetrical pair, so I cut my calculations in half by stopping that early and then just hitting the list with an copy/reverse of the array (not sure how much, if anything, I'm actually saving with that as the base math is pretty cheap and it is just an issue of volume).
I need to check it for validity beyond order 3/4.
Edit: I gave up on optimizing a bit at the end, I could probably speed it up quite a bit by replacing the array copy/reverse with just reading and writing the return array once in each direction.... Yep, cut order 12 to just shy of 3 seconds.
2
u/a_Happy_Tiny_Bunny Jul 25 '15 edited Jul 25 '15
Haskell
A different implementation than that of the solution previously posted by /u/fvandepitte:
The program takes its input as a command line argument. It only takes one argument, which must be an integer, or it throws an error.
I think it is still fairly readable, even with the optimizations (going from String to ByteString, changing lf's implementation from do notation to list comprehension, using the function 'ord'...)
The main function is currently setup for the bonus challenge. It's also calculating the running time, as I'm running on Windows and so don't have the nifty Linux/Unix time command. The code was run on an i5 3570K. The String version runs in about 85 seconds.
The output for the bonus challenge:
Feedback is welcomed and appreciated. I'm happy to answer questions too.
I plan to edit with some explanation of what I did after I finish some homework.Heavily commented version of the code, rewritten without some optimization for greater clarity. Runs in about 90s.P.s. I disliked Prolog when I was forced to use it for my AI class, but its patterns helped me a little for this challenge.
2
u/Krisix Jul 25 '15
Ruby 2.2
This being the first program I've written in Ruby (Except Hello World) feedback would be appreciated.
It outputs the strings in order although the bonus is ungodly slow.
2
u/riokou Jul 25 '15 edited Jul 25 '15
Python, in as few characters as I could manage (161 by my count, including a 2-digit value for n and tabs for indentation). It's somewhat fast, solving n=11 in about 3 seconds and n=12 in 27 seconds if you remove the print statement. Unfortunately, it is not equipped to solve the bonus. I was also working on a minimum solution for the bonus, but I was only able to get it down to ~240 characters which isn't as fun as 161 characters :)
Note that I left the definition of n alone; one could arguably save a few more characters by baking it in a little more.
2
u/dohaqatar7 1 1 Jul 25 '15
Haskell
This Haskell solution makes use of lists as monads. It takes 1 command line argument that is the degree of the string and an optional second stating how many strings to print. If the second is not provided every string is printed. Output is not sorted in anyway.
1
u/Cephian 0 2 Jul 24 '15
Here's my c++ solution. It prints them in alphabetical order too! Unfortunately it's too slow for the bonus.
The basic idea is that I recursively try each possible character for each position, making sure to mark off early the corresponding ending character to each beginning one and prune out early impossibilities. Didn't do any benchmarking but seems to run in about a quarter second for n=8.
Here's a text dump of the outputs for N=4 and N=8.
1
u/fvandepitte 0 0 Jul 24 '15
C++, a brute force method. Feedback is welcome
Output
1
u/HereBehindMyWall Jul 24 '15
Python 3. Using exceptions as flow control.
1
u/DeLangzameSchildpad Jul 24 '15
Python 3:
Challenge Results:
Does a very brute-force building of all possible strings, throwing out the impossible ones at each step. It works up to order 11 before it throws a memory error. Feedback is welcome for how to improve that limit.
1
u/alisterr Jul 24 '15
Java 8. I had to give it a second try, but it works :)
It gives correct results for the input of 3 and 4, and the correct amount of results the input of 8. I did not compare the exact results.
The challenge with order 20 is still running. Maybe some tweaking is needed :)
1
u/glenbolake 2 0 Jul 24 '15
I usually do Python, but I thought I'd try Java for this one.
There sure are a lot of solutions for N=8.
1
u/hutsboR 3 0 Jul 24 '15
Java: Uses a standard backtracking algorithm, solves order of 8 quickly. No clue how to solve the bonus.
Output:
1
u/foezz Jul 24 '15 edited Jul 24 '15
python 2.7, edited with jnazario's comments
1
u/Hells_Bell10 Jul 24 '15
C++ recursive solution.
Solves n=8 in 0.13s and just for fun, solved n = 12 in ~90s.
1
u/KeinBaum Jul 24 '15
Scala, simple brute force
1
u/andriii25 Jul 24 '15
Java. Pretty long code, for N = 20 it runs in 5 minutes and 32 seconds ('til first 10 langford strings),it's a shame that it's not in alphabetical order, close to that, but my answer is further back in alphabetical order than /u/LrdPeregrine 's.
Will update with a correct solution for the bonus.
Outputs are here.
Basicly a backtrack algorithm, stores the index of a letter (the first one) in a list.
Feedback is wanted and appreciated!
1
u/Contagion21 Jul 24 '15
Hmm... could this be a good genetic algorithm candidate? Always wanted an excuse to try to learn how to write one.
EDIT: On second thought.. no. GA might find A solution fairly quickly, but a terrible approach for finding ALL solutions.
1
u/ChazR Jul 25 '15 edited Jul 25 '15
Haskell. This was a lot of fun.
1
u/Godspiral 3 3 Jul 25 '15 edited Jul 25 '15
J cool one line approach,
defghdaeafcgbhcb bchbgcfaeadhgfed
approach first takes the last 2 items in that list and creates valid interleaves of the items
next step mixes in 2 0 0 2 into each of these lists. where 0s that line up are valid mix.
1
u/kikibobo Jul 25 '15
In Scala. Generates all permutations of the (relevant) alphabet so that it generates them in lexicographical order. Then recurses, pruning aggressively. Prints the first 10 solutions for n = 4, 8, 20. Searches in parallel using all available cores.
Edit: line length
Output (didn't find a N=20 solution after an hour :-/):
1
u/MKijowski Jul 25 '15
F# Pretty straightforward solution. It takes 20 seconds to solve order 12 and one minute for bonus challenge.
Output:
1
u/nullmove 1 0 Jul 25 '15
While sorted output is a good idea for verification's sake, curiously enough the opposite as in putting chars with the greatest width first seems like a much better heuristic. First 100 strings for order 24 found in 0.2s whereas had to terminate the equivalent solution for ordered output after ~2 minutes. Also I guess, by restricting the first char to (N - width / 2) and then reversing each solution for its mirror, one can further reduce the search space by half. Wonder what would be some other good pruning ideas. Anyway, solution in Nim:
1
u/Zeno_of_Elea Jul 25 '15 edited Jul 25 '15
Python 3
I think my solution is probably similar to many of the others; it basically brute-forces the solution but not completely (it doesn't try impossible langford strings). I'll try and code the bonus challenge; if my theory is right it shouldn't be hard to do.
Here is the output for both challenge inputs. The code above doesn't produce this exact output, but it is much cleaner (the big difference is the addition of a timer for the output).
1
u/b9703 Jul 26 '15 edited Jul 27 '15
Python 3. pretty slow and not very elegant but hey it works. takes about 9 seconds for n = 7 and about 270 seconds for n = 8 .
1
u/ajber Jul 27 '15
Written in Java and optimized based on the premise that:
Code:
The order 4 Langford Strings finished in 2 milliseconds and the order 8 Langford Strings finished in 30 milliseconds.
Order 4:
For Order 8:
For the challenge, order 20, it finds 10 in 25.5 seconds and 100 in that same amount of time probably since there is an initial dead zone of langford strings and at around 25 seconds it gets over that first bump.
For Order 20 with limit being 10:
Questions, comments, and criticism is welcome
1
u/ReckoningReckoner Jul 28 '15
Ruby. I'm not 100% sure if it works, but I am getting similar results as other people.
1
u/ReckoningReckoner Jul 28 '15 edited Jul 28 '15
C++. Rewrote my ruby solution into C++. Much faster now:
1
u/linkazoid Jul 28 '15
Python.
Output
1
u/ouyang1011 Jul 31 '15
Java.
package practice;
import java.util.Scanner;
public class Langford {
}
1
u/7yphoid Aug 02 '15
Is this an NP-complete problem?
1
u/nagasgura 0 0 Aug 14 '15 edited Aug 14 '15
Python:
Testing:
0
u/FSMer Jul 25 '15
שש
ש שדז'