How to resolve the algorithm Doomsday rule step by step in the V (Vlang) programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Doomsday rule step by step in the V (Vlang) programming language

Table of Contents

Problem Statement

John Conway (1937-2020), was a mathematician who also invented several mathematically oriented computer pastimes, such as the famous Game of Life cellular automaton program. Dr. Conway invented a simple algorithm for finding the day of the week, given any date. The algorithm was based on calculating the distance of a given date from certain "anchor days" which follow a pattern for the day of the week upon which they fall. The formula is calculated assuming that Sunday is 0, Monday 1, and so forth with Saturday 7, and which, for 2021, is 0 (Sunday). To calculate the day of the week, we then count days from a close doomsday, with these as charted here by month, then add the doomsday for the year, then get the remainder after dividing by 7. This should give us the number corresponding to the day of the week for that date. Given the following dates:

Use Conway's Doomsday rule to calculate the day of the week for each date.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Doomsday rule step by step in the V (Vlang) programming language

Source code in the v programming language

const 
(
	days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
	first_days_common = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]
	first_days_leap = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]
)

fn main() {
	dates := [
		"1800-01-06",
		"1875-03-29",
		"1915-12-07",
		"1970-12-23",
		"2043-05-14",
		"2077-02-12",
		"2101-04-02"
	]
	mut y, mut m, mut d, mut a, mut f, mut w, mut dow := 0,0,0,0,0,0,0
	println("Days of week given by Doomsday rule:")
	for date in dates {
		y = date[0..4].int()
		m = date[5..7].int()
		m--
		d = date[8..10].int()
		a = anchor_day(y)
		f = first_days_common[m]
		if is_leap_year(y) {
			f = first_days_leap[m]
		}
		w = d - f
		if w < 0 {
			w = 7 + w
		}
		dow = (a + w) % 7
		println('$date -> ${days[dow]}')
	}
}

fn anchor_day(y int) int {
	return (2 + 5 *(y % 4) + 4 * (y % 100) + 6 *(y % 400)) % 7
}

fn is_leap_year(y int) bool { 
	return y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) 
}

  

You may also check:How to resolve the algorithm Death Star step by step in the Raku programming language
You may also check:How to resolve the algorithm Random numbers step by step in the Sidef programming language
You may also check:How to resolve the algorithm Binary digits step by step in the Free Pascal programming language
You may also check:How to resolve the algorithm Hash join step by step in the ECL programming language
You may also check:How to resolve the algorithm URL encoding step by step in the FutureBasic programming language