バッチファイルでProject Euler(45)

Problem 19


この問題は月の日数が必要ですが、

call :set_v m 31 28 31 30 31 30 31 31 30 31 30 31

として、%m1%などとして取り出します。
本当は、1年の初めの曜日とうるう年かをキーにしてメモ化すればよいですが、
そこまでする必要もないでしょう。

@echo off

setlocal enabledelayedexpansion
call :set_v m 31 28 31 30 31 30 31 31 30 31 30 31
set /a w = 1
set /a num_sunday = 0
call :num_1st_sunday 1900
for /L %%y in (1901, 1, 2000) do (
    call :num_1st_sunday %%y
    set /a num_sunday += !ERRORLEVEL!
)
echo %num_sunday%
exit /b 0

:num_1st_sunday
    set /a counter = 0
    for /L %%m in (1, 1, 12) do (
        if !w! == 0 set /a counter += 1
        call :num_days %1 %%m
        set /a w += !ERRORLEVEL!
        set /a w %%= 7
    )
    exit /b %counter%

:num_days
    setlocal
    set /a n = "m_%2"
    if %2 NEQ 2 exit /b %n%
    call :is_leap_year %1
    set /a n += %ERRORLEVEL%
    exit /b %n%

:is_leap_year
    setlocal
    set /a y = %1
    set /a r4 = %y% %% 4
    if %r4% NEQ 0 exit /b 0
    set /a r100 = %y% %% 100
    if %r100% NEQ 0 exit /b 1
    set /a r400 = %y% %% 400
    if %r400% NEQ 0 exit /b 0
    exit /b 1

:set_v
    set /a m = 1
    :loop_set_v
        if "%2" == "" exit /b 0
        set /a %1_%m% = %2
        shift /2
        set /a m += 1
        goto :loop_set_v
    exit /b 0