Code golf: combining multiple sorted lists into a single sorted list

前端 未结 26 1836
余生分开走
余生分开走 2020-12-29 12:42

Implement an algorithm to merge an arbitrary number of sorted lists into one sorted list. The aim is to create the smallest working programme, in whatever language you like.

26条回答
  •  隐瞒了意图╮
    2020-12-29 13:10

    Common Lisp already has a merge function for general sequences in the language standard, but it only works on two sequences. For multiple lists of numbers sorted ascendingly, it can be used in the following function (97 essential characters).

    (defun m (&rest s)
      (if (not (cdr s))
          (car s)
          (apply #'m
                 (cons (merge 'list (car s) (cadr s) #'<)
                       (cddr s))))) 

    edit: Revisiting after some time: this can be done in one line:

    (defun multi-merge (&rest lists)
      (reduce (lambda (a b) (merge 'list a b #'<)) lists))
    

    This has 79 essential characters with meaningful names, reducing those to a single letter, it comes out at 61:

    (defun m(&rest l)(reduce(lambda(a b)(merge 'list a b #'<))l))
    

提交回复
热议问题