Как сделать список с простым перебором? - C#

Узнай цену своей работы

Формулировка задачи:

требуется написать программу, которая получает на входе набор идентификаторов, организует таблицу по заданному методу и позволяет осуществить поиск идентификатора в этой таблице. Список идентификаторов считать заданным в виде текстового файла. Длину идентификаторов можно считать ограниченной 32 символами. Для организации таблицы используется простейшая хэш-функция, указанная в варианте задания, а при возникновении коллизий используется дополнительный метод размещения идентификаторов в памяти. Если в качестве этого метода используется дерево или список, то они должны быть связаны с элементом главной хэш-таблицы. В каждом варианте требуется, чтобы программа сообщала среднее число коллизий и среднее количество сравнений, выполненных для поиска идентификатора. тип хеш-функции - Сумма кодов первой и средней букв. способ разрешения коллизий - список с простым перебором. Вот мой код, как сделать список с простым перебором и вместо последней буквы, суммировать среднюю?
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.IO;
  7. namespace ConsoleApplication11
  8. {
  9. class Program
  10. {
  11. public struct city
  12. {
  13. public string name;
  14. public int hash;
  15. public city(string name1, int hash1)
  16. {
  17. name = name1;
  18. hash = hash1;
  19. }
  20. }
  21. static void Main(string[] args)
  22. {
  23. StreamReader readfile = File.OpenText("spisok.txt");
  24. string input = null;
  25. List<city> CityList = new List<city>();
  26. while ((input = readfile.ReadLine()) !=null)
  27. {
  28. city CITY = new city(input, (int)input[0] + (int)input.Last());
  29. CityList.Add(CITY);
  30. }
  31. Console.WriteLine("===========");
  32. Console.WriteLine("чтение завершено");
  33. Console.WriteLine();
  34. Console.WriteLine("в итоге {0} городов", CityList.Count);
  35. Console.WriteLine("===========");
  36. Console.ReadLine();
  37. for (int i = 0; i < CityList.Count; i++)
  38. {
  39. Console.WriteLine("{0}) Город: {1} |Хеш:{2}", i + 1, CityList[i].name, CityList[i].hash);
  40. }
  41. Console.ReadLine();
  42. }
  43. }
  44. }

Решение задачи: «Как сделать список с простым перебором?»

textual
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. struct City
  5. {
  6.     public readonly string Name;
  7.     public City(string Name = "") { this.Name = Name; }
  8.  
  9.     public override int GetHashCode()
  10.     {
  11.         return string.IsNullOrEmpty(Name) ? 0 :
  12.             Name[0] + Name[Name.Length / 2];
  13.     }
  14.  
  15.     public override string ToString() { return Name; }
  16.  
  17.     public static City Empty { get { return new City(); }}
  18. }
  19.  
  20. struct StorageFinder
  21. {
  22.     public City City;
  23.     public int Index;
  24.     public int Hash;
  25.     public List<City> List;
  26.     public int NewCollisions;
  27.  
  28.     public StorageFinder(Storage Storage, string Key)
  29.     {
  30.         NewCollisions = 0;
  31.         City = new City(Key);
  32.         Hash = City.GetHashCode();
  33.         List = Storage.Table[Hash] ?? (Storage.Table[Hash] = new List<City>());
  34.         for (Index = 0; Index < List.Count; Index++)
  35.             if (List[Index].Equals(City)) break;
  36.  
  37.         if (Index == List.Count)
  38.         {
  39.             List.Add(City);
  40.             if (List.Count == 2) NewCollisions = 2;
  41.             if (List.Count > 2) NewCollisions = 1;
  42.         }
  43.     }
  44. }
  45.  
  46. class Storage
  47. {
  48.     // хэш таблица
  49.     public readonly List<City>[] Table = new List<City>[255 * 2];
  50.  
  51.     // Число коллизий
  52.     public int Collisions = 0;
  53.  
  54.     // Число сравнений
  55.     public int Сomparison = 0;
  56.     public int ComparisonCount = 0;
  57.  
  58.     void Log(StorageFinder Finder)
  59.     {
  60.         Collisions += Finder.NewCollisions;
  61.         Сomparison += Finder.Index + 1;
  62.         ComparisonCount++;
  63.     }
  64.  
  65.     public City this[string Key]
  66.     {
  67.         get
  68.         {
  69.             var finder = new StorageFinder(this, Key);
  70.             Log(finder);
  71.             return finder.List[finder.Index];
  72.         }
  73.         set
  74.         {
  75.             var finder = new StorageFinder(this, Key);
  76.             Log(finder);
  77.             finder.List[finder.Index] = value;
  78.         }
  79.     }
  80.  
  81.     public void Load(string data)
  82.     {
  83.         foreach(string key in data.Split())
  84.             this[key] = new City(key);
  85.     }
  86. }
  87.  
  88. class Program
  89. {
  90.     static void Main(string[] args)
  91.     {
  92.         Storage storage = new Storage();
  93.         storage.Load("aab aac aad abc");
  94.  
  95.         // тестовый поиск:
  96.         Console.WriteLine(storage["aad"]);
  97.  
  98.         Console.WriteLine("Коллизии: {0}", storage.Collisions);
  99.         Console.WriteLine("Среднее число сравнений: {0,2}", (float)storageomparison / storage.ComparisonCount);
  100.         Console.ReadKey();
  101.     }
  102. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

14   голосов , оценка 4.357 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы