资源描述
<html>
<script type="text/javascript">
<!--
// 一座桥,同时只能两个人过桥,他们共用一个手电筒。现有四个人,
//每个人的过桥时间都不一样,分别为:10、5、2、1。怎样让他们用最短的时间过去。
var passer = function(name,time){
this.name = name;
this.time = time;
}
var passBridge=function(tempArr){
this.backarray = []; //未过桥数组
this.passarray = []; //过桥数组
this.backarray = tempArr;
this.amounttime = 0; //总时长
this.passcount = 1; //过桥次数
this.pass();
}
passBridge.prototype.pass = function(){
this.backarray.sort(function(a,b){
if(a.time > b.time) return 1;
if(a.time == b.time) return 0;
if(a.time < b.time) return -1;
});
if(this.passcount % 2 != 0){ //单次数过桥,由未过桥数组中最小的两个人过桥
alert(this.backarray[0].name + " 和 " + this.backarray[1].name + "正在过桥,时间为:" + this.backarray[1].time);
this.passarray.push(this.backarray[0]);
this.passarray.push(this.backarray[1]);
this.amounttime += this.backarray[1].time;
this.backarray.splice(0,2);
}else{ //双次数过桥,由未过桥数组中最大的两个人过桥
alert(this.backarray[this.backarray.length-1].name + " 和 " + this.backarray[this.backarray.length-2].name + "正在过桥,时间为:" + this.backarray[this.backarray.length-1].time);
this.passarray.push(this.backarray[this.backarray.length-1]);
this.passarray.push(this.backarray[this.backarray.length-2]);
this.amounttime += this.backarray[this.backarray.length-1].time;
this.backarray.splice(this.backarray.length-2,2);
}
this.passcount++;
if(this.backarray.length == 0){
alert("成功过桥,总时长为:" + this.amounttime);
}else{
this.back();
}
}
passBridge.prototype.back = function(){
this.passarray.sort(function(a,b){
if(a.time > b.time) return 1;
if(a.time == b.time) return 0;
if(a.time < b.time) return -1;
});
alert(this.passarray[0].name + "正在返回,时间为:" + this.passarray[0].time);
this.amounttime += this.passarray[0].time;
this.backarray.push(this.passarray[0]);
this.passarray.splice(0,1);
this.pass();
}
if(!Array.prototype.indexOf){
Array.prototype.indexOf=function(el, index){
var n = this.length>>>0, i = ~~index;
if(i < 0) i += n;
for(; i < n; i++) if(i in this && this[i] === el) return i;
return -1;
}
}
var temp = new passBridge([new passer('a',1),new passer('b',2),new passer('c',5),new passer('d',10)]);
//-->
</script>
</html>
展开阅读全文