completed rationals + added IntSet base
This commit is contained in:
@ -1,31 +1,41 @@
|
||||
class Rational(n: Int, d: Int) {
|
||||
def num = n
|
||||
def denom = d
|
||||
import scala.annotation.tailrec
|
||||
|
||||
def add(that: Rational): Rational = new Rational(
|
||||
class Rational(n: Int, d: Int) {
|
||||
require(d != 0)
|
||||
|
||||
@tailrec
|
||||
private def gcd(x: Int, y: Int): Int =
|
||||
if (y == 0) x else gcd(y, x % y)
|
||||
|
||||
private val g: Int = gcd(n, d)
|
||||
def num: Int = n / g
|
||||
def denom: Int = d / g
|
||||
|
||||
|
||||
def +(that: Rational): Rational = new Rational(
|
||||
this.num * that.denom + this.denom * that.num,
|
||||
this.denom * that.denom
|
||||
)
|
||||
|
||||
def neg: Rational = new Rational(-num, denom)
|
||||
def unary_- : Rational = new Rational(-num, denom)
|
||||
|
||||
def smallerThan(that: Rational): Boolean = this.num * that.denom < that.num * this.denom
|
||||
def <(that: Rational): Boolean = this.num * that.denom < that.num * this.denom
|
||||
|
||||
def max(that: Rational): Rational = if (this.smallerThan(that)) that else this
|
||||
def max(that: Rational): Rational = if (this < that) that else this
|
||||
|
||||
override def toString = num + "/" + denom
|
||||
override def toString = if (math.abs(denom) == 1) "" + denom else num + "/" + denom
|
||||
}
|
||||
|
||||
val r1 = new Rational(1, 3)
|
||||
val r2 = new Rational(2, 3)
|
||||
val r3 = r1.add(r2)
|
||||
val r3 = r1 + r2
|
||||
|
||||
r3
|
||||
|
||||
r2.neg
|
||||
-r2
|
||||
|
||||
r2.smallerThan(r1)
|
||||
r2.smallerThan(r3)
|
||||
r2 < r1
|
||||
r2 < r3
|
||||
|
||||
r2.max(r1)
|
||||
r2.max(r3)
|
Reference in New Issue
Block a user