DEV Community

vindarel
vindarel

Posted on

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

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))

(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 ✓

Top comments (0)