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

前端 未结 26 1841
余生分开走
余生分开走 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 12:58

    Python, 107 chars:

    def f(l):  
     n=[]  
     for t in l:  
      for i in t: n+=[t]  
     s=[]  
     while n: s.+=[min(n)]; n.remove(min(n))  
     return s  
    
    0 讨论(0)
  • 2020-12-29 12:59

    Though I have not had the patience to try this, a colleague of mine showed me a way that it may be possible to do this using 0 character key - Whie Space

    0 讨论(0)
  • 2020-12-29 12:59

    F#, 32 chars

    let f x=List.sort(List.concat x)
    

    And without using a built in function for the concat (57 chars):

    let f x=List.sort(Seq.toList(seq{for l in x do yield!l}))
    
    0 讨论(0)
  • 2020-12-29 12:59

    I don't think you can get much better than @Sykora's response, here, for Python.

    Changed to handle your inputs:

    import heapq
    def m(i): 
        return list(heapq.merge(*i))
    
    print m(((1, 4, 7), (2, 5, 8), (3, 6, 9)))
    

    For the actual function, 59 characters, or the 52 in reduced version:

    import heapq
    def m(i): return list(heapq.merge(*i))
    

    This also has the benefit of using a tested and true implementation built into Python

    Edit: Removed the semi-colons (thanks @Douglas).

    0 讨论(0)
  • 2020-12-29 13:00

    I'll just leave this here...

    Language: C, Char count: 265

    L[99][99];N;n[99];m[99];i;I;b=0;main(char t){while(scanf("%d%c",L[i]+I,&t)+1){++
    I;if(t==10){n[i++]=I;I=0;}}if(I)n[i++] = I;N=i;while(b+1){b=-1;for(i=0;i<N;++i){
    I=m[i];if(I-n[i])if(b<0||L[i][I]<L[b][m[b]])b=i;}if(b<0)break;printf("%d ",L[b][
    m[b]]);++m[b];}puts("");}
    

    Takes input like such:

    1 4 7
    2 5 8
    3 6 9
    (EOF)
    
    0 讨论(0)
  • 2020-12-29 13:00

    Even though it might break the rules. Here's a nice and short c++ entry:

    13 Characters

    l1.merge(l2); // Removes the elements from the argument list, inserts 
                  // them into the target list, and orders the new, combined 
                  // set of elements in ascending order or in some other 
                  // specified order.
    
    0 讨论(0)
提交回复
热议问题