Xah Talk Show 2022-12-29 Advent of Code Day 5, in Emacs Lisp, Live Coding

    [D]
[N] [C]
[Z] [M] [P]
 1   2   3

move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2
                        [R] [J] [W]
            [R] [N]     [T] [T] [C]
[R]         [P] [G]     [J] [P] [T]
[Q]     [C] [M] [V]     [F] [F] [H]
[G] [P] [M] [S] [Z]     [Z] [C] [Q]
[P] [C] [P] [Q] [J] [J] [P] [H] [Z]
[C] [T] [H] [T] [H] [P] [G] [L] [V]
[F] [W] [B] [L] [P] [D] [L] [N] [G]
 1   2   3   4   5   6   7   8   9
(setq xinput "    [D]
[N] [C]
[Z] [M] [P]
 1   2   3

move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2")

;; first, split the input into 2 parts

(setq xinputParts (split-string xinput "\n\n"))

(setq xBoxesText (nth 0 xinputParts))
(setq xProcedure (nth 1 xinputParts))

;; split the boxes input, per line, into a list of 4 chars

(setq xBoxesLineList (split-string xBoxesText "\n"))

(setq
 xNumOfColumns
 (string-to-number
  (car (last
        (split-string
         (car (last xBoxesLineList)) " +")))))

;; drop the last time
(setq xBoxesLineList (reverse (rest (reverse xBoxesLineList))))

(require 'subr-x)

;; a list of list. each sublist is a row of boxes
(setq xBoxMatrix nil)

;; built the xBoxMatrix
(mapc
 (lambda (x)
   (let ((xx (string-pad x (* 4 xNumOfColumns) 32))
         (xlist nil))
     (message "%s" xx)
     ;; split each line, into 4 chars
     (while (not (equal (length xx) 0))
       (push (string-trim (substring xx 0 4)) xlist)
       (setq xx (substring xx 4)))
     (setq xlist (reverse xlist))
     (message "%s" xlist)
     (push xlist xBoxMatrix)))
 xBoxesLineList)

(setq xBoxMatrix (reverse xBoxMatrix))

;; convert xBoxMatrix into a netsed vector
(setq xBoxMatrix
      (vconcat
       (mapcar
        (lambda (x) (vconcat x))
        xBoxMatrix)))
;; [["" "[D]" ""] ["[N]" "[C]" ""] ["[Z]" "[M]" "[P]"]]

(defun xah-transpose (Matrix)
  "transpose a matrix.
the matrix is assumed to be 2D.
and assumed to be nested vector, not list.
 before
 a b c
 d e f
 after transpose
 a d
 b e
 c f
Version 2022-12-29"
  (interactive)
  (let (($flatList '())
        ($rowCount (length Matrix))
        ($colCount (length (aref Matrix 0))))
    (message "row count %s" $rowCount)
    (message "col count %s" $colCount)

    (dotimes (i COUNT [RESULT])
      (dotimes (j COUNT [RESULT])
        ;; # python
        ;; # transpose, body of
        ;; temp = arr[i][j]
        ;; arr[i][j] = arr[j][i]
        ;; arr[j][i] = temp
        ))

    (mapc
     (lambda (x)
       (mapc
        (lambda (y) (push y $flatList))
        x))
     Matrix)
    (seq-partition (reverse $flatList) $rowCount)
    ;; (vconcat (seq-partition $flatList $rowCount))
    ;;
    ))

(xah-transpose
[
[1 2 3]
[4 5 6]
]
)

Emacs Lisp: Transpose Matrix 🚀