一个负载均衡的算法

去一家游戏公司面试,题目大概是给出权值,求出值,
当时题目太多了,没有做完



import java.util.HashMap;

/***
* hcmfys@163.com
* tomjnefu
* 一个负载均衡的算法
* * 2013-06-05 20:51
*
* @author Administrator
*
*/
public class WeightCheck {

private static HashMap<Integer, Integer> weightList = new HashMap<Integer, Integer>();

public synchronized void reset() {
weightList.clear();
}

public int getWeight(int weight[]) {
return getMaxWeight(weight);

}

/**
*
* @param weight
* @param curTotalSize
* @return
*/
private synchronized int getMaxWeight(int weight[]) {
double max = Double.MIN_VALUE;
int index = 0;
int total = 0;
int curTotalSize = 0;
int pos = 1;
if (weightList.get(0) == null) {
pos = 0;
weightList.put(0, 0);
}
if (pos == 0) {
for (int i = 0; i < weight.length; i++) {
int w = weight[i];
if (max < w) {
max = w;
index = i;
}
}
weightList.put(index, 1);
return index;
}
for (int i = 0; i < weight.length; i++) {
int w = weight[i];
total += w;
if (weightList.get(i) == null) {
weightList.put(i, 0);
}
curTotalSize += weightList.get(i);

}
for (int i = 0; i < weight.length; i++) {

int curWeight = weightList.get(i);

int w = weight[i];
double dw = curTotalSize * (w / (total + 0.0000000001)) - curWeight;

if (dw > max) {
max = dw;
index = i;
}

}

int toal = weightList.get(index);
weightList.put(index, toal + 1);
return index;

}

/**
* @param args
*/
public static void main(String[] args) {
int weight[] = { 3, 2, 2 };
WeightCheck wi = new WeightCheck();
int totalSize = 1000;
for (int i = 0; i < totalSize; i++) {
int ret = wi.getWeight(weight);
System.out.println(ret);
}
System.out.println("================");
for (int i = 0; i < weight.length; i++) {
System.out.println("wight=" + weight[i] + " total=["
+ weightList.get(i) + "] " + weightList.get(i)
/ (totalSize + 0.00001));
}
}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值