Created
September 13, 2013 13:20
-
-
Save vlasovskikh/6550633 to your computer and use it in GitHub Desktop.
Programmers day in Erlang
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
-module(pday). | |
-export([main/1, pday/1, ordinal_to_date/2, date_to_string/1]). | |
ordinal_to_date(Year, N) -> | |
{Month, Day} = submod(N, months(Year)), | |
{Year, Month + 1, Day}. | |
date_to_string({Year, Month, Day}) -> | |
lists:flatten(io_lib:format("~4..0b-~2..0b-~2..0b", [Year, Month, Day])). | |
pday(Year) -> | |
ordinal_to_date(Year, 256). | |
months(Year) -> | |
Leap = is_leap(Year), | |
Feb = if Leap -> 29; true -> 28 end, | |
[31, Feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]. | |
is_leap(Year) when Year rem 400 == 0 -> | |
true; | |
is_leap(Year) when Year rem 100 == 0 -> | |
false; | |
is_leap(Year) when Year rem 4 == 0 -> | |
true; | |
is_leap(_) -> | |
false. | |
submod(X, Ys) -> | |
submod(X, 0, Ys). | |
submod(X, Sub, [Y|_]) when X =< Y -> | |
{Sub, X}; | |
submod(X, Sub, [Y|Ys]) -> | |
submod(X - Y, Sub + 1, Ys). | |
main([Year]) -> | |
D = pday(list_to_integer(Year)), | |
io:format("~s~n", [date_to_string(D)]); | |
main(_) -> | |
io:format("usage: escript pday.erl YEAR~n"). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment