Advertisement
PavloSerg

Untitled

Mar 17th, 2023
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.46 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace Substring
  5. {
  6. public class RabinKarpAlgorithm : ISubstringSearch
  7. {
  8. private readonly int _baseOfTheNumeralSystem;
  9. private readonly int _primeNumber;
  10.  
  11. public RabinKarpAlgorithm(int baseOfTheNumeralSystem = char.MaxValue, int primeNumber = 115249)
  12. {
  13. _baseOfTheNumeralSystem = baseOfTheNumeralSystem;
  14. _primeNumber = primeNumber;
  15. }
  16.  
  17. public List<int> IndexesOf(string input, string pattern)
  18. {
  19. List<int> indexesList = new List<int>();
  20. int inputLength = input.Length;
  21. int patternLength = pattern.Length;
  22. int maxBase = GetMaxBase(patternLength, _primeNumber, _baseOfTheNumeralSystem);
  23. int patternHash = GetHashOfString(pattern, _primeNumber, _baseOfTheNumeralSystem);
  24. int substringHash =
  25. GetHashOfString(input.Substring(0, patternLength), _primeNumber, _baseOfTheNumeralSystem);
  26.  
  27. for (int i = 0; i <= inputLength - patternLength; i++)
  28. {
  29.  
  30. if (patternHash == substringHash)
  31. {
  32. bool success = true;
  33. for (int j = 0; j < patternLength; j++)
  34. {
  35. if (input[i + j] != pattern[j])
  36. {
  37. success = false;
  38. break;
  39. }
  40. }
  41. if (success)
  42. indexesList.Add(i);
  43. }
  44. if (i != inputLength - patternLength)
  45. substringHash =
  46. (_baseOfTheNumeralSystem * (substringHash - input[i] * maxBase) +
  47. input[i + patternLength]) % _primeNumber;
  48. if (substringHash < 0) substringHash += _primeNumber;
  49. }
  50. return indexesList;
  51. }
  52. private int GetHashOfString(string s, int q, int b)
  53. {
  54. int result = 0;
  55. int length = s.Length;
  56.  
  57. for (int i = 0; i < length; i++)
  58. result = (b * result + s[i]) % q;
  59. return result;
  60. }
  61. private int GetMaxBase(int length, int q, int b)
  62. {
  63. int result = 1;
  64. for (int i = 0; i < length - 1; i++)
  65. result = (result * b) % q;
  66. return result;
  67. }
  68. }
  69. }
  70.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement