去百度面试,编程+算法题被问道了类似于服务器权重分配的问题(原题不是这样,我更换了一下场景)。——如何在一组服务器中,根据权重不同随机选取出一个服务器。
结构代码如下:
package com.mrbug.algorithm; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Random; public class Weight { private Random random = new Random(); private List<ServerConfig> servers; private int factor; public void init() { this.servers = new ArrayList<ServerConfig>(); servers.add(new ServerConfig("127.0.0.1", 30)); servers.add(new ServerConfig("127.0.0.2", 50)); servers.add(new ServerConfig("127.0.0.3", 1000)); servers.add(new ServerConfig("127.0.0.4", 100)); // 初始化 this.factor = 0; for (Iterator<ServerConfig> iter = servers.iterator(); iter.hasNext();) { ServerConfig server = iter.next(); server.startWeight = factor; factor += server.weight; } } public static void main(String[] args) { Weight w = new Weight(); w.init(); for (int i = 0; i < 100; i++) { ServerConfig server = w.choose(); System.out.println(server.ip); } } } class ServerConfig { public String ip; public int weight; public int startWeight; public ServerConfig(String ip, int weigth) { this.ip = ip; this.weight = weigth; } }
我写的第一种脑残的算法:
public ServerConfig choose0() { while (true) { for (int i = 0; i < servers.size(); i++) { ServerConfig server = servers.get(i); for (int j = 0; j < server.weight; j++) { int k = random.nextInt(factor); if (k == i) { return server; } } } } }
经过指点,优化过的代码:
public ServerConfig choose() { ServerConfig selected = null; int rv = random.nextInt(factor); for (int i = servers.size() - 1; i >= 0; i--) { ServerConfig server = servers.get(i); if (rv >= server.startWeight) { selected = server; break; } } return selected; }
ps:面试过几家,感觉百度的面试是最靠谱的,并没有问一些时髦的技术,只是最基础的知识,从一点出发考察你的分析问题思考能力。虽然这次挂掉了,但是心服口服。呵呵,以后有机会再说吧。