Advertisement
Guest User

Untitled

a guest
Dec 13th, 2019
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.67 KB | None | 0 0
  1.     class Program
  2.     {
  3.         static void Main(string[] args)
  4.         {
  5.             const int rangeStart = 206938;
  6.             const int rangeEnd = 679128;
  7.             var result = Enumerable.Range(rangeStart, rangeEnd - rangeStart).Select(MatchesCriteria);
  8.  
  9.             Console.WriteLine($"Part 1 Possible passwords: {result.Count(r => r.Item1)}");
  10.             Console.WriteLine($"Part 2 Possible passwords: {result.Count(r => r.Item2)}");
  11.         }
  12.  
  13.         static (bool, bool) MatchesCriteria(int n)
  14.         {
  15.             var exactPair = false;
  16.             var runLength = 0;
  17.             var maxRunLength = 0;
  18.             var prev = 11;
  19.  
  20.             while (n >= 10)
  21.             {
  22.                 var least = n % 10;
  23.  
  24.                 if (!Check(prev, least, ref runLength, ref maxRunLength, ref exactPair))
  25.                     return (false, false);
  26.  
  27.                 n /= 10;
  28.                 prev = least;
  29.             }
  30.  
  31.             if (!Check(prev, n, ref runLength, ref maxRunLength, ref exactPair))
  32.                 return (false, false);
  33.  
  34.             if (runLength == 2)
  35.                 exactPair = true;
  36.  
  37.             return (maxRunLength >= 2, exactPair);
  38.         }
  39.  
  40.         static bool Check(int prev, int x, ref int runLength, ref int maxRunLength, ref bool exactPair)
  41.         {
  42.             if (x == prev)
  43.             {
  44.                 maxRunLength = Math.Max(++runLength, maxRunLength);
  45.             }
  46.             else
  47.             {
  48.                 if (!exactPair)
  49.                 {
  50.                     exactPair = runLength == 2;
  51.                 }
  52.                 runLength = 1;
  53.             }
  54.  
  55.             return !(prev < x);
  56.         }
  57.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement