原题:
Problem
某企业面试编程题:蚂蚁爬杆
有一根300厘米的细木杆,在第30厘米、80厘米、110厘米、160厘米、250厘米这五个位置上各有一只蚂蚁。
木杆很细,不能同时通过两只蚂蚁。开始时,蚂蚁的头朝左还是朝右是任意的,它们只会朝前走或调头,但不会后退。
当任意两只蚂蚁碰头时,两只蚂蚁会同时调头朝相反方向走。假设蚂蚁们每秒钟可以走5厘米的距离。
请编写一个程序,计算各种可能情形下所有蚂蚁都离开木杆的最小时间和最大时间。

我这个题目做了两次,一次是用JS实现滴,一次是用C#实现的
js的实现类分析不明确,没能挖掘出隐藏的类,所以感觉很乱,后面的C#版本有很大的改进,
但是后面涉及图形的演示的时候,又发现自己设计有遗漏:

现在 把代码发上来以后可以看看 还有可以修改的地方吧!
js:

  1 function walk()
  2 {//debugger;
  3     this._pos += this._dir*this._speed;
  4 }
  5 function whenMeet()
  6 {
  7     this._dir = -1*this._dir;
  8 }
  9 function subMakeAnts(pos)
 10 {
 11     var _res = new Array();
 12     var _ant_1 = new ants();
 13     _ant_1._pos = pos;
 14     _ant_1._dir = 1;
 15     _res.push(_ant_1);
 16     var _ant_2 = new ants();
 17     _ant_2._pos = pos;
 18     _ant_2._dir = -1;
 19     _res.push(_ant_2);
 20     
 21     return _res;
 22 }
 23 function makeAntGroup(tempAnts,indexs)
 24 {
 25     var _res = new Array();
 26     _res.push(tempAnts[0][indexs[0]]);
 27     _res.push(tempAnts[1][indexs[1]]);
 28     _res.push(tempAnts[2][indexs[2]]);
 29     _res.push(tempAnts[3][indexs[3]]);
 30     _res.push(tempAnts[4][indexs[4]]);
 31     return _res;
 32 }
 33 function makeTempAnts()
 34 {
 35     var _pos = new Array();
 36     _pos.push(60);
 37     _pos.push(160);
 38     _pos.push(220);
 39     _pos.push(320);
 40     _pos.push(500);
 41     var _tempAnts = new Array();
 42     for(var i=0; i<_pos.length; i++)
 43     {
 44         _tempAnts.push(subMakeAnts(_pos[i]));
 45     }
 46     return _tempAnts;
 47 }
 48 function makeAnts()
 49 {
 50     var _tempAnts = makeTempAnts();
 51     var _res = new Array();
 52     for(var a=0; a<2; a++ )
 53     {
 54         for(var b=0; b<2; b++ )
 55         {
 56             for(var c=0; c<2; c++ )
 57             {
 58                 for(var d=0; d<2; d++ )
 59                 {
 60                     for(var e=0; e<2; e++ )
 61                     {
 62                         var _indexs = new Array();
 63                         _indexs.push(a);
 64                         _indexs.push(b);
 65                         _indexs.push(c);
 66                         _indexs.push(d);
 67                         _indexs.push(e);
 68                         _res.push(makeAntGroup(_tempAnts,_indexs));
 69                     }
 70                 }
 71             }
 72         }
 73     }
 74     //alert(_res.length);//must32
 75     return _res;
 76 }
 77 
 78 function isLeave()
 79 {
 80     if(this._pos<=0 || this._pos>=600)
 81     {
 82         return true;
 83     }
 84     return false;
 85 }
 86 
 87 function ants()
 88 {
 89     this._pos = 0;
 90     this._dir = 1;
 91     this._speed = 1;
 92     this.walk = walk;
 93     this.whenMeet = whenMeet;
 94     this.makeAnts = makeAnts;
 95     this.isLeave = isLeave;
 96 }
 97 /*-----------stick-------------*/
 98 function makeSticks(ants)
 99 {
100     var _res = new Array();
101     var _stick;
102     for(var i=0; i<ants.length; i++)
103     {
104         _stick = new sticks();
105         _stick._ants = ants[i];
106         _res.push(_stick);
107     }
108     return _res;
109 }
110 
111 function judgeMeet()
112 {
113     for(var i=0; i<this._ants.length; i++)
114     {
115         for(var j=i+1;j<this._ants.length; j++)
116         {
117             if(this._ants[i]._pos == this._ants[j]._pos&&
118                 !this._ants[i].isLeave()&&
119                 !this._ants[j].isLeave()&&
120                 j!=i)
121             {
122                 this._ants[i].whenMeet();
123                 this._ants[j].whenMeet();
124             }
125         }
126     }
127 }
128 
129 function judgeAllLeave()
130 {
131     for(var i=0; i<this._ants.length; i++)
132     {
133         if(!this._ants[i].isLeave())
134             return false;
135     }
136     return true;
137 }
138 
139 function moveAnts()
140 {
141     this._time +=1;
142     this.judgeMeet();
143     for(var i=0; i<this._ants.length; i++)
144     {
145         if(!this._ants[i].isLeave())
146         {
147             this._ants[i].walk();
148         }
149     }
150 }
151 function resetAnts()
152 {
153 /*
154     _pos.push(60);
155     _pos.push(160);
156     _pos.push(220);
157     _pos.push(320);
158     _pos.push(500);
159     this._ants[0]._pos
160     this._ants[1]
161     this._ants[2]
162     this._ants[3]
163     this._ants[4]
164     */
165 }
166 function sticks()
167 {
168     this._width = 600;
169     this._ants = new Array();
170     this._time = 0;
171     
172     this.makeSticks = makeSticks;
173     this.judgeMeet = judgeMeet;
174     this.judgeAllLeave = judgeAllLeave;
175     this.moveAnts = moveAnts;
176     this.resetAnts = resetAnts;
177 }
178 /*----------manager------------*/
179 function initAnts()
180 {
181     var _ant = new ants();
182     this._ants = _ant.makeAnts();
183 }
184 function initSticks()
185 {
186     var _stick = new sticks();
187     this._sticks = _stick.makeSticks(this._ants);
188 }
189 var cal_p = 0;
190 var stick_p = null;
191 var antDivs_p = null;
192 function moveAntDivs()
193 {
194     for(var i=0; i<antDivs_p.length; i++)
195     {
196         antDivs_p[i].style.left =  88+stick_p._ants[i]._pos;
197     }
198 }
199 function doTest(stick)
200 {
201     var _antDivs = new Array();
202     var _antDiv;
203     //alert(stick._ants.length);//must5
204     for(var i=0; i<stick._ants.length; i++)
205     {
206         _antDiv = document.createElement("DIV");
207         _antDiv.style.position = "absolute";
208         _antDiv.style.width = 20;
209         _antDiv.style.height = 20;
210         _antDiv.innerText = i;
211         _antDiv.style.left = 110+stick._ants[i]._pos;
212         _antDiv.style.top = 225;
213         document.body.appendChild(_antDiv);
214         _antDivs.push(_antDiv);
215     }
216     stick_p = stick;
217     antDivs_p = _antDivs;
218     moveAction();
219 }
220 function moveAction()
221 {
222     moveDiv();
223     stick_p.moveAnts();
224     cal_p = 0;
225     if(stick_p.judgeAllLeave())
226     {
227         alert(stick_p._time/10+"S");
228         _manager._results.push(stick_p._time/10);
229         while(antDivs_p.length>0)
230         {
231             var _div = antDivs_p.pop();
232             document.body.removeChild(_div);
233         }
234         window.location.reload();
235     }
236     else
237         setTimeout("moveAction();",1);        
238 }
239 function moveDiv()
240 {
241     for(var i=0; i<stick_p._ants.length; i++)
242     {
243         if(!stick_p._ants[i].isLeave())
244             antDivs_p[i].style.left = 110+stick_p._ants[i]._pos;
245     }
246 }
247 function doSolute(group)
248 {
249     //for(var i=0; i<this._sticks.length; i++)
250     //{
251         this.doTest(this._sticks[group]);
252     //}
253 }
254 function doSort()
255 {
256     var _min = this._results[0];
257     var _max = this._resules[0];
258     for(var i=1; i<this._results.length; i++)
259     {
260         if(_min>this._results[i])
261             _min = this._results[i];
262         if(_max<this._results[i])
263             _max = this._results[i];
264     }
265     alert("最短时间:"+_min+" 最大时间:"+_max);
266 }
267 function manager()
268 {
269     this._ants = new Array();
270     this._sticks = new Array();
271     this._results = new Array();
272     
273     this.initAnts = initAnts;
274     this.initSticks = initSticks;
275     this.doTest = doTest;
276     this.doSolute = doSolute;
277     this.doSort = doSort;
278 }

