For this challenge, you must implement Ruby's Abbrev
module in as little code as possible.
Challenge
The input will be whatever your language has as an array (array, list, sequence, etc.) of strings. You may write a function, or you may accept comma-separated words on STDIN.
You must then calculate the set of unambiguous prefixes for those strings. This means you must return a hash (or map, object, etc.) of abbreviations to their original strings.
A "prefix" is a substring of the original string starting at the beginning of the string. For example, "pref" is an prefix of the word "prefix."
An unambiguous prefix is one that can only mean one word. For example, if your input is
car,cat
, thenca
is not an unambiguous prefix because it could mean either "car" or "cat."The exception to this rule is that a word is always a prefix of itself. For example, if you have input such as
car,carpet
,car:car
must be in your output.
You can then return the hash/map/object/etc. from your function (or do the equivalent in your language), or print it out to STDOUT in
key:value
pairs in the form off:foo,fo:foo,...
. (The key-value pairs may also be separated by whitespace if it makes your code shorter.)
Test cases
Input code,golf,going
Output c:code,co:code,cod:code,code:code,gol:golf,golf:golf,goi:going,goin:going,going:going
Input pie
Output p:pie,pi:pie,pie:pie
Input pie,pier,pierre
Output pie:pie,pier:pier,pierr:pierre,pierre:pierre
Input a,dog
Output a:a,d:dog,do:dog,dog:dog
Rules
The input will not contain duplicate elements.
Your output may be in any order; you don't have to sort it.
You may not use a built-in
Abbrev
module/function/thing like Ruby's.This is code-golf, so the shortest code in bytes will win!
key:value\nkey:value\nkey:value
... ? \$\endgroup\$