码迷,mamicode.com
首页 > 其他好文 > 详细

Math.random 重复随机,不重复随机

时间:2015-06-07 09:45:37      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:javase   random   string   数组   数学   

package random;

public class RandomRepeatOrNotRepeat {
	// 随机数字最大值
	public final static int maxValue = 11;
	// 随机数字最小值
	public final static int minValue = 1;
	// 需要几位数字
	public final static int resultLength = 5;
	// 生成多少行
	public final static int rows = 10;

	public static void main(String args[]) {
		// 不重复随机,将已经随机到的下标移动到最后一个,减少数组长度
		three();
		// 不重复随机,标记数组中的值
		// two();
		// 普通随机
		// one();

	}

	public static void three() {
		int[] a = new int[maxValue];
		int[] result = new int[resultLength];

		for (int j = 0; j < rows; j++) {
			a = new int[maxValue];
			init(a);
			for (int i = 0; i < resultLength; i++) {
				int random = (int) (Math.random() * a.length);
				swap2tail(a, random);

				result[i] = a[a.length - 1];
				a = decreaseLength(a);
			}
			for (int i = 0; i < result.length; i++)
				System.out.print(result[i] + ",");
			System.out.println();
		}
	}

	private static int[] decreaseLength(int[] a) {
		int[] result = new int[a.length - 1];
		for (int i = 0; i < result.length; i++)
			result[i] = a[i];
		return result;
	}

	private static void swap2tail(int[] a, int random) {
		if (random == a.length - 1)
			return;
		a[random] ^= a[a.length - 1];
		a[a.length - 1] ^= a[random];
		a[random] ^= a[a.length - 1];
	}

	private static void init(int[] a) {
		for (int i = 0; i < a.length; i++)
			a[i] = i + minValue;
	}

	public static void two() {
		for (int j = 0; j < rows; j++) {
			int[] a = new int[maxValue];
			for (int i = 0; i < resultLength; i++) {
				int random = (int) (Math.random() * maxValue);
				markA(a, random);
			}
			printValueNotOne(a);
		}

	}

	private static void printValueNotOne(int[] a) {
		for (int i = 0; i < a.length; i++) {
			if (a[i] != 0)
				System.out.print(i + minValue + ",");
		}
		System.out.println();
	}

	public static void markA(int[] a, int random) {
		if (a[random] == 0) {
			a[random] = 1;
			return;
		}

		markA(a, (random + 1) % a.length);

	}

	public static void one() {
		String s = "";
		for (int j = 0; j < rows; j++) {
			for (int i = 0; i < resultLength; i++) {
				s += ((int) (Math.random() * maxValue + minValue)) + ",";
			}
			System.out.println(s);
			s = "";
		}
	}

	public static void printTestArray(int[] a) {
		System.out.println("----------- Test -----------");
		for (int i = 0; i < a.length; i++)
			System.out.print(a[i] + ",");
		System.out.println();

		System.out.println("----------- Test -----------");
	}

}


Math.random 重复随机,不重复随机

标签:javase   random   string   数组   数学   

原文地址:http://blog.csdn.net/tragedyxd/article/details/46390343

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!