A0: Warmup

https://www.cs.cornell.edu/courses/cs3110/2020sp/a0/

Time taken to implement ~ 4h 30min.
This commit is contained in:
Vladan Popovic 2020-06-11 23:11:45 +02:00
parent 36b190b716
commit 98d37ebf50

47
warmup.ml Normal file
View file

@ -0,0 +1,47 @@
(* requires: y >= 0 *)
(* requires: d >= 0 *)
let valid_date (y: int) (m: string) (d: int) =
if y < 0 || d < 0 then false
else match m with
| "Jan" | "Mar" | "May" | "Jul" | "Aug" | "Oct" | "Dec" -> d < 32
| "Feb" -> if (y mod 4 == 0) && (y mod 100 <> 0) then d < 30 else d < 29
| "Apr" | "Jun" | "Sep" | "Nov" -> d < 31
| _ -> false
(* Test leap day in a non-century leap year. *)
let () = assert (valid_date 2020 "Feb" 29)
(* Test invalid day. *)
let () = assert (not (valid_date 2010 "Jun" 50))
(* requires: n > 0 *)
let syr n =
let rec collatz n res =
if n == 1 then res
else if n mod 2 == 0 then collatz (n/2) (res+1)
else collatz ((n*3)+1) (res+1) in collatz n 0
(* Test syr *)
let () = assert (syr 1 = 0)
let () = assert (syr 2 = 1)
let () = assert (syr 10 = 6)
let () = assert (syr 3 = 7)
let rec next_nacci n l sum =
if n = 0 then sum
else match l with
| [] -> next_nacci (n - 1) [] sum
| h :: t -> next_nacci (n - 1) t (sum + h)
let nacci n k =
let rec tail_nacci n k res =
if k = 0 then res
else tail_nacci n (k - 1) ((next_nacci n res 0) :: res)
in if k = 1 || k = 0 then [1] else List.rev (tail_nacci n (k - 2) [1; 1])
let () = assert (nacci 2 6 = [1; 1; 2; 3; 5; 8])
let () = assert (nacci 4 9 = [1; 1; 2; 4; 8; 15; 29; 56; 108])
let () = assert (nacci 5 9 = [1; 1; 2; 4; 8; 16; 31; 61; 120])
let () = assert (nacci 7 9 = [1; 1; 2; 4; 8; 16; 32; 64; 127])