【原创:DHTML】JavaScript解决Joseph问题
首发于bbs.huse.cnjavascript中的数组对象捆绑了强大的方法
因此它可以用很简短的代码实现强大的数组操作
而这些功能要C或者c++实现的话可能需要花费几倍的代码
而且可读性更差
-----------------------------------------
<html>
<head>
<title>约瑟夫问题的javascript解答</title>
<script language="javascript">
//written by lola.huse.2006-4-1
function printArray(Arr)
{
for(var j=0;j<Arr.length;j++)
document.write(Arr+" ");
document.write("<br>")
}
function a(peopleAmount,passKey)
{
var ar=new Array();
for(var i=0;i<peopleAmount;i++)
ar.push(i+1);
document.write("最初队伍为:<br>")
printArray(ar);
document.write("关键字为"+passKey+"<br>-----------<br>")
var currentPos=1;
while(ar.length>1)
{
currentPos=(currentPos+(passKey-1))%ar.length;//
if(currentPos==0)currentPos=ar.length
//document.write(currentPos+1+"<br>");
document.write(ar.splice(currentPos-1,1)+"号走了,剩下成员为:");
printArray(ar);
}
document.write("最后剩下的是:")
printArray(ar);
document.write("<a href=javascript:history.back(-1)>继续</a>");
}
</script>
</head>
<body
onLoad="javascript:document.form1.T1.value='';javascript:document.form1.T2.value=''"
>
<form method="POST" name="form1" action="javascript:a(parseInt
(document.form1.T1.value),parseInt(document.form1.T2.value))">
<p>人数<input type="text" name="T1">
</p>
<p>Key<input name="T2" type="text" id="T2">
</p>
<p>
<input type="submit" value="提交" name="B1" onClick="javascript:return
(document.form1.T1.value!=''||document.form1.T2.value!='')">
</p>
</form>
</body>
</html>
[ 本帖由 lola 最后编辑于 2006-5-21 15:48 ] 用单向循环链表也就是几行代码的事情
页:
[1]