美文网首页
从1到1000取随机不重复值

从1到1000取随机不重复值

作者: Twinkle_______ | 来源:发表于2016-01-29 16:39 被阅读419次
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 用Java代码实现: 从自然数1到1000中随机取900个不重复的数并打印出来
 * Created by jiaobuchong on 1/29/16.
 */
public class RandomDemo {
    // 方式1
    public static void method1() {
        List<Integer> randomNum = new ArrayList<>();
        for (int i = 1; i <= 1000; i++) {
            randomNum.add(i);
        }

        for (int j = 0; j < 900; j++) {
            Random r = new Random();
            int rand = r.nextInt(randomNum.size());  // 随机生成一个 index between [ 0, randomNum.size() )
            System.out.println(randomNum.get(rand));
            randomNum.remove(rand);
        }
    }

    // 方式2
    public static void method2() {
        int count = 0;    // 统计900次
        List<Integer> randomNum = new ArrayList<>();
        Random r = new Random();

        while (count < 900) {
            int rand  = r.nextInt(1000) + 1; // nextInt(1000) [0, 1000)+1 = [1, 1000]
            if (!randomNum.contains(rand)) {
                randomNum.add(rand);
                count++;
            }
        }
        System.out.println("length: " + randomNum.size());
        System.out.println(randomNum);

    }

  //方式3
    public static void method3() {
        Random r = new Random();
        HashSet<Integer> randomNum = new HashSet<>();
        while (randomNum.size() < 900) {
            int rand = r.nextInt(1000) + 1;
            randomNum.add(rand);
        }
        System.out.println("length: " + randomNum.size());
        System.out.println(randomNum);
    }


    public static void main(String[] args) {
//        method1();
//        method2();
        method3();
    }
}

相关文章

网友评论

      本文标题:从1到1000取随机不重复值

      本文链接:https://www.haomeiwen.com/subject/ehvjkttx.html