Last active
June 25, 2020 06:19
-
-
Save pythonhacker/ef837efa598be32f5bdb9d007de3f817 to your computer and use it in GitHub Desktop.
@fermatslibrary - Anagram finder implemented using Prime Numbers in Rust
This file contains 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
// Courtesy: @Fermatslibrary | |
// Reference: https://twitter.com/fermatslibrary/status/1275066521450975234 | |
// Copyright: Anand B Pillai @skeptichacker | |
// LICENSE: MIT | |
use std::env; | |
use std::collections::HashMap; | |
pub fn is_prime(n: u64) -> bool { | |
if n <= 1 { | |
return false; | |
} | |
let mut flag = true; | |
let mut item: u64 = 2; | |
loop { | |
if item*item > n { break; } | |
if n % item == 0 { | |
flag = false; | |
break; | |
} | |
item += 1; | |
} | |
return flag; | |
} | |
pub fn get_prime_factors(n: u64) -> Vec<u64> { | |
let mut p: u64 = 3; | |
let mut factors: Vec<u64> = vec![]; | |
if n % 2 == 0 { | |
factors.push(2); | |
} | |
loop { | |
if n % p == 0 && is_prime(p) { | |
factors.push(p); | |
} | |
if p >= n/2 { break; } | |
p += 2; | |
} | |
return factors; | |
} | |
fn prime_map() -> HashMap<char, u64> { | |
let mut alpha_hash: HashMap<char, u64> = HashMap::new(); | |
let alphas:Vec<char> = "abcdefghijklmnopqrstuvwxyz".chars().collect(); | |
let mut n: u64 = 3; | |
alpha_hash.insert('a', 2); | |
for alpha in alphas.iter() { | |
if *alpha == 'a' { continue; } | |
while !is_prime(n) { | |
n += 2; | |
} | |
alpha_hash.insert(*alpha, n); | |
n += 2; | |
} | |
println!("{:?}", alpha_hash); | |
return alpha_hash; | |
} | |
fn main() { | |
// Pass two strings into the program | |
let args: Vec<String> = env::args().collect(); | |
let word1 = &args[1]; | |
let word2 = &args[2]; | |
println!("Words are {} and {}", word1, word2); | |
// Build alpha->primes map | |
let _alpha_prime = prime_map(); | |
// Get word1 -> prime factors product | |
let _prod1 = word1.chars().map(|c| _alpha_prime.get(&c)).fold(1, |p, x| p*x.unwrap()); | |
let _prod2 = word2.chars().map(|c| _alpha_prime.get(&c)).fold(1, |p, x| p*x.unwrap()); | |
if _prod1 == _prod2 { | |
println!("Yes: anagrams"); | |
} else { | |
println!("Nope: nanagrams"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment