let make_spiral n = if n mod 2 = 0 then raise (Invalid_argument "Size should be odd"); let res = Array.make_matrix n n 0 in let last_value = n * n in let current_value = ref 1 in let i = ref (n / 2) in let j = ref (n / 2) in let shift = ref 1 in let delta = ref 1 in res.(!i).(!j) <- !current_value; while !current_value < last_value do for k = 1 to !shift do if !current_value < last_value then begin j := !j + !delta; current_value := !current_value + 1; res.(!i).(!j) <- !current_value; end; done; for k = 1 to !shift do if !current_value < last_value then begin i := !i + !delta; current_value := !current_value + 1; res.(!i).(!j) <- !current_value; end; done; delta := - !delta; shift := !shift + 1; done; res;; let sum_diagonals arr = let size = Array.length arr in let sum = ref 0 in for i = 0 to size - 1 do sum := !sum + arr.(i).(i) + arr.(i).(size - 1 - i) done; !sum - 1;; Printf.printf "%d\n" (sum_diagonals (make_spiral 1001));;Very bad OCaml ;)
mercredi 28 avril 2010
Project Euler #28
Inscription à :
Publier les commentaires (Atom)
Aucun commentaire:
Enregistrer un commentaire