2016-09-25 56 views
0

newb初學者這裏的次數。我試圖理解如何在兩個數組(單詞和獨特單詞)之間循環,以便我可以找出單詞數組中每個元素出現在單詞數組中的次數。 這是我的非工作代碼,請有人幫我看看我在哪裏搞亂循環?如何統計一個數組中元素出現在另一個

謝謝!

#define MAXWORDS 100 
#define ALLWORDS 1000 

int main() 
{ 

int c, state, nowords; 
state = OUT; 

int array[MAXWORDS] = {0}; 
char words[ALLWORDS] = {'0'}; 


for (int i = 0; i < MAXWORDS; ++i) 
    /* printf("%i", array[i]) */; 
/* printf("\n"); */ 

/* Filling an array correctly!!! */ 
int count; 
count = 0; 
int countchars; 
countchars = 0; 
while((c = getchar())!= EOF) 
{ 
    words[countchars++] = c; 
    count++; 

    switch(c) { 
     case ' ': 
     case '\n': 
     case '\t': 
      if(state == IN) 
      { 
       state = OUT; 
       ++nowords; 
      } 
      count = 0; 
      break; 
     default: 
      state = IN; 
      if(count > 0) 
       array[nowords] = count; 
      break; 
    } 
} 

words[countchars + 1] = '\0'; 

printf("number of chars in each word in the sentence: "); 
for (int i = 0; array[i] != 0; i++) 
    printf("%i,", array[i]); 
printf("\n"); 

printf("What was typed and stored into the words array: "); 
for(int k = 0; words[k] != '\0'; k++) 
    printf("%c", words[k]); 
printf("\n"); 

printf("Finding unique chars: "); 
int a, b; 
char uniques[ALLWORDS] = {'0'}; 

for(a = 0; a < countchars; a++) 
{ 
    for(b = 0; b < a; b++) 
    { 
     if(words[a] == words[b]) 
     { 
      break; 
     } 
    } 
    if(a == b) 
    { 
     uniques[a] = words[a]; 
    } 
} 

uniques[a + 1] = '\0'; 

for(int d = 0; d != ALLWORDS; d++) 
    printf("%c", uniques[d]); 
printf("\n"); 

int counting = 0; 
for(int j = 0; j < countchars; j++) 
{ 
    counting = 0; 
    for(int h = 0; h < a; h++) 
    { 
     if(words[h] == uniques[j]) 
      ++counting; 
    } 
    printf("\"%c\": %i ", uniques[j], counting); 
    printf("\n"); 
} 

return 0; 
} 

我越來越喜歡這個輸出是一種奇怪:

./homework 
a big fat herd of kittens 
number of chars in each word in the sentence: 1,3,3,4,2,7, 
What was typed and stored into the words array: a big fat herd of kittens 

Finding unique chars: a bigftherdokns 

"a": 2 
" ": 5 
"b": 1 
"i": 2 
"g": 1 
"": 0 
"f": 2 
"": 0 
"t": 3 
"": 0 
"h": 1 
"e": 2 
"r": 1 
"d": 1 
"": 0 
"o": 1 
"": 0 
"": 0 
"k": 1 
"": 0 
"": 0 
"": 0 
"": 0 
"n": 1 
"s": 1 
" 
": 1 
+0

什麼是'countchars'和'了' –

+0

如何是 'A' 初始化 - 希望爲 'strlen的(字);'? –

+0

對不起。 countchars和a是用於計算數組長度的變量。單詞是從用戶輸入中收集的,單詞是通過統計單詞中的獨特元素而得到的。對不起,混音。 – Sina

回答

0

這樣做的一個有效方式如下: 使用第三個數組:字符計數[5](絕與您的唯一身份證數組大小相同) counts [0]將保存字母'a'出現在「words」數組中的次數,counts [1]將保存字母'b'出現在「words」中的次數「陣列,等等......

因此,你只需要唱歌le for循環你在做以下事情: 檢查單詞[i]是否在唯一數組中(基本上你檢查單詞[i] < ='e')。如果單詞[i]確實是< ='e',那麼您將增加計數[單詞[i] - 'a']。

現在我們來看看「單詞[i] - 'a'」實際上是如何工作的。 如果單詞[i]是'a',那麼你會有單詞[i] - 'a'='a' - 'a'= 0(計數陣列中的第一個位置) 如果單詞[i]是'b',那麼你會有單詞[i] - 'a'='b' - 'a'= 1(count個數組中的第二個位置)。

您使用2 for循環的低效方法。

另外,發現錯誤,尤其是在像這樣的小碼的一個好辦法,就是採取實際一張紙和一支筆,並嘗試跟隨如何編寫小輸入工作。另一種(也是更有效的方法)是逐步調試,並且實際看到每個變量的值。

希望我是很清晰。祝你好運:d

+0

不,你不是很清楚。 – Sina