Advertisement
Guest User

counting occurrences

a guest
Oct 25th, 2014
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.30 KB | None | 0 0
  1. package jah.tests;
  2.  
  3. public class TestMe {
  4.  
  5.     public static final int MAX_VAL=20;
  6.  
  7.     public static void countOccurrencesId(int[] arr) {
  8.         int[] counts = new int[MAX_VAL+1];
  9.         //first we work out the count for each one
  10.         for (int i: arr)
  11.             counts[i]++;
  12.         //now we print the results
  13.         for (int i: arr)
  14.             if (counts[i]>0) {
  15.                 System.out.println(i+" occurs "+counts[i]+" times");
  16.                 //now set this count to zero so we won't get duplicates
  17.                 counts[i]=0;
  18.             }
  19.     }
  20.    
  21.     public static void countOccurrences(int[] arr) {
  22.         int[] counts = new int[MAX_VAL+1];
  23.         //first we work out the count for each one
  24.         for (int i=0; i<arr.length; i++)
  25.             counts[arr[i]]++;
  26.         //now we print the results
  27.         for (int i=0; i<arr.length; i++)
  28.             if (counts[arr[i]]>0) {
  29.                 System.out.println(arr[i]+" occurs "+counts[arr[i]]+" times");
  30.                 //now set this count to zero so we won't get duplicates
  31.                 counts[arr[i]]=0;
  32.             }
  33.     }
  34.  
  35.     public static void main(String[] args) {
  36.        
  37.         int[] countMe = { 10, 10, 20, 10, 20, 15 };
  38.        
  39.         System.out.println("First version:");
  40.         countOccurrencesId(countMe);
  41.         System.out.println();
  42.         System.out.println("Second version:");
  43.         countOccurrences(countMe);
  44.     }
  45.    
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement