2

我们有 K 组不同的数字。我们必须从每组中选择一个数字,以使较大数字和较小数字之间的差异最小

有任何想法吗?

4

1 回答 1

0

像这样的东西(用Haskell写的)?

import Data.List (minimum, maximum, minimumBy)

minDiff (x:xs) = comb (head x) (diff $ matches (head x)) x where
  lenxs = length xs
  diff m = maximum m - minimum m
  matches y = minimumBy (\a b -> compare (diff a) (diff b)) $ p [] 0 where
    md = map (minimumBy (\a b -> compare (abs (a - y)) (abs (b - y)))) xs
    mds = [m | m <- foldl (\b a -> filter (\z -> abs (z - y) == abs (y - md!!a)) (xs!!a) : b) [] [0..lenxs - 1]]
    p result index
      | index == lenxs = [y:result]
      | otherwise      = do
          p' <- mds!!index
          p (p':result) (index + 1)
  comb result difference []     = matches result
  comb result difference (z:zs) =
    let diff' = diff (matches z)
    in if diff' < difference
          then comb z diff' zs
          else comb result difference zs


OUTPUT:
*Main> minDiff [[1,3,5,9,10],[2,4,6,8],[7,11,12,13]]
[5,6,7]
于 2013-04-12T04:53:39.110 回答