C#:
1、Ant.cs

 1using System;
 2
 3namespace AntExcise
 4{
 5    /**//// <summary>
 6    /// Ant 的摘要说明。
 7    /// </summary>
 8    public class Ant
 9    {
10        private int _position;
11        private int _direction;
12        private int _speed;
13        public Ant()
14        {
15            //
16            // TODO: 在此处添加构造函数逻辑
17            //
18        }
19        
20        public Ant(int position,int direction,int speed)
21        {
22            this._position = position;
23            this._direction = direction;
24            this._speed = speed;
25        }
26        public int Position
27        {
28            get{return this._position;}
29            set{this._position = value;}
30        }
31        public int Direction
32        {
33            get{return this._direction;}
34            set{this._direction=value;}
35        }
36        public int Speed
37        {
38            get{return this._speed;}
39            set{this._speed=value;}
40        }
41        // 行进
42        public void MoveForward()
43        {
44            this._position += this._speed*this._direction; 
45        }
46        //掉头
47        public void TurnDirection()
48        {
49            this._direction = (-1)*this._direction;
50        }
51        //判断掉落
52        public bool IsDrop()
53        {
54            if(this._position<=0||this._position>=Stick.Length())
55                return true;
56            else
57                return false;
58        }
59        //判断与另外一只碰头
60        public bool IsMeetWith(Ant ant)
61        {
62            if(this._position==ant._position)
63                return true;
64            else
65                return false;
66        }
67        public static bool operator == (Ant antA,Ant antB)
68        {
69            return ((antA._direction == antB._direction)&&
70                    (antA._position == antB._position)&&
71                    (antA._speed == antB._speed));
72        }
73        public static bool operator != (Ant antA,Ant antB)
74        {
75            return ((antA._direction != antB._direction)||
76                (antA._position != antB._position)||
77                (antA._speed != antB._speed));
78        }
79    }
80}
81

