标签:
public class AntRun { public static void main(String[] args) { Ant[] woods = { new Ant(), new Ant(), new Ant(), new Ant(), new Ant() }; int[] pos = { 3, 7, 11, 18, 23 }; boolean[][] dirs = new boolean[32][5]; for (int i = 0; i < dirs.length; i++) { for (int j = 0; j < dirs[i].length; j++) { dirs[i][j] = (i & (0x01 << j)) == 0;// true 左 false 右 } } int time = 0; int max = -1; int min = 100; // 蚂蚁移动模拟 for (int i = 0; i < dirs.length; i++) { time = 0; // 初始化 for (int j = 0; j < woods.length; j++) { woods[j].setAlive(true); woods[j].setPosition(pos[j]); woods[j].setDirection(dirs[i][j]); } // 蚂蚁移动 while (true) { System.out.println("time:----------"+time); output(woods);//输出各蚂蚁的当前位置 time++; // 移动 for (int j = 0; j < woods.length; j++) { woods[j].move(1); } // 相遇 for (int j = 0; j < woods.length - 1; j++) { if (woods[j].isAlive && woods[j + 1].isAlive && !woods[j].direction && woods[j + 1].direction) { // 相撞,要退一步 if (woods[j + 1].position == woods[j].position) { System.out.println("相撞,回到原来的位置,方向相反"); woods[j].move(-1); woods[j].direction = !woods[j].direction; woods[j + 1].move(-1); woods[j + 1].direction = !woods[j + 1].direction; } // 相遇 if ((woods[j + 1].position - woods[j].position == 1)) { System.out.println("相遇"); woods[j].direction = !woods[j].direction; woods[j + 1].direction = !woods[j + 1].direction; } } } // 蚂蚁是否全部掉下 boolean isEnd = true; for (int j = 0; j < woods.length; j++) { if (woods[j].isAlive) { isEnd = false; } } if (isEnd) { break; } } System.out.println("蚂蚁全部走出。。。。"); if (max < time) { max = time; } if (min > time) { min = time; } } System.out.println("max:" + max + "min:" + min); } private static void output(Ant[] ants){ for(int i=0;i<ants.length; i++){ System.out.print(ants[i].position+"\t"); } System.out.println(); } } class Ant { boolean direction; int position; boolean isAlive; final int START = 0; final int END = 27; public void setDirection(boolean direction) { this.direction = direction; } public void setPosition(int position) { this.position = position; } public void setAlive(boolean isAlive) { this.isAlive = isAlive; } public void move(int n) { if (isAlive) { if (direction) { position -= n; } else { position += n; } if (position == START) { isAlive = false; } if (position == END) { isAlive = false; } } } }
标签:
原文地址:http://blog.csdn.net/hncu1306602liuqiang/article/details/46323501