summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJérémy Zurcher <jeremy@asynk.ch>2013-05-17 17:17:29 +0200
committerJérémy Zurcher <jeremy@asynk.ch>2016-11-10 18:03:25 +0100
commitb95dd68188634f826bbbab79d47c65f39ee5a06e (patch)
treec9d9ff33742d2c01b74781c036e9e39cfaddd242
parentd8d74ed55984d2ae39cbdb965dd42bba984735a9 (diff)
downloadcoursera-b95dd68188634f826bbbab79d47c65f39ee5a06e.zip
coursera-b95dd68188634f826bbbab79d47c65f39ee5a06e.tar.gz
Scala : add 13-polynomials to sandbox
-rw-r--r--Scala/sandbox/0-main.scala1
-rw-r--r--Scala/sandbox/13-polynomials.scala43
2 files changed, 44 insertions, 0 deletions
diff --git a/Scala/sandbox/0-main.scala b/Scala/sandbox/0-main.scala
index f6d6652..297fab9 100644
--- a/Scala/sandbox/0-main.scala
+++ b/Scala/sandbox/0-main.scala
@@ -15,5 +15,6 @@ object Main extends App {
MergeSort.run
Pack.run
NQueens.run
+ Polynomials.run
}
diff --git a/Scala/sandbox/13-polynomials.scala b/Scala/sandbox/13-polynomials.scala
new file mode 100644
index 0000000..ebf3818
--- /dev/null
+++ b/Scala/sandbox/13-polynomials.scala
@@ -0,0 +1,43 @@
+object Polynomials
+{
+
+ class Poly(terms0: Map[Int, Double]) {
+ def this(bindings: (Int, Double)*) = this(bindings.toMap)
+ val terms = terms0 withDefaultValue 0.0
+
+ def add (other: Poly) = new Poly(terms ++ (other.terms map adjust))
+
+ def adjust(term: (Int, Double)): (Int, Double) = {
+ val (exp, coeff) = term
+ exp -> (coeff + terms(exp))
+ // before adding defauld value
+ /* terms get exp match { */
+ /* case Some(coeff1) => exp -> (coeff + coeff1) */
+ /* case None => exp -> coeff */
+ /* } */
+ }
+
+ def + (other: Poly) = new Poly((other.terms foldLeft terms)(addTerm))
+
+ def addTerm(terms: Map[Int, Double], term: (Int, Double)) = {
+ val (exp, coeff) = term
+ terms + (exp -> (coeff + terms(exp)))
+ }
+
+ override def toString =
+ (for ((exp, coeff) <- terms.toList.sorted.reverse) yield coeff+"^"+exp) mkString " + "
+ }
+
+ def run = {
+ println("Polynomials")
+ /* val p1 = new Poly(Map(1 -> 2.0, 3 -> 4.0, 5 -> 6.2)) */
+ /* val p2 = new Poly(Map(0 -> 3.0, 3 -> 7.0)) */
+ val p1 = new Poly(1 -> 2.0, 3 -> 4.0, 5 -> 6.2)
+ val p2 = new Poly(0 -> 3.0, 3 -> 7.0)
+ println(p1.terms(7))
+ println(p1)
+ println(p2)
+ println(p1 add p2)
+ println(p1 + p2)
+ }
+}