Introduction
My Clojure skills are rarely used, but it is a fun language for thinking outside the box. I'll jump at a chance to apply it. So I jumped at Advent of Code 2019!
Day 1.1
The first test was nice and simple for Clojure. Iterating over collections and then summing the result is a breeze.
As I suspected the calculation for the amount of fuel would need to be reused, I broke it into its own function. I was glad I did.
This is the code that produces the correct answer to Day 1.1. I moved the inputs into their own inputs.clj
file to avoid cluttering my code. day1_masses
is the input provided by Advent of Code. I packaged it into a vector for index access.
(ns advent.core
(:gen-class)
(:require [advent.inputs :refer [day1_masses]]))
(defn day1_fuel_calc
"I do the fuel calculation as defined for day 1"
[mass]
(- (int (Math/floor (/ mass 3))) 2))
(defn day1_1
"I take the mass vector and produce a single fuel requirement"
[mass_vec]
(reduce + (map day1_fuel_calc mass_vec)))
(defn -main
"I call the functions for the Advent of Code"
[]
(println "Day 1.1 - Module masses only:" (day1_1 day1_masses)))
Day 1.2
Once again, the second part of the day utilized some nice Clojure features. In this case, loop/recur. I used the day1_2
function with map to produce a collection of individual fuel calculations. The additional fuel is calculated per individual mass, not total mass, so having the map/reduce in the day1_2
function would have been too complicated. For cleanliness, I should really have another function perform the map/reduce and call that function from main
, but it's not overly messy.
The following code produces the correct result.
(ns advent.core
(:gen-class)
(:require [advent.inputs :refer [day1_masses]]))
(defn day1_fuel_calc
"I do the fuel calculation as defined for day 1"
[mass]
(- (int (Math/floor (/ mass 3))) 2))
(defn day1_2
"I take the individual masses for each item, work out the fuel requirement for each item, and then recursively calculate the fuel requirement for the fuel"
[mass]
(loop [fuel_needed (day1_fuel_calc mass)
total_fuel 0]
(if (< fuel_needed 0)
total_fuel
(recur (day1_fuel_calc fuel_needed) (+ total_fuel fuel_needed)))))
(defn -main
"I call the functions for the Advent of Code"
[]
(println "Day 1.2 - Fuel for the fuel:" (reduce + (map day1_2 day1_masses))))
Top comments (0)