Determine if a string has all unique characters: Difference between revisions
Content added Content deleted
(Added Prolog) |
|||
Line 1,555: | Line 1,555: | ||
"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ" (length 36): first duplicate character "0"(#30) at positions 10 and 25 |
"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ" (length 36): first duplicate character "0"(#30) at positions 10 and 25 |
||
</pre> |
</pre> |
||
=={{header|Prolog}}== |
|||
<lang prolog>report_duplicates(S) :- |
|||
duplicates(S, Dups), |
|||
format('For value "~w":~n', S), |
|||
report(Dups), |
|||
nl. |
|||
report(Dups) :- |
|||
maplist(only_one_position, Dups), |
|||
format(' All characters are unique~n'). |
|||
report(Dups) :- |
|||
exclude(only_one_position, Dups, [c(Char,Positions)|_]), |
|||
reverse(Positions, PosInOrder), |
|||
atomic_list_concat(PosInOrder, ', ', PosAsList), |
|||
format(' The character ~w is non unique at ~p~n', [Char, PosAsList]). |
|||
only_one_position(c(_,[_])). |
|||
duplicates(S, Count) :- |
|||
atom_chars(S, Chars), |
|||
char_count(Chars, 0, [], Count). |
|||
char_count([], _, C, C). |
|||
char_count([C|T], Index, Counted, Result) :- |
|||
select(c(C,Positions), Counted, MoreCounted), |
|||
succ(Index, Index1), |
|||
char_count(T, Index1, [c(C,[Index|Positions])|MoreCounted], Result). |
|||
char_count([C|T], Index, Counted, Result) :- |
|||
\+ member(c(C,_), Counted), |
|||
succ(Index, Index1), |
|||
char_count(T, Index1, [c(C,[Index])|Counted], Result). |
|||
test :- report_duplicates(''). |
|||
test :- report_duplicates('.'). |
|||
test :- report_duplicates('abcABC'). |
|||
test :- report_duplicates('XYZ ZYX'). |
|||
test :- report_duplicates('1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ').</lang> |
|||
{{out}} |
|||
<pre> |
|||
?- forall(test, true). |
|||
For value "": |
|||
All characters are unique |
|||
For value ".": |
|||
All characters are unique |
|||
For value "abcABC": |
|||
All characters are unique |
|||
For value "XYZ ZYX": |
|||
The character X is non unique at '0, 6' |
|||
For value "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ": |
|||
The character 0 is non unique at '9, 24' |
|||
true. |
|||
?-</pre> |
|||
=={{header|Python}}== |
=={{header|Python}}== |