Created
June 16, 2017 12:53
-
-
Save expersso/27f3964528604484c1abe3c3d0f19754 to your computer and use it in GitHub Desktop.
Fundamental theorem of arithmetic to determine anagrams
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Uses Fundamental Theorem of Arithmetic to determine if | |
# two character strings are anagrams of each other. | |
# | |
# Inspired by: | |
# https://www.reddit.com/r/math/comments/6hb0xk/ | |
# clever_algorithm_to_determine_whether_or_not_two/ | |
library(primes) | |
library(purrr) | |
primes <- generate_primes(2, 101) %>% | |
set_names(letters) | |
get_prime <- function(l, p = primes) p[l] | |
prime_rep_prod <- . %>% | |
tolower() %>% | |
strsplit("") %>% | |
.[[1]] %>% | |
keep(~. %in% letters) %>% | |
map_int(get_prime) %>% | |
prod() | |
anagrams <- function(s1, s2) { | |
prime_rep_prod(s1) == prime_rep_prod(s2) | |
} | |
anagrams("abc", "aba") | |
anagrams("Alec Guinness", "Genuine class") | |
anagrams("Jeremy Irons", "Jeremy's iron") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment