Add files via upload
This commit is contained in:
parent
adbd25aa77
commit
47d1cd807d
34
2019/Scala/day01/Day1.scala
Normal file
34
2019/Scala/day01/Day1.scala
Normal file
|
@ -0,0 +1,34 @@
|
|||
package day01
|
||||
|
||||
import kamlib.{Reader, Wrapper}
|
||||
|
||||
class Day1 {
|
||||
|
||||
/** Find fuel needed */
|
||||
def solveP1(input: List[Int]): Int =
|
||||
input.foldLeft (0) { (acc, i) => acc + (i/3-2)}
|
||||
|
||||
/** Find fuel needed and recursive fuel */
|
||||
def solveP2(input: List[Int]): Int =
|
||||
{
|
||||
@scala.annotation.tailrec
|
||||
def findRecursiveFuel(fuel: Int, acc: Int): Int =
|
||||
{
|
||||
if (fuel <= 0) acc
|
||||
else findRecursiveFuel((fuel/3)-2, fuel+acc)
|
||||
}
|
||||
input.foldLeft (0) { (acc, i) => acc + findRecursiveFuel((i/3)-2, 0)}
|
||||
}
|
||||
|
||||
/** MAIN */
|
||||
def main(args: Array[String]): Unit =
|
||||
{
|
||||
val input: List[Int] = Reader.readList("/input1.txt").map(_.toInt)
|
||||
|
||||
println("Part 1")
|
||||
Wrapper(solveP1(input)).print()
|
||||
println("Part 2")
|
||||
Wrapper(solveP2(input)).print()
|
||||
}
|
||||
|
||||
}
|
18
2019/Scala/day01/worksheet1.sc
Normal file
18
2019/Scala/day01/worksheet1.sc
Normal file
|
@ -0,0 +1,18 @@
|
|||
import scala.io.Source
|
||||
val lines = Source.fromFile(getClass.getResource("/input1.txt").getFile).getLines().toList
|
||||
|
||||
// 1
|
||||
val result1 = lines.foldLeft (0) { (acc, i) => acc + (i.toInt/3-2)}
|
||||
println(result1)
|
||||
|
||||
// 2
|
||||
@scala.annotation.tailrec
|
||||
def findRecursiveFuel(fuel:Int, acc:Int):Int =
|
||||
{
|
||||
val nextFuel = (fuel/3)-2
|
||||
if (nextFuel <= 0) acc
|
||||
else findRecursiveFuel(nextFuel, nextFuel+acc)
|
||||
}
|
||||
|
||||
val result2 = lines.foldLeft (0) { (acc, i) => acc + findRecursiveFuel(i.toInt, 0)}
|
||||
println(result2)
|
Loading…
Reference in a new issue