2017-09-17 73 views
-1

計算數組元素頻率我想找到陣列元件的頻率。像:沒有重複

輸入數組:

1,2,3,4,2,3,4,5,8 

預期輸出(位頻率):

1 1 
2 2 
3 2 
4 2 
5 1 
8 1 

我的Java代碼是:

class Fre 
{ 
public static void main(String ar[]) 
{ 
    frequencycount(new int[]{1,2,3,3,2,1,1,1,5,6,5,8,9,6}); 
} 


static void frequencycount(int x[]) 
{ 
    int i=0; 
    int j=0; 
    int fr[]=new int[x.length]; 
    for(i=0;i<fr.length;i++) { 
    fr[i]=0; 
    } 

    /////calculating frequency 
    for(i=0;i<digit.length;i++) { 
     for(j=0;j<digit.length;j++) { 
      if(x[i]==x[j]) { 
      fr[i]++; 
      } 
     } 
     } 

    for(i=0;i<fr.length;i++) { 
     System.out.println(x[i]+" "+fr[i]); 
    } 
    } 
}//class 

與輸出的問題是它是重複數組元素。像:

digit frequency: 


1 1 
2 2 
3 2 
4 2 
2 2 
3 2 
4 2 
7 1 
8 1 

我怎樣才能得到所需的頻率,而不重複數組元素?任何幫助將不勝感激。

+0

想一想,什麼是你的獨特的價值觀,當你迭代達到一個已經計數一次的值時會發生什麼......還不知道你如何在每行打印這兩個值。 – nullpointer

+1

我想,而不是'X [I]'你應該打印'i' – 3stud1ant3

+0

@ 3stud1ant3爲什麼呢? – user227666

回答

0

爲什麼不直接使用地圖一樣Map<Integer, Integer>並在每次找到值時增加關鍵的價值?然後你可以遍歷地圖並打印出它的值。這也可以避免嵌套for循環。

Here's a tutorial讓你開始使用Map

+0

你可能要替換'和'地圖<整數,整數>地圖'' –

+0

我需要做的是不使用的地圖。這是棘手的部分。 – user227666

+0

@ArchdukeLiamus忘記仿製藥不能使用的原語,感謝 – EthanBar

0

有很多在你code.Instead編譯和邏輯錯誤的,我用下面的代碼。

class Fre { 
    public static void main(String ar[]) { 
     frequencycount(new int[]{1, 2, 3, 3, 2, 1, 1, 1, 5, 6, 5, 8, 9, 6}); 
    } 


    static void frequencycount(int x[]) { 

     int fr[] = new int[maxElement(x)]; 
     /* default value of all elements is 0 no need to run this code 
     for (i = 0; i < fr.length; i++) { 
      fr[i] = 0; 
     }*/ 


     for (int k = 0; k < x.length; k++) { 
      //update index with count 
      int value = x[k]; 
      fr[value] = fr[value] + 1; 
     } 

     for (int k = 0; k < fr.length; k++) { 
      if (fr[k] != 0) { 
       System.out.println(k+" " + fr[k]); 
      } 
     } 
    } 
} 
+0

獲取array'indexOutofBound error in line'fr [value] = fr [value] + 1;' – user227666

+0

這裏的問題是int fr [] = new int [x.length];您必須將長度定義爲最大元素而不是x.length。 – Gaurav

+0

@ user227666如果不使用地圖,則需要一個與您可能需要接受的值範圍一樣長的數組。要麼你必須使自己的'Map'像函數,或者只是做一個愚蠢的長陣列, – EthanBar