fork download
  1. use std::collections::HashMap;
  2.  
  3. fn main() {
  4. let data = r#"outlook temperature humidity windy play
  5. sunny hot high FALSE no
  6. sunny hot high TRUE no
  7. overcast hot high FALSE yes
  8. rainy mild high FALSE yes
  9. rainy cool normal FALSE yes
  10. rainy cool normal TRUE no
  11. overcast cool normal TRUE yes
  12. sunny mild high FALSE no
  13. sunny cool normal FALSE yes
  14. rainy mild normal FALSE yes
  15. sunny mild normal TRUE yes
  16. overcast mild high TRUE yes
  17. overcast hot normal FALSE yes
  18. rainy mild high TRUE no"#;
  19.  
  20. let lines: Vec<&str> = data.lines().collect();
  21. let headers: Vec<&str> = lines[0].split('\t').collect();
  22. let mut counts: HashMap<&str, HashMap<&str, usize>> = HashMap::new();
  23.  
  24. for &header in &headers {
  25. counts.insert(header, HashMap::new());
  26. }
  27.  
  28. for line in &lines[1..] {
  29. let fields: Vec<&str> = line.split('\t').collect();
  30. for (i, val) in fields.iter().enumerate() {
  31. let map = counts.get_mut(headers[i]).unwrap();
  32. *map.entry(val).or_insert(0) += 1;
  33. }
  34. }
  35.  
  36. for h in &headers {
  37. println!("{} counts:", h);
  38. for (k, v) in &counts[h] {
  39. println!(" {}: {}", k, v);
  40. }
  41. }
  42. }
  43.  
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
outlook counts:
  rainy: 5
  overcast: 4
  sunny: 5
temperature counts:
  mild: 6
  cool: 4
  hot: 4
humidity counts:
  normal: 7
  high: 7
windy counts:
  TRUE: 6
  FALSE: 8
play counts:
  no: 5
  yes: 9