Author Topic: Assoc List - Group By Keys  (Read 647 times)

0 Members and 1 Guest are viewing this topic.

Marc'Antonio Alessi

  • Swamp Rat
  • Posts: 776
  • Marco
Re: Assoc List - Group By Keys
« Reply #15 on: October 09, 2017, 03:38:51 pm »
Just a little faster
Code: [Select]
(defun ALE_GroupByKey2 (lst / TKey OKey RKey keys tmpL OutLst)
  (setq TKey (strcat "#" (caar lst))  keys (list TKey))
  (set (read TKey) (list (caar lst) (cdar lst)))
  (foreach itm (cdr lst)
    (setq OKey (car itm)   tmpL (cdr itm) TKey (strcat "#" OKey)  RKey (read TKey))
    (if (vl-position TKey keys)
      (set RKey (vl-list* OKey tmpL (cdr (eval RKey))))
      (progn
        (set RKey (list OKey tmpL))
        (setq keys (cons TKey keys))
      )
    )
  )
  (foreach itm keys
    (setq RKey (read itm)  OutLst (cons (eval RKey) OutLst))
    (set RKey nil)
  )
  OutLst
)
Code: [Select]
Benchmark.lsp | 2005 Michael Puckett | All Rights Reserved
Elapsed milliseconds / relative speed for 1 iteration(s):
    (ALE_GROUPBYKEY2 TEST1)......2547 / 1.05 <fastest>
    (GROUPBYKEY-FOOLS TEST1).....2672 / 1 <slowest>
Marc'Antonio Alessi http://alessi.xoom.it//alessi/  Coding manual: http://tinyurl.com/zza7ega

Marc'Antonio Alessi

  • Swamp Rat
  • Posts: 776
  • Marco
Re: Assoc List - Group By Keys
« Reply #16 on: October 10, 2017, 08:46:18 am »
Other 2 versions slower on big lists:
Code: [Select]
(defun ALE_GroupByKey3 (l / k s r p)
  (foreach i l
    (if (vl-position (setq k (car i)) s)
      (setq p (assoc k r)  r (subst (vl-list* (car i) (cdr i) (cdr p)) p r))
      (setq s (cons k s)   r (cons (list k (cdr i)) r))
    )
  )
)
(defun ALE_GroupByKey4 (l / k s r p x)
  (foreach i l
    (if (setq x (vl-position (setq k (car i)) s))
      (setq p (nth x r)    r (subst (vl-list* (car i) (cdr i) (cdr p)) p r))
      (setq s (cons k s)   r (cons (list k (cdr i)) r))
    )
  )
)
« Last Edit: October 10, 2017, 10:06:20 am by Marc'Antonio Alessi »
Marc'Antonio Alessi http://alessi.xoom.it//alessi/  Coding manual: http://tinyurl.com/zza7ega

Marc'Antonio Alessi

  • Swamp Rat
  • Posts: 776
  • Marco
Re: Assoc List - Group By Keys
« Reply #17 on: October 10, 2017, 10:10:59 am »
; UltraDemential > ALE_List_Nth see: https://www.theswamp.org/index.php?topic=46419.msg514475#msg514475
Code: [Select]
(defun ALE_GroupByKeyUD (l / k s r p x)
  (foreach i l
    (if (setq x (vl-position (setq k (car i)) s))
      (setq p (ALE_List_Nth x r)   r (subst (vl-list* (car i) (cdr i) (cdr p)) p r))
      (setq s (cons k s)           r (cons (list k (cdr i)) r))
    )
  )
)
Marc'Antonio Alessi http://alessi.xoom.it//alessi/  Coding manual: http://tinyurl.com/zza7ega