Advent of Code: alexandria's map-permutations was perfect for day 08. Common Lisp tip.
vindarel

vindarel @vindarel

About: Full-stack, Python, Common Lisp in production. Building a video course to learn Lisp efficiently.

Location:
France
Joined:
Oct 14, 2022

Advent of Code: alexandria's map-permutations was perfect for day 08. Common Lisp tip.

Publish Date: Dec 9 '24
1 2

As the title says. Did you know about alexandria:map-permutations ?

If not, you could have discovered it with (apropos "permutation"). Run this on the REPL, it returns you all results it knows of symbols that have it in their name. You can also try apropos-regex from cl-ppcre. It's best to run them when you have loaded a few utility packages, like Alexandria or Serapeum. I run them when I loaded CIEL, so they are here, plus a few more.

Look at the Alexandria functions on sequences here:

map-permutations:

Calls function with each permutation of length constructable from
the subsequence of sequence delimited by start and end. start
defaults to 0, end to length of the sequence, and length to the
length of the delimited subsequence.
Enter fullscreen mode Exit fullscreen mode

If you call it on a large input, it won't return an insanely large list of permutations. We can work on them one after the other. You can also pass :copy nil to it, in which case "all combinations are eq to each other", so I suppose the function re-uses a structure, and it is advised to not modify the permutation.

Examples:

(alexandria:map-permutations (lambda (it) (print it)) '(a b))
;; or just
(alexandria:map-permutations #'print '(a b))

(A B)
(B A)


(alexandria:map-permutations (lambda (it) (print it)) '(a b c))

(A B C)
(B A C)
(C A B)
(A C B)
(B C A)
(C B A)
Enter fullscreen mode Exit fullscreen mode

ask for permutations of length 2:

(alexandria:map-permutations (lambda (it) (print it)) '(a b c) :length 2)

(A B)
(B A)
(A C)
(C A)
(B C)
(C B)
Enter fullscreen mode Exit fullscreen mode

There is also map-combinations, this one considers (a b) and (b a) to be the same combination:

(alexandria:map-combinations (lambda (it) (print it)) '(a b c) :length 2)

(A B)
(A C)
(B C)
Enter fullscreen mode Exit fullscreen mode

I solved Advent of Code's day 08 with this. This year I learned ✓

Comments 2 total

  • Antonio Juan Querol
    Antonio Juan QuerolDec 24, 2024

    Thanks for this tip, why you do not change (lambda (it) (print it)) with #'print??

    • vindarel
      vindarelDec 30, 2024

      You are so right^^ My real code is doing more stuff in the lambda but this needs editing. Thanks.

Add comment