读:<测试一下你解决问题的逻辑思维及算法能力>后
今天在
http://www.cnblogs.com/tonybinlj/archive/2009/01/04/1367856.html中看到这篇文章。
其中提到
大家来做这样一道简单题目,测试一下你解决问题的逻辑思维及算法能力。如果你能在三个小时之内能写出实现算法,恭喜你,你有成为大师级别程序员的潜在能 力。如果三天内写出算法,你一直努力就可以成为牛人级程序员。如果三个星期内能写出来,你是一个正常的程序员的思维水平。如果两个月都没有写出来,你智商 不适合做程序员,还是早点放弃吧。
我就感到有些兴趣试试了,希望能成为大师级别的。
开始我尝试使用集合+迭代的方式来做。
代码如下(不作优化,仅用作实现):
Code
1 class Program
2 {
3 private static int tickets = 0; //从1开始报数
4 static void Main(string[] args)
5 {
6 //有17个人,编号0-16,第0人从1开始报数,报到3的倍数的人离开圈子,如此重复,直到留下最后一人。请问最后一人原来的位置是多少?
7 //第到17后,接下来接着报18
8 IList<int> persons=new List<int>();
9
10 for (int i = 0; i <= 16; i++)
11 {
12 persons.Add(i); //第0人,第0位置
13 }
14 DoCount(persons);
15 Console.WriteLine(tickets);
16 Console.ReadLine();
17 }
18 private static void DoCount(IList<int> countSource)
19 {
20 IList<int> tempPerson = new List<int>();
21
22 foreach (int pisition in countSource)
23 {
24 tickets++;
25 if (tickets % 3 != 0)
26 {
27 tempPerson.Add(pisition);
28 }
29 }
30 if (tempPerson.Count > 1)
31 {
32 DoCount(tempPerson);
33 }
34 else
35 {
36 tickets = tempPerson[0];
37 }
38 return;
39 }
40 }
以上实现方式能达到题目要求,答案为:10
但是,使用了迭代,并且多次声明IList<int>类型,总感觉有些不妥。
因此,尝试使用了另一种方案:
使用数组,并使用for()循环来进行判断。
在for()中,我们可以将判别条件置0,这样可以达到迭代的效果。
个人写的代码仍然很杂乱。
以下代码摘自:http://www.the9web.com/blog/2009/01/04/90/,写得很巧妙,值得大家研究研究
Code
1 int[] num = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
2 int count = 0;
3 ArrayList al = new ArrayList(num);
4 for (int i = 0; i < al.Count; i++)
5 {
6 count++; //报数
7 if (count % 3 == 0)
8 {
9 al.RemoveAt(i);
10 i--;
11 }
12 if (i == al.Count - 1)
13 {
14 i = -1;
15 }
16 if (al.Count == 1)
17 {
18 break;
19 }
20 }
21 num = (int[])al.ToArray(typeof(int));
22 for (int i = 0; i < num.Length; i++)
23 {
24 Console.WriteLine(num[i]);
25 }
26 Console.ReadLine();
//最后,我感觉无论在哪种语言下,实现这个题目的需求并不难,难的在于如何巧妙的实现。
//当然,我的第一种方式写得很稚嫩,拿不上台面。各位不要拍砖。
<h3>
心静似高山流水不动,心清若巫峰雾气不沾。
</h3>
原文地址:https://www.cnblogs.com/McJeremy/p/1368111.html