fork download
  1. import java.util.HashMap;
  2.  
  3. class Problem {
  4. private int count;
  5. private final HashMap<String, Integer> counts;
  6.  
  7. public Problem() {
  8. this.counts = new HashMap<>();
  9. }
  10.  
  11. public void addName(String name) {
  12. counts.put(name, counts.getOrDefault(name, 0) + 1);
  13. count++;
  14. }
  15.  
  16. public double nameProportion(String name) {
  17. return counts.get(name) / (double) count;
  18. }
  19.  
  20. public static void main(String[] args) {
  21. Problem namesCount = new Problem();
  22.  
  23. namesCount.addName("James");
  24. namesCount.addName("John");
  25. namesCount.addName("Mary");
  26. namesCount.addName("Mary");
  27.  
  28. System.out.println("Fraction of Johns: " + namesCount.nameProportion("John"));
  29. System.out.println("Fraction of Marys: " + namesCount.nameProportion("Mary"));
  30. }
  31. }
Success #stdin #stdout 0.1s 36412KB
stdin
Standard input is empty
stdout
Fraction of Johns: 0.25
Fraction of Marys: 0.5