将一个数组分成相加结果最相近的两个数组

分组的思想就是先把数组排序,分成两组,然后再把这两组的值相减,根据这个值再递归的进行调整,直到这个值小于任何两个相减的值。

str =  [1,2,3,4,5,6,7,8,9,11,100]
str = str.sort
a = []
b = []

for i in 0..str.length-1
  if i%2==0
    a<<str[i]
  else
    b<<str[i]
  end
end

if a.length > b.length and a.inject(&:+)>b.inject(&:+)
  b<<a.min;a.delete_at(a.index(a.min))
elsif b.length > a.length and b.inject(&:+)>a.inject(&:+)
  a<<b.min;b.delete_at(b.index(b.min))
end

def getSum arr
  a = arr[0]
  for i in 1..arr.length
    a = a+arr[i].to_i
  end
  a
end

def exchange a,b,sum1,sum2  
  flag = (sum1 - sum2).abs/2
  for i in 0..a.length-1
    temp_ = flag
    for j in 0..b.length-1  
      if a[i]>b[j]
        if flag - (a[i] - b[j]) < temp_ && flag >= (a[i] - b[j])
          temp_ = flag -a[i] + b[j]
          #p flag
          temp = a[i]
          a[i] = b[j]
          b[j] = temp
          #p a
          #p b
          ret = true
          break
        end
      end      
    end
    break if ret
  end
  return if ret == nil   
  ret = nil
  sum1 = getSum a
  sum2 = getSum b
  exchange (sum1>sum2)?(a):(b),(sum1>sum2)?(b):(a),(sum1>sum2)?(sum1):(sum2),(sum1>sum2)?(sum2):(sum1)    
end

def assign a,b
  sum1 = getSum a
  sum2 = getSum b
  if sum1==sum2    
    return
  else
    exchange (sum1>sum2)?(a):(b),(sum1>sum2)?(b):(a),(sum1>sum2)?(sum1):(sum2),(sum1>sum2)?(sum2):(sum1)    
  end  
end

assign a,b
p a.sort
p b.sort

 

posted on 2013-09-13 21:58  张飞_  阅读(1342)  评论(0编辑  收藏  举报

导航