Created
December 18, 2024 03:36
-
-
Save Alwinfy/7ab43ce57ac0853e952f4643efa90c1d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(def prgn | |
[2 4 | |
1 2 | |
7 5 | |
0 3 | |
1 7 | |
4 1 | |
5 5 | |
3 0]) | |
(defn sdecode-arg [arg] | |
(case arg | |
(0 1 2 3) arg | |
4 :a | |
5 :b | |
6 :c)) | |
(defn sdecode [op arg] | |
(case op | |
0 [:shra :a (sdecode-arg arg)] | |
6 [:shra :b (sdecode-arg arg)] | |
7 [:shra :c (sdecode-arg arg)] | |
1 [:xorb arg] | |
2 [:movb (sdecode-arg arg)] | |
3 [:jnza arg] | |
4 [:xorb :c] | |
5 [:out (sdecode-arg arg)])) | |
(prn (map (partial apply sdecode) (partition 2 prgn))) | |
(def state | |
{:ip 0 | |
:a 27334280 | |
:b 0 | |
:c 0 | |
:out []}) | |
(defn decode [state op] | |
(case op | |
(0 1 2 3) op | |
4 (:a state) | |
5 (:b state) | |
6 (:c state))) | |
(defn shra [state op] | |
(bit-shift-right (:a state) (decode state op))) | |
(def ops | |
; shra | |
[(fn [state op] (assoc state :a (shra state op))) | |
; bxl | |
(fn [state op] (update state :b bit-xor op)) | |
; bst | |
(fn [state op] (assoc state :b (bit-and 7 (decode state op)))) | |
; jnz | |
(fn [state op] | |
(cond-> state | |
(not (zero? (:a state))) | |
(assoc :ip op))) | |
; bxc | |
(fn [state _] (update state :b bit-xor (:c state))) | |
; out | |
(fn [state op] (update state :out conj (bit-and 7 (decode state op)))) | |
; bdv | |
(fn [state op] (assoc state :b (shra state op))) | |
; cdv | |
(fn [state op] (assoc state :c (shra state op)))]) | |
(defn small-step [prog state] | |
(let [{ip :ip} state] | |
(when-let [op (get prog ip)] | |
((ops op) | |
(update state :ip + 2) | |
(prog (inc ip)))))) | |
(defn trace [prog state] | |
(take-while some? (iterate (partial small-step prog) state))) | |
(println (clojure.string/join "," (:out (last (trace prgn state))))) | |
(defn first-output [trace] | |
(some (comp first :out) trace)) | |
(defn generate-a [a-values target] | |
(filter | |
(fn [a] | |
(->> a | |
(assoc state :a) | |
(trace prgn) | |
first-output | |
(= target))) | |
(for [a a-values | |
i (range 8)] | |
(+ (* 8 a) i)))) | |
(prn (first (reduce generate-a [0] (reverse prgn)))) | |
;(prn (map Long/toOctalString (reduce generate-a [0] (reverse prgn)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment