What is an anagram? Well, two words are anagrams of each other if they both contain the same letters. For example:
'abba' & 'baab' == true
'abba' & 'bbaa' == true
'abba' & 'abbba' == false
'abba' & 'abca' == false
Write a function that will find all the anagrams of a word from a list. You will be given two inputs a word and an array with words. You should return an array of all the anagrams or an empty array if there are none. For example:
anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']) => ['aabb', 'bbaa']
anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']) => ['carer', 'racer']
anagrams('laser', ['lazing', 'lazy', 'lacer']) => []
For Go: Empty string slice is expected when there are no anagrams found.
rearrange(str::String)::String = collect(str) |> sort |> join
#> rearrange (generic function with 1 method)
"""
words 中与 word 拥有相同字母的元素
"""
#> "words 中与 word 拥有相同字母的元素\n"
function anagrams(word::String, words::Vector{String})::Vector{String}
filter(w -> rearrange(w) == rearrange(word), words)
end
#> anagrams (generic function with 1 method)
anagrams("abba", ["aabb", "abcd", "bbaa", "dada"])
#> 2-element Vector{String}:
#> "aabb"
#> "bbaa"
library(tidyverse)
#' 挑选出 words 中所含字母与 word 相同的元素
<- function(word, words) {
anagrams <- function(w) {
rearrange %>%
w str_split("") %>%
unlist() %>%
sort() %>%
str_c(collapse = "")
}
# 该问题的核心就是一步 filter
%>%
words keep(function(element) rearrange(element) == rearrange(word))
}
anagrams("abba", c("aabb", "abcd", "bbaa", "dada"))
#> [1] "aabb" "bbaa"
function anagrams(word, words) {
= string => string.split('').sort().join('');
rearrange return words.filter(w => rearrange(w) === rearrange(word));
}
console.log(anagrams("abba", ["aabb", "abcd", "bbaa", "dada"]));
#> [ 'aabb', 'bbaa' ]