Guest User

Untitled

a guest
Nov 25th, 2017
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1. void Main()
  2. {
  3. string nip = "1220781342";
  4.  
  5. Console.WriteLine(Validator.IsValidNIP(nip) ? "NIP is valid" : "NIP is not valid");
  6.  
  7. string regon = "730295378";
  8.  
  9. Console.WriteLine(Validator.IsValidREGON(regon) ? "REGON is valid" : "REGON is not valid");
  10.  
  11. string pesel = "93111698132";
  12.  
  13. Console.WriteLine(Validator.IsValidPESEL(pesel) ? "PESEL is valid" : "PESEL is not valid");
  14.  
  15. }
  16.  
  17. public class Validator
  18. {
  19. private static byte[] ToByteArray(string input) => input
  20. .ToCharArray()
  21. .Select(c => byte.Parse(c.ToString()))
  22. .ToArray();
  23.  
  24. private static int ControlSum(byte[] numbers, byte[] weights) => numbers
  25. .Take(numbers.Length - 1)
  26. .Select((number, index) => new { number, index })
  27. .Sum(n => n.number * weights[n.index]);
  28.  
  29.  
  30. private static bool IsValid(string input, byte[] weights, Func<int, int> control)
  31. {
  32. var numbers = ToByteArray(input);
  33.  
  34. bool result = false;
  35.  
  36. if (input.Length == weights.Length + 1)
  37. {
  38. int controlSum = ControlSum(numbers, weights);
  39.  
  40. int controlNum = control(controlSum);
  41.  
  42. if (controlNum == 10)
  43. {
  44. controlNum = 0;
  45. }
  46.  
  47. result = controlNum == numbers.Last();
  48. }
  49.  
  50. return result;
  51. }
  52.  
  53. public static bool IsValidREGON(string input)
  54. {
  55. byte[] weights = null;
  56.  
  57. switch (input.Length)
  58. {
  59. case 7: weights = new byte[] { 2, 3, 4, 5, 6, 7 };
  60. break;
  61.  
  62. case 9: weights = new byte[] { 8, 9, 2, 3, 4, 5, 6, 7 };
  63. break;
  64.  
  65. case 14: weights = new byte[] { 2, 4, 8, 5, 0, 9, 7, 3, 6, 1, 2, 4, 8 };
  66. break;
  67.  
  68. default: return false;
  69. }
  70.  
  71. return IsValid(input, weights, controlSum => controlSum % 11);
  72.  
  73. }
  74.  
  75. public static bool IsValidPESEL(string input)
  76. {
  77. byte[] weights = { 1, 3, 7, 9, 1, 3, 7, 9, 1, 3 };
  78.  
  79. return IsValid(input, weights, controlSum => 10 - controlSum % 10);
  80. }
  81.  
  82. public static bool IsValidNIP(string input)
  83. {
  84. byte[] weights = { 6, 5, 7, 2, 3, 4, 5, 6, 7 };
  85.  
  86. return IsValid(input, weights, controlSum => controlSum % 11);
  87.  
  88. }
  89. }
Add Comment
Please, Sign In to add comment