Re-sorting a list of pairs by like elements

Discussion in 'AutoCAD' started by Jason Piercey, Apr 14, 2004.

  1. For the life of me I can't seem to come up with a
    solution for the following.

    Original list
    '((1 . "A") (2 . "A") (3 . "B") (4 . "B") (5 . "C"))

    Sorted list
    '(("A" 1 2) ("B" 3 4) ("C" 5))

    Anyone care to provide a lesson?
     
    Jason Piercey, Apr 14, 2004
    #1
  2. Thanks, Michael. I'll give 'er a go.

    --

    Autodesk Discussion Group Facilitator


    <snip>
     
    Jason Piercey, Apr 14, 2004
    #2
  3. Jason Piercey

    Doug Broad Guest

    One possiblitity, assuming the initial list is already key sorted.

    (defun collect (lst / result key) ;;D. C. Broad
    (foreach n lst
    (setq key (cdr n)
    result
    (if (assoc key result)
    (subst (append (assoc key result) (list (car n))) (assoc key result) result)
    (cons (list (cdr n) (car n)) result))))
    (reverse result))
     
    Doug Broad, Apr 14, 2004
    #3
  4. You're welcome Jason. Once you get your head
    wrapped around it distilling it is easy.

    This version also ensures the cdr data is sorted:

    (defun foo42 ( lst / key item result )
    (vl-sort
    (mapcar
    '(lambda (x) (cons (car x) (vl-sort (cdr x) '<)))
    (foreach x lst
    (setq result
    (if (setq item (assoc (setq key (cdr x)) result))
    (subst
    (cons key (cons (car x) (cdr item)))
    item
    result
    )
    (cons
    (cons key (list (car x)))
    result
    )
    )
    )
    )
    )
    '(lambda (a b) (< (car a) (car b)))
    )
    )

    (foo42
    '(
    (5 . "C")
    (2 . "A")
    (4 . "B")
    (3 . "B")
    (1 . "A")
    )
    )

    (("A" 1 2) ("B" 3 4) ("C" 5))

    You may wish to revamp the sort algor for the
    cdr data given vl-sort's, ummm behavior.
     
    michael puckett, Apr 14, 2004
    #4
  5. Thanks for contributing, Doug.
     
    Jason Piercey, Apr 14, 2004
    #5
  6. In this particular case the order really isn't of
    any concern, just the grouping. Perhaps my
    example was poor in showing things sorted.


    Thanks again.
     
    Jason Piercey, Apr 14, 2004
    #6
Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.