首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Haskell中的平衡分区

Haskell中的平衡分区
EN

Stack Overflow用户
提问于 2014-08-18 01:25:47
回答 3查看 935关注 0票数 2

在haskell中,如何生成集合的平衡分区?

假设我有一个集合{1,3,4,6,9},该集合的平衡分区将是s1{9,3}s2{6,4,1},因为s1-s21

EN

Stack Overflow用户

发布于 2014-11-18 00:39:44

这是一个做得更好的解决方案:

代码语言:javascript
运行
复制
balancedPartition :: (Num a, Ord a) => [a] -> ([a], [a])
balancedPartition = snd . head . partitionsByBadness . sort
  where
    -- recursively builds a list of possible partitionings and their badness
    -- sorted by their (increasing) badness
    partitionsByBadness []     = [(0, ([], []))]
    partitionsByBadness (x:xs) = let res = partitionsByBadness xs
                                     withX = map (      (+x) *** first  (x:)) res
                                     sansX = map (subtract x *** second (x:)) res
                                 in merge withX $ normalize sansX

    -- When items are added to the second list, the difference between the sums
    -- decreases - and might become negative
    -- We take those cases and swap the lists, so that the first list has always
    -- a greater sum and the difference is always positive
    -- So that we can sort the list again (with linear complexity)
    normalize xs = let (neg, pos) = span ((<0) . fst) xs
                   in merge pos $ reverse $ map (negate *** swap) neg

-- merge two sorted lists (as known from mergesort, but
-- omits "duplicates" with same badness)
merge :: Ord k => [(k, v)] -> [(k, v)] -> [(k, v)]
merge []         zss        = zss
merge yss        []         = yss
merge yss@(y:ys) zss@(z:zs) = case comparing fst y z of
                                LT -> y : merge ys zss
                                EQ -> merge ys zss
                                GT -> z : merge yss zs
票数 1
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25351718

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档