标签:不重复随机数
示例1:C语言版
#include <stdio.h> #include <stdlib.h> #include <time.h> //随机产生规定个数的不重复数字 int findSame(int *arr, int in, int n); int main() { //设置随机种子 srand((int)time(0)); int arr[40] = {0}, tmp, length = 0; while(length <= 39) { tmp = (40 * rand()) / RAND_MAX; //第一个下标数直接复制进数组 if (length == 0) arr[length] = tmp; else { //第二个下标数开始,判断随机数是否在数组已经存在,存在的话跳过,不存在就复制进数组 if (findSame(arr, tmp, length) == 1) continue; else arr[length] = tmp; } length++; } for (int i = 0; i < 40; i++) printf("%d ", arr[i]); return 0; } int findSame(int *arr, int in, int n) { for (int i = 0; i < n; i++) { if (arr[i] == in) return 1; } return 0; }
import java.util.*; //打印10个不重复的随机数字1~10 public class NoRepeatNumber { public static void main(String[] args) { Random random = new Random(); int [] nums = new int[10]; List<Integer> mylist = new ArrayList<Integer>(); int n = 10, temp, i = 0; while(mylist.size() < n){ temp = random.nextInt(n) + 1; if (!mylist.contains(temp)) { mylist.add(temp); nums[i] = temp; System.out.print(nums[i] + " "); } } } }
标签:不重复随机数
原文地址:http://blog.csdn.net/fisherwan/article/details/41114075