Last active
June 25, 2020 06:19
Revisions
-
pythonhacker revised this gist
Jun 22, 2020 . 1 changed file with 1 addition and 0 deletions.There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -1,4 +1,5 @@ // Courtesy: @Fermatslibrary // Reference: https://twitter.com/fermatslibrary/status/1275066521450975234 // Copyright: Anand B Pillai @skeptichacker // LICENSE: MIT -
pythonhacker created this gist
Jun 22, 2020 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,93 @@ // Courtesy: @Fermatslibrary // 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"); } }