Determine if a string has all unique characters: Difference between revisions
Content added Content deleted
No edit summary |
(Add OCaml) |
||
Line 2,691: | Line 2,691: | ||
The string contains duplicate characters. |
The string contains duplicate characters. |
||
Character 🐡 (1f421) is present at positions 3 and 8.</pre> |
Character 🐡 (1f421) is present at positions 3 and 8.</pre> |
||
=={{header|OCaml}}== |
|||
Using a map to store characters we've met (as keys) and their first position (as indexes). |
|||
<lang ocaml>module CMap = Map.Make(struct |
|||
type t = char |
|||
let compare = compare |
|||
end) |
|||
(** Add index as argument to string.fold_left *) |
|||
let string_fold_left_i f acc str = |
|||
snd (String.fold_left |
|||
(fun (index, acc) char -> (index+1, f acc index char)) |
|||
(0, acc) str) |
|||
exception Found of int * int * char |
|||
let has_duplicates str = |
|||
try let _ = string_fold_left_i |
|||
(fun map index char -> |
|||
match CMap.find_opt char map with |
|||
| None -> CMap.add char index map |
|||
| Some i -> raise (Found (i,index,char))) |
|||
CMap.empty str |
|||
in Ok () |
|||
with Found (i,j,c) -> Error (i,j,c) |
|||
let printer str = |
|||
Format.printf "%S (len %d) : " str (String.length str); |
|||
match has_duplicates str with |
|||
| Ok () -> Format.printf "No duplicates.\n" |
|||
| Error (i,j,c) -> Format.printf "Duplicate '%c' (%#x) at %d and %d\n" c (int_of_char c) i j |
|||
let () = |
|||
printer ""; |
|||
printer "."; |
|||
printer "abcABC"; |
|||
printer "XYZ ZYX"; |
|||
printer "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"</lang> |
|||
{{out}} |
|||
<pre>"" (len 0) : No duplicates. |
|||
"." (len 1) : No duplicates. |
|||
"abcABC" (len 6) : No duplicates. |
|||
"XYZ ZYX" (len 7) : Duplicate 'Z' (0x5a) at 2 and 4 |
|||
"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ" (len 36) : Duplicate '0' (0x30) at 9 and 24</pre> |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |