【C#数据结构与算法 Marcin Jamro】第四章 字典与集合

///  Chapter 4: 字典与几何 Dictionaries and Sets
/*
Hash tables : phone book 
Dictionaries: product location \user details
Sorted dictionaries:  difinitions
Hash sets: coupons \  swimming pools
"Sorted" sets :  removing duplicates 
*/



///  Chapter 4: 字典与几何 Dictionaries and Sets 
/*
Hash tables : phone book 
Dictionaries: product location \user details
Sorted dictionaries:  difinitions
Hash sets: coupons \  swimming pools
"Sorted" sets :  removing duplicates 
*/

/1.1   HashtablePhoneBook 哈希表使用  电话本
			Phone numbers:
			 - John Smith: 111-111-111
			 - Mary Fox: 222-222-222
			 - Lily Smith: 333-333-333
			 - Marcin Jamro: 000-000-000

			Search by name: Lily Smith
			Found phone number: 333-333-333
/*Main 程序 */
using System;
using System.Collections;

namespace HashtablePhoneBook
{
    class Program
    {
        static void Main(string[] args)
        {
            Hashtable phoneBook = new Hashtable()
            {
                { "Marcin Jamro", "000-000-000" },
                { "John Smith", "111-111-111" }
            };

            phoneBook["Lily Smith"] = "333-333-333";
            
            try
            {
                phoneBook.Add("Mary Fox", "222-222-222");
            }
            catch (ArgumentException)
            {
                Console.WriteLine("The entry already exists.");
            }

            Console.WriteLine("Phone numbers:");
            if (phoneBook.Count == 0)
            {
                Console.WriteLine("Empty");
            }
            else
            {
                foreach (DictionaryEntry entry in phoneBook)
                {
                    Console.WriteLine($" - {entry.Key}: {entry.Value}");
                }
            }

            Console.WriteLine();
            Console.Write("Search by name: ");
            string name = Console.ReadLine();
            if (phoneBook.Contains(name))
            {
                string number = (string)phoneBook[name];
                Console.WriteLine($"Found phone number: {number}");
            }
            else
            {
                Console.WriteLine("The number does not exist.");
            }
        }
    }
}

  2.1   字典:产品定位
			All products:
			 - 5900000000000: A1
			 - 5901111111111: B5
			 - 5902222222222: C9
			 - 5903333333333: D7
			 - 5904444444444: A3

			Search by barcode: 2901
			The product does not exist.

/* Main 程序 */
using System;
using System.Collections.Generic;

namespace DictionaryProductLocation
{
    class Program
    {
        static void Main(string[] args)
        {	//创建实例是添加项
            Dictionary<string, string> products = new Dictionary<string, string>
            {
                { "5900000000000", "A1" },
                { "5901111111111", "B5" },
                { "5902222222222", "C9" }
            };

            products["5903333333333"] = "D7"; //添加键值对 KeyValuePair<string,string>

            try
            {
                products.Add("5904444444444", "A3");
            }
            catch (ArgumentException)
            {
                Console.WriteLine("The entry already exists.");
            }

            Console.WriteLine("All products:");
            if (products.Count == 0)
            {
                Console.WriteLine("Empty");
            }
            else
            {
                foreach (KeyValuePair<string, string> product in products) //遍历字典
                {
                    Console.WriteLine($" - {product.Key}: {product.Value}");
                }
            }

            Console.WriteLine();
            Console.Write("Search by barcode: ");
            string barcode = Console.ReadLine();
            if (products.TryGetValue(barcode, out string location)) //尝试获取指定键关联的值
            {
                Console.WriteLine($"The product is in the area {location}.");
            }
            else
            {
                Console.WriteLine("The product does not exist.");
            }
            Console.ReadLine();
        }
    }
}

/  2.2 员工详情  DictionaryUserDetails
			Enter the employee identifier: 210
			First name: Mary
			Last name: Fox
			Phone number: 111-111-111
			Enter the employee identifier: 222
			The employee with the given identifier does not exist.
			Enter the employee identifier:
/* 员工类 */
    public class Employee
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string PhoneNumber { get; set; }
    }
/* Main 程序 */
using System;
using System.Collections.Generic;

namespace DictionaryUserDetails
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, Employee> employees = new Dictionary<int, Employee>(); //员工信息字典
            employees.Add(100, new Employee() { FirstName = "Marcin", LastName = "Jamro", PhoneNumber = "000-000-000" });
            employees.Add(210, new Employee() { FirstName = "Mary", LastName = "Fox", PhoneNumber = "111-111-111" });
            employees.Add(303, new Employee() { FirstName = "John", LastName = "Smith", PhoneNumber = "222-222-222" });

            bool isCorrect = true;
            do
            {
                Console.Write("Enter the employee identifier: ");
                string idString = Console.ReadLine();
                isCorrect = int.TryParse(idString, out int id); //员工ID   key
                if (isCorrect)//输入了正确的id
                {
                    Console.ForegroundColor = ConsoleColor.White;
                    if (employees.TryGetValue(id, out Employee employee))//根据id获取字典中员工信息
                    {
                        Console.WriteLine(
                            "First name: {1}{0}Last name: {2}{0}Phone number: {3}",
                            Environment.NewLine,
                            employee.FirstName,
                            employee.LastName,
                            employee.PhoneNumber);
                    }
                    else
                    {
                        Console.WriteLine("The employee with the given identifier does not exist.");
                    }
                    Console.ForegroundColor = ConsoleColor.Gray;
                }
            }
            while (isCorrect);
            Console.ReadLine();
        }
    }
}

  3.1    Sorted dictionaries  排序的字典
			Choose an option ([a] - add, [l] - list): A
			Enter the name: CHS
			Enter the explanation: kldjokjl
			Choose an option ([a] - add, [l] - list): a
			Enter the name: lkih
			Enter the explanation: lj;hghjjjk
			Choose an option ([a] - add, [l] - list): t
			Do you want to exit the program? Press [y] (yes) or [n] (no).
			nChoose an option ([a] - add, [l] - list): a
			Enter the name: tshd
			Enter the explanation: skldjaieojajlk
			Choose an option ([a] - add, [l] - list): a
			Enter the name: wdf
			Enter the explanation: lkxjvoaskdlj
			Choose an option ([a] - add, [l] - list): a
			Enter the name: likhkj
			Enter the explanation: hgjhkljl;kjkk
			Choose an option ([a] - add, [l] - list): a
			Enter the name: uxd
			Enter the explanation: hghj;hghgkjhk
			Choose an option ([a] - add, [l] - list): k
			Do you want to exit the program? Press [y] (yes) or [n] (no).
			nChoose an option ([a] - add, [l] - list): l
			CHS: kldjokjl
			likhkj: hgjhkljl;kjkk
			lkih: lj;hghjjjk
			tshd: skldjaieojajlk
			uxd: hghj;hghgkjhk
			wdf: lkxjvoaskdlj
			Choose an option ([a] - add, [l] - list):

/*  Main  程序 */
using System;
using System.Collections.Generic;

namespace DictionaryDefinitions
{
    class Program
    {
        static void Main(string[] args)
        {
            SortedDictionary<string, string> definitions = new SortedDictionary<string, string>();
            do
            {
                Console.Write("Choose an option ([a] - add, [l] - list): ");
                ConsoleKeyInfo keyInfo = Console.ReadKey();//输入 a  -add      
                Console.WriteLine();
                if (keyInfo.Key == ConsoleKey.A)
                {
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.Write("Enter the name: ");
                    string name = Console.ReadLine(); //输入名字
                    Console.Write("Enter the explanation: ");
                    string explanation = Console.ReadLine(); //输入 解释
                    definitions[name] = explanation; //添加到排序字典
                    Console.ForegroundColor = ConsoleColor.Gray;
                }
                else if (keyInfo.Key == ConsoleKey.L)
                {
                    Console.ForegroundColor = ConsoleColor.White;
                    foreach (KeyValuePair<string, string> definition in definitions) //遍历排序字典
                    {
                        Console.WriteLine($"{definition.Key}: {definition.Value}");
                    }
                    Console.ForegroundColor = ConsoleColor.Gray;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.WriteLine("Do you want to exit the program? Press [y] (yes) or [n] (no).");
                    Console.ForegroundColor = ConsoleColor.Gray;
                    if (Console.ReadKey().Key == ConsoleKey.Y)//退出 
                    {
                        break;
                    }
                }
            }
            while (true);
        }
    }
}


//  4.1 优惠券 coupons 集合
			Thank you! :-)
			Enter the coupon number: 524
			Thank you! :-)
			Enter the coupon number: 536
			Thank you! :-)
			Enter the coupon number: 215
			Thank you! :-)
			Enter the coupon number: 523
			The coupon has been already used :-(
			Enter the coupon number: 1
			Thank you! :-)
			Enter the coupon number: KLJ

			A list of used coupons:
			523
			842
			524
			536
			215
			1 
/*  Main  程序 */
using System;
using System.Collections.Generic;

namespace SetCoupons
{
    class Program
    {
        static void Main(string[] args)
        {
            HashSet<int> usedCoupons = new HashSet<int>();
            do
            {
                Console.Write("Enter the coupon number: ");
                string couponString = Console.ReadLine(); //输入数字
                if (int.TryParse(couponString, out int coupon))
                {
                    if (usedCoupons.Contains(coupon))//集合已包含
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("The coupon has been already used :-(");
                        Console.ForegroundColor = ConsoleColor.Gray;
                    }
                    else
                    {
                        usedCoupons.Add(coupon);//添加到集合
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.WriteLine("Thank you! :-)");
                        Console.ForegroundColor = ConsoleColor.Gray;
                    }
                }
                else//非数字
                {
                    break;
                }
            }
            while (true);

            Console.WriteLine();
            Console.WriteLine("A list of used coupons:");
            foreach (int coupon in usedCoupons) //遍历集合
            {
                Console.WriteLine(coupon);
            }
            Console.ReadLine();
        }
    }
}

///  4.2  swimming pools   游泳池
			Number of visitors by a pool type:
			 - recreation: 53
			 - competition: 41
			 - thermal: 42
			 - kids: 44
			Pool 'recreation' was the most popular.
			93 people visited at least one pool.
			4 people visited all pools.
			RECREATION: 1 5 6 7 8 9 10 11 12 14 15 20 22 26 27 30 33 35 36 38 40 41 43 46 47 48 49 50 51 55 60 61 63 67 68 69 70 71 72 73 75 76 77 78 80 82 83 85 86 87 90 93 96
			COMPETITION: 1 2 8 10 11 17 18 19 23 26 28 29 30 31 35 37 38 40 46 47 50 51 56 61 64 66 69 71 74 75 79 80 81 86 90 92 93 95 96 98 99
			THERMAL: 5 11 14 18 21 22 24 25 26 28 29 30 32 34 37 39 41 42 44 51 56 59 60 61 62 63 64 65 68 73 76 78 80 81 89 90 91 93 94 96 97 98
			KIDS: 1 3 5 7 9 11 12 13 15 16 18 20 21 25 26 29 30 32 33 35 36 37 41 43 45 49 50 54 55 58 59 68 70 71 72 73 74 77 78 79 80 83 97 99

/* Main 程序 */
using System;
using System.Collections.Generic;
using System.Linq;

namespace SetPools
{
    class Program
    {
        private static Random random = new Random();

