Source

ScalaEuler / src / com / mklinke / euler / Problem33.scala

Full commit
package com.mklinke.euler

class Rational(n: Int, d: Int) {
  private def gcd(x: Int, y: Int): Int =
    {
      if (x == 0) y
      else if (x < 0) gcd(-x, y)
      else if (y < 0) -gcd(x, -y)
      else gcd(y % x, x)
    }
  private val g = gcd(n, d)

  val numer: Int = n // /g
  val denom: Int = d // /g

  def +(that: Rational) =
    new Rational(numer * that.denom + that.numer * denom, denom * that.denom)
  def -(that: Rational) =
    new Rational(numer * that.denom - that.numer * denom, denom * that.denom)
  def *(that: Rational) =
    new Rational(numer * that.numer, denom * that.denom)
  def /(that: Rational) =
    new Rational(numer * that.denom, denom * that.numer)

  def simplify() =
    new Rational(numer / g, denom / g)

  override def toString() =
    "Rational: [" + numer + " / " + denom + "]"
}

object Problem33 {

  def check(rat: Rational): Boolean = {
    val numerChars = rat.numer.toString().toCharArray()
    val denomChars = rat.denom.toString().toCharArray()
    val commonChars = numerChars.filter(char => denomChars.
      filter(char2 => char == char2).length > 0)
    if (commonChars.length == 1 && commonChars(0) != '0') {
      val simpleNumerChars = numerChars.filter(c => c != commonChars(0))
      val simpleDenomChars = denomChars.filter(c => c != commonChars(0))
      if (simpleNumerChars.length > 0 && simpleDenomChars.length > 0) {
        val source = rat.simplify
        val target = new Rational(simpleNumerChars(0) - 48,
          simpleDenomChars(0) - 48).simplify
        return source.numer == target.numer && source.denom == target.denom
      }
    }
    false
  }

  def main(args: Array[String]) {

    val result = (1 to 99).map(num =>
      num to 99 map (denom => new Rational(num, denom)) filter (rational => check(rational)))

    val filtered = result.filter(_.length > 0)
    val mapped = filtered.map(entry => entry.reduceLeft(_ * _))
    val product = mapped.reduceLeft(_ * _).simplify

    Console println product
  }
}