Selection.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace GFGGame
  5. {
  6. public class Selection<K, T> where K : IComparable<K>
  7. {
  8. public K Min { get; set; }
  9. public K Max { get; set; }
  10. public T Value { get; set; }
  11. private readonly SelectionModel model;
  12. public Selection(K min, K max, T value, SelectionModel model = SelectionModel.Right)
  13. {
  14. Min = min;
  15. Max = max;
  16. Value = value;
  17. this.model = model;
  18. }
  19. public bool CheckInclude(K checkKey)
  20. {
  21. switch (model)
  22. {
  23. case SelectionModel.Right:
  24. return Min.CompareTo(checkKey) < 0 && checkKey.CompareTo(Max) <= 0;
  25. case SelectionModel.Left:
  26. return Min.CompareTo(checkKey) <= 0 && checkKey.CompareTo(Max) < 0;
  27. case SelectionModel.AllInclude:
  28. return Min.CompareTo(checkKey) <= 0 && checkKey.CompareTo(Max) <= 0;
  29. case SelectionModel.AllExclude:
  30. return Min.CompareTo(checkKey) < 0 && checkKey.CompareTo(Max) < 0;
  31. default:
  32. return false;
  33. }
  34. }
  35. public enum SelectionModel
  36. {
  37. Right, // ( ], 包含右边
  38. Left, // [ ), 包含左边
  39. AllInclude, // [], 两端包含
  40. AllExclude //(), 两端都不包含
  41. }
  42. public static List<Selection<K, T>> CreateSelections(List<KeyValuePair<K, T>> res, K min, K max, T defaultValue)
  43. {
  44. List<Selection<K, T>> list = new List<Selection<K, T>>();
  45. // 添加首区间
  46. KeyValuePair<K, T> firstRes = res[0];
  47. list.Add(new Selection<K, T>(min, firstRes.Key, defaultValue, SelectionModel.Left));
  48. for (int i = 1; i < res.Count - 1; i++)
  49. {
  50. list.Add(new Selection<K, T>(res[i - 1].Key, res[i].Key, res[i].Value, SelectionModel.Left));
  51. }
  52. KeyValuePair<K, T> lastRes = res[res.Count - 1];
  53. // 添加尾区间
  54. list.Add(new Selection<K, T>(lastRes.Key, max, lastRes.Value, SelectionModel.Left));
  55. return list.OrderBy(x => x.Min).ToList();
  56. }
  57. public static List<Selection<K, T>> CreateSelections(List<KeyValuePair<K, T>> res, K max)
  58. {
  59. List<Selection<K, T>> list = new List<Selection<K, T>>();
  60. // 添加首区间
  61. for (int i = 0; i < res.Count; i++)
  62. {
  63. K maxVal = i == res.Count - 1 ? max : res[i + 1].Key;
  64. list.Add(new Selection<K, T>(res[i].Key, maxVal, res[i].Value, SelectionModel.Left));
  65. }
  66. return list.OrderBy(x => x.Min).ToList();
  67. }
  68. }
  69. }