从1到m随机n个数

以下代码实现从1到m,随机n个数

	public static int[] random(int m, int n) {

		Random r = new Random();

		if (n <= 0 || m <= 0 || m < n) {
			return null;
		}

		int[] ary = new int[m];
		for (int i = 0; i < m; i++) {
			ary[i] = i + 1;
		}

		int[] result = new int[n];
		int temp = 0;
		for (int i = 0; i < n; i++) {
			int index = r.nextInt(m - i);
			temp = ary[index];
			ary[index] = ary[m - 1 - i];
			result[i] = temp;
		}
		return result;
	}

猜你喜欢

转载自blog.csdn.net/weihao_/article/details/72781797