Determine if a string has all unique characters: Difference between revisions
Determine if a string has all unique characters (view source)
Revision as of 10:26, 10 January 2022
, 2 years ago→{{header|R}}: Improved syntax.
ReeceGoding (talk | contribs) m (→{{header|R}}: Syntax highlighting.) |
ReeceGoding (talk | contribs) (→{{header|R}}: Improved syntax.) |
||
Line 3,241:
=={{header|R}}==
Most of this is adapted from [[Determine if a string has all the same characters#R]].
<lang rsplus>isAllUnique <- function(string)
{
strLength <- nchar(string)
if(length(strLength) > 1)
{
#R has a distinction between the length of a string and that of a character vector. It is a common source
Line 3,252:
stop("This task is intended for character vectors with lengths of at most 1.")
}
else if(length(strLength) == 0)
{
cat("Examining a character vector of length 0.",
Line 3,258:
TRUE
}
else if(strLength == 0)
{
cat("Examining a character vector of length 1, containing an empty string.",
Line 3,264:
TRUE
}
else if(strLength == 1)
{
cat("Examining the string", paste0(sQuote(string), ","),
Line 3,276:
"which is of length", paste0(strLength, ":"), "\n")
#strsplit outputs a list. Its first element is the vector of characters that we desire.
characters <- strsplit(string, "")[[1]]
#Our use of match is using R's vector recycling rules. Element i is being checked
#against every other.
indexesOfDuplicates <- sapply(seq_len(strLength), function(i) match(TRUE, characters[i] == characters[-i], nomatch = -1)) + 1
firstDuplicateElementIndex <- indexesOfDuplicates[indexesOfDuplicates != 0][1]
if(is.na(firstDuplicateElementIndex))
{
Line 3,289:
{
cat("It has duplicates. ")
firstDuplicatedCharacter <- characters[firstDuplicateElementIndex]
cat(sQuote(firstDuplicatedCharacter), "is the first duplicated character. It has hex value",
sprintf("0x%X", as.integer(charToRaw(firstDuplicatedCharacter))),
|