为什么对数组进行排序后,前两个索引值总是变成零?

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

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

问题

我正在尝试获得一个随机数生成器,它将生成五行由1到70的随机数和一个由1到25的随机数,就像Mega Millions彩票一样。

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

好的,你的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的位置,然后对数组进行洗牌(将数字“放在某个地方”),然后对数组进行排序(将数字放在最后一个位置,因为其他四个数字都是0)。在这之后,索引0的值变为0。

然后重复以上步骤,将第二个数字放入索引1的位置。请注意,索引0仍然是0。再次洗牌和排序。前三个数字将是0,这是因为数组中只有两个非零数字。

现在是第三个数字的迭代。请注意,索引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

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

第一次和第二次迭代会生成一个数字数组,其中元素0和1都是零。

要获取5个唯一的随机数,可以创建一个包含1到70的值的列表,并使用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)

不,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 < 5; i++) {
            megamillions.play();
        }
    }
}    
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);
        for(int i = 0; i < 5; i++) {
            System.out.print(numbers[i] + " ");
        }
        int megaBall = rand.nextInt(24) + 1;
        System.out.println("(" + megaBall + ")"); 
    }
}
英文:

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't necessary for the mega ball.

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.html
匿名

发表评论

匿名网友

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

确定