7

We all know a conspicuous member of our community got hitched recently. As most of us are not in Malta, and weren't able to fly there, I thought of a celebration question. Sort of.

The challenge is golfing a function (Mma only) that finds a prefix free encoding for the letters of two sentences.

The trick is that both sentences (given as parameters) must share the same encoding, with one of them written backwards.

The number of available symbols for the encoding is also a parameter for the function (always less than 10), and the function should attempt to find the shortest encoding for that number of symbols. There is no a-priori guarantee that a solution exists for every parameter set.

As an example, related to our celebration:

we wish you the best

and

sz is the handsomest groom

Inspiration was taken from this question (which does not require a prefix free code), but is a good explanation of what is required.

Happy wedding and golfing!

Shortest code wins!

PS: A bounty of 100, a wedding garter and the party leftovers to the winner

EDIT Clarifications. To be updated as comments and answers arise

  1. No caps. Only lowercase.
  2. No need to encode whitespaces, special chars or punctuation (skip them and consider only lowercase letters)
  3. Your solution should be able to show up results before they are back from the honeymoon.
Dr. belisarius
  • 115,881
  • 13
  • 203
  • 453

1 Answers1

5

Here's my obligatory silly answer:

f[s_, t_, e_] := With[{r = #[[1]] -> #[[2]] & /@ e},
  StringReplace[s, r] != StringReverse[StringReplace[t, r]]]
p[{s_, t_}] := StringMatchQ[s, t ~~ ___] || StringMatchQ[t, s ~~ ___]
p[e_] := Or @@ p /@ Subsets[#[[2]] & /@ e, {2}]
m[s_, t_, k_] := Module[{h = Union @@ Characters /@ {s, t}, e, b = True},
  While[b, e = h /. c_String :> {c, 
   StringJoin[ToString /@ RandomInteger[k - 1, RandomInteger[{1, 10^6}]]]};
   b = p[e] || f[s, t, e]]; e]

Example usage:

m["We wish you the best", "Sz is the handsomest groom", 3]

It will return a list representing the encoding, such as:

{{"W", "012"}, {"e", "2111"}, ...}

Description: Creates a random encoding e of all the characters while it is prefixed p[e] or doesn't encode the strings to be the reverse of each other f[s, t, e].

It'll probably work, but I wouldn't try to run it.

I'm not particularly good at golf, but if you take my handicap into consideration, I'm sure I stand a good chance. ;-)

wxffles
  • 14,246
  • 1
  • 43
  • 75