You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

weightDistributing.go 1.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package weightDistributing
  2. import (
  3. "errors"
  4. "math"
  5. )
  6. type Weight struct {
  7. Id string
  8. Weight int32
  9. Replica int32
  10. }
  11. func DistributeReplicas(weights []*Weight, replicas int32) error {
  12. var weightSum int32
  13. weightSum = 0
  14. for _, w := range weights {
  15. weightSum += w.Weight
  16. }
  17. if weightSum == 0 {
  18. return errors.New("static weights are empty")
  19. }
  20. weightRatio := make([]float64, len(weights))
  21. for i, w := range weights {
  22. weightRatio[i] = float64(w.Weight) / float64(weightSum)
  23. }
  24. var rest = replicas
  25. for i := 0; i < len(weights); i++ {
  26. var n = math.Round(float64(replicas) * weightRatio[i])
  27. rest -= int32(n)
  28. weights[i].Replica = int32(n)
  29. }
  30. for {
  31. if rest == 0 {
  32. break
  33. }
  34. maxIdx := 0
  35. minIdx := 0
  36. if rest > 0 {
  37. for i, ratio := range weightRatio {
  38. if ratio > weightRatio[maxIdx] {
  39. maxIdx = i
  40. }
  41. }
  42. } else {
  43. for i, ratio := range weightRatio {
  44. if ratio < weightRatio[minIdx] {
  45. minIdx = i
  46. }
  47. }
  48. }
  49. if rest > 0 {
  50. weights[maxIdx].Replica++
  51. weightRatio[maxIdx]--
  52. rest--
  53. } else {
  54. if weights[minIdx].Replica == 0 {
  55. weightRatio[minIdx]++
  56. continue
  57. }
  58. weights[minIdx].Replica--
  59. weightRatio[minIdx]++
  60. rest++
  61. }
  62. }
  63. return nil
  64. }

PCM is positioned as Software stack over Cloud, aiming to build the standards and ecology of heterogeneous cloud collaboration for JCC in a non intrusive and autonomous peer-to-peer manner.