How to resolve the algorithm Day of the week step by step in the OCaml programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Day of the week step by step in the OCaml programming language

Table of Contents

Problem Statement

A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).

In what years between 2008 and 2121 will the 25th of December be a Sunday? Using any standard date handling libraries of your programming language; compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to   y2k   type problems.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Day of the week step by step in the OCaml programming language

Source code in the ocaml programming language

#load "unix.cma"
open Unix

try
  for i = 2008 to 2121 do
    (* I'm lazy so we'll just borrow the current time
       instead of having to set all the fields explicitly *)
    let mytime = { (localtime (time ())) with
                   tm_year  = i - 1900;
                   tm_mon   = 11;
                   tm_mday  = 25 } in
    try
      let _, mytime = mktime mytime in
        if mytime.tm_wday = 0 then
          Printf.printf "25 December %d is Sunday\n" i
    with e ->
      Printf.printf "%d is the last year we can specify\n" (i-1);
      raise e
  done
with _ -> ()


open CalendarLib

let list_make_seq first last =
  let rec aux i acc =
    if i < first then acc
    else aux (pred i) (i::acc)
  in
  aux last []
 
let print_date (year, month, day) =
  Printf.printf "%d-%02d-%02d\n" year month day
 
let () =
  let years = list_make_seq 2008 2121 in
  let years = List.filter (fun year ->
    Date.day_of_week (Date.make year 12 25) = Date.Sun) years in
  print_endline "December 25 is a Sunday in:";
  List.iter (Printf.printf "%d\n") years


  

You may also check:How to resolve the algorithm Assertions step by step in the Smalltalk programming language
You may also check:How to resolve the algorithm Arithmetic numbers step by step in the Pascal programming language
You may also check:How to resolve the algorithm Sorting algorithms/Shell sort step by step in the Liberty BASIC programming language
You may also check:How to resolve the algorithm Enforced immutability step by step in the Haskell programming language
You may also check:How to resolve the algorithm Roots of a function step by step in the PicoLisp programming language