This question brings me back to my college days, but since I haven’t coded since those days (more than 20 years ago) I am a bit rusty.
Basically I have an array of 256 elements. there might be 1 element on the array, 14 or 256. This array contains the usernames of people requesting data from the system. I am trying to count the duplicates on the list so I can give the priority to the user with most requests. So, if I have a list such as:
{john, john, paul, james, john, david, charles, charles, paul, john}
I would choose John because it appeared 4 times.
I can iterate the array and copy the elements to another and start counting but it gets complicated after a while. As I said, I am very rusty.
I am sure there is an easy way to do this. Any ideas? Code would be very helpful here.
Thank you!
EDIT:
The buffer is declared as:
static WCHAR userbuffer[150][128];
There could be up to 150 users and each username is up to 128 chars long.
Here’s how I would solve it:
First, define a structure to hold user names and frequency counts and make an array of them with the same number of elements as your
userbufferarray (150 in your example).Now, loop through
userbufferand for each entry, check and see if you have an entry inusersthat has the samename. If you find a match, increment thecountfor that entry inusers. If you don’t find a match, copy the user’s name fromuserbufferinto a blank entry inusersand set that user’scountto1.After you have processed the entire
userbufferarray, you can use thecountvalues from yourusersarray to see who has the most requests. You can either iterate through it manually to find the max or useqsort.It’s not the most efficient algorithm, but it’s direct and doesn’t do anything too clever or fancy.
Edit:
To qsort the
usersarray, you will need to define a simple function that qsort can use to sort by. For this example, something like this should work:Now, you can pass this function to
qsortlike: