求一个按概率从不同数组中取数据的算法

hzdzd 2014-10-18 04:37:33
有两组数据分别放在两个list里, 例如数据A为:{12,33,23,33},数据B为{'233e','w4rrr','erff','dffdd','3eee'}

在页面上有一个按钮,点击按钮时随机从一个数组中随机抽取一个数据显示到页面上.
要求: 从A数据组取出数据的概率是十分之一, 即点按钮10次,只有一次从A数据组中取,另九次从B数据组中取,请问怎么实现?
...全文
364 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
rumlee 2014-10-18
  • 打赏
  • 举报
回复
引用 1 楼 rumlee 的回复:


	public Object get(List list1,List list2){
		Random r = new Random();
		if(r.nextInt(10)<1){
			return list1==null && list1.size()==0 ? null : list1.get(r.nextInt(list1.size()));
		}else{
			return list2==null && list2.size()==0 ? null : list2.get(r.nextInt(list2.size()));
		}
	}

概率只能说是很多次点击之后统计的规律,而不是说点10次就肯定一次去A里面取,9次去B里面去。 你对概率的说法有问题。
写错了,不好意思,return里面的条件应该用 || ,而不是 &&


	public Object get(List list1,List list2){
		Random r = new Random();
		if(r.nextInt(10)<1){
			return list1==null || list1.size()==0 ? null : list1.get(r.nextInt(list1.size()));
		}else{
			return list2==null || list2.size()==0 ? null : list2.get(r.nextInt(list2.size()));
		}
	}
rumlee 2014-10-18
  • 打赏
  • 举报
回复


	public Object get(List list1,List list2){
		Random r = new Random();
		if(r.nextInt(10)<1){
			return list1==null && list1.size()==0 ? null : list1.get(r.nextInt(list1.size()));
		}else{
			return list2==null && list2.size()==0 ? null : list2.get(r.nextInt(list2.size()));
		}
	}

概率只能说是很多次点击之后统计的规律,而不是说点10次就肯定一次去A里面取,9次去B里面去。 你对概率的说法有问题。

81,122

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