Sunday, September 8, 2024

use elisp to find lowest price per category

evaluated.org
** Lowest Price Item In Each Category

| Category             | Price | Item            |
|----------------------|-------|-----------------|
| beverages            | 1.95  | canned pop      |
| side-orders          | 1.15  | gravy on fries  |
| subs                 | 5.45  | veggie (small)  |
| hot-sandwiches       | 11.95 | hot hamburger   |
| on-a-bun             | 5.25  | hamburger       |
| ask-your-server      | 3.95  | s.o.t.d         |
| salads               | 4.15  | small tossed salad |
| sandwiches           | 5.15  | fried egg       |
| pitas                | 6.25  | breakfast       |
| omelets              | 9.95  | cheese          |
| french-toast-and-pancakes | 3.75 | 1 lg pancake |
| breakfast-sides      | 1.75  | muffin          |
| breakfast            | 9.25  | meatless        |


** lisp code to find lowest price per category

#+BEGIN_SRC emacs-lisp :results output
(defun find-lowest-price-per-category ()
  "Find the item with the lowest price for each category from an Org table."
  (interactive)
  ;; Ensure we're in an Org table
  (when (org-at-table-p)
    (let ((table (org-table-to-lisp))
          (result '()))
      ;; Skip the header row
      (dolist (row (cdr table))
        (let* ((category (nth 0 row))
               (item (nth 1 row))
               (price (string-to-number (nth 2 row)))
               (existing-entry (assoc category result)))
          (if existing-entry
              (let ((current-lowest (cdr existing-entry)))
                (if (< price (car current-lowest))
                    (setcdr existing-entry (cons price item))
                  ;; Do nothing if the current price is not lower
                  ))
            (push (cons category (cons price item)) result))))
      ;; Print the result in the buffer
      (with-output-to-temp-buffer "*Lowest Prices by Category*"
        (dolist (entry result)
          (let ((category (car entry))
                (lowest (cdr entry)))
            (princ (format "%s: %.2f - %s\n" category (car lowest) (cdr lowest)))))))))

;; Bind the function to a key for easy access
(global-set-key (kbd "C-c l") 'find-lowest-price-per-category)
#+END_SRC

No comments:

Post a Comment