java从数组中随机取出几个数并且不重复

  • Post author:
  • Post category:java


package org.mybatis.model;

import java.util.Arrays;
import java.util.Scanner;

public class LotteryDrawing {
	public static void main(String[] args) {

		Scanner scanner = new Scanner(System.in);

		// 筛选随机数组大小
		int k = scanner.nextInt();

		// 待筛选数组最大上标
		int n = scanner.nextInt();

		int[] numbers = new int[n];

		for (int i = 0; i < numbers.length; i++) {
			numbers[i] = i + 1;
		}

		int[] results = new int[k];

		for (int i = 0; i < results.length; i++) {

			// 取出一个随机数
			int r = (int) (Math.random() * n);

			results[i] = numbers[r];

			// 排除已经取过的值
			numbers[r] = numbers[n - 1];

			n--;
		}

		Arrays.sort(results);

		for (int i : results) {
			System.out.print(i + " ");
		}

		scanner.close();
	}
}



版权声明:本文为zhouyufengqingyang原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。