fork download
  1. import scala.math.Numeric
  2. import scala.reflect.ClassTag
  3.  
  4. trait ScalesBy[A, B] {
  5. def scale(value: A, scale: B): A
  6. }
  7.  
  8. object ScalesByInstances {
  9. implicit val scalesIntByInt = new ScalesBy[Int, Int] {
  10. def scale(value: Int, scale: Int) = value * scale
  11. }
  12. implicit val scalesIntByDouble = new ScalesBy[Int, Double] {
  13. def scale(value: Int, scale: Double) = (value.toDouble * scale).toInt
  14. }
  15. implicit val scalesDoubleByDouble = new ScalesBy[Double, Double] {
  16. def scale(value: Double, scale: Double) = value * scale
  17. }
  18. implicit val scalesDoubleByInt = new ScalesBy[Double, Int] {
  19. def scale(value: Double, scale: Int) = value * scale
  20. }
  21. // TODO: Provide more instances
  22. }
  23.  
  24. class Matrix[A](val rowsCount: Int, val columnsCount: Int)
  25. (implicit numOps: Numeric[A], classTag: ClassTag[A]) {
  26.  
  27. private[this] val data = new Array[A](rowsCount * columnsCount)
  28.  
  29. def apply(coords: (Int, Int)) = {
  30. val (row, column) = coords
  31. data(row * columnsCount + column)
  32. }
  33.  
  34. def update(coords: (Int, Int), newVal: A) = {
  35. val (row, column) = coords
  36. data.update(row * columnsCount + column, newVal)
  37. }
  38.  
  39. def scaledBy[B](scale: B)(implicit scalesBy: ScalesBy[A, B]) = {
  40. val result = new Matrix(rowsCount, columnsCount)
  41. for (r <- 0 until rowsCount; c <- 0 until columnsCount) {
  42. val cell = apply((r, c))
  43. val scaledCell = scalesBy.scale(cell, scale)
  44. result.update((r, c), scaledCell)
  45. }
  46. result
  47. }
  48. }
  49.  
  50. object Main {
  51. import ScalesByInstances._
  52.  
  53. def main(args: Array[String]) = {
  54. // your code goes here
  55. val intMx = new Matrix[Int](3, 2)
  56. val doubleMx = new Matrix[Double](3, 2)
  57. intMx((1, 2)) = 3
  58. doubleMx((1, 2)) = 3
  59. println("Int cell before: " + intMx((1, 2)))
  60. println("Double cell before: " + doubleMx((1, 2)))
  61. val scaledIntMx = intMx.scaledBy(2.5)
  62. println("Int cell scaled by 2.5: " + scaledIntMx((1, 2)))
  63. val scaledDoubleMx = doubleMx.scaledBy(2.5)
  64. println("Double cell scaled by 2.5: " + scaledDoubleMx((1, 2)))
  65. }
  66. }
Success #stdin #stdout 0.33s 322240KB
stdin
Standard input is empty
stdout
Int cell before: 3
Double cell before: 3.0
Int cell scaled by 2.5: 7
Double cell scaled by 2.5: 7.5