2、Environment.cs

  1using System;
  2using System.Collections;
  3using System.Windows.Forms;
  4
  5namespace AntExcise
  6{
  7    /**//// <summary>
  8    /// Environment 的摘要说明。
  9    /// </summary>
 10    public class Environment
 11    {
 12        private ArrayList _instances;
 13        private int _instanceNum;
 14        public Environment()
 15        {
 16            //
 17            // TODO: 在此处添加构造函数逻辑
 18            //
 19            this.InitInstances();
 20            this._instanceNum = this._instances.Count;
 21        }
 22        public int getInstanceNum()
 23        {
 24            return this._instanceNum;
 25        }
 26        public Instance GetInstance(int index)
 27        {
 28            return (Instance)this._instances[index];
 29        }
 30        /**//*
 31        private int getDir(int count,int dig)
 32        {
 33            string str = count.ToString();
 34            if(str.Length<dig)
 35                return -1;
 36            else
 37                return Convert.ToInt32(str.Substring(dig-1,1))==0?-1:1;
 38        }
 39        private int getInt(int num)
 40        {
 41            int res = 1;
 42            for(int i=0; i<num; i++)
 43            {
 44                res*=2;
 45            }
 46            return res;
 47        }
 48        */
 49        //初始化所有场景
 50        private void InitInstances()
 51        {
 52            /**//*
 53            this._instances = new ArrayList();
 54            ArrayList dir;
 55            for(int count = 0;count<getInt(5);count++)
 56            {
 57                dir = new ArrayList();
 58                dir.Add(getDir(count,1));
 59                dir.Add(getDir(count,2));
 60                dir.Add(getDir(count,3));
 61                dir.Add(getDir(count,4));
 62                dir.Add(getDir(count,5));
 63                this._instances.Add(new Instance(dir));
 64            }
 65            */
 66
 67            this._instances = new ArrayList();
 68            ArrayList dir;
 69            for(int a=0; a<2; a++ )
 70            {
 71                for(int b=0; b<2; b++ )
 72                {
 73                    for(int c=0; c<2; c++ )
 74                    {
 75                        for(int d=0; d<2; d++ )
 76                        {
 77                            for(int e=0; e<2; e++ )
 78                            {
 79                                dir = new ArrayList();
 80                                dir.Add(a==0?-1:1);
 81                                dir.Add(b==0?-1:1);
 82                                dir.Add(c==0?-1:1);
 83                                dir.Add(d==0?-1:1);
 84                                dir.Add(e==0?-1:1);
 85                                this._instances.Add(new Instance(dir));
 86                            }
 87                        }
 88                    }
 89                }
 90            }
 91        }
 92        //a=b 2
 93        //a>b 0
 94        //a<b 1
 95        private int CompareInstance(Instance instanceA,Instance instanceB)
 96        {
 97            int temp = instanceA.GetTimeCount()-instanceB.GetTimeCount();
 98            if(temp==0)
 99                return 2;
100            else if(temp>0)
101                return 0;
102            else//if(temp<0)
103                return 1;
104
105        }
106        public void Start()
107        {
108            this.RunInstanceAll();
109        }
110        public void RunInstanceAll()
111        {
112            Instance temp;
113            string _res = "";
114            for(int i=0; i<this._instanceNum; i++)
115            {
116                temp = (Instance)this._instances[i];
117                temp.Run();
118                _res+=temp.GetTimeCount().ToString()+"_";
119            }
120            //MessageBox.Show(_res);
121            //MessageBox.Show(this.GetMin().GetTimeCount().ToString());
122        }
123        //时间值最大的场景
124        public Instance GetMax()
125        {
126            Instance tempIns = (Instance)this._instances[0];
127            for(int i=0; i<this._instances.Count; i++)
128            {
129                if(this.CompareInstance(tempIns,(Instance)this._instances[i])==1)
130                {
131                    tempIns = (Instance)this._instances[i];
132                }
133            }
134            return tempIns;
135        }
136        //时间值最小的场景
137        public Instance GetMin()
138        {
139            Instance tempIns = (Instance)this._instances[0];
140            for(int i=0; i<this._instances.Count; i++)
141            {
142                
143                if(this.CompareInstance(tempIns,(Instance)this._instances[i])==0)
144                {
145                    tempIns = (Instance)this._instances[i];
146                }
147            }
148            return tempIns;
149        }
150        
151    }
152}
153

