Even though I'm an artist I find the need to return the statistical mode from an array of numbers. I want the function to avoid using associative arrays (as I need version to run in JavaScript as well as Maxscript and it would be better to use the same codebase) Maxscript doesn't use associative arrays; which is a pity as this is a rather good solution.
The code below works in the first example, but not in the second. At a guess I'd say the array needs sorting beforehand but that didn't work (and I've omitted it from the code) Can anyone point out where I am going wrong? Thank you.
var textArr = new Array();
arrOne = [0,1,0,2,3,10,10]
arrTwo = [1,2,3,1,1,1]
mode_without_associative_arrays(arrOne) // works fine
mode_without_associative_arrays(arrTwo) // doesn't work
function mode_without_associative_arrays(arr)
{
if(arr.length == 0)
return null;
var collectArr = []; // array
var countArr = [] // array to hold the count of each element in collectArr
collectArr[0] = arr[0]
countArr[0] = 1
var mode = arr[0]
maxCount = 1;
for(var i = 0; i < arr.length; i++)
{
var ele = arr[i];
for(var j = 0; j < collectArr.length; j++)
{
var addMe = false;
if (collectArr[j] != ele) addMe = true
}
if (addMe == true)
{
collectArr.push(ele)
countArr.push(1)
}
else
{
// count it up
countArr[j]+=1
if (countArr[j] > maxCount)
{
maxCount = countArr[j]
mode = ele
}
}
}
alert("Mode is " + mode + " which appears " + maxCount + " times!")
return mode;
}