练习题:Java随机在某个区间中生成n个随机数并升序排列,并把其余位置补0

数组版

<br />
int min = 1, max = 10, count = 5,n;<br />
int[] array = new int[min+max];<br />
do {<br />
    n = new Random().nextInt(max)%(max-min+1) + min;<br />
    if (array[n] == 0) {<br />
        array[n] = n;<br />
        count--;<br />
    }<br />
} while (count &gt; 0);<br />
for (int i = min; i &lt;= max; i++) {<br />
    System.out.println(array[i]);<br />
}<br />

2015-11-26_111602

List版

<br />
// 最小数<br />
int min = 1;<br />
// 最大数<br />
int max = 10;<br />
// 几率<br />
int per = (int) Math.round(max * 0.5);</p>
<p>Random random = new Random();<br />
List&lt;Integer&gt; countList = new ArrayList&lt;Integer&gt;();<br />
List&lt;Integer&gt; countMaxList = new ArrayList&lt;Integer&gt;();<br />
int x = 0;<br />
int count = 0;<br />
// 加倍生成,以防止生成随机总数不够<br />
for (int i = 0; i &lt; max + max; i++) {<br />
    x = random.nextInt(max) + min;<br />
    if (count == per) break;<br />
    if (!countList.contains(x)) {<br />
        countList.add(x);<br />
        count++;<br />
    }<br />
}<br />
Collections.sort(countList);<br />
System.out.println(&quot;=======随机从&quot; + min + &quot;到&quot; + max + &quot;,生成&quot; + per + &quot;个不重复的升序随机数=======&quot;);<br />
for (Integer i : countList) {<br />
    System.out.println(i);<br />
}<br />
// 先计算随机数前部分<br />
if (countList.get(0) != 1) {<br />
    for (int i = 1; i &lt; countList.get(0); i++) {<br />
        countMaxList.add(0);<br />
    }<br />
}<br />
// 开始计算随机数<br />
for (int i = 0; i &lt; countList.size(); i++) {<br />
    countMaxList.add(countList.get(i));<br />
    // 如果是最后一个就结束循环<br />
    if (i == countList.size() - 1) break;<br />
    for (int j = countList.get(i) + 1; j &lt; countList.get(i + 1); j++) {<br />
        countMaxList.add(0);<br />
    }<br />
}<br />
// 计算随机数后部分<br />
if (countList.get(countList.size() - 1) != max) {<br />
    for (int i = countList.get(countList.size() - 1) + 1; i &lt;= max; i++) {<br />
        countMaxList.add(0);<br />
    }<br />
}<br />
countList.clear();<br />
System.out.println(&quot;=======除随机生成&quot; + per + &quot;个随机数外,其余位置依次按照升序补0填满&quot; + max + &quot;位数=======&quot;);<br />
for (Integer i : countMaxList) {<br />
    System.out.println(i);<br />
}<br />

执行效果截图如下:
2015-11-25_155451

发表评论

电子邮件地址不会被公开。 必填项已用*标注

This site uses Akismet to reduce spam. Learn how your comment data is processed.