Skip to content

Instantly share code, notes, and snippets.

@tong92
Created February 10, 2023 13:18
Show Gist options
  • Save tong92/519396fe27956c0174e103135adc5c91 to your computer and use it in GitHub Desktop.
Save tong92/519396fe27956c0174e103135adc5c91 to your computer and use it in GitHub Desktop.
import scala.io.Source
def toRange(section: String): (Int, Int) =
val xs = section.split("-")
(xs(0).toInt, xs(1).toInt)
def contain(a: (Int, Int), b: (Int, Int)): Boolean =
a._1 <= b._1 && a._2 >= b._2
def isContain(pair: String): Boolean =
val xs = pair.split(",").map(toRange)
contain(xs(1), xs(0)) || contain(xs(0), xs(1))
def ans1(xs: List[String]): Int =
xs.filter(isContain).length
def overlap(a: (Int, Int), b: (Int, Int)): Boolean =
(a._1 to a._2).contains(b._1) || (a._1 to a._2).contains(b._2)
def isOverlap(pair: String): Boolean =
val xs = pair.split(",").map(toRange)
overlap(xs(1), xs(0)) || overlap(xs(0), xs(1))
def ans2(xs: List[String]): Int =
xs.filter(isOverlap).length
def solve =
val input = Source.fromFile("day4.txt").getLines.toList
println(ans1(input))
println(ans2(input))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment