为什么对我的数组排序总是使前两个索引值为零?

huangapple go评论69阅读模式
英文:

Why does sorting my array always make the first two index values a zero?

问题

我正在尝试获得一个随机数生成器,它会生成五行数字,每行包含1到70之间的5个随机数字,以及一个1到25之间的额外数字,就像买"百万大奖"彩票一样。

以下是代码部分:

import java.util.Arrays;
import java.util.Collections;
import java.util.Random;

public class MegaMillions {
    
	public void play() {
		Random rand = new Random();
		int[] numbers = new int[5];
		for(int i = 0; i < 5; i++) {
			numbers[i] = rand.nextInt(69) + 1;
			Collections.shuffle(Arrays.asList(numbers));
			Arrays.sort(numbers);
			System.out.print(numbers[i] + " ");
		}
		Collections.shuffle(Arrays.asList(numbers));
		int megaBall = rand.nextInt(24) + 1;
		System.out.println("(" + megaBall + ")");
	}

}

这是您得到的示例输出:

0 0 21 21 35 (1)

0 0 16 26 32 (9)

0 0 39 39 53 (3)

0 0 22 37 51 (14)

0 0 18 18 60 (14)

我理解您的意思是Collections.shuffle应该处理任何重复的整数,而Arrays.sort应该按数字顺序排列它们。

英文:

What I am trying to get is a random number generator that will produce five lines of 5 random numbers 1 through 70 and one more number 1 through 25 like a mega millions ticket.

import java.util.Arrays;
import java.util.Collections;
import java.util.Random;

public class MegaMillions {
    
	public void play() {
		Random rand = new Random();
		int[] numbers = new int[5];
		for(int i = 0; i &lt; 5; i++) {
			numbers[i] = rand.nextInt(69) + 1;
			Collections.shuffle(Arrays.asList(numbers));
			Arrays.sort(numbers);
			System.out.print(numbers[i] + &quot; &quot;);
		}
		Collections.shuffle(Arrays.asList(numbers));
		int megaBall = rand.nextInt(24) + 1;
		System.out.println(&quot;(&quot; + megaBall + &quot;)&quot;);
	}

}

Here is an example of what I'm getting:

0 0 21 21 35 (1)

0 0 16 26 32 (9)

0 0 39 39 53 (3)

0 0 22 37 51 (14)

0 0 18 18 60 (14)

My understanding was that Collections.shuffle should take care of any repeating integers and Arrays.sort should put in numerical order.

答案1

得分: 3

> Collections.shuffle(Arrays.asList(numbers));

好的,你的numbers数组现在已经被打乱了。紧接着下一行:

> Arrays.sort(numbers);

...现在它又被排序了。如果你接下来就要排序,那么先打乱就没有任何意义。看起来你可能对这些调用的作用或你的算法运作方式有所误解,但从你的问题中并不清楚你具体是如何误解这些内容的。

为什么我得到了两个零?

因为这正是你的算法所做的。计算机只会按照你的指令执行。

让我们来看一个例子:

  1. 你开始用一个新的大小为5的数组:[0, 0, 0, 0, 0]
  2. 循环5次。
  3. (循环1)将0索引设置为随机数:[50, 0, 0, 0, 0]
  4. (循环1)打乱列表。这个操作无关紧要,因为我们之后会排序它。
  5. (循环1)排序它:[0, 0, 0, 0, 50]
  6. (循环1)打印0索引的数字。这始终是0
  7. (循环2)将1索引设置为随机数:[0, 45, 0, 0, 50]
  8. (循环2)打乱列表。这个操作无关紧要,因为我们之后会排序它。
  9. (循环2)排序它:[0, 0, 0, 45, 50]
  10. (循环2)打印1索引的数字。这始终是0
  11. (循环3)将2索引设置为随机数:[0, 0, 47, 45, 50]
  12. (循环3)打乱列表。这个操作无关紧要,因为我们之后会排序它。
  13. (循环3)排序它:[0, 0, 45, 47, 50]
  14. (循环3)打印2索引的数字。这打印的是'45'。

