需求背景:闪屏页根据weight的权重随机加载一张图片,weight是int类型的数值。(来自我们的开发,我只是翻译成python和抽象成java)
实现(python):
定义的模拟图片类weight_pic
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
'''
author:cloudhuan
'''
class Pic():
_weight = 0
def __init__(self,_weight):
self._weight = _weight
def getWeight(self):
return self._weight
def getName(self):
print u'我是第%s张图片'%str(self._weight)
然后是小算法(三张图片,权重为1、2、3):
#!/usr/bin/env python
#_*_ conding:utf-8 _*_
'''
author:cloudhuan
'''
import random
import weight_pic
pic00 = weight_pic.Pic(1)
pic01 = weight_pic.Pic(2)
pic02 = weight_pic.Pic(3)
_list = [pic00,pic01,pic02]
all_weight = pic00.getWeight() + pic01.getWeight() + pic02.getWeight()
index = random.randint(1,all_weight)
print 'index is ',index
start = 0
end = 0
for i in _list:
end = start + i.getWeight()
if index > start and index <= end:
print i.getName()
start = end
运行结果:
实现(java):
import java.util.ArrayList;
import java.util.Random;
public class weight_test {
/**
* @param args
* @author cloudhuan
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new weight_test().random_test();
}
public void random_test(){
Weight_pic pic00 = new Weight_pic(1);
Weight_pic pic01 = new Weight_pic(2);
Weight_pic pic02 = new Weight_pic(3);
ArrayList<Weight_pic> list = new ArrayList<>();
list.add(pic00);
list.add(pic01);
list.add(pic02);
int start = 0,end = 0;
int all_weight = pic00.getWeight() + pic01.getWeight() + pic02.getWeight() ;
int index = new Random().nextInt(all_weight-1)+1;
System.out.println(""+index);
for(Weight_pic pic:list){
end = pic.getWeight() + start;
if(start < index && index <= end){
pic.getName();
}
start = end;
}
}
}
class Weight_pic{
int _weight;
Weight_pic(int _weight){
this._weight = _weight;
}
protected int getWeight(){
return _weight;
}
public void getName(){
String result = "这是第"+_weight+"张图片";
System.out.println(result);
}
}
结果: