fork download
  1. using System;
  2.  
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. var rnd = new Random();
  8. for (int i = 0; i < 10; i++)
  9. {
  10. int x = rnd.Next(10000);
  11. string encoded = AbcNotation.Encode(x);
  12. int decoded = AbcNotation.Decode(encoded);
  13. Console.WriteLine("{0} -> {1} -> {2}", x, encoded, decoded);
  14. }
  15. }
  16. }
  17.  
  18. public static class AbcNotation
  19. {
  20. public const int AlphabetsCount = 26;
  21.  
  22. // A -> 1, AA -> 27, AAA -> 703, .....
  23. private static int DecodeRepeatedA(int digits)
  24. {
  25. return digits == 1 ? 1 : (int)Math.Pow(26, digits - 1) + DecodeRepeatedA(digits - 1);
  26. }
  27.  
  28. // decode "ABC" as simple 26-adic encoded.
  29. private static int DecodeAs26Adic(string se)
  30. {
  31. int msd = AtoI(se[0]);
  32. int power = (int)Math.Pow(AlphabetsCount, se.Length - 1);
  33. return se.Length == 1 ? msd : msd * power + DecodeAs26Adic(se.Substring(1));
  34. }
  35.  
  36. public static int Decode(string abc)
  37. {
  38. return DecodeRepeatedA(abc.Length) + DecodeAs26Adic(abc);
  39. }
  40.  
  41. // Encode to Simple 26-adic notaion using A to Z.
  42. private static string EncodeAs26Adic(int x, int digits)
  43. {
  44. int power = (int)Math.Pow(AlphabetsCount, digits - 1);
  45. int msd = x / power;
  46. int remainder = x - power * msd;
  47.  
  48. return digits == 1 ? ItoA(x).ToString() : ItoA(msd) + EncodeAs26Adic(remainder, digits - 1);
  49. }
  50.  
  51. public static string Encode(int x)
  52. {
  53. int digits = GetEncodedLength(x);
  54. return EncodeAs26Adic(x - DecodeRepeatedA(digits), digits);
  55. }
  56.  
  57. // Return length of ABC encoded string.
  58. private static int GetEncodedLength(int x)
  59. {
  60. for (int i = 2; ; i++) if (x < DecodeRepeatedA(i)) return i - 1;
  61. }
  62.  
  63. private static int AtoI(char c)
  64. {
  65. return c - 'A';
  66. }
  67.  
  68. private static char ItoA(int figure)
  69. {
  70. return (char)('A' + figure);
  71. }
  72.  
  73. }
  74.  
Success #stdin #stdout 0.04s 24216KB
stdin
Standard input is empty
stdout
4836 -> GCZ -> 4836
4264 -> FGZ -> 4264
6071 -> HYM -> 6071
5955 -> HUA -> 5955
1953 -> BWC -> 1953
4601 -> FTY -> 4601
6483 -> IOI -> 6483
2605 -> CVE -> 2605
699 -> ZW -> 699
3605 -> EHQ -> 3605