r/dailyprogrammer • u/Blackshell 2 0 • Nov 06 '15
[2015-11-06] Challenge #239 [Hard] An Encoding of Threes
Are you ready to take the Game of Threes to the next level?
Background
As it turns out, if we chain the steps of a Threes solution into a sequence (ignoring their signs), the sequence becomes a ternary representation of numeric data. In other words, we can use base 3 (instead of decimal or binary) to store numbers!
For example, if we were to use ASCII character values as our "data", then we could encode the letter a into a Threes solution like this:
ais97in decimal97in base 3 (ternary) is10121- We can "reverse" the Threes process in order to come up with a number that has a threes solution containing the numbers
[1, 0, 1, 2, 1]in that order.- Start at 1 (where Threes ends)
1 * 3 + 1=44 * 3 - 2=1010 * 3 - 1=2929 * 3 + 0=8787 * 3 + 1=262
- A "Threes-encoded"
ais then the number262.
Note that at a couple steps, we subtracted instead of adding. Since the sign in the solution is not significant, additions can be flipped for subtractions to achieve different results. That means that a could actually be encoded as: 260, 278, 386, 388, or others. For example, 260 could be decoded like this:
260 1
87 0
29 1
10 2
4 -1
1
That still results in 10121, in base 10 is 97, or ASCII a. However, there is now the possibility to go wrong in the decoding!
262 2
88 2
30 0
10 -1
3 0
1
1
That decoding resulted in 22010, which is base 10 219, or ASCII Û. Oops!
The Problem
Now that we have a way to encode/decode characters into "Threes", let's encode words:
three->[11022, 10212, 11020, 10202, 10202](ternary)- Concatenate them all into:
1102210212110201020210202 - Encode that string by working Threes backwards so it becomes:
1343814725227
Where is this all going? Your mission for this challenge is to take a Threes-encoded English word as input, and output the original, un-encoded word. You may want to use a dictionary file containing a list of valid words. See: enable1.txt. Since enable1.txt is all lowercase, you should make your word checking case-insensitive (e.g. "ExtrapOlation" is a word). Just remember that encoded upper and lower case letters have very different codes.
Note: Some encoded numbers have multiple possible word solutions. If you get a slightly different word, that's okay. Alternatively, you could make your solution output all possible word solutions!
Sample Input 1
1343814725227
Sample Output 1
three
Sample Input 2
66364005622431677379166556
Sample Output 2
Programming
Challenge Input
1023141284209081472421723187973153755941662449
Bonus Points
Solve the problem without using a words file (like "enable1.txt"). Note: This may or may not be possible; I'm not actually sure. Update: The bonus is actually impossible. As others and I remarked, there are just too many possible solutions/combinations. A dictionary or other language guide is necessary.
Fluff
This concludes the Game of Threes series. Since this was my (/u/Blackshell's) first series of posted problems, I would really appreciate feedback on how it went. Thanks for playing!
3
u/Blackshell 2 0 Nov 06 '15 edited Nov 06 '15
Finally finished my own solution. That was much harder than I thought. Hosted here because it's way too long to put in a comment: https://github.com/fsufitch/dailyprogrammer/blob/master/239_hard/decode_threes.go
I also wrote a small test script that verifies that, by following the ternary bits in the output word, you can "play" Threes and reduce the input to 1. It takes the input number on the first standard input line, followed by your solutions, one per line.
Some thoughts on how it went:
My approach: I traversed the tree of all possible solutions, using a trie based on enable1.txt to stop traversal of branches that were clearly not words. At each step I maintained 3 things: my current remaining number to be decoded (decoding ends when it reaches 1); the characters I've found so far; a buffer of ternary bits that are waiting to get turned into characters. Then I branch, looking to either add to the buffer, or convert the buffer into a character if possible.
This worked well enough, but it was sorta hellish to debug. Speaking of debugging...
Zero-padded numbers: Suppose I was solving for the word "MOLLUSC". I just converted the buffer into "S" (so it is now empty), and my remaining number is 384. Traversing down the tree, i end up with the bits [0, 1, 1, 1, 2], or the character "C". That's all fine and good, right? No! C translates into [1, 1, 1, 2]. The leading zero gets lost in translation, and can cause trouble. I had to make sure my buffers cannot start with a leading zero.
"Solution found" conditions: It's enough to check that the current number is 1, and my word so far is actually a word, right? No! I also needed to check that the bit buffer was empty. If not, then I was possibly ignoring up to almost an entire character.
Big integers: It turns out that Go's
math/biglibrary is nice, but weird. Why are all the math operations in-place but still require assignment?! Why is there no good way to copy a big Int (other than adding it to 0)?!Was this the right approach? Maybe. It feels like the right approach, but it also feels unnecessarily complicated. On the other hand, it was easily modified to exclude the trie and instead just use nice text ASCII characters, in order to solve the bonus. As it turns out, the bonus is impossible. Even the first small input (the "three" one) has 95569 possible solutions. Without some further language guidance, there is no way to find any solution to this problem.
9
u/adrian17 1 4 Nov 06 '15 edited Nov 06 '15
Python. Casual recursion with impossible words pruning done with a trie. Since I've already used a hand-written trie in C++ a couple of times, I decided it's time to get lazy and use some external library. marisa-trie seems quite efficient (it uses a C core implementation) and has some neat features like saving the generated trie to a file, so you don't have to regenerate it each time.
Solves inputs in 0.23s, most of the time is generating the trie. If I load it from the file, the time is ~0.03s (2/3 of which is Python warmup).
2
u/zengargoyle Nov 06 '15
Is this a typo?
three -> [10222, 10212, 11020, 10202, 10202] (ternary)
I get
'three'.comb».ord».base(3)
(11022 10212 11020 10202 10202)
1
u/wizao 1 0 Nov 06 '15 edited Nov 06 '15
I believe
4 * 3 - 2 = 11should be4 * 3 - 2 = 10giving262in the example for "three-encoding"97instead of2891
u/casualfrog Nov 06 '15
4 * 3 - 2 is not 11
3
u/casualfrog Nov 06 '15 edited Nov 07 '15
JavaScript (feedback welcome):
Edit: Now uses javascript-bignum to parse the large input. Handles upper- and lowercase letters, prunes tree as early as possible.
Output:
3
u/wizao 1 0 Nov 07 '15
Haskell: extending from my previous solution:
2
u/smls Nov 06 '15 edited Nov 07 '15
I don't think the bonus (solving it without a dictionary) is possible. Here are all the solutions consisting only of lower-case
a-z, that I get for Sample Input 1:With upper-case letters etc. allowed as well, it only gets worse. I don't think there's a feasible heuristic to pick the word
threeout of all of those.Update: The above word list includes a bunch of false positives. These are actually the only possibly ASCII letter solutions for Sample Input 1, even if uppercase letters are allowed:
2
u/smls Nov 07 '15 edited Nov 07 '15
Perl 6 - recursive, memoized
Based on the Python solution by adrian17, except that I did not have a suitably scalable trie implementation at hand, so I attempted to get by without one.
Recursion paths that fail to produce pure ASCII letter words are pruned, but that still leaves lots of iterations - e.g. even for the smallest sample input, the function is called 27203 times.
The
is cachedsubroutine trait brings the number of times the function body is evaluated, down to 782 for that input - but the total number of iterations including cache look-ups, is still relatively high. It's faster than without caching, but still slow... :(PS: In order to make caching work, I had to turn it into a side-effect free recursive function that assembles the results from the bottom up.
1
u/Godspiral 3 3 Nov 06 '15
In J, easy alternative problem of making a deterministic encode because I just don't understand this,
10222 is the letter k, btw
1480997213812
1 2 0 2 0 1 2 0 2 0 1 0 2 0 1 1 2 1 2 0 1 2 2 2 0 1
which suggests there is an even easier encode of reverse input and append 1
1480997213812
in J, you can convert from a base with negative indexes, so all of the original "permutations" of encodings can (I think) be obtained by flipping signs of indexes in the simple encoding
262
For the shortest challenge inputs there are 220 permutations, but if there is an assumption of 5 length base 3 encodings of each letter (valid if all lowercase or within ascii 81 to 243) then,
or as ascii, 184 193 142 166 107
shows the letters in reverse order, where last is first letter unchanged, and others are out of range (97-122) and need transformations.
It looks like a letter by letter approach would work. transformation to alternative negative index base representations is done by subtracting 3 from one index, and adding 1 to its left neighbour. Still manageable on 5 digit groups as long as you leave the leftmost digit unmodified.
Still lots of false hits within transformation space. for instance 'h' result 2 0 0 1 1 transforms to: 2 1 _2 _1 _2, and random flipping finds 'h'
h
Still seems too hard, since I didn't fully understand the last challenge.
1
u/FelixMaxwell 1 0 Nov 07 '15
C++ 11
I didn't feel like using a trie, so most of the time taken is in loading all the word permutations into a hash map for spell checking (based on a submission to the red squiggles challenge a month ago)
The solution exploits the fact that all characters have an encoding either 4 or 5 digits long. It finds all paths from the current point that are 4 or 5 digits in length and converts them to their character representations. Then it checks if the current string is a part of any word in the file, and if it isn't it bails out.
As the C++ max int is far lower than even second input, I've used the InfInt header to deal with numbers of arbitrary size.
The solution runs in a few seconds for the challenge input. You can find it here.
1
u/mantisbenji Nov 07 '15
Extremely slow Haskell solution. The "ZeroSumGameOfThrees" module is just last challenge's solution without a main function.
Runs within reasonable time for simple inputs, such as 1343814725227, but is extremely slow for any of the larger inputs.
This was a very good series of challenges. Even though for both this and the intermediate solution my code is too inefficient, it was great seeing the solutions people come up with and the gradual nature in which the elements of the underlying concept were introduced.
1
u/[deleted] Nov 07 '15
PROLOG
Works for small words, like "a", but takes too long for "three" because of sheer amount of sublists I can make out of result list.
1
u/Godspiral 3 3 Nov 07 '15 edited Nov 07 '15
In J, basically /u/adrian17 's solution, except not looking up dictionary yet.
fairly fast by filtering every 5 jumps (so assumes lower case)
With filter for remaining digit = 1 too.
with deterministic encoding, first word result is original encoding