• java获取随机不重复的数得值


    假如我有一个数组: 

    ArrayList<Integer> mArrayList = new ArrayList<Integer>();
        	mArrayList.add(0);
        	mArrayList.add(1);
        	mArrayList.add(2);
        	mArrayList.add(3);

    我需要从中随机抽取2个数  不能重复抽取,我就会用这个方法

     public void getValue(ArrayList<Integer> mArrayList){
        	Random mRandom = new Random();
        	int a = mRandom.nextInt(mArrayList.size());
        	
        	int value = mArrayList.get(a);
        	System.out.println(value + "");
        	mArrayList.remove(a);
        }

    原理就是每抽取一次就删除已经抽取出来的值,这样获取到的值就不会重复了

    完整代码:

    package com.xiaoqiu.test;
    
    import java.util.ArrayList;
    import java.util.Random;
    
    public class Test {
        public static void main(String[] args) {
        	ArrayList<Integer> mArrayList = new ArrayList<Integer>();
        	mArrayList.add(0);
        	mArrayList.add(1);
        	mArrayList.add(2);
        	mArrayList.add(3);
        	
        	Test mTest = new Test();
        	mTest.getValue(mArrayList);
        	mTest.getValue(mArrayList);
        }
        
        public void getValue(ArrayList<Integer> mArrayList){
        	Random mRandom = new Random();
        	int a = mRandom.nextInt(mArrayList.size());
        	
        	int value = mArrayList.get(a);
        	System.out.println(value + "");
        	mArrayList.remove(a);
        }
    }

    测试结果:

    3

    2


    3

    0


    2

    3


  • 相关阅读:
    VS2005下安装boost
    NOIP2017宝藏 [搜索/状压dp]
    SCOI2008奖励关 [状压dp]
    莫队算法解析
    SCOI2005 互不侵犯 [状压dp]
    Codeforces ----- Kefa and Dishes [状压dp]
    TSP问题之状压dp法
    NOI2001炮兵阵地 [状压dp]
    状压dp入门
    「网络流24题」餐巾计划问题
  • 原文地址:https://www.cnblogs.com/tqj-zyy/p/4559759.html
Copyright © 2020-2023  润新知