Get ent with max value using APPLY and MAPCAR

Get ent with max value using APPLY and MAPCAR

ВeekeeCZ
Consultant Consultant
1,163 Views
5 Replies
Message 1 of 6

Get ent with max value using APPLY and MAPCAR

ВeekeeCZ
Consultant
Consultant

Hello, I was trying figure out how to get entity name with max number using apply and mapcar.

 

Example

 

(setq lst '(("<Entname1>" . 1) ("<Entname2>" . 3) ("<Entname3>" . 2)))

;Goal: Get Entname with max number:
;Result: "<Entname2>"

;PS. String syntax is just for test purpose.

 

I came up with:  (but for opposite order in pairs...)

Spoiler
(setq emax (cdr (assoc (apply 'max (mapcar 'car lst)) lst)))

 

Maybe using vl-sort.... but I'am pretty sure there must be better way than using assoc or vl-sort... I have have too little experience with this... Thx.

0 Likes
1,164 Views
5 Replies
Replies (5)
Message 2 of 6

marko_ribar
Advisor
Advisor

This looks robust, but works...

(setq emax (cadr (assoc (apply 'max (mapcar 'car (mapcar 'reverse (mapcar '(lambda ( x ) (list (car x) (cdr x))) lst)))) (mapcar 'reverse (mapcar '(lambda ( x ) (list (car x) (cdr x))) lst)))))

Still (max) or (min) functions are limited to some number of items to process, so I strongly suggest that you construct (maxn) function...

 

(defun emax ( lst / maxn emax )

  (defun maxn ( l / x r )
    (if (cadr l)
      (progn
        (while (cadr l)
          (if (null r)
            (setq x (car l))
            (setq x r)
          )
          (if (> x (cadr l))
            (setq r x)
            (setq r (cadr l))
          )
          (setq l (cdr l))
        )
        r
      )
      (car l)
    )
  )

  (setq emax (cadr (assoc (maxn (mapcar 'car (mapcar 'reverse (mapcar '(lambda ( x ) (list (car x) (cdr x))) lst)))) (mapcar 'reverse (mapcar '(lambda ( x ) (list (car x) (cdr x))) lst)))))
  
  emax
)
Marko Ribar, d.i.a. (graduated engineer of architecture)
Message 3 of 6

Anonymous
Not applicable

(caar (vl-sort lst '(lambda (x y)(> (cdr x )(cdr y)))))

0 Likes
Message 4 of 6

Anonymous
Not applicable

(car (nth (vl-position (apply 'max (setq qlst (mapcar 'cdr lst))) qlst) lst))

0 Likes
Message 5 of 6

Anonymous
Not applicable

In case more than one entity contains the max number:

(mapcar 'car
  (vl-remove-if
    '(lambda (x)
      (/=
        (cdar
          (vl-sort lst '(lambda (x y)(> (cdr x )(cdr y))))
        )
        (cdr x)
      )
    )
  lst
  )
)
Message 6 of 6

ВeekeeCZ
Consultant
Consultant

Thank you guys, I like to see there are various possibilities.

 

But one thing caught my attention. As I can see, Marco converts dotted list into the regular because reverse function doesn't work with that. I noticed myself before, that (last '(0 . 0)) doesn't work either. So my question is what other limitations has dotted list? Why even use it? I know, it's an essential element definitions for all entities, but...

0 Likes