创建一个包含随机整数且无重复的数组。

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

Create an array with random integers but with no duplicates

问题

// 用随机值创建数组的解决方案,并且没有重复值
我的问题是,当我创建一个没有重复项的数组时,它会删除重复项,并且会在数组中保留一些 0 值。

我应该如何创建一个带有特定索引的数组,但是不仅仅是删除重复项,还要将其更改为另一个值,

注意: 必须仅使用常规数组完成,而不使用集合,因为这是流程控制中的一个任务。

// 用随机数初始化第一个数组
for (int i = 0; i < guesses.length; i++) {
guesses[i] = rand.nextInt(10) + 1;
}

// 创建第二个数组,同时删除重复项
int[] array2 = new int[5];
int index = 0;

lbl: for (int i = 0; i < guesses.length; i++) {
int x = guesses[i];

for (int j = 0; j < index; j++) {
    if (array2[j] == x) {
        continue lbl;
    }
}
array2[index++] = x;

}

有重复项的数组:

[6, 9, 8, 5, 5, 6]

删除重复项后的结果(可以看到我有两个 0):

[6, 9, 8, 5, 0, 0]

我需要的示例:

[6, 9, 8, 5, 3, 1]

英文:

I need a solution to create an array with random values and with no duplicates.
My issue is when I create an array with no duplicates it removes the duplicates and keeps my array with some 0 values.

How can I create an array with a specific index but instead of just removing duplicates, changes it to another value,

note: it has to be done only with regular arrays and not collections since its a task in flow control.

// *Initializing first array with random numbers*
for (int i = 0; i &lt; guesses.length; i++) {
    guesses[i] = rand.nextInt(10) + 1;
}

// *Creating a second array while removing duplicates*
int[] array2 = new int[5];
int index = 0;

lbl: for (int i = 0; i &lt; guesses.length; i++) {
    int x = guesses[i];

	for (int j = 0; j &lt; index; j++) {
	    if (array2[j] == x) {
			continue lbl;
		}

	}
	array2[index++] = x;
}

Array with duplicates:

[6, 9, 8, 5, 5, 6]

What I get after removing duplicates (as you can see i have two 0's)

[6, 9, 8, 5, 0, 0]

example of What i need:

[6, 9, 8, 5, 3, 1]

答案1

得分: 1

我认为你是在尝试这样做:

guesses[] // 你定义了一个数组

for (int i = 0; i < guesses.length; i++) {
    boolean exist = true; // 我们创建一个布尔变量来判断随机数是否存在,并且初始值为 true,用于 while 循环
    while (exist) {
        exist = false; // 我们将它设置为 false,因为直到在数组中找不到相同的值,我们才认为不存在
        int x = rand.nextInt(10) + 1;
        
        for (int k = 0; k < i; k++) { // 我们检查每个数字,直到达到 "i"
            if (x == guesses[k]) { // 如果存在相同的值,我们标记为存在
                exist = true;
                break;
            }
        }
        
        if (!exist) { // 如果相同的值不存在,我们将它保存在数组中
            guesses[i] = x;
        }
    }
}
英文:

I think you are trying this:

guesses[]// you define

for (int i = 0; i &lt; guesses.length; i++) {
    boolean exist = true;//we create a boolean is random number exist and start with true for while loop
   while(exist){
    exist = false;//we change it because until we didn&#39;t see the same value on array, we accept as non-exist.
    int x = rand.nextInt(10) + 1;
    
    for(int k = 0; k &lt; i; k++){//we check everynumber until &quot;i&quot; we come.
     if(x == guesses[k]){//if exist we said same value exist
      exist = true; break;}
    }
    if(!exist){//if same value not exist we save it in our array
     guesses[i] = x;}
  }

}

答案2

得分: 0

根据你已经有的想法,你的问题是Java中的数组从默认值开始,因此,假设你创建一个大小为10的数组,该数组将填充int的默认值(即0)。

你需要做的是保持一个索引,表示数组的“实际大小”,这样当你向数组添加元素时,你会增加这个计数器,当你移除元素时,你会减少这个计数器。
也就是说,你应该使用这个实际大小来知道在哪里放置你的新数字。

注意,这种解决方案不需要额外的数组。

这种方法基本上使用了所谓的基于数组的列表,也许稍微研究一下这方面的内容会对你有所帮助。

英文:

Following the same idea you already have, your problem is that arrays in Java start with a default value, so, let's say you create an array of size 10, the array will be filled with the default value for ints (which is 0).

What you need to do is to keep an index with the "actual size" of the array, so when you add an element to the array you increase the counter, and when you remove you decrease the counter.
That said, you should use this actual size to know where to put your new number.

Note that this solution doesn't need an additional array.

This approach basically uses what's known as an Array-Based List, maybe researching a little about that could help you.

答案3

得分: 0

以下是您要求的翻译内容:

这是多个可能解决方案之一。

需要注意的是,随机数范围与数组长度之间的差异越大,重复出现的次数就越少,算法运行速度也越快。

相反,如果随机数范围小于数组大小,则该方法永远不会结束。(例如,无法用范围为“1到5”的随机数填充大小为10的数组,并且不会有重复项)。

Random r = new Random();
int[] guesses = r.ints(20,1,20).toArray();
int N = guesses.length;

// 开始查找重复项
for (int i = 0; i < N;) {
	  int check = guesses[i];
	  for (int x = 0; x < i; x++) {
		   // 检查是否重复
		   // 如果找到,分配新值并重新检查。
		   if (guesses[x] == check) {
			   guesses[x] = r.nextInt(N)+1;
               // 重置 i 以重新开始外部循环。
			   i = -1;
			   break;
		   }
	  }
	  i++;
}
	      
// 现在进行排序以显示独特性。
Arrays.sort(guesses);
System.out.println(Arrays.toString(guesses));

对于当前的练习和值,输出结果为:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

另一种方法是基于先前生成的数字的最大值来确定范围。在这种情况下,我选择了“起始和范围”来生成连续的数字,以便它们是相邻且已排序的。增加起始值会使数字分布开,但它们仍然会被排序。请注意,这些不符合随机数的条件,因为它们是基于先前选择的值生成的。

int range = 2;
int start = 1;
int[] vals = new int[20];
int max = Integer.MIN_VALUE;
for (int i = 0; i < vals.length; i++) {
	vals[i] = r.nextInt(start) + range;
    // 需要保持目前为止生成的最大值
    // 以避免重叠和可能的重复
    max = vals[i] > max ? vals[i] : max;
    range = max+1;
}
System.out.println(Arrays.toString(vals));

输出结果为:

[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
英文:

Here is one of several possible solutions.

Note that the greater the range of random numbers is to the length for the array, the less duplicates appear and the faster the algorithm will run.

Conversely, if the range of random numbers is less than the size of the array, the method will never finish. (E.g you can't fill an array of size 10 with a range of 1 to 5 and not have duplicates).

Random r = new Random();
int[] guesses = r.ints(20,1,20).toArray();
int N = guesses.length;

// Start searching for duplicates
for (int i = 0; i &lt; N;) {
	  int check = guesses[i];
	  for (int x = 0; x &lt; i; x++) {
		   // check for duplicate
		   // if found, assign new value and check again.
		   if (guesses[x] == check) {
			   guesses[x] = r.nextInt(N)+1;
               // rest i to start the outer loop anew.
			   i = -1;
			   break;
		   }
	  }
	  i++;
}
	      
// now sort to show distinctiveness.
Arrays.sort(guesses);
System.out.println(Arrays.toString(guesses));

For the current exercise and values, prints.

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

Another way is to base the range on the maximum of the previous generated numbers. In this case, I chose start and range to generate sequential numbers so that they would be adjacent and sorted. Increasing the value of start would spread out the numbers but they would still be sorted. Note that these don't qualify as random numbers as they are being generated based on previously chosen values.

int range = 2;
int start = 1;
int[] vals = new int[20];
int max = Integer.MIN_VALUE;
for (int i = 0; i &lt; vals.length; i++) {
	vals[i] = r.nextInt(start) + range;
    // need to maintain the max generate thus far
    // to avoid overlap and possible duplication
    max = vals[i] &gt; max ? vals[i] : max;
    range = max+1;
}
System.out.println(Arrays.toString(vals));

Prints

[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
 

</details>



huangapple
  • 本文由 发表于 2020年10月14日 02:09:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/64340800.html
匿名

发表评论

匿名网友

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

确定