Results 1 to 3 of 3
Thread: Count occurances in array
- 11-07-2012, 11:34 PM #1
Member
- Join Date
- Nov 2012
- Posts
- 2
- Rep Power
- 0
Count occurances in array
Hello, I am new to java and am trying to count the highest occruance that appears in an array but I'm not entirely sure how to do this
so far I've got
public class counter {
public static void main(String[] args) {
final int N = (args.length);
int count= 1;
int[] a;
a = new int[N];
for (int i = 0; i < N; i++)
a[i] = Integer.parseInt(args[i]);
for (int i = 0; i < N; i++)
for(int j = i+1; j<N; j++)
if (a[i] == a[j]) {
count++;
}
System.out.println(duplicate);
}
}
But this just increments the count by one everytime ANY duplicate is found, I have no idea how to pick the highest occurance of a number out
Any help would be appreciated
Rachel
- 11-08-2012, 07:23 AM #2
Re: Count occurances in array
You will need three variables:
a: the current count
b: the highest count so far
c: the value that has the highest count so far.
Then use 2 nested loops. Count how many times the first number occurs using a. Store the count in b and the number in c. Reset a to 0 and go around again counting the second number. If the count for the second number is higher than b then reassign b and c. etc.
Note: use better variable names than a b and c.
- 11-08-2012, 05:16 PM #3
Member
- Join Date
- Nov 2012
- Posts
- 2
- Rep Power
- 0
Re: Count occurances in array
Can someone just confirm that this is right to count and store the number?
Thank you, I think I'm just not getting something here :(Java Code:if (a[i] == a[j]) { value = a[i]; if (value == a[j]) { count++; duplicate = count; } } count = 1;
EDIT: Ok for some reason it's counting everything past the second occurance as that number
eg. if I type in 3 4 3 5 6 it'll give me a count of 4 instead of 2 =/Last edited by quad64bit; 11-09-2012 at 05:45 PM.
Similar Threads
-
Example Count From Array Snippet
By Vinx in forum Reviews / AdvertisingReplies: 1Last Post: 05-18-2012, 05:22 AM -
Duplicate count in array
By louboulos in forum New To JavaReplies: 2Last Post: 05-10-2012, 05:37 PM -
How to count records WITHOUT an array?
By teekei in forum New To JavaReplies: 17Last Post: 07-25-2011, 12:42 PM -
i can do count, but having problem with array
By judy318 in forum New To JavaReplies: 4Last Post: 10-29-2009, 09:23 PM -
Array count number Occurances
By gwithey in forum New To JavaReplies: 2Last Post: 04-17-2009, 08:34 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks