Given a set of substrings, such as [ca, ar, car, rd]
, it's possible to create infinitely many strings by concatting them together. Some examples of this for the given substrings could be:
ca
caar
card
rdca
carrd
rdrd
...
One interesting property of this set of substrings is that any string can only be constructed in one way using them; there is no string where it's ambiguous which combination was used. As a counterexample, take the set [foo, bar, obar, fo, baz]
. The string foobar
could either be foo + bar
or fo + obar
.
Task:
Given a set of substrings, which will not contain duplicates, determine if the above property holds; that is, if for any concatenated ordering of any number of the substrings, it is unambiguously possible to determine the original order of the substrings that it was constructed out of.
In place of substrings you may use lists, with any reasonable data type in place of characters. You may also restrict the characters used in the substrings within reason, such as only using lowercase letters. Your chosen representation of the substrings must be able to represent at least a dozen "characters".
You may produce output using any of the following:
- A truthy/falsy value, with truthy representing either ambiguous or unambiguous (your choice)
- Two consistent values representing ambiguous and unambiguous
- One consistent value representing either ambiguous or unambiguous, and any other value representing the other
Test cases:
[ca, ar, car, rd] unambiguous
[foo, bar, obar, fo, baz] ambiguous
[a, b, c] unambiguous
[a, ab] unambiguous
[ab, bc, c] unambiguous
[b, ab, ba] ambiguous
[b, ab, ba, aa] ambiguous
[a, aa] ambiguous
[abc, bcd, cda, dab, abcd] ambiguous
[nn, no, on, oo] unambiguous
[atombomb, at, omb] ambiguous
[abc, dx, yz, ab, cd, xyz] ambiguous
[xxx, xxxxx] ambiguous
[a, ax, xx] unambiguous
[baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac, w, wb, acx, xba, aacy, ybaa, aaacz, zbaaa, aaaacd, d] ambiguous
(Thanks to @Arnauld, @CursorCoercer, and @loopywalt for the last three test cases)
Scoring:
This is code-golf, so shortest answer (in bytes, per language) wins.
[xxx, xxxxx]
. \$\endgroup\$[a, ax, xx]
\$\endgroup\$