...

View Full Version : Javascript argument to pick the largest number and break a tie if exists



brandonlee
06-12-2010, 12:55 AM
Hi there,

I am trying to pick the larger of 5 numbers and sometimes there is a tie. I would like to prioritize variable c1 if there is a tie. This data is from a quiz I am writing.

var c1 = 2; // Takes priority if there is a tie.
var c2 = 1;
var c3 = 2;
var c4 = 0;
var c5 = 0;

jmrker
06-12-2010, 07:32 PM
Can you modify this logic to suit your needs?


<html>
<head>
<title>Max Number Tie</title>
<script type="text/javascript">
// From: http://www.codingforums.com/showthread.php?t=197967

// array to represent 5 answers to the 'c' question (c1-c5)
var c = [2,1,2,0,0];

var str = '';
str += 'Original responses to question "c":<br>';
for (var i=0; i<c.length; i++) { str += 'c'+(i+1)+'='+c[i]+', '; }

var cmax = [];
var maxC = -1e10;
for (var i=0; i<c.length; i++) {
if (c[i] > maxC) { maxC = c[i]; cmax = []; cmax.push('c'+(i+1)); }
else { if (c[i] == maxC) { cmax.push('c'+(i+1)); } }
}
cmax.sort();
str += '<br>Max response: '+maxC+'<br>';
str += cmax.join('<br>');

str += '<br>Priority goes to: '+cmax[0];
document.write(str);
</script>
</head>
<body>
</body>
</html>

brandonlee
06-20-2010, 05:34 AM
Can you modify this logic to suit your needs?


<html>
<head>
<title>Max Number Tie</title>
<script type="text/javascript">
// From: http://www.codingforums.com/showthread.php?t=197967

// array to represent 5 answers to the 'c' question (c1-c5)
var c = [2,1,2,0,0];

var str = '';
str += 'Original responses to question "c":<br>';
for (var i=0; i<c.length; i++) { str += 'c'+(i+1)+'='+c[i]+', '; }

var cmax = [];
var maxC = -1e10;
for (var i=0; i<c.length; i++) {
if (c[i] > maxC) { maxC = c[i]; cmax = []; cmax.push('c'+(i+1)); }
else { if (c[i] == maxC) { cmax.push('c'+(i+1)); } }
}
cmax.sort();
str += '<br>Max response: '+maxC+'<br>';
str += cmax.join('<br>');

str += '<br>Priority goes to: '+cmax[0];
document.write(str);
</script>
</head>
<body>
</body>
</html>


Thanks a ton this helps out tremendously!

jmrker
06-20-2010, 01:19 PM
Thanks a ton this helps out tremendously!

You're most welcome.
Happy to help.
Good Luck!
:)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum