A-A+

投票问题

2009年08月30日 未分类 暂无评论 阅读 1 次

[关键字(Tags):字符串数组string[ ]、哈希表Hashtable、统计排序]
假如现在有个活动,要进行投票选举。投票箱中有N张选票,选票上的人名未知,那么怎么统计选票结果呢?如果觉得有些抽象,那么现在我们把问题具体化一下,就如同以下的问题。
比如有个字符串数组
string[ ] str={"杰克逊","叮当","叮当","约翰逊","刘易斯","路易斯","劳斯",
"史密斯","牛顿","劳斯","刘易斯","路易斯","劳斯","杰克逊","约翰逊","史密斯","叮当","牛顿",
"劳斯","史密斯"};
对上面的字符串数组进行操作,统计各个人名出现的次数,并且要求按以下格式排序输出:
                                   2:杰克逊
                                   2:约翰逊
                                   2:刘易斯
                                   2:路易斯
                                   2:牛顿
                                   3:叮当
                                   3:史密斯
                                   4:劳斯

有了这么个具体的问题,接下来就是要考虑怎么实现了,其实要实现这个目标,可以使用哈希表(主要考虑哈希表有键值对),代码如下:
Hashtable hashtable = new Hashtable();
            for (int i = 0; i < str.Length; i++)
            {
                if (hashtable.ContainsKey(str[i]))
                {
                    int n = (int)hashtable[str[i]] + 1;
                    hashtable[str[i]] = n;
                }
                else
                {
                    hashtable.Add(str[i], 1);

                }

      
            }
            string[] strResult = new string[hashtable.Count];
            int[] numResult = new int[hashtable.Count];
            int j = 0;
            foreach (DictionaryEntry entry in hashtable)
            {
                strResult[j] = entry.Key.ToString();
                numResult[j] = Convert.ToInt32(entry.Value);
                j++;
            }
            Array.Sort(numResult, strResult);
               for (int i= 0;i<hashtable.Count; i++)
            {
                Console.WriteLine(numResult[i]+ ":" +strResult[i].ToString());
            }
另外,还有一点经验总结:在效率要求不是很高的情况下,对数组进行排序,我们不需要编写冒泡排序、快速排序、折半排序,直接用Array.Sort()方法好了,省了不少力气。当需要升序时,正好符合条件,降序时,再调用一下Array.Reverse()方法就OK了!

给我留言

Copyright © 浩然东方 保留所有权利.   Theme  Ality 07032740

用户登录