基于数组值

时间:2016-03-10 16:42:10

标签: java arrays

我有2个阵列

int[] count = {7,   17, 704,    17, 704,    7,  1}
int[] number = {2,  8,  8,  600,    600,    1200,   30056}

代表这些数据:

+------+-----------+
| Item | Frequency |
+------+-----------+
|   2  |     7     |
|   8  |     17    |
|   8  |    704    |
|  600 |     17    |
|  600 |    704    |
| 1200 |     7     |
| 30056|     1     |
+------+-----------+

计数总和

1457

如何获得这样的东西

Percentage of 2 is 0.5% /* 7/1457 */
Percentage of 8 is 49.5% /*(17+704)/1457*/
Etc ...

尝试

for (int i = 0; i < count.size(); i++) {
                // calculate freq percentage
                double percent =count.get(i)*100.0/total;
                String temp = df.format(percent);

            }

但似乎它只得到单独的结果而不是联盟

2|0.5%|8|1.2%|8|48.3%|600|1.2%|600|48.3%|1200|0.5%|30056|0.1%|

尝试搜索一些,但似乎我无法找到正确的关键字来搜索所需的答案。

3 个答案:

答案 0 :(得分:0)

public double get(int match){
    int numSum = 0; // numerators
    int denSum = 0; // denominators
    assert count.length == number.length; // assert that they are of the same size. Strange things may occur if this assumption is false.
    for(int i = 0; i < count.length; i++){
        denSum += count[i]; // add the count to denominator
        if(number[i] == match){
            numSum += count[i]; // add to numerator if relative `number` matches
        }
    }
    return numSum * 100d / denSum; // convert to percentage
}

答案 1 :(得分:0)

HashMap<Integer, Integer> map = new HashMap<>();
    int totalCnt = 0;
    for (int j = 0; j < number.length; j++) {
        totalCnt += count[j];
        if(map.containsKey(number[j]))
            map.put(number[j], map.get(number[j]) + count[j]);
        else 
            map.put(number[j], count[j]);
    }

    for (Entry<Integer, Integer> i : map.entrySet()) {
        double fraction = (double)i.getValue()/totalCnt;
        System.out.println("Percentage of " + i.getKey() + " is " + fraction*100);
    }

答案 2 :(得分:0)

import java.text.DecimalFormat;
import java.text.NumberFormat;

public class Test {

   static int[] count = {7,   17, 704,    17, 704,    7,  1};
   static int[] number = {2,  8,  8,  600,    600,    1200,   30056};
   static int  sum = 0;

   public static void main(String[]args){
      NumberFormat formatter = new DecimalFormat("#0.00%"); 
      for(int i : count){
        sum = sum+i;
      }
      int tempNumber = number[0];
      int tempCount = 0;

      for (int j=0;j<count.length;j++){

        if(number[j]!=tempNumber){
            System.out.println("Percentage of "+tempNumber+ " is " + formatter.format((double)tempCount/sum ));             
            tempCount = count[j];
            tempNumber = number[j];

            if(j==count.length-1){
               System.out.println("Percentage of "+tempNumber+ " is " + formatter.format((double)tempCount/sum ));  
            }             
        }
        else{              
          tempCount +=count[j];              
        }

    }
}

}