Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. use std::time::Instant;
  2.  
  3. fn sunday_the_first_in_year(start_day : usize, leap_year : bool) -> usize {
  4. let mut current_day = start_day;
  5. let mut sundays = 0;
  6. for i in 1..12 {
  7. if current_day == 0 {
  8. sundays += 1;
  9. }
  10.  
  11. let modulo = match i {
  12. 1 | 3 | 5 | 7 | 8 | 10 | 12 => {
  13. 31 % 7
  14. },
  15. 4 | 6 | 9 | 11 => {
  16. 30 % 7
  17. },
  18. 2 => {
  19. if leap_year {
  20. 29 % 7
  21. }else{
  22. 28 % 7
  23. }
  24. }
  25. _ => unreachable!()
  26. };
  27. current_day = (current_day + modulo) % 7;
  28. }
  29.  
  30. if current_day == 0 {
  31. sundays += 1;
  32. }
  33.  
  34. sundays
  35. }
  36.  
  37. pub fn counting_sundays() -> usize {
  38. let mut days : [usize;14] = [0;14];
  39.  
  40. for i in 0..7 {
  41. days[i] = sunday_the_first_in_year(i,false);
  42. days[i+7] = sunday_the_first_in_year(i,true);
  43. }
  44.  
  45. let mut sundays = 0;
  46. let mut start_day = 2;
  47. for year in 1901..2001 {
  48. let is_leap_year = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
  49.  
  50. let index = if is_leap_year {
  51. start_day + 7
  52. }else {
  53. start_day
  54. };
  55.  
  56. sundays += days[index];
  57.  
  58. if is_leap_year {
  59. start_day = (start_day + 2) % 7;
  60. }else{
  61. start_day = (start_day + 1) % 7;
  62. }
  63. }
  64.  
  65. sundays
  66. }
  67.  
  68. pub fn main() {
  69. let now = Instant::now();
  70. let solution = counting_sundays();
  71. println!("{} in {:?}", solution, now.elapsed());
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement