Skip to content

Commit 81c4a9b

Browse files
authored
Add doomsday algorithm (rust-lang#391)
1 parent 9ffcb51 commit 81c4a9b

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

src/math/doomsday.rs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
const T: [i32; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
2+
3+
pub fn doomsday(y: i32, m: i32, d: i32) -> i32 {
4+
let y = if m < 3 { y - 1 } else { y };
5+
(y + y / 4 - y / 100 + y / 400 + T[(m - 1) as usize] + d) % 7
6+
}
7+
8+
pub fn get_week_day(y: i32, m: i32, d: i32) -> String {
9+
let day = doomsday(y, m, d);
10+
let day_str = match day {
11+
0 => "Sunday",
12+
1 => "Monday",
13+
2 => "Tuesday",
14+
3 => "Wednesday",
15+
4 => "Thursday",
16+
5 => "Friday",
17+
6 => "Saturday",
18+
_ => "Unknown",
19+
};
20+
21+
day_str.to_string()
22+
}
23+
24+
#[cfg(test)]
25+
mod tests {
26+
use super::*;
27+
28+
#[test]
29+
fn doomsday_test() {
30+
assert_eq!(get_week_day(1990, 3, 21), "Wednesday");
31+
assert_eq!(get_week_day(2000, 8, 24), "Thursday");
32+
assert_eq!(get_week_day(2000, 10, 13), "Friday");
33+
assert_eq!(get_week_day(2001, 4, 18), "Wednesday");
34+
assert_eq!(get_week_day(2002, 3, 19), "Tuesday");
35+
}
36+
}

src/math/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ mod amicable_numbers;
22
mod armstrong_number;
33
mod baby_step_giant_step;
44
mod chinese_remainder_theorem;
5+
mod doomsday;
56
mod extended_euclidean_algorithm;
67
mod fast_fourier_transform;
78
mod fast_power;
@@ -36,6 +37,7 @@ pub use self::amicable_numbers::amicable_pairs_under_n;
3637
pub use self::armstrong_number::is_armstrong_number;
3738
pub use self::baby_step_giant_step::baby_step_giant_step;
3839
pub use self::chinese_remainder_theorem::chinese_remainder_theorem;
40+
pub use self::doomsday::get_week_day;
3941
pub use self::extended_euclidean_algorithm::extended_euclidean_algorithm;
4042
pub use self::fast_fourier_transform::{
4143
fast_fourier_transform, fast_fourier_transform_input_permutation,

0 commit comments

Comments
 (0)