2015-11-10 17 views
4

所以不得不
A = {1,3,3,4-}
B = {5,4,7,3}如何計數相同數量的元素的兩個陣列之間,不重複

我想要查看數組B的元素出現在數組A中的次數,但是,我只想對數組A中的每個元素進行一次計數。因此,如果3出現多次,3將只計算一次,依此類推。

這裏我的答案是2,因爲我有3,4這是在B陣列,同時也是在陣列A.

這是我到目前爲止有:

int count = 0; 
for(int z = 0; z <4; z++) 
    { 
     for(int y = 0; y <4; y++) 
     { 
     if(arrayA[z] == arrayB[y]) 
     { 
      count++; 
     } 
     }//end for loop 
    }//end for loop 

當我運行這個,我得到3.我知道爲什麼。我正在計算A {3,3,4}數組中的重複項。我怎麼不算他們?我卡住了。

這是一個小問題,我一直在卡住。

回答

2

一個簡單的解決辦法是引入另一個陣列來存儲計數和零初始化(我使用c#,所以它會默認使用0初始化int數組)。

 int[] totals = new int[10]; 
     int[] arrayA = new int[] { 1,3,3,4}; 
     int[] arrayB = new int[] { 5,4,7,3}; 
     for (int z = 0; z < 4; z++) 
     { 
      for (int y = 0; y < 4; y++) 
      { 
       if (arrayA[z] == arrayB[y]) 
       { 
        totals[arrayA[z]]++; 
       } 
      }//end for loop 
     }//end for loop 

     // Count your numbers through indices 
     for (int i = 0; i < totals.Length; i++) 
     { 
      if (totals[i] > 0) 
      { 
      count++; 
      } 
     } //end for loop 
+0

現在我得到一個ArrayIndexOutOfBoundsException:50當我試圖實現我自己的數字:A = 1,2,3,4 B = 2,2,2,2 –

+0

你可以告訴我你的代碼嗎?你使用哪種語言? – Bilal

1

這是我的解決方案: 第1步:檢查數組中存在的元素。 第2步:遍歷第一個數組中的每個元素。檢查它存在於第二個數組中而不存在於結果數組中。

這是我與Swift實現:

let A = [1,2,3,3,4,7] 
let B = [3,4,1,2,5,7,8,3,2] 
var C : [Int] = [] 

for (_,a) in A.enumerate() { 
    if B.contains(a) && !C.contains(a){ 
     C.append(a) 
    } 
} 

希望幫助!

+0

其實我的天堂我沒有在課堂上學到Swift函數,所以我不認爲我可以在我的程序中實現類似的東西。不過謝謝你。 –

1

它的方便,你可以用(PHP語言)以下做: 令:

$A = [1,2,3,4]; 
$B = [2,4,6,7]; 
$count = 0; 
$b_count = array_count_values($B); 
foreach($A as $val) 
{ 
    if(in_array($val, $B) && $b_count[$val] == 1) 
    { 
     $count++; 
    } 
} 
echo "Total number of elements => ".$count; 
+0

雖然我不想重複重複。我試圖對B中出現在數組A中的每個元素進行一次計數。 –

+0

爲此,您可以稍微更改上面的代碼。 $ A = [1,2,3,4]; $ B = [2,4,6,7]; $ count = 0; $ b_count = array_count_values($ B); foreach($ A as $ val) { if(in_array($ val,$ B)&& $ b_count [$ val] == 1) { $ count ++; } } echo「元素總數=>」。$ count; –

1

如果不考慮程序的運行時間複雜度,你可以使用一些內置庫像地圖或設置爲很容易的代碼,但這裏是

// complexity O(n * log(n)), which is fast enough. 
// language c++ 
#include<stdio.h> 
#include<algorithm> 
using namespace std; 
int main() 
{ 
    int i, j, count = 0; 
    int A[] = {1,3,3,4}, B[] = {5,4,7,3}; 
    int lenA = 4, lenB = 4; 

    // sorting, to overlook the repeated numbers. 
    sort(A, A + lenA); 
    sort(B, B + lenB); 

    for(i=0, j=0; i<lenA; i++) 
    { 
     // ignoring the repeated A elements. 
     if(i>0 && A[i] == A[i-1]) 
      continue; 

     //we can ignore all the elements of B where it's less than current A element. 
     //this can be assured because of sorting. 
     while(j<lenB && B[j]<A[i]) 
      j++; 

     if(A[i] == B[j]) 
     { 
      count++; 
      j++; 
     } 
    } 

    printf("%d\n", count); 

    return 0; 
} 
相關問題