Skip to content

Commit 7f00733

Browse files
authored
Add an algorithm for checking anagrams (#128)
1 parent 61eed38 commit 7f00733

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

text_manipulation/is.anagram.R

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
is.anagram <- function(word1, word2) {
2+
# Convert words to lowercase
3+
word1 <- tolower(word1)
4+
word2 <- tolower(word2)
5+
6+
# Check if the words have the same length
7+
if (nchar(word1) != nchar(word2)) {
8+
return(FALSE)
9+
}
10+
11+
# Check if the sorted characters of the words are the same
12+
sorted_word1 <- sort(strsplit(word1, "")[[1]])
13+
sorted_word2 <- sort(strsplit(word2, "")[[1]])
14+
15+
if (identical(sorted_word1, sorted_word2)) {
16+
return(TRUE)
17+
} else {
18+
return(FALSE)
19+
}
20+
}
21+
22+
is.anagram(word1 = "rats",word2 = "star")

0 commit comments

Comments
 (0)