Code Red > AutoLISP (Vanilla / Visual)

sort a list of strings

(1/1)

Coder:
Hello guys.

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


--- Code: ---(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")))

--- End code ---


--- Code: ---(vl-sort the_list
         '(lambda (x y)
            (< (cadr x) (cadr y))
          )
)

--- End code ---
The result is not correct.

Thank you.

Dlanor:
Try this. It uses a string->list function


--- Code - Auto/Visual Lisp: ---(defun _split (str char / pos lst )  (while (vl-string-position (ascii char) str)          (setq lst (cons (substr str 1 (setq pos (vl-string-position (ascii char) str))) lst)                str (substr str (+ 2 pos))          );end_setq  );end_while  (setq lst (vl-remove-if '(lambda (x) (= x "")) (reverse (cons str lst)))));end_defun (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"))) (vl-sort the_list '(lambda (x y / a b)                      (setq a (_split (cadr x) "x") b  (_split (cadr y) "x"))                     (if (= (atoi (car a)) (atoi (car b))) (< (atoi (cadr a)) (atoi (cadr b))) (< (atoi (car a)) (atoi (car b))))                  )) 

Lee Mac:
I might suggest something along the lines of the following:

--- Code - Auto/Visual Lisp: ---(defun mysort ( l )    (mapcar '(lambda ( n ) (nth n l))        (vl-sort-i (mapcar '(lambda ( x ) (read (strcat "(" (vl-string-subst " " "x" (cadr x)) ")"))) l)           '(lambda ( a b )                (if (= (car  a) (car  b))                    (< (cadr a) (cadr b))                    (< (car  a) (car  b))                )            )        )    ))
--- Code - Auto/Visual Lisp: ---_$ (mysort the_list)(    ("Right Beam"    "45x35")    ("Right Beam"    "55x25")    ("Bottom Beam" "100x175")    ("Bottom Beam" "100x200")    ("Left Beam"   "150x200")    ("Left Beam"   "200x100")    ("Top Beam"    "200x150")    ("Bottom Beam"  "225x75"))

Coder:
Thank you Dlanor and Lee.

Both works great.

Navigation

[0] Message Index

Go to full version