Created
December 29, 2020 19:46
-
-
Save amuradyan/1f1200c23d0e2f988a61f34bb54af4c1 to your computer and use it in GitHub Desktop.
Hackerrank `Day of the Programmer` problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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