PDA

View Full Version : function mode(list);



Turpinator
11-25-2013, 10:43 PM
Didnt see a mode function, and elfyyy needed one for his awesome Pest Control script, so i figured id give it a shot...

function mode(arr: TIntegerArray): Integer;
var
i, dcount, maxloc, finalloc: Integer;
dif: TIntegerArray;
begin
SetLength(dif, length(arr));
for i := 0 to length(arr) - 1 do
dif[i] := 1;
QuickSort(arr);

dcount := 0;
for i := 0 to length(arr) - 2 do
if arr[i] = arr[i+1] then
inc(dif[dcount])
else inc(dcount);

maxloc := 0;
for i := 0 to length(dif) - 1 do
if (dif[i] > dif[maxloc]) then
maxloc := i;

finalloc := 0;
for i := 0 to maxloc - 1 do
finalloc := finalloc + dif[i];

result := arr[finalloc];
end;

I realize this probably isnt the most efficient way of doing it, but it was a slight modification my first attempt (second one failed).

How it works...
sorts integer array/list
compares adjacent numbers and if they match, increments a matching integer in a 'difference' array (should be renamed to numbercount or something)
if the numbers are different, it moves on to the next index in the difference array and repeats
once done, it finds the max of the difference array's index and then sums up all the previous indices to determine the final loc of the mode.


heres the link to the pseudo-code i attempted to copy on the second try. http://forum.canucks.com/topic/335748-computer-science-pseudocode/#entry10914848
but in the end, my own made up code actually worked while this one didnt (i probably just translated something wrong)