Area Under Curves and Volume of Revolving a Curve Discussions | Functional Programming | HackerRank

Area Under Curves and Volume of Revolving a Curve

  • + 0 comments

    scala:

      private val dx = 0.001
      def readLine() = scala.io.StdIn.readLine()
    
      def f(coefficients: Seq[Int], powers: Seq[Int], x: Double) = {
        (coefficients zip powers)
          .map { case (a, b) => a * math.pow(x, b) }
          .sum
      }
    
      def area(coefficients: Seq[Int], powers: Seq[Int], x: Double): Double = {
        Math.PI * Math.pow(f(coefficients, powers, x), 2)
      }
    
      def summation(
          func: (Seq[Int], Seq[Int], Double) => Double,
          upperLimit: Int,
          lowerLimit: Int,
          coefficients: Seq[Int],
          powers: Seq[Int]
      ): Double = {
        val steps = ((upperLimit - lowerLimit) / dx).toInt
        val range = (0 to steps).map(lowerLimit + _ * dx)
        val result = range
          .map(func(coefficients, powers, _) * dx)
          .sum
        BigDecimal(result).setScale(1, BigDecimal.RoundingMode.UP).toDouble
      }