在命令行任意輸入一組數字(0~9),而後統計這組數據中每一個數字出現的個數,而後將統計個數逆序輸出

需求:在命令行任意輸入一組數字(0~9),而後統計這組數據中每一個數字出現的個數,而後將統計個數逆序輸出編程

輸出樣例:ide

開始分解:函數

一、首先看到樣例輸出,第一想到的是什麼,怎麼從命令行中獲取一組數字(根據需求值應該只有0~9)?spa

二、怎麼去除重複的數字?命令行

三、怎樣將出現的數字和統計個數結合起來?主要是結合。orm

四、怎樣將數字和計數結合後的集合按照計數的逆序輸出?這個很關鍵。對象


那好,就剩下就是解決問題了。blog

第1步:排序

  首先咱們知道命令行獲讀取通常都是字符串,最經常使用的就是Console.Read和Console.ReadLine。可是這塊用Read的話就有些不太方便了,由於你要用循環讀取,並且你讀過來的是字符的ASCII碼值,因此咱們用ReadLine方法。字符串

  那用ReadLine的話,讀取的是字符串,那就須要咱們把字符串處理一下,編程一個個的數字便可。那好辦了。

  關鍵代碼:

  

static List<int> GetConvertResult(List<string> list)
        {
            List<int> iList = new List<int>();
            int iTemp = 0;
            list.ForEach(item =>
            {
                if (int.TryParse(item, out iTemp))
                {
                    iList.Add(iTemp);
                }
            });

            return iList;
        }

  

List<int> list = GetConvertResult(Console.ReadLine().Split(' ').Where(item => item.Trim() != "").ToList());

  上面這句話的意思就是:從命令行讀取的字符串,而後用空格(' ')分割,而後篩選出不爲「」的,再轉成List,傳給

GetConvertResult(List<string> list)函數。好了第一個問題解決了

第2步:

  去除重複數據,這個簡單。List有個擴展方法Distinct(這個方法是經過使用默認的相等比較器對值進行比較返回序列中的非重複元素,也就是說若是是你自定義的類型,Distinct 就不認了,可是這裏是int類型,恰好能用)。那這樣要解決第二個問題,那就是一句代碼了

list = list.Distinct().ToList();可是這裏不這麼用,能夠連着第三步驟一塊兒完成。

第3步:

  將數字和計數結合在一塊兒。這塊的話方法就多了,能夠用Dictionary,也可用List<自定義對象>,也能夠用List<KeyValuePair>,也能夠用Tuple。

那這裏,我們就用個簡單的自定義對象Data.

class Data
    {
        public int Value { get; set; }
        public int Count { get; set; }

        public Data()
        {

        }

        public Data(int iValue, int iCount)
        {
            Value = iValue;
            Count = iCount;
        }

        public override string ToString()
        {
            return string.Format("數字{0},出現次數{1}次", Value, Count);
        }
    }

  那把第2步和第3步結合起來就是:

static List<Data> GetStatResult(List<int> list)
        {
            List<Data> dataList = new List<Data>();

            list.Distinct().ToList().ForEach(item =>
            {
                dataList.Add(new Data(item, list.Where(d => d == item).Count()));
            });

            // 先用值OrderBy進行正序,而後再用OrderByDescending計數逆序
            //return dataList.OrderBy(data => data.Value).OrderByDescending(data => data.Count).ToList();

            // 用Count逆序排序的同時用Value逆序排序,相似於SQL中的 ORDER BY Count DESC, Id DESC
            //return dataList.OrderByDescending(data => data.Count).ThenByDescending(data => data.Value).ToList();

            // 用Count逆序的同時用Value正序,這塊若是要Value逆序,則只需在x.Value加個-,即-x.Value.CompareTo(y.Value)
            //dataList.Sort((x, y) => (x.Value.CompareTo(y.Value) + -x.Count.CompareTo(y.Count) * 2));
            //return dataList;

            // linq大法,像SQL同樣優雅的排序
            return (from data in dataList orderby data.Count descending, data.Value ascending select data).ToList();
        }

  以上代碼有好幾種方法均可以達到效果,可是感受Linq的寫法仍是比較優雅的,因此保留Linq用法。

  說道這其實第四部的結合起來也已經實現了,就是那個Data類封裝了數字和數字的統計個數,以及ToString的內容格式。

