`
hcmfys
  • 浏览: 348225 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

一个负载均衡的算法

阅读更多

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


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));
		}
	}

}



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics