*最近培训的一个题目:蚂蚁爬竿

原题:
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
posted @ 2007-03-08 18:25  健忘猪  阅读(955)  评论(0编辑  收藏  举报