Euler Project Problems 7-9 in Scala

This is my continuing series on using Project Euler to learn Scala.
You can see the other posts in the series by visiting the Project Euler category.

Problem #7

import collection.mutable.ListBuffer

object problem7 {
  private val primes: ListBuffer[Int] = ListBuffer[Int]()

  private def isPrime(number: Int) =
    !primes.toStream
      .takeWhile(_ <= math.sqrt(number).floor.toInt)
      .exists(number % _ == 0)

  private def findPrimesStream(): Stream[Int] = {
    // Start running from the last prime + 1 (or from 2 if no primes exist) until the first prime
    val startAt = if (primes.isEmpty) 2 else (primes.max + 1)
    val num: Int = Stream.from(startAt).find(isPrime(_)).head

    // Memoize
    primes.append(num)

    // Continue the stream
    num #:: findPrimesStream
  }

  def main(args: Array[String]) {
    // stream.apply at index 10001
    println(findPrimesStream()(10000))
  }
}

I tried to rely on Streams here, along with the obvious memoization that needed to take place.

Problem #8

object problem8 {
  private val number = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"

  private def numbersStream(implicit index: Int = 0): Stream[String] = {
    if (index > number.length() - 5)
      return Stream.empty

    number.substring(index, index + 5) #:: numbersStream(index + 1)
  }

  def main(args: Array[String]) {
    // Get all consecutive fives
    val max = numbersStream().map(
      // Convert each to a stream of bytes
      _.toStream
        // Convert each one to a number and find their product
        .map(c => Integer.parseInt(c.toString, 10))
        .foldLeft(1)(_ * _))
      // Find the max product
      .max

    println(max)
  }
}

Problem #9

object problem9 {
  def main(args: Array[String]) {
    println(
      Range(1, 999)
        .map(a => (a, Range(a + 1, 999 - a).find(b => a + b + math.sqrt(a*a + b*b) == 1000)))
        .collectFirst{case (a, b) if b != None => a * b.get * math.sqrt(a*a + b.get*b.get) }
        .get
        .toInt)
  }
}

This time I found out about the collect/collectFirst methods that are pretty much filter and map in one. Also, the fact that I worked with a tuple meant that it was easier to have a case handle it, rather than fall back to ._1, et al.

Additional Reading:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s