设为首页收藏本站订阅更新

无忧脚本

 找回密码
 加入无忧

QQ登录

只需一步,快速开始

查看: 11817|回复: 2

【原创:DHTML】JavaScript解决Joseph问题 [复制链接]

Rank: 3Rank: 3

升级  28.67%

注册时间
2006-5-15
威望
142
阅读权限
30
积分
286
帖子
169
精华
0
UID
51690
状态
当前离线
发表于 2006-5-21 15:41:41 |显示全部楼层 |串个门|加好友|打招呼|发消息 |
查看详细资料
一键分享 一键分享
首发于bbs.huse.cn
javascript中的数组对象捆绑了强大的方法
因此它可以用很简短的代码实现强大的数组操作
而这些功能要C或者c++实现的话可能需要花费几倍的代码
而且可读性更差
-----------------------------------------
  1. <html>

  2. <head>
  3. <title>约瑟夫问题的javascript解答</title>
  4. <script language="javascript">
  5. //written by lola.huse.2006-4-1
  6. function printArray(Arr)
  7. {
  8. for(var j=0;j<Arr.length;j++)
  9. document.write(Arr[j]+" ");
  10. document.write("<br>")
  11. }
  12. function a(peopleAmount,passKey)
  13. {
  14. var ar=new Array();
  15. for(var i=0;i<peopleAmount;i++)
  16. ar.push(i+1);
  17. document.write("最初队伍为:<br>")
  18. printArray(ar);
  19. document.write("关键字为"+passKey+"<br>-----------<br>")
  20. var currentPos=1;
  21. while(ar.length>1)
  22. {
  23. currentPos=(currentPos+(passKey-1))%ar.length;//
  24. if(currentPos==0)currentPos=ar.length
  25. //document.write(currentPos+1+"<br>");
  26. document.write(ar.splice(currentPos-1,1)+"号走了,剩下成员为:");
  27. printArray(ar);
  28. }
  29. document.write("最后剩下的是:")
  30. printArray(ar);
  31. document.write("<a href=javascript:history.back(-1)>继续</a>");
  32. }
  33. </script>
  34. </head>
  35. <body

  36. onLoad="javascript:document.form1.T1.value='';javascript:document.form1.T2.value=''"

  37. >
  38. <form method="POST" name="form1" action="javascript:a(parseInt

  39. (document.form1.T1.value),parseInt(document.form1.T2.value))">
  40.  <p>人数<input type="text" name="T1">
  41.  </p>
  42.  <p>Key<input name="T2" type="text" id="T2">
  43.  </p>
  44.  <p>
  45.   <input type="submit" value="提交" name="B1" onClick="javascript:return

  46. (document.form1.T1.value!=''||document.form1.T2.value!='')">
  47.  </p>
  48. </form>
  49. </body>

  50. </html>
复制代码运行代码另存代码

[ 本帖由 lola 最后编辑于 2006-5-21 15:48 ]

Rank: 2

升级  84%

注册时间
2003-4-23
威望
95
阅读权限
20
积分
176
帖子
92
精华
0
UID
2199
状态
当前离线
发表于 2006-5-22 18:00:42 |显示全部楼层 |串个门|加好友|打招呼|发消息 |
查看详细资料
用单向循环链表也就是几行代码的事情
以责人之心责己以恕己之心恕人

使用道具 举报

您需要登录后才可以回帖 登录 | 加入无忧

Archiver|手机版|无忧脚本 ( 苏ICP备05080427号 )|值班电话:027-62300445  

GMT+8, 2012-2-7 21:42 , Processed in 0.057846 second(s), 14 queries , Gzip On, Memcache On.

Powered by Discuz! X2

© 1999-2011 无忧脚本

回顶部