Adjacent number algorithm grouper

前端 未结 13 2049
不思量自难忘°
不思量自难忘° 2021-02-15 06:55

By which I mean this:

Given the input set of numbers:

1,2,3,4,5 becomes \"1-5\".

1,2,3,5,7,9,10,11,12,14 becomes \"1-3, 5, 7, 9-12, 14\"

This is

13条回答
  •  轮回少年
    2021-02-15 07:45

    Here's my Haskell entry:

    runs lst = map showRun $ runs' lst
    
    runs' l = reverse $ map reverse $ foldl newOrGlue [[]] l 
    
    showRun [s] = show s
    showRun lst = show (head lst) ++ "-" ++ (show $ last lst)
    
    newOrGlue [[]] e = [[e]]
    newOrGlue (curr:other) e | e == (1 + (head curr)) = ((e:curr):other)
    newOrGlue (curr:other) e | otherwise              = [e]:(curr:other)
    

    and a sample run:

    T> runs [1,2,3,5,7,9,10,11,12,14]
    
    ["1-3","5","7","9-12","14"]
    

提交回复
热议问题