Skip to content

Instantly share code, notes, and snippets.

@kaj
Created May 2, 2016 20:23
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 kaj/9a089d12ca0bad44c46555dabf1098b0 to your computer and use it in GitHub Desktop.
Save kaj/9a089d12ca0bad44c46555dabf1098b0 to your computer and use it in GitHub Desktop.
Count nucleotiedes using an array for the count values.
use std::fmt;
use std::ops::{Index, IndexMut};
struct NucleotideCounts {
counts: [u64; 4],
}
impl NucleotideCounts {
fn new() -> Self {
NucleotideCounts { counts: [0; 4] }
}
fn count(&mut self, strand: &str) {
for c in strand.bytes() {
self[c] += 1;
}
}
}
impl fmt::Debug for NucleotideCounts {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let c = self.counts;
write!(f, "[{}, {}, {}, {}]", c[0], c[2], c[1], c[3])
}
}
impl Index<u8> for NucleotideCounts {
type Output = u64;
fn index(&self, c: u8) -> &u64 {
&self.counts[(((c as u8)/2) & 3) as usize]
}
}
impl IndexMut<u8> for NucleotideCounts {
fn index_mut(&mut self, c: u8) -> &mut u64 {
&mut self.counts[(((c as u8)/2) & 3) as usize]
}
}
fn main() {
//let mut count : [u32; 4] = [0, 0, 0, 0];
let mut counter = NucleotideCounts::new();
counter.count("AATCGAAAGTTTCCTTTTTAATTTACCCTATTTATATATTAT");
for c in "ATCG".bytes() {
println!("{}: {}", c as char, counter[c]);
}
println!("{:?}", counter)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment