View Single Post
Old 12-01-2012, 11:47 PM   PM User | #15
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,579
Thanks: 62
Thanked 4,064 Times in 4,033 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
Is *THIS* what you are after:
Code:
<script type="text/javascript">

function findMode( arr )
{
    var counts = [ ];
    for ( var a = 0; a < arr.length; ++a )
    {
        var elem = "E" + arr[a];
        if ( counts[ elem ] == null ) 
        {
            counts[ elem ] = 1;
        } else {
            ++counts[ elem ];
        }
    }
    var half = 0.5 * arr.length;
    for ( var elem in counts )
    {
        // I don't think >= half works...what if the array is simply [1,2] ?? SO I used >
        if ( counts[elem] > half ) { return elem.substring(1); }
    }
    return "NONE";
}

var atest = [ 1, 37, 3, 2, 44, 1, 99, 1 ];
document.write( "Mode of [" + atest + "] is " + findMode(atest) + "<hr>" );

atest = [ 77, 101, 191, 91, 91, 191, 191, 191, 191 ];
document.write( "Mode of [" + atest + "] is " + findMode(atest) + "<hr>" );
</script>
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.

Last edited by Old Pedant; 12-01-2012 at 11:51 PM..
Old Pedant is offline   Reply With Quote
Users who have thanked Old Pedant for this post:
evaaa (12-01-2012)