Chinaunix首页 | 论坛 | 博客
  • 博客访问: 222281
  • 博文数量: 136
  • 博客积分: 2919
  • 博客等级: 少校
  • 技术积分: 1299
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-11 09:08
文章分类

全部博文(136)

文章存档

2013年(1)

2011年(135)

我的朋友

分类: Java

2011-08-31 09:43:53

  1. /**********************************************************************************
  2.   * Compilation: javac SelfAvoidingWalk
  3.   * Execution: java SelfAvoidingWalk N T
  4.   *
  5.   * Generate T self-avoiding walks of length N.
  6.   * Report the fraction of time the random walk is not self-intersecting.
  7.   *
  8.   * Simple execution: % java SelfAvoidingWalk 20 100
  9.   * 26% deak ends
  10.   *
  11.   * *********************************************************************************/

  12. public class SelfAvoidingWalk {
  13.     public static void main(String[] args) {
  14.         int N = Integer.parseInt(args[0]); // lattice size
  15.         int T = Integer.parseInt(args[1]); // number of trials
  16.         int deadEnds = 0; // trials resulting in a dead end
  17.         
  18.         for (int t = 0; t < T; t++) {
  19.             int x = N/2, y = N/2; // current position
  20.             boolean[][] a = new boolean[N][N]; // intersections visited
  21.             while (x > 0 && x < N-1 && y > 0 && y < N-1) { // check for dead end and make a random move.
  22.                 a[x][y] = true;
  23.                 if (a[x-1][y] && a[x+1][y] && a[x][y-1] && a[x][y+1]) {
  24.                     deadEnds++;
  25.                     break;
  26.                 }
  27.                 double r = Math.random();
  28.                 if (r < 0.25 && !a[x+1][y]) x++; // move right
  29.                 else if( r < 0.50 && !a[x-1][y]) x--; // move left
  30.                 else if (r < 0.75 && !a[x][y+1]) y++; // move up
  31.                 else if (r < 1.00 && !a[x][y-1]) y--; // move down
  32.             }
  33.         }
  34.         System.out.println(100*deadEnds/T + " % dead ends");
  35.     }
  36. }
阅读(560) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~