How to count point mutations
Published in
2 min readDec 7, 2023
A Rust function that returns count of point mutations (hamming distance)
Arguments
- seq1: a string slice that holds a DNA sequence
- seq2: another string slide that holds a DNA sequence
Example
let seq1 = "ACGT";
let seq2 = "ACCT";
let count = count_point_mutations(seq1, seq2).unwrap();
// count holds 1
Code
fn main() {
let seq1: &str = "GAGCCTACTAACGGGAT";
let seq2: &str = "CATCGTAATGACGGCCT";
let count = count_point_mutations(seq1, seq2).unwrap();
println!("{}", count)
}
fn count_point_mutations(seq1: &str, seq2: &str) -> Option<i32> {
if seq1.len() == seq2.len() {
let mut distance = 0;
for (x, y) in seq1.chars().zip(seq2.chars()) {
if x != y {
distance += 1;
}
}
Some(distance)
} else {
None
}
}
Some notes on the code
- I need to use
.unwrap()
becausecount_point_mutations
returns anOption
- The
zip
function takes 2 iterators and returns a new iterator that yields pairs of elements from both input iterators - If the inputs sequences are not of the same length, the code will panic. You can use
if let
instead. distance
stands for hamming distance. Naming this variablecount
is probably a wiser choice.
fn main() {
let seq1: &str = "GAGCCTACTAACGGGAT";
let seq2: &str = "CATCGTAATGACGGCCT";
if let Some(count) = count_point_mutations(seq1, seq2) {
println!{"{}", count};
} else {
println!("The input sequence lengths are not same.");
}
}
Next Steps
- Play with this code in the Rust Playground
- Solve a Rosalind challenge