3、Instance.cs

  1using System;
  2using System.Collections;
  3using System.Windows.Forms;
  4
  5namespace AntExcise
  6{
  7    /**//// <summary>
  8    /// Instance 的摘要说明。
  9    /// </summary>
 10    public class Instance
 11    {
 12        private ArrayList _ants;
 13        private Stick _stick;
 14        private int _timeCount;
 15        //通过GroupID来初始化
 16        public Instance(int groupID)
 17        {
 18            //
 19            // TODO: 在此处添加构造函数逻辑
 20            //
 21        }
 22        public Instance(ArrayList directions)
 23        {
 24            this._timeCount = 0;
 25            this.InitStick();
 26            this.InitAnts(directions);
 27        }
 28        public int GetTimeCount()
 29        {
 30            return this._timeCount;
 31        }
 32        public Ant GetAnt(int index)
 33        {
 34            return (Ant)this._ants[index];
 35        }
 36        //初始化棍子
 37        private void InitStick()
 38        {
 39            this._stick = new Stick();
 40            int _length = 300;
 41            int [] pos = {30,80,110,160,250};
 42            this._stick.SetLength(_length);
 43            this._stick.SetPositions(pos);
 44        }
 45        /**/////通过蚂蚁方向来初始化蚂蚁
 46        private void InitAnts(ArrayList dir)
 47        {
 48            this._ants = new ArrayList();
 49            int [] _pos = this._stick.GetPositions();
 50            Ant ant;
 51            ant = new Ant(_pos[0],(int)dir[0],5);
 52            this._ants.Add(ant);
 53            ant = new Ant(_pos[1],(int)dir[1],5);
 54            this._ants.Add(ant);
 55            ant = new Ant(_pos[2],(int)dir[2],5);
 56            this._ants.Add(ant);
 57            ant = new Ant(_pos[3],(int)dir[3],5);
 58            this._ants.Add(ant);
 59            ant = new Ant(_pos[4],(int)dir[4],5);
 60            this._ants.Add(ant);
 61        }
 62        //所有蚂蚁行动起来
 63        public void MoveAnts()
 64        {
 65            Ant ant;
 66            for(int i=this._ants.Count-1;i>=0;i--)
 67            {
 68                ant = (Ant)this._ants[i];
 69                if(!ant.IsDrop())
 70                    ant.MoveForward();
 71            }
 72        }
 73        //时间累加
 74        private void TimeAdd()
 75        {
 76            this._timeCount++;
 77        }
 78        //是否所有的都掉下来
 79        public bool IsAllDropped()
 80        {
 81            foreach(Ant ant in this._ants)
 82            {
 83                if(!ant.IsDrop())
 84                    return false;
 85            }
 86            return true;
 87        }
 88
 89        //处理相遇的蚂蚁
 90        private void ProcMeet()
 91        {
 92            Ant tempA;
 93            Ant tempB;
 94            for(int i=0; i<this._ants.Count; i++)
 95            {
 96                for(int j=i+1;j<this._ants.Count; j++)
 97                {
 98                    tempA = (Ant)this._ants[i];
 99                    tempB = (Ant)this._ants[j];
100                    if(tempA.IsMeetWith(tempB)&&
101                        !tempA.IsDrop()&&
102                        !tempB.IsDrop()&&
103                        j!=i)
104                    {
105                        tempA.TurnDirection();
106                        tempB.TurnDirection();
107                    }
108                }
109            }
110        }
111        //单步运行
112        public void RunStep()
113        {
114            this.MoveAnts();
115            this.ProcMeet();
116            this.TimeAdd();
117        }
118        //运行场景
119        public void Run()
120        {
121            while(!this.IsAllDropped())
122            {
123                this.RunStep();
124            }
125        }
126    }
127}
128

