1

Input, by example (4 is the maximum length):

(my-partition-randomly '(a b c d e f g h i j k l) 4) 

Output:

'((a b c) (d) (e f g h) (i j k) (l)) 

The code should run in the Emacs Lisp interpreter.

2
  • 1
    Can you show the code for your current attempt to write it? Commented Nov 16, 2018 at 10:12
  • @AlexOtt No attempt yet. I could write something rather complex, but am looking for a simple solution. Commented Nov 16, 2018 at 10:20

1 Answer 1

2

My elisp-fu is weak, but I was able to write the following function:

(defun my-partition-randomly (list max-length) "" (let ((result '())) (while list (push (seq-take-while (lambda (x) x) (map 'list (lambda (x) (pop list)) (number-sequence 1 (+ 1 (random max-length))))) result)) (reverse result))) 

It extracts random initial sequences of the input list and adds them to result (the seq-take-while is needed not to include nils when the last subsequence wants to be longer than the remaining list). push adds elements to the left, so the result has to reversed.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, your elisp-fu is better than mine, and this does the trick! I learned new functions, seq-take-while and map, and this was kind of the intention of my question. Let’s see if there is an even simpler solution.
You might get more attention at emacs.stackexchange.com with your future questions.
I chose Stack Overflow because my question is about Elisp the programming language. (not a fan of having so many overlapping platforms now)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.