2015-04-01 20 views
-2

我正在試圖找到我的程序的模式,用戶輸入的數量從0-100到儘可能多的數量,我試圖找到模式這些數字,但每次我試圖找到它給我回3模式,我發現了一切,我只需要模式的幫助。如何使用Java找到數組的模式

import java.util.Scanner; 

public class deveation { 
    public static void main(String Args[]) { 
     Scanner kbReader = new Scanner(System.in); 
     int sum = 0; 
     int bob[] = new int[101]; 
     int total = 0; 
     int a = 0; 
     int min = 0; 
     int max = 100; 
     int mode = 0; 
     boolean stay_in_loop = true; 

     while (stay_in_loop) { 

      System.out.println("Please enter interger(s) from 0-100: "); 
      int number = kbReader.nextInt(); 

      if (number < 0) { 
       stay_in_loop = false; 
      } 

      else { 
       total++; 
       bob[number]++; 
      } 
     } 

     int median = total/2 + 1; 
     while (median > 0) { 
      median -= bob[a]; 
      a++; 
     } 
     a--; 
     boolean findit = true; 
     while (findit) { 
      if (bob[min] != 0) 
       findit = false; 
      else 
       min++; 
     } 

     boolean findme = true; 

     while (findme) { 
      if (bob[max] != 0) 
       findme = false; 
      else 
       max--; 
     } 

     for (int p = 0; p < 101; p++) { 
      if (bob[p] > mode) { 
       mode = bob[p]; 
      } 
      for (int j = 0; j < 101; j++) 
       if (bob[j] <= mode) 
       //I don't know why I'm getting three for this 
       { 

       } 
     } 

     for (int i = 0; i < 101; i++) { 
      sum += bob[i] * i; 

     } 
     System.out.println(sum); 
     System.out.println(sum /= total); 
     System.out.println(a); 
     System.out.println(min); 
     System.out.println(max); 
     System.out.println(mode); 
     //You should start putting down these comments 
    } 

} 
+0

無法重現您的問題。你的意思是你總是得到三個? – Aify 2015-04-01 17:20:10

+0

在同一天有兩個答案,但你沒有投票,接受或答覆 - 如此低估。由於評論者說他們無法複製,投票也要關閉。 – halfer 2016-01-23 13:56:54

回答

0

嘗試使用類似hashmap的東西,其中鍵的數量和值將是出現的次數。你可以跟蹤最高價值。你也應該能夠在O(n)時間內完成這個操作,意味着在一個循環中通過數組。網上有很多關於尋找模式的例子。

+0

'bob [i]'已經計算了'i'的出現次數。 – 2015-04-01 17:22:42

+0

@pbabcdefp啊啊,我的壞..只是 – Kerbstomp 2015-04-01 18:07:47

1

您製作mode = bob[p],但bob[p]只是您的數組中出現的次數的多少倍。 mode應該確實是p

例如,假設bob陣列是:

[2, 1, 3, 1, 1, 2] 

這意味着0出現了兩次,1出現一次,2出現三次等等。在這種情況下,mode2,它由數組索引給出,而不是存儲在數組中的值。

爲了找到模式,我們需要遍歷計數數組(bob),並且保留兩個變量mode和最高的count直到現在。沒有必要循環兩次或使用嵌套循環。

int count = 0; 
int mode = 0; 
for (int p = 0; p < bob.length; p++) { 
    // If the count of the p element is greater than the greatest count until now 
    if (bob[p] > count) { 
     // Update the greatest count 
     count = bob[p]; 
     // p is the new mode 
     mode = p; 
    } 
} 
1

模式是最經常重複的數字。我會擺脫你有的循環內部。

for (int p = 0; p<101; p++) { 
    if (bob[p]>mode) { 
     mode=bob[p]; 
    } 
} 

我不知道爲什麼你說你總是得到三個。在上述循環結束時,mode變量將包含您的bob數組中數字的最大計數。

然後,您可以循環回列表(或循環存儲值)並打印出與您的模式值相匹配的數字。

for (int p = 0; p < 101; p++) { 
    if (bob[p] == mode) { 
     System.out.println("Mode Number: " + p); 
    } 
} 

請記住,模式可以不止一個數字。

相關問題