腾讯面一个试题

题目:给你5个球,每个球被抽到的可能性为30、50、20、40、10,设计一个随机算法,该算法的输出结果为本次执行的结果。

输出A,B,C,D,E即可。

import java.util.ArrayList;
import java.util.List;


public class Ball {
/** 记录总共的可能性 */
private static int total = 0;
/** 记录该球可能性的其实范围 */
public int current = 0;
/** 记录该球的可能性 */
private int times = 0;
/** 记录该球的代表字母 */
private String name = null;


public Ball(int times, String name) {
this.current = total;
total += times;
this.times = times;
this.name = name;
}


/**
* 根据参数返回其对应的字符

* @param number
*            :给定的参数
* @return:返回对应的字符
*/
public String play(int number) {
if (number < current + times && current <= number) {
return name;
} else {
return null;
}
}


/**
* 返回记录总共的可能性

* @return:记录总共的可能性
*/
private static double getTotal() {
return total;
}


public static void main(String[] args) {
// 实例化ball对象
Ball ball01 = new Ball(30, "A");
Ball ball02 = new Ball(50, "B");
Ball ball03 = new Ball(20, "C");
Ball ball04 = new Ball(40, "D");
Ball ball05 = new Ball(10, "E");


// 创建容器,并把求全放进容器
List<Ball> ballList = new ArrayList<Ball>();
ballList.add(ball01);
ballList.add(ball02);
ballList.add(ball03);
ballList.add(ball04);
ballList.add(ball05);


// 随机产生五个数字,并将其翻译成要表示的字符
for (int i = 0; i < 5; ++i) {
int number = (int) (Math.random() * Ball.getTotal());
PrintName(ballList, number);
}
}


/**
* 打印翻译以后的结果

* @param ballList
*            :存放ball的容器
* @param number
*            :给定的数字,由此数字产生对应的字母
*/
private static void PrintName(List<Ball> ballList, int number) {
for (Ball ball : ballList) {
String name = ball.play(number);
if (name != null) {
System.out.print(name + "\t");
}
}
}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值