1

我写了一个似乎工作正常的函数。(再想一想,它错过了前两组的联系……我得再考虑一下。)

import Data.List (groupBy)

makeGroups xs = 
  map concat $ groupBy (\a b -> head b == last a + 1) (groupBy mGroups0 xs)
    where mGroups0 = \a b -> a == length xs && elem b [1,2] 
                             || b /= length xs && b == a + 1


输出:

*Main> makeGroups [3,4,5,6,7,8,1,9,10,2]
[[3,4,5,6],[7,8],[1],[9,10,2]]

(谢谢大家对标签的回答......现在我只要求一般的编码天才)

是否有更有效/更方便的方法将排序的升序整数序列分组到列表中(保持原始顺序)?

唯一的额外规定是:

the possible groups [length xs] [1] [2] [1,2] [length xs,1] [length xs,2] 
must be separated, but [length xs, 1, 2] should join any larger sequence.
4

1 回答 1

1

像这样的东西?(感谢 Daniel Fischer 的建议)

makeGroups xs = foldr comb [[last xs]] (init xs) where
  comb a b = if a == head (head b) - 1
                then (a:head b) : tail b
                else [a] : b


*Main> makeGroups [3,4,5,6,7,8,1,9,10,2]
[[3,4,5,6,7,8],[1],[9,10],[2]]


这是一个丑陋的刺:

makeGroups xs = foldr comb [[last xs]] (init xs) 
  where n = length xs
        ngroup = [1,2,n]
        comb a b = let (x:xs) = head b in 
          if a == n && isPrefixOf [1,2] (x:xs)
             then if not (null $ tail b) && head (head $ tail b) == 3
                     then ((n:head b) ++ (head $ tail b)) : drop 1 (tail b)
                     else (n:head b) : tail b
             else if a == n && isPrefixOf [2,1] (x:xs)
                     then if null (drop 1 xs)
                             then [n,2,1] : tail b
                             else [n,2,1] : drop 1 xs : tail b
             else if elem a ngroup
                     then if elem x ngroup
                             then if null xs
                                     then [a,x] : tail b
                                     else [a,x] : xs : tail b
                             else [a] : b
             else if a /= n && a == x - 1
                     then if x /= n
                             || isPrefixOf [n,1,2] (x:xs)
                             then (a:x:xs) : tail b
                             else [a] : b
                     else [a] : b
于 2013-03-14T21:34:31.667 回答