454,507 Members | 1,758 Online
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,507 IT Pros & Developers. It's quick & easy.

# mode from array

 P: n/a Cannot seem to wrap my head around this, could someone help me with the logic? I need to pull the value which occurs most frequently from array - am writing a mini program to get logic sorted out, but it just doesn't get there. int main(void) { int i; int data[8]; //create static array to hold data for (i=0;i<8;i++) { data[i] = i; } //set static value to increase freq of 42. data[6] = 3; printf("data = "); for (i=0;i<8;i++) printf("%d ", data[i]); //now get frequency array int freq[8]; for (i=0;i<8;i++) { freq[i] = 0; } printf("\n \n freq = "); for (i=0;i<8;i++) printf("%d ", freq[i]); //now count frequency... int freqcount = 0;//will hold frequencies int oldfreq=0; int nownum = 0; int newoldfreq=0; for(nownum=0;nownum<8;nownum++) { for(i=0;i<8;i++) { if(nownum==data[i]) { freqcount ++; if(freqcount > oldfreq) { nownum = newoldfreq; } newoldfreq=oldfreq; } } } printf("\n mode = %d \n", oldfreq); return 0; } Output; data = 0 1 2 3 4 5 3 7 freq = 0 0 0 0 0 0 0 0 mode = 0 obviously the mode should 3 - but my logic is horrible - any suggestions on how to get this value? Nov 20 '05 #1

 P: n/a Sluggoman said: Cannot seem to wrap my head around this, could someone help me with the logic? I need to pull the value which occurs most frequently from array - am writing a mini program to get logic sorted out, but it just doesn't get there. Take a look at the following code, which does what you want. I've taken the unusual step of commenting (almost) every line, in the hope that it helps you clear your head a little. :-) MINVAL and MAXVAL can be tweaked to taste, within reason, if you wish. #include /* prototype for printf, and def of size_t */ #define MINVAL 0 /* the lowest allowable data value */ #define MAXVAL 42 /* the highest allowable data value */ int main(void) { int data[] = { 0, 1, 2, 3, 4, 5, 3, 7 }; /* initialise the data array */ int freq[MAXVAL + 1 - MINVAL] = { 0 }; /* clear the frequency * counts to 0. */ size_t i = 0; /* loop counter */ int mode = 0; /* for recording the modal value */ for(i = 0; i < sizeof data / sizeof data[0]; i++) /* for each datum */ { ++freq[data[i]]; /* track the frequency */ if(freq[data[i]] > mode) /* is this now the most common item? */ { mode = data[i]; /* yes, so log it */ } } printf("The modal value is %d which occurs %d time%s.\n", mode, freq[mode], freq[mode] == 1 ? "" : "s"); /* 1 time, 2 time>>s<< */ return 0; } -- Richard Heathfield "Usenet is a strange place" - dmr 29/7/1999 http://www.cpax.org.uk email: rjh at above domain (but drop the www, obviously) Nov 20 '05 #2

### This discussion thread is closed

Replies have been disabled for this discussion.