Last active
May 15, 2017 12:53
-
-
Save hessammehr/106199fb6ab9a3ecffc4bfff41305957 to your computer and use it in GitHub Desktop.
Anagram scoring 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
#[derive(Debug,Clone)] | |
struct Match { | |
c: u8, // character | |
pos: usize // position | |
} | |
fn score(matches: &[Match]) -> usize { | |
let l = matches.len(); | |
let mut s = 1; | |
if l < 2 { return s } | |
let c1 = &matches[0..(l-1)]; | |
let c2 = &matches[1..l]; | |
for n in 0..(l-1) { | |
if (c2[n].pos as isize) - (c1[n].pos as isize) != 1 { s += 1 } | |
} | |
s | |
} | |
fn matches(s1: &[u8], s2: Vec<u8>, acc: Vec<Match>) -> Vec<Vec<Match>> { | |
let l = s1.len(); | |
if l == 0 { return vec![acc] } | |
let mut res: Vec<Vec<Match>> = vec![]; | |
let c = s1[0]; | |
for x in 0..s2.len() { | |
if s2[x] == c { | |
let mut ss2 = s2.clone(); | |
ss2[x] = 0; | |
let mut acc = acc.clone(); | |
acc.push(Match { c: c, pos: x }); | |
res.append(&mut matches(&s1[1..l], ss2, acc)); | |
} | |
} | |
res | |
} | |
fn main() { | |
let results = matches("cinematographer".as_bytes(), "megachiropteran".as_bytes().to_vec(), vec![]); | |
let x = results.into_iter().map(|r| score(r.as_slice())).min().unwrap(); | |
println!("{:?}", x); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment