2015-05-26 48 views
-2

我的程序应该计算数组中有多少个唯一值。到目前为止,我已经按升序对数组进行了排序(只是为了使用不同的算法),并且正在试图计算每个唯一值有多少个值(4,4,4,4,2,3,2,其中2是2和3是1)。为什么我的循环跳过我的数组中的最后一个值?

我有一个数组示例,我一直在测试这个数组,它由数字1-10组成,但是我的for循环只会计数8.这可能是明显的,但现在我只是卡住了试图找到错误。

受影响的我的代码段:

指数=阵列

for (int i = 0; i < index; i++) 
{ 
    uniqueness = true; 

    for (int l = 0; l < index; l++) 
    { 

     if (numbers[i] == temporary[l]) 
     { 
      uniqueness = false; 
     } 
    } 

    if (uniqueness) 
    { 
     temporary[i] = numbers[i]; 

     number_amount = 0; 
     for (int j = 0; j < index; j++) 
     { 
      if (numbers[j] == temporary[i]) 
      { 
       number_amount++; 
      } 
     } 

     Output(temporary[i], number_amount); 
    } 
} 
+6

你缺少代码最有趣的部分后 - “指数=数组的大小”。 –

+0

你的循环变量最多可以达到,但不包括'index'。虽然我们无法知道“索引”究竟是什么,但名字有点怀疑。为什么不叫'长度'? –

+0

使用'if(唯一性)'似乎是错误的。我认为它应该是相反的,'if(!uniqueness)'。 –

回答

0

/*寻找从一个数组唯一编号排序的数组*/

int arr = [ 1, 1, 1, 2, 2, 2, 3, 3, 4, 5, 7, 9]; 
int unique[arr.length]; 
int arrCount = 0; 

for (int i = 0; i < arr.length;) { 
    bool isUnique = true; 
    int currentIndex = i + 1; 

    for (int j = i + 1; j < arr.length; j++) { 
     if (arr[i] == arr[j]) { 
      isUnique = false; 
     } else { 
      currentIndex = j; 
      break; 
     } 
    } 

    i = currentIndex; 

    if (isUnique) { 
     unique[arrCount]=arr[i - 1]; 
     arrCount++; 
    } 

} 

enter code here 
+0

我用javascript完成http://jsfiddle.net/wmjtxa5d/1/如果任何pbm与上述C++解决方案,请参考小提琴代码 –

-1

对于所有的for循环,它应该是“< =指数”,而不是“<索引的大小“,考虑到你的索引设置正确。这是因为它只循环到低于索引(<索引)的值,而不是索引本身(< =索引)。

+0

数组索引从0开始,所以如果数组的大小是5,最后一个索引应该是4而不是5.数组的大小和索引之间是有区别的。 – Abhineet

+0

char a [4] = {a,b,c,d};这意味着一个[0] = a;一个[1] = B; A [2] = C; A [3] = d;数组索引从0开始到(大小-1)。 – udit043

相关问题