Quest 2: From Complex to Clarity

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL

Link to participate: https://everybody.codes/

  • ystael@beehaw.org
    link
    fedilink
    arrow-up
    2
    ·
    5 days ago

    I was sad to discover that division wasn’t actual complex division. As in some other languages, one has to implement this “division” by hand because the library designers assume that you never want truncating integer division together with complex numbers. Which is reasonable, I guess.

    (ql:quickload :cl-ppcre)
    (ql:quickload :str)
    
    (defun parse-line (line)
      (ppcre:register-groups-bind
          (name x y)
          ("^([A-Za-z]+)=[[]([\-0-9.]+),([\-0-9.]+)[]]$" line)
        (cons name (complex (parse-integer x) (parse-integer y)))))
    
    (defun read-inputs (filename)
      (let ((input-lines (uiop:read-file-lines filename)))
        (parse-line (car input-lines))))
    
    (defun fake-complex-division (y d)
      (complex (truncate (realpart y) (realpart d))
               (truncate (imagpart y) (imagpart d))))
    
    (defun f (x a)
      (+ a (fake-complex-division (* x x) #C(10 10))))
    
    (defun main-1 (filename)
      (let* ((a (cdr (read-inputs filename)))
             (result (f (f (f #C(0 0) a) a) a)))
        (str:concat "["
                    (write-to-string (realpart result))
                    ","
                    (write-to-string (imagpart result))
                    "]")))
    
    (defun engrave? (p)
      (labels ((iter (x n)
                 (if (zerop n)
                     t
                     (let ((next-x (+ p (fake-complex-division (* x x) #C(100000 100000)))))
                       (if (or (> (abs (realpart next-x)) 1000000)
                               (> (abs (imagpart next-x)) 1000000))
                           nil
                           (iter next-x (- n 1)))))))
        (iter 0 100)))
    
    (defun count-engraves (a spacing)
      (let ((steps (/ 1000 spacing)))
        (loop for x from 0 to steps
              sum (loop for y from 0 to steps
                        for p = (+ a (complex (* spacing x) (* spacing y)))
                        sum (if (engrave? p) 1 0)))))
    
    (defun main-2 (filename)
      (count-engraves (cdr (read-inputs filename)) 10))
    
    (defun main-3 (filename)
      (count-engraves (cdr (read-inputs filename)) 1))