Skip to content

Instantly share code, notes, and snippets.

@amuradyan
Created December 29, 2020 19:46
Show Gist options
  • Save amuradyan/1f1200c23d0e2f988a61f34bb54af4c1 to your computer and use it in GitHub Desktop.
Save amuradyan/1f1200c23d0e2f988a61f34bb54af4c1 to your computer and use it in GitHub Desktop.
Hackerrank `Day of the Programmer` problem
import scala.io._
trait Date {
def toDDMMYYYY: String = ???
}
case class ConcreteDate(day: Int, month: String, year: Int) extends Date {
override def toDDMMYYYY = s"$day.$month.$year"
}
case object EmptyDate extends Date
object DayOfTheProgrammer {
val months = List(("01", 31), ("02", 28), ("03", 31), ("04", 30), ("05", 31), ("06", 30),
("07", 31), ("08", 31), ("09", 30), ("10", 31), ("11", 30), ("12", 31))
private def isJulianLeap(year: Int): Boolean = year % 4 == 0
private def isGregorianLeap(year: Int): Boolean = (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)
def dayOfProgrammer(year: Int): String = {
lazy val isLeapJulian = isJulianLeap(year)
lazy val isLeapGregorian = isGregorianLeap(year)
val dayOfProgrammer = months.foldLeft((EmptyDate, 256): Tuple2[Date, Int])((acc, month) => {
val daysRemaining = acc._2
val currentDate = acc._1
val monthName = month._1
val daysInMonth = if (monthName == "02") {
if (year < 1918 && isLeapJulian ) month._2 + 1
else if (year > 1918 && isLeapGregorian) month._2 + 1
else if (year == 1918) month._2 - (if (isLeapGregorian) 12 else 13)
else month._2
} else month._2
if (daysRemaining == 0) acc
else if (daysRemaining < daysInMonth) (ConcreteDate(daysRemaining, monthName, year), 0)
else (ConcreteDate(daysInMonth, monthName, year), daysRemaining - daysInMonth)
})._1
dayOfProgrammer.toDDMMYYYY
}
def main(args: Array[String]): Unit = {
val year = StdIn.readLine.trim.toInt
val result = dayOfProgrammer(year)
println(result)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment