Anyone with better maths than me i.e. everyone - C coding

Locked
Geebs
Posts: 3849
Joined: Tue Feb 08, 2005 4:56 pm

Anyone with better maths than me i.e. everyone - C coding

Post by Geebs »

Does anyone know where I can find a generalized approach to taking an array containing list of numbers, some of which are the same, and counting a) the number of duplicates and b) the number of times a duplicate occurs? I've figured out that sorting the list first might help, but then got stuck.

e.g. array is 1, 3, 2, 4, 2, 5, 2, 3, 4
output would be:
1, 2, 2, 2, 3, 3, 4, 4, 5
and there is one instance of 1, three of 2, two of 3, two of 4, one of 5

The reason for this is that I'm trying to group a list of entries into a database by date - in the same way that outlook produces section headings for emails like received today, yesterday, in the last 7 days etc. The records are stored as objects in an array and then displayed by date.
epicgoo
Posts: 44
Joined: Sun Mar 01, 2009 4:24 pm

Re: Anyone with better maths than me i.e. everyone - C coding

Post by epicgoo »

run thru the array
use a secondary array to store the counts
so if you see the same number second time search the count array for it and add 1
it can be like num_1, count_1, num_2, count_2 ...
at the end the numbers with count > 1 are duplicates.
and you have just weekdays you can use
int days[7];
... if (array>=0 && array<7) days++; ...
^misantropia^
Posts: 4022
Joined: Sat Mar 12, 2005 6:24 pm

Re: Anyone with better maths than me i.e. everyone - C coding

Post by ^misantropia^ »

Is there a reason why it must be C? If it's a one-off thing, this will be much easier to do in Perl, Python or PHP.
^misantropia^
Posts: 4022
Joined: Sat Mar 12, 2005 6:24 pm

Re: Anyone with better maths than me i.e. everyone - C coding

Post by ^misantropia^ »

Oh, and to prove how simple it is - the PHP solution:

Code: Select all

function filter_non_dups($value)
{
    return $value > 1;
}

$a = array(1,3,2,4,2,5,2,3,4);
$dup_freq = array_count_values($a);
$dup_freq = array_filter($dup_freq, 'filter_non_dups');
$dup_count = count($a) - count(array_unique($a));
print_r($dup_freq);
print_r($dup_count);
Geebs
Posts: 3849
Joined: Tue Feb 08, 2005 4:56 pm

Re: Anyone with better maths than me i.e. everyone - C coding

Post by Geebs »

Thanks guys, I'm much more of a doctor fiddling around with coding than a programmer! It's objective C 'cos it's for a medical casenotes app for the iPhone
Geebs
Posts: 3849
Joined: Tue Feb 08, 2005 4:56 pm

Re: Anyone with better maths than me i.e. everyone - C coding

Post by Geebs »

Hmm, I appear to be too stupid to get this to work
^misantropia^
Posts: 4022
Joined: Sat Mar 12, 2005 6:24 pm

Re: Anyone with better maths than me i.e. everyone - C coding

Post by ^misantropia^ »

Post the code and have others take a look at it. Many eyes make bugs shallow and all that. =)
Locked