Skip to content

Instantly share code, notes, and snippets.

@hessammehr
Last active May 15, 2017 12:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hessammehr/106199fb6ab9a3ecffc4bfff41305957 to your computer and use it in GitHub Desktop.
Save hessammehr/106199fb6ab9a3ecffc4bfff41305957 to your computer and use it in GitHub Desktop.
Anagram scoring in Rust
#[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