-
modal average
I am trying to get started on writting some code on modal average. The "modal average" of a set of values is the most commonly occurring value in that set. For example, the modal average of {0, 0, 1, 1, 1, 2, 1000} is 1. The modal average of {"abc", "abc", "def", "g", "g", "g", "hijk", "hijk"} is "g".
So, I am trying to write a function template for finding the modal average of sequence of values of any type that supports the < operator. Assume that the sequence is in sorted order, so that all occurrences of the same value will be adjacent within the array. If the modal average is ambiguous (i.e., the sequence contains multiple values that each occur k times, and no values that occur more than k times), then I want it to select the smallest value from among the possible modal averages. Help is all I can say.
Thanks
-
templated function
return type is void
single argument is an array of template type
determine size of argument arrray
declare variable of template type called modalValue
declare variable of template type called currentValue
declare int called modalNumber and initialize to zero
declare int called currentNumber and initialize to zero
assign value of first element in array to modalValue and currentValue
use a for loop to evaluate all elements in array
while array[i] == array[0] && array[i] == currentValue
increment modalNumber by 1
if array[i] != array[0] && array[i] == currentValue
increment currentValue by 1
if array[i] != array[0] && array[i] != currentValue && currentNumber > modalNumber
then assign currentValue to modalValue and
currentNumber to modalNumber and
assign array[i] to currentValue and
assign 1 to currentValue
if array[i] != array[0] && array[i] != currentValue && currentNumber <= modalNumber
assign array[i] to currentValue and
assign 1 to currentNumber
end for loop
when for loop done check if last currentValue is modal value by testing if currentNumber > modalNumber
then assign currentValue to modalValue and
assign currentNumber to modalNumber
now print out modalValue and, if you want, modalNumber.
end function
with a little thought you should be able to use < instead of == in most of the code so you don't have to have classes with overloaded == as well as overloaded < and still maintain same logic, but I'll leave that for you.