美文网首页
和果子一起来做题-Project Euler-19-R语言版本

和果子一起来做题-Project Euler-19-R语言版本

作者: 9d760c7ce737 | 来源:发表于2018-01-28 18:24 被阅读18次
    You are given the following information, but you may prefer to do some research for yourself.
    1 Jan 1900 was a Monday.
    Thirty days has September,
    April, June and November.
    All the rest have thirty-one,
    Saving February alone,
    Which has twenty-eight, rain or shine.
    And on leap years, twenty-nine.
    A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
    How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
    

    构造一个函数计算每个月初距离1 Jan 1900的天数

    只需要判断是否闰年,这里面只有2000特殊,但是2000正好能被400整除。

    n<- c()
    n[1] <- 0
    for (i in 2:1212){
      if ((1900 +((i-1) %/%12)) %% 4 ==0 ){
        dm <- c(31,29,31,30,31,30,31,31,30,31,30,31)
      }else{
        dm <- c(31,28,31,30,31,30,31,31,30,31,30,31)
      }
      n[i] <- n[i-1] +dm[(i-2)%%12+1] 
    }
    

    去掉1900年的12个月

    n <- n[-c(1:12)]
    

    判断这些月首里面有多少个星期一

    这些天数除以7,如果能整除,这些天就是星期天。

    > sum(n[n!=0]%%7 == 0)
    [1] 171
    

    下面这个方法更加容易理解:

    date.leap <- c(1:31, 1:29, 1:31, 1:30, 1:31, 1:30, 1:31, 1:31, 1:30, 1:31, 1:30, 1:31)
    date.norm <- c(1:31, 1:28, 1:31, 1:30, 1:31, 1:30, 1:31, 1:31, 1:30, 1:31, 1:30, 1:31)
    

    这个很巧妙,所有这101年的日子全部排开

    dates <- c(date.norm, rep(c(rep(date.norm, 3), date.leap), 25))  
    

    选出是月初的日子,用which返回他们的序号,实际上就是距离1900 1月1日的天数

    firsts <- which(dates == 1) 
    

    去掉1900年的12个月初

    firsts <- firsts[-c(1:12)]  
    

    找出是星期天的月初

    result <- sum(firsts %% 7 == 0)
    cat("The result is:", result, "\n")
    

    依然是171个。

    相关文章

      网友评论

          本文标题:和果子一起来做题-Project Euler-19-R语言版本

          本文链接:https://www.haomeiwen.com/subject/efezaxtx.html