栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

唯一随机生成的整数的Java数组

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

唯一随机生成的整数的Java数组

for (int i = 0; i < size; i++) {    a[i] = (int)(Math.random()*10);    for (int j = 0; j < i; j++) {        if (a[i] == a[j]) { a[j] = (int)(Math.random()*10); //What's this! Another random number!        }    }   }

您确实找到重复的值。但是,您将其替换为另一个可能重复的随机数。相反,请尝试以下操作:

for (int i = 0; i < size; i++) {    a[i] = (int)(Math.random()*10);//note, this generates numbers from [0,9]    for (int j = 0; j < i; j++) {        if (a[i] == a[j]) { i--; //if a[i] is a duplicate of a[j], then run the outer loop on i again break;        }    }  }

但是,这种方法效率低下。我建议列出数字,然后将其随机化:

ArrayList<Integer> a = new ArrayList<>(11);for (int i = 0; i <= 10; i++){ //to generate from 0-10 inclusive.          //For 0-9 inclusive, remove the = on the <=    a.add(i);}Collections.shuffle(a);a = a.sublist(0,4);//turn into array

或者您可以这样做:

ArrayList<Integer> list = new ArrayList<>(11);for (int i = 0; i <= 10; i++){    list.add(i);}int[] a = new int[size];for (int count = 0; count < size; count++){    a[count] = list.remove((int)(Math.random() * list.size()));}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/449677.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号