Guest User

Untitled

a guest
Mar 23rd, 2018
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. object CumulativeOps {
  2. def cumSum[A](xs: Seq[A])(implicit num: Numeric[A]): Seq[A] = {
  3. xs.tail.scanLeft(xs.head)(num.plus)
  4. }
  5.  
  6. def cumDiff[A](xs: Seq[A])(implicit num: Numeric[A]): Seq[A] = {
  7. val total = xs.sum
  8. xs.scanLeft(total)(num.minus).dropRight(1)
  9. }
  10.  
  11. def cumMultiplication[A](xs: Seq[A])(implicit num: Numeric[A]): Seq[A] = {
  12. xs.tail.scanLeft(xs.head)(num.times)
  13. }
  14. }
  15.  
  16. class CumulativeOpsTest extends WordSpec with Matchers {
  17. "CumulativeOps" should {
  18.  
  19. "calculate cumulative sum of Ints" in {
  20. CumulativeOps.cumSum(Vector(1, 2, 4, 7, 3, 4)) should
  21. contain theSameElementsInOrderAs (Seq(1, 3, 7, 14, 17, 21))
  22. }
  23.  
  24. "calculate cumulative sum of Doubles" in {
  25. CumulativeOps.cumSum(Vector(1.25, 2, 4.25, 7.5, 3.25, 4.75)) should
  26. contain theSameElementsInOrderAs (Vector(1.25, 3.25, 7.5, 15.0, 18.25, 23.0))
  27. }
  28.  
  29. "calculate cumulative diff of Ints" in {
  30. CumulativeOps.cumDiff(Vector(1, 2, 4, 7, 3, 4)) should
  31. contain theSameElementsInOrderAs (Vector(21, 20, 18, 14, 7, 4))
  32. }
  33.  
  34. "calculate cumulative diff of Doubles" in {
  35. CumulativeOps.cumDiff(Vector(1.25, 2.5, 4, 7.25, 3, 4)) should
  36. contain theSameElementsInOrderAs (Vector(22.0, 20.75, 18.25, 14.25, 7.0, 4.0))
  37. }
  38.  
  39. "calculate cumulative multiplication of Ints" in {
  40. CumulativeOps.cumMultiplication((List(2, 3, 7, 14, 17, 21))) should
  41. contain theSameElementsInOrderAs (Vector(2, 6, 42, 588, 9996, 209916))
  42. }
  43.  
  44. "calculate cumulative multiplication of Doubles" in {
  45. CumulativeOps.cumMultiplication((List(0.99, 0.83, 0.74, 0.5, 0.5, 0.5))) should
  46. contain theSameElementsInOrderAs (Vector(0.99, 0.8217, 0.608058, 0.304029, 0.1520145, 0.07600725))
  47. }
  48. }
  49. }
Add Comment
Please, Sign In to add comment