根据权重决定展示哪张图片的小算法(python+java)板砖

需求背景:闪屏页根据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); 
    }
}

结果:
这里写图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值