Created
November 11, 2015 21:08
-
-
Save blippy/b71525e9ec7243c63db7 to your computer and use it in GitHub Desktop.
Count the number of alphabetical characters in a file
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
import Data.Array | |
import Data.Char | |
outputs text = | |
let arr = accumArray (+) 0 (0, 255) $ map (\c -> (ord c, 1)) text | |
hits = filter (\(c, qty) -> (isAlpha $ chr c) && (qty > 0) ) $ assocs arr | |
in | |
map (\(c, qty) -> [chr c] ++ " (" ++ (show qty) ++")") hits | |
main = do | |
text <- readFile "/etc/passwd" | |
putStrLn $ unlines $ outputs text |
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
/* frequency.rs | |
Count the number of alphabetical characters in a file | |
*/ | |
use std::fs::File; | |
use std::io::Read; | |
use std::error::Error; | |
fn main() | |
{ | |
let f = match File::open("/etc/passwd") // it will be closed automatically | |
{ | |
Ok(file) => file, | |
Err(e) => panic!("Error: {}", Error::description(&e)) | |
}; | |
let mut count = [0i32; 255]; | |
for b in f.bytes() { count[b.unwrap() as usize] += 1 } | |
for i in (0u8..128u8) { | |
let c: char = i as char; | |
let is_alpha: bool = ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'); | |
if is_alpha && (count[i as usize] > 0) { | |
println!("{} ({})", c, count[i as usize]); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment