有人能解释一下为什么System.out.println("Doesn't repeat: "+a[i]);
不打印任何东西吗?
import java.util.Arrays;
import java.util.Random;
public class Practice {
public static void main(String[] args) {
int []a=new int[100];
Random rand =new Random();
for(int i=0;i<100;i++)
{
a[i]=rand.nextInt((100-1)+1)+1;
}
Arrays.sort(a);
for(int i=0;i<100;i++)
{
System.out.print(a[i]+ " ");
}
boolean flag;
System.out.print(" ");
System.out.print(" ");
for(int i=0;i<100;i++)
{
flag=false;
for(int j=0;j<100;j++)
{
if(a[i]==a[j])
{
flag=true;
break;
}
}
if(flag==false)
{
System.out.println("Doesn't repeat: "+a[i]);
}
}
}
}
我只得到当前100个元素的数组,元素不会出现两次或更多的行不会出现。
编辑:
import java.util.Arrays;
import java.util.Random;
public class Practice {
public static void main(String[] args) {
int []a=new int[100];
Random rand =new Random();
for(int i=0;i<100;i++)
{
a[i]=rand.nextInt((100-1)+1)+1;
}
Arrays.sort(a);
for(int i=0;i<100;i++)
{
System.out.print(a[i]+ " ");
}
boolean flag;
System.out.print(" ");
System.out.print(" ");
for(int i=0;i<100;i++)
{
flag=false;
for(int j=0;j<100;j++)
{
if (i==j) {
continue;
}
else if(a[i]==a[j])
{
flag=true;
break;
}
}
if(flag==false)
{
System.out.println("Doesn't repeat: "+a[i]);
}
}
}
}
到目前为止,这是我能得到的最好的结果,但是代码排除了相等的元素,即使它们是唯一的。
发布于 2019-01-03 03:48:51
我对您的代码做了一些更改(删除了flag
并使用unique
,因为它更具可读性)。
另外,我在包含非唯一项的最后一个索引中添加了一个修改i
的内部循环:
boolean unique;
System.out.println();
for (int i = 0; i < 100; i++) {
unique = true;
for (int j = i + 1; j < 100; j++) {
if (a[i] == a[j]) {
unique = false;
break;
}
}
if (unique) {
System.out.println("Doesn't repeat: " + a[i]);
} else {
for (int k = i + 1; k < 100; k++) {
if (a[k] != a[i]) {
i = k - 1;
break;
}
}
}
}
发布于 2019-01-03 03:09:15
您总是对照它自己的位置检查重复项。每一次嵌套循环迭代,i
将等于j
,你会发现一个“重复的”。对当前代码最简单的修复方法是测试i
是否等于j
。
此外,因为您已经对数组进行了排序,所以所有重复项都会在连续的位置中找到。您只需扫描阵列一次,而不是100次,即可找到重复项。只需存储前一个值,这样您就可以查看当前元素是否重复。
您应该获得许多不重复的元素,但不是所有元素。在填充最后一个(第100个)随机元素时,即使之前选择的所有99个整数都是唯一的,也只有1/ 100的机会选择唯一未选择的整数以防止重复。在此之前,在第99个随机元素上,从2个未选择的整数中选择一个以防止重复的概率仅为2/ 100,对于每个选择的整数依此类推。如果您确实为所有元素打印了一行,那么您应该选择彩票。
如果您想要所有唯一的元素,那么就使用initialize the values sequentially, then shuffle them。
发布于 2019-01-03 02:48:08
变化
for (int j = 0; j < 100; j++) // ends up comparing a number with itself as well
至
for (int j = i+1; j < 100; j++) // compares with the rest of the elements ahead of it
https://stackoverflow.com/questions/54011557
复制相似问题