Author Topic: sort a list of strings  (Read 1471 times)

0 Members and 1 Guest are viewing this topic.

Coder

  • Swamp Rat
  • Posts: 827
sort a list of strings
« on: July 05, 2020, 06:58:15 AM »
Hello guys.

I have a problem with sorting a list of strings based on the second item of the list ascendingly.

Code: [Select]
(setq the_list '(("Top Beam" "200x150") ("Left Beam" "200x100") ("Left Beam" "150x200") ("Bottom Beam" "225x75")
                 ("Bottom Beam" "100x200") ("Right Beam" "45x35") ("Bottom Beam" "100x175") ("Right Beam" "55x25")))

Code: [Select]
(vl-sort the_list
         '(lambda (x y)
            (< (cadr x) (cadr y))
          )
)
The result is not correct.

Thank you.

Dlanor

  • Bull Frog
  • Posts: 263
Re: sort a list of strings
« Reply #1 on: July 05, 2020, 09:40:59 AM »
Try this. It uses a string->list function

Code - Auto/Visual Lisp: [Select]
  1. (defun _split (str char / pos lst )
  2.   (while (vl-string-position (ascii char) str)
  3.           (setq lst (cons (substr str 1 (setq pos (vl-string-position (ascii char) str))) lst)
  4.                 str (substr str (+ 2 pos))
  5.           );end_setq
  6.   );end_while
  7.   (setq lst (vl-remove-if '(lambda (x) (= x "")) (reverse (cons str lst))))
  8. );end_defun
  9.  
  10. (setq the_list '(("Top Beam" "200x150") ("Left Beam" "200x100") ("Left Beam" "150x200") ("Bottom Beam" "225x75")
  11.                  ("Bottom Beam" "100x200") ("Right Beam" "45x35") ("Bottom Beam" "100x175") ("Right Beam" "55x25")))
  12.  
  13. (vl-sort the_list '(lambda (x y / a b)
  14.                      (setq a (_split (cadr x) "x") b  (_split (cadr y) "x"))
  15.                      (if (= (atoi (car a)) (atoi (car b))) (< (atoi (cadr a)) (atoi (cadr b))) (< (atoi (car a)) (atoi (car b))))
  16.                   )
  17. )
  18.  

Lee Mac

  • Seagull
  • Posts: 12912
  • London, England
Re: sort a list of strings
« Reply #2 on: July 05, 2020, 01:07:41 PM »
I might suggest something along the lines of the following:
Code - Auto/Visual Lisp: [Select]
  1. (defun mysort ( l )
  2.     (mapcar '(lambda ( n ) (nth n l))
  3.         (vl-sort-i (mapcar '(lambda ( x ) (read (strcat "(" (vl-string-subst " " "x" (cadr x)) ")"))) l)
  4.            '(lambda ( a b )
  5.                 (if (= (car  a) (car  b))
  6.                     (< (cadr a) (cadr b))
  7.                     (< (car  a) (car  b))
  8.                 )
  9.             )
  10.         )
  11.     )
  12. )
Code - Auto/Visual Lisp: [Select]
  1. _$ (mysort the_list)
  2. (
  3.     ("Right Beam"    "45x35")
  4.     ("Right Beam"    "55x25")
  5.     ("Bottom Beam" "100x175")
  6.     ("Bottom Beam" "100x200")
  7.     ("Left Beam"   "150x200")
  8.     ("Left Beam"   "200x100")
  9.     ("Top Beam"    "200x150")
  10.     ("Bottom Beam"  "225x75")
  11. )

Coder

  • Swamp Rat
  • Posts: 827
Re: sort a list of strings
« Reply #3 on: July 05, 2020, 02:49:39 PM »
Thank you Dlanor and Lee.

Both works great.