两个整形数组和的差最小

package main

import (
	"fmt"
	"math"
)

func main() {
	a := []int{1, 1}
	b := []int{2, 2, 4}
	a_len, b_len, a_sum, b_sum := cal(a, b)
	for i := 0; i < a_len; i++ {
		a_len, b_len, a_sum, b_sum = cal(a, b)
		for j := 0; j < b_len; j++ {
			if math.Abs(float64(a_sum)-float64(a[i])+float64(b[j])) < math.Abs(float64(a_sum)-float64(b_sum)) {
				var tmp int
				tmp = a[i]
				a[i] = b[j]
				b[j] = tmp
			}
		}
	}
	a_len, b_len, a_sum, b_sum = cal(a, b)
	fmt.Println(a_sum - b_sum)
	fmt.Println(a)
	fmt.Println(b)
}

func cal(a []int, b []int) (int, int, int, int) {
	a_len := len(a)
	b_len := len(b)
	var a_sum int
	var b_sum int
	for _, i2 := range a {
		a_sum += i2
	}
	for _, i2 := range b {
		b_sum += i2
	}
	return a_len, b_len, a_sum, b_sum
}

你可能感兴趣的:(算法,开发语言,golang)