given N absolute values of integers find the combination of N/2 negative and N/2 positive values whose sum is closest to 0

后端 未结 5 1431
隐瞒了意图╮
隐瞒了意图╮ 2021-01-21 04:36

Let\'s say that I have an array of 10 numbers whose absolute value range can go from 1 to 10. Values can be repeated. An example of this could be

{2, 4, 2, 6, 9         


        
5条回答
  •  一生所求
    2021-01-21 05:13

    Here's an example in Haskell that lists and compares all 126 possible combinations:

    import Data.List
    import Data.Ord
    
    {-code by Will Ness-}
    divide :: [a] -> [([a], [a])]
    divide [] = [([],[])]
    divide (x:xs) = go ([x],[],xs,1,length xs) where
      go (a,b,[],i,j) = [(a,b)]
      go (a,b, s@(x:xs),i,j) 
         | i>=j = [(a,b++s)]
         | i>0  = go (x:a, b, xs, i+1, j-1) ++ go (a, x:b, xs, i-1, j-1)
         | i==0 = go (x:a, b, xs,   1, j-1) ++ go (x:b, a, xs,   1, j-1)  
    
    {-code by groovy-}       
    minCombi list = 
      let groups = map (\x -> map (negate) (fst x) ++ snd x) (divide list)
          sums = zip (map (abs . sum) groups) groups
      in minimumBy (comparing fst) sums
    

    *Main> minCombi [2, 4, 2, 6, 9, 10, 1, 7, 6, 3]
    (0,[-7,-10,-2,-4,-2,1,9,6,6,3])

提交回复
热议问题