-
Javscript struggle
Hi,
Can any1 help me with a little javascripting; The scenario is:
There are four modules.. 1.Database 2.Network 3.Project 4.Programming.. what I want the script to do is select only the three best marks out of four.. i.e.
If a student gained:
Database: 50
Network: 60
Project: 10
Programming: 40
Then the script would only select: 50 + 60 + 40..
can this actually be done on javascript?
any help would be appreciated?
Amer
-
Here's one method. Get the input (I'd use a form). Then store the data in an array. then do a bubble sort on the array. Then output the last 3 items in the array. I'll get onto coding it now if you want.
-
Here you go:
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Bubble sort</title>
<script type="text/javascript">
function doIt() {
score = new Array()
score[0] = document.getElementById('scoreDB').value
score[1] = document.getElementById('scoreNW').value
score[2] = document.getElementById('scorePR').value
score[3] = document.getElementById('scorePG').value
BubbleSort(score)
document.getElementById('answer').innerHTML = score[1]+"<br />"+score[2]+"<br />"+score[3]
}
function Bubble(list) {
for (i=0; i<11; i++)
{
if (list[i] > list[1+i])
{
swap(list,i,i+1);
}
}
}
function BubbleSort(list) {
for (j=0; j<list.length; j++)
{
Bubble(list);
}
}
function swap(list,x,y) {
temp = list[x];
list[x] = list[y];
list[y] = temp;
}
</script>
</head>
<body>
<label>Database score:<input type="text" id="scoreDB" /></label><br />
<label>Network score:<input type="text" id="scoreNW" /></label><br />
<label>Project score:<input type="text" id="scorePR" /></label><br />
<label>Programming score:<input type="text" id="scorePG" /></label><br />
<input type="button" value="Select best ones" onclick="doIt()" /><br />
<span id="answer"></span>
</body>
</html>
-
Cheers Acid :thumb: ....
That was exactly wat i was looking for!...
:afrog:
-
Acidic...
Just for info purposes: (I think) Javascript arrays have a .Sort() method ;) which is faster than bubble sort (I think) although in this case its probably negligible.
Vince
-
aah, very true. I've never actually used that function though. I just remember fixing the bubble sort alog for some guy a while back and copy pasted and edited it in.