        static void Main(string[] args)
        {   //4个游泳池 腕带号
            Dictionary<PoolTypeEnum, HashSet<int>> tickets = new Dictionary<PoolTypeEnum, HashSet<int>>()
            {
                { PoolTypeEnum.RECREATION, new HashSet<int>() },
                { PoolTypeEnum.COMPETITION, new HashSet<int>() },
                { PoolTypeEnum.THERMAL, new HashSet<int>() },
                { PoolTypeEnum.KIDS, new HashSet<int>() }
            };

            for (int i = 1; i < 100; i++)
            {
                foreach (KeyValuePair<PoolTypeEnum, HashSet<int>> type in tickets)
                {
                    if (GetRandomBoolean())// 0/1 随机添加i 到集合。 
                    {
                        type.Value.Add(i);//腕带号
                    }
                }
            }

            Console.WriteLine("Number of visitors by a pool type:"); //游泳池类型
            foreach (KeyValuePair<PoolTypeEnum, HashSet<int>> type in tickets)
            {
                Console.WriteLine($" - {type.Key.ToString().ToLower()}: {type.Value.Count}");// 每个游泳池 人数
            }

            PoolTypeEnum maxVisitors = tickets
                .OrderByDescending(t => t.Value.Count) //按照人数降序排列
                .Select(t => t.Key)  //保留key  游泳池类型
                .FirstOrDefault();//人数最多游泳池类型
            Console.WriteLine($"Pool '{maxVisitors.ToString().ToLower()}' was the most popular.");

            HashSet<int> any = new HashSet<int>(tickets[PoolTypeEnum.RECREATION]);
            any.UnionWith(tickets[PoolTypeEnum.COMPETITION]);
            any.UnionWith(tickets[PoolTypeEnum.THERMAL]);
            any.UnionWith(tickets[PoolTypeEnum.KIDS]);
            Console.WriteLine($"{any.Count} people visited at least one pool.");//所有集合求并集

            HashSet<int> all = new HashSet<int>(tickets[PoolTypeEnum.RECREATION]);
            all.IntersectWith(tickets[PoolTypeEnum.COMPETITION]);
            all.IntersectWith(tickets[PoolTypeEnum.THERMAL]);
            all.IntersectWith(tickets[PoolTypeEnum.KIDS]);
            Console.WriteLine($"{all.Count} people visited all pools.");//所有集合求交

            Console.WriteLine("RECREATION: " + string.Join(" ", tickets[PoolTypeEnum.RECREATION]));
            Console.WriteLine("COMPETITION: " + string.Join(" ", tickets[PoolTypeEnum.COMPETITION]));
            Console.WriteLine("THERMAL: " + string.Join(" ", tickets[PoolTypeEnum.THERMAL]));
            Console.WriteLine("KIDS: " + string.Join(" ", tickets[PoolTypeEnum.KIDS]));
            Console.ReadLine();
        }

        private static bool GetRandomBoolean()
        {
            return random.Next(2) == 1;
        }
    }
}

/* 泳池类型 */
namespace SetPools
{
    /*  娱乐,
        竞争,
        热能,
        孩子们*/
    public enum PoolTypeEnum
    {
        RECREATION,
        COMPETITION,
        THERMAL,
        KIDS
    };
}


///  5.1  SetDuplicates "排序“的集合  ”Sorted" set
			Albert
			Emily
			James
			Jane
			Lily
			Marcin
			Mary
/* Main 程序  */
using System;
using System.Collections.Generic;

namespace SetDuplicates
{
    class Program
    {
        static void Main(string[] args)
        {   //有重复元素的列表
            List<string> names = new List<string>()
            {
                "Marcin",
                "Mary",
                "James",
                "Albert",
                "Lily",
                "Emily",
                "marcin",
                "James",
                "Jane"
            };
            //从指定的可枚举集合names复制的元素,并使用指定的比较器。
            SortedSet<string> sorted = new SortedSet<string>(
                names,
                Comparer<string>.Create((a, b) => a.ToLower().CompareTo(b.ToLower())));
            foreach (string name in sorted)
            {
                Console.WriteLine(name);
            }
            Console.ReadLine();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/cxyhjl/article/details/129692961