challenge LL Golf Hole 3 - 13日の金曜日を数え上げる

今日から2013年12月31日までの、13日の金曜日とその総数を表示してください。

余力のあるものはこのプログラムを短くしてみたり、短くしてみたり、短くしてください。

※LL Future実行委員の高野光弘です。この出題は LL Future公式の出題であり、優れたものについてはLL Golfのセッションでご紹介させていただくかもしれません。ご理解の上、ご投稿ください。また、LL Futureのチケットは現在も発売中です。よろしければ、メインイベントの方にもぜひご参加ください。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#!/usr/bin/env ruby
require 'date'

from = DateTime.now
to = DateTime.parse("2013-12-31")

friday = (from..to).inject(0) do |friday, date|
    if date.mday == 13 and date.wday == 5 then
        puts date.strftime('%Y-%m-%d')
        friday + 1
    else
        friday
    end
end

puts friday

Posted feedbacks - C

ツェラーの公式を変形して。「今日の日付」はコマンドライン引数でもらいます。

$ ./fri13 2008 8 7
'09年2月13日
'09年3月13日
'09年11月13日
'10年8月13日
'11年5月13日
'12年1月13日
'12年4月13日
'12年7月13日
'13年9月13日
'13年12月13日
総数:10個
$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
#include <stdlib.h>

int main(int c, char *v[]) {
  int n = 0, y, m, y0 = atoi(v[1])-2000, m0 = atoi(v[2]);
  if (m0 < 3) { y0--; m0 += 12; }
  for (y = y0; y < 14; y++)
    for (m = 3; m < 15; m++) {
      if (y == y0 && (m < m0 || (m == m0 && atoi(v[3]) > 13))) continue;
      if (!((26*(m+1)/10+y+y/4)%7)) {
        printf("'%02d年%d月13日\n", (m>=13)?y+1:y, (m>=13)?m-12:m);
        n++;
      }
    }
  printf("総数:%d個\n", n);

  return 0;
}

Cだとmktime(3C)を使うと便利です。
まぁ、ほんとにmktime()が本領発揮するのは日時へ変換したときなのですけど^^;;

// gcc -Wall -std=c99 doukaku197.c -o doukaku197
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <stdio.h>
#include <time.h>

static const char *weekdayname[] = {"Sun","Mon","Tue","Wed","Thi","Fri","Sat"};

int main(int argc, char *argv[])
{
    static const int YEAR_END = (2013 - 1900) + 1;
    struct tm t      = {0};
    time_t    now    = 0;
    int       count  = 0;

    now = time(NULL);
    localtime_r(&now, &t);
    t.tm_mday = 13; // 13日固定

    /* 2014年までの13日の金曜日を検索する */
    count = 0;
    while( t.tm_year < YEAR_END )
    {
        // 13日の金曜日を探す
        if( t.tm_wday == 5 )
        {
            // 13日の金曜日なら表示してカウントアップ
            printf("%d/%02d/%02d (%s)\n"
                    , t.tm_year+1900, t.tm_mon+1, t.tm_mday
                    , weekdayname[ t.tm_wday ]);
            count ++;
        }
        t.tm_mon ++;
        mktime( &t ); // 日時の再計算(正規化)
    }
    printf("COUNT:[%d]\n", count);

    return 0;
}
/* EOF */

Index

Feed

Other

Link

Pathtraq

loading...