4、 Stick.cs

 1using System;
 2using System.Collections;
 3
 4namespace AntExcise
 5{
 6    /**//// <summary>
 7    /// Stick 的摘要说明。
 8    /// </summary>
 9    public class Stick
10    {
11        private static int _length;
12        private int [] _positions;
13        public Stick()
14        {
15            //
16            // TODO: 在此处添加构造函数逻辑
17            //
18        }
19        public Stick(int length)
20        {
21            _length = length;
22        }
23        public void SetPositions(int [] pos)
24        {
25            this._positions = pos;
26        }
27        public void SetLength(int length)
28        {
29            _length = length;
30        }
31        public int GetLength()
32        {
33            return _length;
34        }
35        public int [] GetPositions()
36        {
37            return this._positions;
38        }
39        public static int Length()
40        {
41            return _length;
42        }
43    }
44}
45

转载于:https://www.cnblogs.com/dwjaissk/archive/2007/03/08/668446.html

*最近培训的一个题目:蚂蚁爬竿相关推荐

  1. 蚂蚁爬绳问题 java_趣味数学网

    蚂蚁爬绳问题 发布:深蓝 | 发布时间: 2009年4月27日  浏览次数: 一绳长1M,一蚂蚁从绳的一端爬向另一端,速度为每秒1CM,同时,绳子以每秒10CM的速度均匀伸长,问:蚂蚁能否达到绳的另一 ...

  2. 趣味题_蚂蚁爬杆_猴子分桃

    题一: 有些蚂蚁在一条水平线上走动,每只蚂蚁的速率都是1cm/s. 当一只蚂蚁走到水平线的任何一个端点时,它都会立刻掉下来. 当两只蚂蚁碰到一起时他们都会立刻调头向相反方向移动. 我们知道蚂蚁们在水平 ...

  3. 蚂蚁爬杆 java_java蚂蚁爬杆

    import java.util.List; import java.util.ArrayList; import java.math.BigDecimal; /*-作者:volcano_hosan ...

  4. UA MATH523A 实分析3 积分理论例题 证明函数列L1收敛的一个题目

    UA MATH523A 实分析3 积分理论例题 证明函数列L1收敛的一个题目 例 假设fnf_nfn​在[0,1][0,1][0,1]上绝对连续,fn(0)=0,∀n≥1f_n(0)=0,\foral ...

  5. UA MATH523A 实分析3 积分理论例题 判断函数可积性的一个题目

    UA MATH523A 实分析3 积分理论例题 判断函数可积性的一个题目 例 (X,M,μ)(X,\mathcal{M},\mu)(X,M,μ)是一个测度空间,fff是定义在(X,M,μ)(X,\ma ...

  6. 整型和浮点型的区别_浮点整型强转的一个题目解析

    有这么一个题目: int main(){int *p, a = 10;float *q;p = &a;q = (float *)p;printf("%f\n", *q);r ...

  7. 计算机表格填充奖学金,excel奖学金数据表格-Excel2003的一个题目按总分公式填充奖学金数据,总......

    在Excel表格中两张表,都有学号和奖学金这两列.两... 1.首先打开Excel,进入到编辑主界面. 2.接着将学生成数据信息,输入到表中,最后一列学金. 3.然后选中F2单元格,输入公式" ...

  8. 爬楼梯算法 一个小孩练习爬台阶,一共10级台阶,小孩可以一次向上选择爬1-3级

    爬楼梯算法 一个小孩练习爬台阶,一共10级台阶,小孩可以一次向上选择爬1-3级.但是第3级和第6级台阶被施加了魔法,小孩一旦踏上就会停下来就开始跳<新宝岛>.那么,不让小孩跳<新宝岛 ...

  9. 深圳云计算培训:一个全新的世界—Linux

    深圳云计算培训:一个全新的世界-Linux 一个全新的世界 – Linux 1990 年代中期,因特网因出现 World Wide Web, HTML 这种新型态的应用, 而开始迅速的延烧全世界.一夕 ...

  10. 手撸一个仿蚂蚁森林微信小程序

    每天逛逛CSDN,看看大牛们的技术文章,查找自己想了解的知识,是我必做的事情. 每天到支付宝看看自己的余额,看看自己的33块钱还在吗?顺便到蚂蚁森林收下自己和好友的能量是我必做的事.看着自己的能量又被 ...

最新文章

  1. 利用CxImage实现编解码Gif图像代码举例
  2. 分支-08. 高速公路超速处罚
  3. Java LinkedHashMap的实现原理详解
  4. ds排序--希尔排序_图解直接插入排序和希尔排序
  5. 分享25个优秀的网站底部设计案例
  6. Gartner:云安全的未来,是安全访问服务边缘架构
  7. jmeter-5.3 测试http接口动态数据 windows+Linux双环境
  8. php判断是否为数字_PHP知识点:从'xulei' == 0是否为真谈谈运算符===和==
  9. 己所不欲,勿施于人的意思,这句话出自哪里?
  10. unittest测试框架详谈及实操(一)
  11. 突发!四川长宁发生6.0级地震
  12. 【激光雷达3D】【论文翻译】Complex-YOLO: An Euler-Region-Proposal for Real-time 3D Object Detection on Point
  13. 计算机在数据处理方面的论文,数据挖掘论文3000字范文参考(2)
  14. 服务器虚拟机迁移的6个步骤,KVM 虚拟机迁移(示例代码)
  15. 大内高手—常见内存错误
  16. 主力大单流入前十的创业板股票中小板股票20180301
  17. Ubuntu 系统开机卡住,解决
  18. 基于大模型GPT,如何提炼出优质的Prompt
  19. Windows 已在tong.exe 中触发一个断点。
  20. DZ全站HTTPS可行,基于网上教程的修改

热门文章

  1. 如何在 Ubuntu 上安装 MongoDB
  2. SpringMVC之安全性(一)
  3. window和document对象
  4. JSP的自定义标签(五)之Tag File
  5. caffe cifar10 net笔记
  6. 图论——两道并查集例题
  7. 谷歌大脑阿尔伯塔联合发表:离线强化学习的优化视角【附代码】
  8. 配置codeblocks 的养眼colour theme ;鼠标颜色与型状配置,界面汉化,以及调试入门
  9. 在Eclipse或工作空间中 ,复制或修改项目后,把项目部署后发现还是原来的项目名称...
  10. android数据交互方式(整理)