2016-04-03 16 views
1

このコードで唯一間違っているのは、返品です。P1年に13番目の金曜日は何回ですか?

1年で金曜日の13日の表示回数を教えてください。

def unlucky_days(year) 
    require 'date' 

    start_date = Date.new(year) 
    end_date = Date.new(year+1) 
    my_fridays = [4] 
    thirteen = "13" 
    result = (start_date..end_date).to_a.select {|k| my_fridays.include?(k.wday) && thirteen.include?(k.strftime('%d'))} 

    result.length 


end 
+1

「このコードで間違っているのは返品だけです」とはどういう意味ですか? 'result.length'を返すので、数値を取得します。 'result'を返そうとしましたか? –

+0

申し訳ありません!問題をよりよく説明するために説明が更新されました。 1年で13番目の総数を求めた。 –

+0

金曜日の日曜日の番号は5で4ではなく5です。次に、単純な等価テストではなく、 'Array#include?'と 'String#include? ' –

答えて

2

あなたのコードはいくつかの点で間違っています。

  1. 金曜日は平日番号5、ない4.
  2. なぜ[4].include?(n)だけではなく、n==4のでしょうか?
  3. "13".include?("#{n}")は、それが1と3だけでなく、13

のためにtrueを返しますので、あなただけの12 13thsを見て、ブルートフォースのレベルに削減行くことができる、ただ奇妙なしかし間違ってはありませんそして多くは、@のtoklandの答えに、ここで再現して、両方の13日の金曜日ですそれらの金曜日ではなく、すべての365または366日を見ていると見ているか数える:

def unlucky_days(year) 
    (1..12).count { |month| Date.new(year, month, 13).friday? } 
end 
のみ14があるので

かを、可能であれば、あらかじめビルドされたテーブルを使用することもできます:

# number of Friday the 13ths in a given year is given by 
# UnluckyDays[weekday of Jan 1][0 if common, 1 if leap] 
UnluckyDays = [ [2,3], [2,2], [2,1], [1,2], [3,2], [1,1], [1,1] ] 
def unlucky_days(year) 
    UnluckyDays[Date.new(year,1,1).wday][Date.leap?(year) ? 1 : 0 ] 
end 
4

私が書きたい:

require 'date' 
(1..12).count { |month| Date.new(year, month, 13).friday? } 
2

+1を@ MarkReedのコメント。また、なぜDate class in Ruby.day.fridayのようなメソッドがある場合、なぜ範囲内で.to_aを呼び出すのですか?私はそれをどうするのですか?

def unlucky_days(year) 
    s = Date.new(year, 1, 1) 
    e = Date.new(year, 12, 31) 
    ((s...e).select {|d| d.friday? && d.day == 13 }).count 
end 
+0

すごい!あなたはおそらく私が本当にこれ(純粋な趣味)に新しいですが、毎日私はちょうどコードの柔軟性と優雅さに驚いていることがわかります! :Dありがとう –

1

これは@ Toklandの回答の変形です。キーで

require 'date' 

def count_em(year) 
    d = Date.new(year, 1, 13) << 1 
    12.times.count { (d >>= 1).friday? } 
end 

(2010..2016).each { |y| puts "%d Friday the 13ths in %s" % [count_em(y), y] } 
    # 1 Friday the 13ths in 2010 
    # 1 Friday the 13ths in 2011 
    # 3 Friday the 13ths in 2012 
    # 2 Friday the 13ths in 2013 
    # 1 Friday the 13ths in 2014 
    # 3 Friday the 13ths in 2015 
    # 1 Friday the 13ths in 2016 

この計算(またはそれのようなもの)が頻繁に行われ、パフォーマンスが重要だった場合、2つのハッシュを構築することができ、うるう年の1、非うるう年の他、週の日にその年の最初の日が下がり、値はその年の金曜日の13日の数になります。

関連する問題