- 9
- 0
- 约6.46千字
- 约 9页
- 2017-10-05 发布于河南
- 举报
《百度技术研发笔试题目》.doc
百度技术研发笔试题目
/*百度面试题
* 有一根27厘米的细木杆,在第3厘米、7厘米、11厘米、17厘米、23厘米这五个位置上各有一只蚂蚁。
* 木杆很细,不能同时通过一只蚂蚁。开始 时,蚂蚁的头朝左还是朝右是任意的,它们只会朝前走或调头,
* 但不会后退。当任意两只蚂蚁碰头时,两只蚂蚁会同时调头朝反方向走。假设蚂蚁们每秒钟可以走一厘米的距离。
* 编写程序,求所有蚂蚁都离开木杆 的最小时间和最大时间。
*
*
* 分析:题目中的蚂蚁只可能相遇在整数点,不可以相遇在其它点,比如3.5cm处之类的,也就是可以让每只蚂蚁走 1秒,然后
* 查看是否有相遇的即可.
*
* 这样我的程序实现思路就是,初始化5只蚂蚁,让每只蚂蚁走1秒,然后看是否有相遇的,如果有则做相应处理.当每只蚂蚁都
* 走出木杆时,我就记录当前时间.这样就可以得到当前状态情况下,需要多久可以走出木杆,然后遍历所有状态则可以得到所胡
* 可能.
*/
package baidu;
public class Ant {
/*
* step 表示蚂蚁每一个单位时间所走的长度
*/
private final static int step = 1;
/*
* position表示蚂蚁所处的初始位置
*/
private int position;
/*
* direction表示蚂蚁的前进方向,如果为1表示向27厘米的方向走, 如果为-1,则表示往0的方向走。
*/
private int direction = 1;
/*
* 此函数运行一次,表示蚂蚁前进一个单位时间,如果已经走下木杆则会抛出异常
*/
public void walk() {
if (isOut()) {
throw new RuntimeException(the ant is out);
}
position = position + this.direction * step;
};
/**
* 检查蚂蚁是否已经走出木杆,如果走出返回true
*
*/
public boolean isOut() {
return position = 0 || position = 27;
}
/**
* 检查此蚂蚁是否已经遇到另外一只蚂蚁
* @param ant
* @return 如果遇到返回true
*/
public boolean isEncounter(Ant ant) {
return ant.position == this.position;
}
/**
* 改变蚂蚁的前进方向
*/
public void changeDistation() {
direction = -1 * direction;
}
/**
* 构造函数,设置蚂蚁的初始前进方向,和初始位置
* @param position
* @param direction
*/
public Ant(int position, int direction) {
this.position = position;
if (direction != 1) {
this.direction = -1;//方向设置初始位置,比如为0时,也将其设置为1.这样可以方便后面的处理
} else {
this.direction = 1;
}
}
}
/////////////////////////////////////////////////////////
package baidu;
public class Controller {
public static void main(String[] args) {
int time = 0;
for (int i = 0; i 32; i++) {
Ant[] antArray = getAntList(getPoistions(), getDirections(i));
while (!isAllOut(antArray)) {
for (Ant ant : antArray) {
if (!ant.isOut()) {
ant.walk();
}
}
time++;
// 查看是否有已经相遇的Ant,如果有则更改其前进方向
dealEncounter(antArray);
}
System.out.println(time);
// 将时间归0,这
您可能关注的文档
最近下载
- 贝纳利BJ250维修手册.pdf VIP
- PasswortD A1 听力原文-德语学习资料.pdf VIP
- 一体化污水处理设备施工工艺.docx VIP
- 自动可调螺杆机组触摸屏说明书_SCC60-TP-V2.05.doc VIP
- 学堂在线 雨课堂 学堂云 如何写好科研论文 章节测试答案.docx VIP
- 人教版八年级数学下册基础知识专项讲练 专题17.20 勾股定理(中考真题专练)(巩固篇)(专项练习).docx VIP
- 教育实习鉴定实习内容.docx VIP
- 《GBT11616-2013-同步带传动节距型号MXL、XXL、XL、L、H、XH和XXH同步带尺寸》.pdf
- 离婚协议书(无子女版).docx VIP
- pluronic系列产品指标.pptx VIP
原创力文档

文档评论(0)