黑马程序员技术交流社区
标题:
java解决百度面试题—蚂蚁爬木杆问题
[打印本页]
作者:
as604049322
时间:
2015-3-17 00:25
标题:
java解决百度面试题—蚂蚁爬木杆问题
QQ截图20150317002443.jpg
(193.53 KB, 下载次数: 17)
下载附件
2015-3-17 00:25 上传
[code]package com.itheima;
/**
* 有一根27厘米的细木杆,在第3厘米、7厘米、11厘米、17厘米、23厘米这五个位置上各有一只蚂蚁。
* 木杆很细,不能同时通过一只蚂蚁。开始时,蚂蚁的头朝左还是朝右是任意的,
* 它们只会朝前走或调头,但不会后退。当任意两只蚂蚁碰头时,两只蚂蚁会同时调头朝反方向走。 假设蚂蚁们每秒钟可以走一厘米的距离。
* 编写程序,求所有蚂蚁都离开木杆 的最小时间和最大时间。
*
* 分析: 当两只蚂蚁都掉头以后,我们把 a 蚂蚁看成 b 蚂蚁,把 b 蚂蚁看成 a 蚂蚁,
* 若不考虑它们的名字a,b,其实这和两只蚂蚁“擦肩而过”有什么区别呢? 也就是说,蚂蚁的碰撞根本不会影响“宏观”上五只蚂蚁的运动情况。
*
* @author 旋风铭
*
*/
public class AntOfTime {
作者:
as604049322
时间:
2015-3-17 00:27
package com.itheima;
/**
* 有一根27厘米的细木杆,在第3厘米、7厘米、11厘米、17厘米、23厘米这五个位置上各有一只蚂蚁。
* 木杆很细,不能同时通过一只蚂蚁。开始时,蚂蚁的头朝左还是朝右是任意的,
* 它们只会朝前走或调头,但不会后退。当任意两只蚂蚁碰头时,两只蚂蚁会同时调头朝反方向走。 假设蚂蚁们每秒钟可以走一厘米的距离。
* 编写程序,求所有蚂蚁都离开木杆 的最小时间和最大时间。
*
* 分析: 当两只蚂蚁都掉头以后,我们把 a 蚂蚁看成 b 蚂蚁,把 b 蚂蚁看成 a 蚂蚁,
* 若不考虑它们的名字a,b,其实这和两只蚂蚁“擦肩而过”有什么区别呢? 也就是说,蚂蚁的碰撞根本不会影响“宏观”上五只蚂蚁的运动情况。
*
* @author 旋风铭
*
*/
public class AntOfTime {
public static void main(String[] args) {
int[] ant;
int time;
boolean[] left = { true, true, true, true, true };// 五只蚂蚁的方向是否向左
boolean[] stillin;// 五只蚂蚁是否还在木杆上
int mintime = 10000;
int maxTime = 0;
String minStr = null;
String maxStr = null;
String str = null;
for (int i = 1; i < Math.pow(2, 5); i++) {
//初始化
time = 0;
ant = new int[] { 3, 7, 11, 17, 23 };// 五只蚂蚁的位置
stillin = new boolean[] { true, true, true, true, true };// 五只蚂蚁是否还在木杆上
//产生代表蚂蚁方向的文本,(0代表向左,1代表向右)
str = Integer.toBinaryString(i);
str = str.replaceAll("([01]+)", "0000$1");
str = str.replaceAll("0*([01]{5})", "$1");
//下面的while循环模拟了五只蚂蚁从初始状态到全部离开木杆的全过程
while (true) {
//str的五个字符分别代表了五只蚂蚁的运动方向
if (str.charAt(0) == '0')
ant[0]--;
else
ant[0]++;
if (str.charAt(1) == '0')
ant[1]--;
else
ant[1]++;
if (str.charAt(2) == '0')
ant[2]--;
else
ant[2]++;
if (str.charAt(3) == '0')
ant[3]--;
else
ant[3]++;
if (str.charAt(4) == '0')
ant[4]--;
else
ant[4]++;
//此时运动完成,耗时1秒
time++;
//判断蚂蚁是否已经离开木杆并记录
if (ant[0] <= 0 || ant[0] >= 27)
stillin[0] = false;
if (ant[1] <= 0 || ant[1] >= 27)
stillin[1] = false;
if (ant[2] <= 0 || ant[2] >= 27)
stillin[2] = false;
if (ant[3] <= 0 || ant[3] >= 27)
stillin[3] = false;
if (ant[4] <= 0 || ant[4] >= 27)
stillin[4] = false;
//如果全部都已经离开木杆则退出循环
boolean flag = false;
for (int j = 0; j < stillin.length; j++) {
flag = flag || stillin[j];
}
if (!flag)
break;
}
//获得该状态下蚂蚁全部离开所需要的时间
if (maxTime < time) {
maxTime = time;
maxStr = str;
}
if (mintime > time) {
mintime = time;
minStr = str;
}
}
System.out.println("最短时间:" + mintime + ",str=" + minStr);
System.out.println("最长时间:" + maxTime + ",str=" + maxStr);
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2