第4步:

  沒什麼內容了。就一個函數。

static void PrintResult(List<Data> list)
        {
            list.ForEach(item => Console.WriteLine(item.ToString()));
        }

  好了。這麼一個需求就基本完成了。

 

完整工程代碼:

using System;
using System.Collections.Generic;
using System.Linq;

/**
*
*                #####################################################
*                #                                                   #
*                #                       _oo0oo_                     #
*                #                      o8888888o                    #
*                #                      88" . "88                    #
*                #                      (| -_- |)                    #
*                #                      0\  =  /0                    #
*                #                    ___/`---'\___                  #
*                #                  .' \\|     |# '.                 #
*                #                 / \\|||  :  |||# \                #
*                #                / _||||| -:- |||||- \              #
*                #               |   | \\\  -  #/ |   |              #
*                #               | \_|  ''\---/''  |_/ |             #
*                #               \  .-\__  '-'  ___/-. /             #
*                #             ___'. .'  /--.--\  `. .'___           #
*                #          ."" '<  `.___\_<|>_/___.' >' "".         #
*                #         | | :  `- \`.;`\ _ /`;.`/ - ` : | |       #
*                #         \  \ `_.   \_ __\ /__ _/   .-` /  /       #
*                #     =====`-.____`.___ \_____/___.-`___.-'=====    #
*                #                       `=---='                     #
*                #     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~   #
*                #                                                   #
*                #               佛祖保佑         永無BUG            #
*                #                                                   #
*                #####################################################
*/

namespace SoftCountDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Run();

            Console.ReadKey();
        }
        
        static List<int> GetConvertResult(List<string> list)
        {
            List<int> iList = new List<int>();
            int iTemp = 0;
            list.ForEach(item =>
            {
                if (int.TryParse(item, out iTemp))
                {
                    iList.Add(iTemp);
                }
            });

            return iList;
        }

        static List<Data> GetStatResult(List<int> list)
        {
            List<Data> dataList = new List<Data>();

            list.Distinct().ToList().ForEach(item =>
            {
                dataList.Add(new Data(item, list.Where(d => d == item).Count()));
            });

            // 先用值OrderBy進行正序,而後再用OrderByDescending計數逆序
            //return dataList.OrderBy(data => data.Value).OrderByDescending(data => data.Count).ToList();

            // 用Count逆序排序的同時用Value逆序排序,相似於SQL中的 ORDER BY Count DESC, Id DESC
            //return dataList.OrderByDescending(data => data.Count).ThenByDescending(data => data.Value).ToList();

            // 用Count逆序的同時用Value正序,這塊若是要Value逆序,則只需在x.Value加個-,即-x.Value.CompareTo(y.Value)
            //dataList.Sort((x, y) => (x.Value.CompareTo(y.Value) + -x.Count.CompareTo(y.Count) * 2));
            //return dataList;

            // linq大法,像SQL同樣優雅的排序
            return (from data in dataList orderby data.Count descending, data.Value ascending select data).ToList();
        }

        static void PrintResult(List<Data> list)
        {
            list.ForEach(item => Console.WriteLine(item.ToString()));
        }

        static void Run()
        {
            try
            {
                do
                {
                    Console.WriteLine("請連續輸入一組數字(0`9),中間用空格隔開");
                    
                    List<int> list = GetConvertResult(Console.ReadLine().Split(' ').Where(item => item.Trim() != "").ToList());
                    PrintResult(GetStatResult(list));

                    Console.WriteLine("按任意鍵繼續...");
                    Console.ReadKey();
                } while (true);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }

    class Data
    {
        public int Value { get; set; }
        public int Count { get; set; }

        public Data()
        {

        }

        public Data(int iValue, int iCount)
        {
            Value = iValue;
            Count = iCount;
        }

        public override string ToString()
        {
            return string.Format("數字{0},出現次數{1}次", Value, Count);
        }
    }
}
相關文章
相關標籤/搜索