依此类推。

看起来你可能既不想打乱也不想排序。

你只是想用随机数填充每个槽位,仅此而已。

如果你想让这5个数字排序 - 只需在之后排序一次。如果你想按排序顺序打印数字,首先填充整个数组而不打印任何内容 - 然后排序它,然后循环打印它,最后添加1-25的数字作为最后一步,并打印它。

英文:

> Collections.shuffle(Arrays.asList(numbers));

Okay, your numbers array is now shuffled. Immediate next line:

> Arrays.sort(numbers);

... and now it's sorted again. There was no point whatsoever in shuffling first if you're going to sort right after. It seems clear you misunderstand what these calls do or how your algorithm works, but exactly how you misunderstand these things isn't clear from your question.

Why do I get two zeroes?

Because that's exactly what your algorithm does. The computer just does what you tell it to.

Let's go through an example:

  1. You start with a new 5-sized array; [0, 0, 0, 0, 0].
  2. loop 5 times.
  3. (loop1) Set the 0-index to a random number: [50, 0, 0, 0, 0].
  4. (loop1) Shuffle the list. Irrelevant, we'll sort it afterwards.
  5. (loop1) sort it: [0, 0, 0, 0, 50].
  6. (loop1) print the 0-index number. This is always 0.
  7. (loop2) Set the 1-index to a random number: [0, 45, 0, 0, 50].
  8. (loop2) Shuffle the list. Irrelevant, we'll sort it afterwards.
  9. (loop2) sort it: [0, 0, 0, 45, 50].
  10. (loop2) print the 1-index number. This is always 0.
  11. (loop3) Set the 2-index to a random number: [0, 0, 47, 45, 50].
  12. (loop3) Shuffle the list. Irrelevant, we'll sort it afterwards.
  13. (loop3) sort it: [0, 0, 45, 47, 50].
  14. (loop3) print the 2-index number. This prints '45'.

And so on.

It seems rather likely that you don't want to shuffle and you don't want to sort.

You want to just fill each slot with a random number and that is all.

If you want the 5 numbers to be sorted - just sort once, afterwards. If you want to print the numbers in sorted order, first fill the entire array and print nothing - then sort it, then loop through to print it, then add the 1-25 number as final step and print that.

答案2

得分: 1

最初你有一个数组如下:

[0,0,0,0,0]

然后你执行 numbers[i] = rand.nextInt(69) + 1;

可能会得到

[21,0,0,0,0]

接着你执行 Arrays.sort(numbers);

这会变成

[0,0,0,0,21]

接下来

[0,12,0,0,21] -> [0,0,0,12,21]

再下一步

[0,0,7,12,21] -> [0,0,7,12,21]

英文:

Originally you have an array like

[0,0,0,0,0]

you do numbers[i] = rand.nextInt(69) + 1;

and may end up with
[21,0,0,0,0]

then you do Arrays.sort(numbers);

which will change to [0,0,0,0,21]

next [0,12,0,0,21] -> [0,0,0,12,21]

next [0,0,7,12,21] -> [0,0,7,12,21]

答案3

得分: 0

你的代码有点奇怪。

循环第一次时,你将第一个随机数放入数组的索引0位置,然后洗牌数组(将数字“随机”放在某个位置),然后对数组进行排序(将数字放在最后的位置,因为其他4个数字都是0)。此后,索引0变为0。

然后重复这个过程,将第二个数字放入索引1。注意索引0保持为0。再次洗牌并排序。前三个数字将为0,这是必然的,因为数组中只有2个非零数字。

现在轮到第三个数字。注意索引0和索引1仍然为0。

依此类推。

总结:先洗牌再排序是没有意义的,因为排序会撤销洗牌所做的任何随机化。

在循环内部进行排序也没有意义,因为它会将非零数字移到最终可能被覆盖的位置,并且保证了一些不会被覆盖的零。

