一年中有多少个星期五13号?

时间:2016-04-03 22:07:39

标签: ruby date

此代码中唯一错误的是返回:P

你怎么能在一年中显示那里的星期五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

4 个答案:

答案 0 :(得分:4)

我写道:

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

答案 1 :(得分:2)

您的代码在几点上是错误的。

  
      
  1. 星期五是工作日5号,而不是4号。
  2.   
  3. 为什么[4].include?(n)而不只是n==4
  4.   
  5. "13".include?("#{n}")不仅奇怪而且不正确,因为它为1和3以及13返回true。
  6.   

你可以通过查看十二月十三日并计算星期五的数量来减少蛮力水平,而不是查看所有365或366天,看看它们中的哪一个都是13日和星期五,如@ tokland的回答,转载于此:

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

答案 2 :(得分:2)

+1来@ MarkReed的评论。另外,为什么在某个范围内调用.to_a,以及为什么在Date class in Ruby已有.day.friday等方法时使用变量?我将如何做到这一点:

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

答案 3 :(得分: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

如果这个计算(或类似的计算)经常完成并且性能很重要,可以构建两个哈希值,一个用于闰年,另一个用于非闰年,用键表示第一天的星期几年度下降和价值这些年份的星期五13日。

相关问题