Determine if a string has all unique characters: Difference between revisions

Content added Content deleted
No edit summary
Line 3,186: Line 3,186:
This is a duplicate of the character at index 10.
This is a duplicate of the character at index 10.
[1] FALSE</pre>
[1] FALSE</pre>
=={{header|Racket}}==

<lang racket>#lang racket

(define (first-non-unique-element.index seq)
(let/ec ret
(for/fold ((es (hash))) ((e seq) (i (in-naturals)))
(if (hash-has-key? es e) (ret (list e (hash-ref es e) i)) (hash-set es e i)))
#f))

(define (report-if-a-string-has-all-unique-characters str)
(printf "~s (length ~a): ~a~%" str (string-length str)
(match (first-non-unique-element.index str)
[#f "contains all unique characters"]
[(list e i i′) (format "has character '~a' (0x~a) at index ~a (first seen at ~a)"
e (number->string (char->integer e) 16) i′ i)])))

(module+ main
(for-each report-if-a-string-has-all-unique-characters
(list "" "." "abcABC" "XYZ ZYX"
"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ")))
</lang>

{{out}}
<pre>"" (length 0): contains all unique characters
"." (length 1): contains all unique characters
"abcABC" (length 6): contains all unique characters
"XYZ ZYX" (length 7): has character 'Z' (0x5a) at index 4 (first seen at 2)
"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ" (length 36): has character '0' (0x30) at index 24 (first seen at 9)</pre>

=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)