Guest User

Untitled

a guest
Jul 19th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. package com.cyrillemartraire.monoids;
  2.  
  3. import static java.util.Arrays.stream;
  4. import static org.junit.Assert.assertEquals;
  5.  
  6. import org.junit.Test;
  7.  
  8. public class AverageTest {
  9.  
  10. @Test
  11. public void basicAverage() throws Exception {
  12. assertEquals(2, Average.of(1, 2, 3).average(), 0.0001);
  13. }
  14.  
  15. @Test
  16. public void neutralElement() throws Exception {
  17. assertEquals(Average.of(1, 2, 3), Average.of(1, 2, 3).add(Average.NEUTRAL));
  18. }
  19.  
  20. @Test
  21. public void combiningAverages() throws Exception {
  22. final Average combinedAverages = Average.of(1, 2, 3).add(Average.of(4, 6));
  23. assertEquals(5, combinedAverages.count());
  24. assertEquals(16. / 5., combinedAverages.average(), 0.0001);
  25. }
  26.  
  27. /** An average that composes well */
  28. public static class Average {
  29.  
  30. private final int count;
  31. private final int sum;
  32.  
  33. public static final Average NEUTRAL = new Average(0, 0);
  34.  
  35. public static final Average of(int... values) {
  36. return new Average(values.length, stream(values).sum());
  37. }
  38.  
  39. private Average(int count, int sum) {
  40. this.count = count;
  41. this.sum = sum;
  42. }
  43.  
  44. public double average() {
  45. return (double) sum / count;
  46. }
  47.  
  48. public int count() {
  49. return count;
  50. }
  51.  
  52. public Average add(Average other) {
  53. return new Average(count + other.count, sum + other.sum);
  54. }
  55.  
  56. @Override
  57. public int hashCode() {
  58. return 31 + count ^ sum;
  59. }
  60.  
  61. @Override
  62. public boolean equals(Object obj) {
  63. if (this == obj) {
  64. return true;
  65. }
  66. if (!(obj instanceof Average)) {
  67. return false;
  68. }
  69. Average other = (Average) obj;
  70. return count == other.count && sum == other.sum;
  71. }
  72.  
  73. @Override
  74. public String toString() {
  75. return " " + sum + " / " + sum + " = " + average();
  76. }
  77.  
  78. }
  79. }
Add Comment
Please, Sign In to add comment