Puzzle1.scala 1.12 KB
Newer Older
David's avatar
Day 1  
David committed
1 2
package is.kow.adventofcode._2019

David's avatar
David committed
3
import scala.annotation.tailrec
David's avatar
Day 1  
David committed
4 5 6 7 8 9
import scala.io.Source

object Puzzle1Main extends App {
  //Read in the inputs, and do all the calcs
  val source = Source.fromResource("input.txt")
  try {
David's avatar
David committed
10
    val lines = source.getLines().toList
David's avatar
Day 1  
David committed
11 12 13 14 15 16 17
    val p1 = new Puzzle1

    val totalFuel = lines.foldLeft(0) { (acc, line) =>
      acc + p1.calculateFuel(line.toInt)
    }

    println("Total fuel required for part 1: " + totalFuel)
David's avatar
David committed
18 19 20 21 22 23 24


    val part2Fuel = lines.foldLeft(0) { (acc, line) =>
      acc + p1.recursiveFuel(0, line.toInt)
    }

    println("total fuel required for part 2: " + part2Fuel)
David's avatar
Day 1  
David committed
25 26 27 28 29 30 31 32 33 34 35
  } finally source.close()

}

class Puzzle1 {
  def calculateFuel(input: Int): Int = {
    val first = Math.floor(input.toFloat / 3).toInt
    first - 2
  }

  //recursive fuel calculation function!
David's avatar
David committed
36 37 38 39 40 41 42 43 44 45
  @tailrec final def recursiveFuel(acc: Int = 0, input: Int): Int = {
    val change = Math.floor(input.toFloat / 3).toInt
    if (change <= 2) {
      acc
    } else {
      //do the calculation and add it to accumulator, and recurse
      val addFuel = change - 2;
      recursiveFuel(acc + addFuel, addFuel)
    }
  }
David's avatar
Day 1  
David committed
46
}