Page 1 of 1

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

Posted: Tue Apr 14, 2009 6:55 am
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.

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

Posted: Tue Apr 14, 2009 7:36 am
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++; ...

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

Posted: Tue Apr 14, 2009 9:47 am
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.

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

Posted: Tue Apr 14, 2009 10:00 am
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);

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

Posted: Tue Apr 14, 2009 11:47 am
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

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

Posted: Wed Apr 15, 2009 5:08 pm
by Geebs
Hmm, I appear to be too stupid to get this to work

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

Posted: Wed Apr 15, 2009 6:55 pm
by ^misantropia^
Post the code and have others take a look at it. Many eyes make bugs shallow and all that. =)