猜测你想要在生成每个“球”时将其打印出来,然后按排序顺序全部打印出来:

for (int i = 0; i < 5; i++) {
    numbers[i] = rand.nextInt(69) + 1;
    System.out.print(numbers[i] + " ");
}
System.out.println();

Arrays.sort(numbers);
for (int i = 0; i < 5; i++) {
    System.out.print(numbers[i] + " ");
}
System.out.println();

这可能会导致重复的随机数,但处理这个问题应该是另一个问题。

英文:

Your code is... odd.

The first time through the loop, ou put the first random number in the array at index 0, shuffle the array (putting the number 'somewhere'), and then sort the array (putting the number in the last place, guaranteed because the other 4 numbers are each 0). Index 0 is 0 after this.

Then repeat with second number, which goes into index 1. Note that the zero index stays zero. Shuffle, and sort again. The first three numbers will be zero; they have to be, because there are only 2 non-zero numbers in the array.

Now the third number. Note that index 0 and index 1 remain zero.

Etc.

Summary: shuffling and then sorting is pointless, since the sort undoes any randomization that shuffling did.

And sorting inside the loop is pointless too, since it is moving non-zero numbers to where they can eventually be overwritten, and guaranteeing some zeroes that won't be.

Guessing that you want to print out each 'ball' as it is generated, and then print them all out in sorted order:

 for (int i = 0; i &lt; 5; i++) {
     numbers[i] = rand.nextInt(69) + 1;
     System.out.print(numbers[i] + &quot; &quot;);
 }
 System.out.println();
 
 Arrays.sort(numbers);
 for (int i = 0; i &lt; 5; i++) {
     System.out.print(numbers[i] + &quot; &quot;);
 }
 System.out.println();

This is liable to having repeated random numbers, but dealing with that should be another question.

答案4

得分: 0

> "为什么对我的数组进行排序总是使前两个索引值为零?..."

这是因为您在每次迭代中对 数字 进行排序。

第一次和第二次迭代将产生一个 数字 数组,其中元素 01 都是零。

> _"...我想要的是一个随机数生成器,它将生成5行5个1到70的随机数,以及另一个1到25的数字,就像大百万彩票一样。..."

要获取5个唯一的随机数,请创建一个值为1到70的 List,并使用 Collections#shuffle

int[] numbers = new int[6];
List<Integer> list = new ArrayList<>();
for (int value = 1; value <= 70; value++) list.add(value);
Collections.shuffle(list);
for (int index = 0; index < 5; index++)
    numbers[index] = list.get(index);
numbers[5] = new Random().nextInt(1, 26);

输出

51 11 30 59 44 (13)

> "...我的理解是Collections.shuffle应该处理任何重复的整数...

不,shuffle 只是重新排列列表。
您可能在考虑一个 Set,它只允许唯一的值。

英文:

> "Why does sorting my array always make the first two index values a zero? ..."

This is because you're sorting numbers on each iteration.

The first and second iterations would yield a numbers array where elements 0 and 1 are zero.

> "... What I am trying to get is a random number generator that will produce five lines of 5 random numbers 1 through 70 and one more number 1 through 25 like a mega millions ticket. ..."

To get 5 unique random numbers, create a List of values 1 through 70, and use Collections#shuffle.

int[] numbers = new int[6];
List&lt;Integer&gt; list = new ArrayList&lt;&gt;();
for (int value = 1; value &lt;= 70; value++) list.add(value);
Collections.shuffle(list);
for (int index = 0; index &lt; 5; index++)
    numbers[index] = list.get(index);
numbers[5] = new Random().nextInt(1, 26);

Output

51 11 30 59 44 (13)

> "... My understanding was that Collections.shuffle should take care of any repeating integers ..."

No, shuffle just re-orders the list.
You may be thinking of a Set, which will only allow unique values.

答案5

得分: 0

我对一些东西进行了调整,似乎可以工作。为了获得我想要的结果,我只是剪切了 Collections.shuffleArrays.sort 这两行,并将它们直接粘贴到了 for 循环下面。然后,在下面,我添加了另一个 for 循环,循环五次打印 numbers[i]。此外,最后的 Collections.shuffle 对于超级球不是必要的。

import java.util.Arrays;
import java.util.Collections;
import java.util.Random;

class Main {
    public static void main(String[] args) {
        MegaMillions megamillions = new MegaMillions();
        for(int i = 0; i &lt; 5; i++) {
            megamillions.play();
        }
    }
}    
class MegaMillions {
    public void play() {
        Random rand = new Random();
        int[] numbers = new int[5]; 
        for(int i = 0; i &lt; 5; i++) {
            numbers[i] = rand.nextInt(69) + 1;
        }
        Collections.shuffle(Arrays.asList(numbers));
        Arrays.sort(numbers);
        for(int i = 0; i &lt; 5; i++) {
            System.out.print(numbers[i] + &quot; &quot;);
        }
        int megaBall = rand.nextInt(24) + 1;
        System.out.println(&quot;(&quot; + megaBall + &quot;)&quot;); 
    }
}
```

<details>
<summary>英文:</summary>

I switched a few things around and it seems to work. In order to get the results that I had intend I simply cut the `Collections.shuffle` and `Arrays.sort` lines and pasted directly below the `for` loop. Then, beneath that, I added another `for` loop that loops five times printing `numbers[i]`.  Also the final `Collections.shuffle` wasn&#39;t necessary for the mega ball.
````java
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;

class Main {
    public static void main(String[] args) {
        MegaMillions megamillions = new MegaMillions();
        for(int i = 0; i &lt; 5; i++) {
            megamillions.play();
        }
    }
}    
class MegaMillions {
    public void play() {
        Random rand = new Random();
        int[] numbers = new int[5]; 
        for(int i = 0; i &lt; 5; i++) {
            numbers[i] = rand.nextInt(69) + 1;
        }
        Collections.shuffle(Arrays.asList(numbers));
        Arrays.sort(numbers);
        for(int i = 0; i &lt; 5; i++) {
            System.out.print(numbers[i] + &quot; &quot;);
        }
        int megaBall = rand.nextInt(24) + 1;
        System.out.println(&quot;(&quot; + megaBall + &quot;)&quot;); 
    }
}
```


</details>



# 答案6
**得分**: 0

答案在使用Arrays.sort(numbers)方法对数组进行排序中

假设您的值如下

0索引循环 [10,0,0,0,0]

然后执行Arrays.sort(numbers);

您将得到这样的数组 [0,0,0,0,10]

1索引循环 [0,12,0,0,10] -> [0,0,0,10,12]

2索引循环 [0,0,15,10,12] -> [0,0,10,12,15]

游戏从这里开始对吧

3索引循环 [0,0,10,21,15]->[0,0,10,15,21]

当您在numbers[i]中添加元素时实际上填充了3索引值在排序后变为[0,0,10,15,21]因此在循环结束之前索引0和1将始终保持为零

如果增加数组numbers的长度索引为零的部分也将增加

<details>
<summary>英文:</summary>

The answer lies in the sorting of array using Arrays.sort(numbers) method.
lets suppose your values is like below

0 index loop  [10,0,0,0,0]

then you do Arrays.sort(numbers);

you will get the array like this [0,0,0,0,10]

1 index loop [0,12,0,0,10] -&gt; [0,0,0,10,12]

2 index loop [0,0,15,10,12] -&gt; [0,0,10,12,15]

the game begins from here right?
3 index loop [0,0,10,21,15]-&gt;[0,0,10,15,21]

when you add elements in numbers[i] this actually fills the 3 index value which after sorting becomes [0,0,10,15,21].so index 0 and 1 will become always zero while looping until loop ends.

if you increase the length of the array numbers then index with zero will also increase.



</details>



huangapple
  • 本文由 发表于 2023年8月9日 09:46:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76864080-2.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定