/**
* @text Finds the item that appears the most in the collection with one single iteration.
* @text Restriction: it must be included more than half the times.
*/
function moda( list ){
var
counter = 1,
elem = list[0];
for( var i=1; i < list.length; i++ ){
if( list[i] === elem ){
++counter;
}else if( --counter === 0 ){
elem = list[i];
counter = 1;
}
}
return elem;
};
Logger.assert( moda([1,2,3,1,1]) === 1 );
Logger.assert( moda([2,2,3]) === 2 );
Logger.assert( moda([1,3,3,3]) === 3 );
Logger.assert( moda([4,4,4,4,4]) === 4 );
Logger.assert( moda([5,4,5,4,5,4,5,4,5]) === 5 );