Add extremely broken day14pt2
[adventofcode2019.git] / src / adventofcode2019 / day14.clj
index e2aae3e11000ebd9e14f8920caec7d10234c9fea..8310b5eace0ea3e0188d37a99df694ca679045c5 100644 (file)
           (map parse-reaction input)))
 
 (defn reduce-reaction [graph producing consuming]
-  (let [[inputs moles] (graph producing)
+  (let [consuming (into #{} (if (coll? consuming) consuming [consuming]))
+        [inputs moles] (graph producing)
         in-chems (keys inputs)
         replace-term (fn [chem]
-                       (if (or (= chem consuming)
+                       (if (or (contains? consuming chem)
                                (neg? (second (graph chem))))
                          {chem (inputs chem)}
                          (let [ch-req (inputs chem)
@@ -27,7 +28,7 @@
                                conversion (int (Math/ceil (/ ch-req ch-mo)))]
                            (assoc (mmap (partial * conversion) ch-in)
                                   chem (- ch-req (* ch-mo conversion))))))
-        check-reduced (fn [[ch ct]] (and (not= ch consuming) (pos? ct)))
+        check-reduced (fn [[ch ct]] (and (not (contains? consuming ch)) (pos? ct)))
         reduced-inputs (reduce (partial merge-with +)
                                (map replace-term in-chems))
         new-graph (assoc graph producing [reduced-inputs moles])]
   (get-in (reduce-reaction graph producing consuming)
           [producing 0 consuming]))
 
+(defn produce-with [graph producing consuming cargo]
+  (println graph producing consuming cargo)
+  (let [cheapest-prod (get-in graph [producing 0])
+        exchange-rate (cheapest-prod consuming)
+        base-times (quot cargo exchange-rate)
+        extra-cargo (mod cargo exchange-rate)
+        extra-resources (assoc (->> cheapest-prod
+                                    (filter (comp neg? second))
+                                    (map (fn [[chem mole]]
+                                             [chem (* -1 base-times mole)]))
+                                    (into {})) consuming extra-cargo)
+        rewrite-with (into #{} (keys extra-resources))
+        second-chance (reduce-reaction graph producing rewrite-with)
+        recursive-times (map (fn [[chem ct]] 
+                                 (let [er (- (get-in second-chance [producing 0 chem]))]
+                                   (println chem ct er)
+                                   (quot ct er))) 
+                             extra-resources)]
+    recursive-times))
+
+(defn maximize-output [graph producing consuming cargo]
+  (produce-with (reduce-reaction graph producing consuming)
+                producing consuming cargo))
+
 (defn day14 []
   (let [graphed (make-graph (get-list-from-file (input-file)))]
     (part1 (find-lowest-exchange-rate graphed "FUEL" "ORE"))
-    #_(part2)))
+    (part2 (maximize-output graphed "FUEL" "ORE" 1000000000000))))