Guest User

Reddit BadCode Challenge #43

a guest
Aug 18th, 2020
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 5.56 KB | None | 0 0
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Linq;
  6. using System.Threading.Tasks;
  7.  
  8. namespace uuid_bad_code
  9. {
  10.     /// <summary>
  11.     /// Program
  12.     /// </summary>
  13.     class Program
  14.     {
  15.         /// <summary>
  16.         /// Main function
  17.         /// </summary>
  18.         static void Main()
  19.         {
  20.             IUuidGenerator generator = new UuidGenerator(new List<char>
  21.             {
  22.                 '0',
  23.                 '1',
  24.                 '2',
  25.                 '3',
  26.                 '4',
  27.                 '5',
  28.                 '6',
  29.                 '7',
  30.                 '8',
  31.                 '9',
  32.                 'a',
  33.                 'b',
  34.                 'c',
  35.                 'd',
  36.                 'e',
  37.                 'f',
  38.                 '-'
  39.             }, new Random(Guid.NewGuid().GetHashCode())); // Not sure what "Guid.NewGuid().GetHashCode()" does, found it on StackOverflow
  40.  
  41.             var uuid = generator.Generate();
  42.             Console.WriteLine($"The uuid is: {uuid}");
  43.             Console.ReadKey();
  44.         }
  45.     }
  46.  
  47.     /// <summary>
  48.     /// An interface for UUID generators
  49.     /// </summary>
  50.     public interface IUuidGenerator
  51.     {
  52.         /// <summary>
  53.         /// Generates
  54.         /// </summary>
  55.         /// <returns>A generated string</returns>
  56.         string Generate();
  57.     }
  58.  
  59.     /// <summary>
  60.     /// A UUID generator
  61.     /// </summary>
  62.     public class UuidGenerator: IUuidGenerator
  63.     {
  64.         /// <summary>
  65.         /// The number of legal chars including hyphens and numbers
  66.         /// </summary>
  67.         private const int NumberOfLegalCharsIncludingHyphenAndIncludingNumbersAsWell = 17;
  68.  
  69.         /// <summary>
  70.         /// Legal chars
  71.         /// </summary>
  72.         private readonly IList<char> _legalChars;
  73.  
  74.         /// <summary>
  75.         /// The <see cref="Random"/> class object
  76.         /// </summary>
  77.         private readonly Random _random;
  78.  
  79.         /// <summary>
  80.         /// A lock for <see cref="_random"/> access
  81.         /// </summary>
  82.         private readonly object _randomLock;
  83.  
  84.         /// <summary>
  85.         /// The UUID generator constructor
  86.         /// </summary>
  87.         /// <param name="legalChars">Legal chars</param>
  88.         /// <param name="random">The <see cref="Random"/> class object</param>
  89.         public UuidGenerator(IList<char> legalChars, Random random)
  90.         {
  91.             _legalChars = legalChars ?? throw new ArgumentNullException(nameof(legalChars));
  92.             _random = random ?? throw new ArgumentNullException(nameof(random));
  93.             _randomLock = new Object();
  94.         }
  95.  
  96.         /// <summary>
  97.         /// Generates
  98.         /// </summary>
  99.         /// <returns>A generated string</returns>
  100.         public string Generate()
  101.         {
  102.             var time = Stopwatch.StartNew();
  103.  
  104.             // It should be a 128-bit number displayed in five groups separated by hyphens in the form 8-4-4-4-12
  105.             // 8 + 1 + 4 + 1 + 4 + 1 + 4 + 1 + 12 = 36
  106.             //     8      13       18     23  
  107.             const int numberOfCharsInLegalUuidStringIncludingHyphensAndIncludingNumbersAsWell = 8 + 1 + 4 + 1 + 4 + 1 + 4 + 1 + 12;
  108.  
  109.             ConcurrentDictionary<int, char> uuid = new ConcurrentDictionary<int, char>();
  110.  
  111.             int iterations = 0;
  112.             bool uuidLegal = false;
  113.             while (!uuidLegal)
  114.             {
  115.                 iterations++;
  116.                 List<int> indicesWhereHyphensShouldBe = new List<int>
  117.                 {
  118.                     8, 13, 18, 23
  119.                 };
  120.  
  121.                 // We run this in parallel because it's faster
  122.                 Parallel.For(0, numberOfCharsInLegalUuidStringIncludingHyphensAndIncludingNumbersAsWell, index =>
  123.                 {
  124.                     // Need to lock before accessing the random class per MSDN
  125.                     // https://docs.microsoft.com/en-us/dotnet/api/system.random?redirectedfrom=MSDN&view=netcore-3.1#ThreadSafety
  126.                     lock (_randomLock)
  127.                     {
  128.                         if (_legalChars.ToList().Count != NumberOfLegalCharsIncludingHyphenAndIncludingNumbersAsWell)
  129.                         {
  130.                             throw new InvalidOperationException($"Can't generate random number because the legal chars list doesn't contain exactly {NumberOfLegalCharsIncludingHyphenAndIncludingNumbersAsWell} characters!");
  131.                         }
  132.                         int charIndex = _random.Next(_legalChars.ToList().Count);
  133.  
  134.                         uuid[index] = _legalChars.ToList()[charIndex];
  135.                     }
  136.                 });
  137.  
  138.                 var uuidLegalLock = new Object();
  139.                 var isUuidLegal = true;
  140.                 Parallel.For(0, uuid.Count, i =>
  141.                 {
  142.                     lock (uuidLegalLock)
  143.                     {
  144.                         isUuidLegal = isUuidLegal &&
  145.                                     (indicesWhereHyphensShouldBe.ToList().Contains(i) && uuid[i] == '-' ||
  146.                                      !indicesWhereHyphensShouldBe.ToList().Contains(i) &&
  147.                                      uuid[i] != '-' &&
  148.                                      _legalChars.ToList().Contains(uuid[i]));
  149.                     }
  150.                 });
  151.  
  152.                 uuidLegal = isUuidLegal;
  153.             }
  154.  
  155.             time.Stop();
  156.             Console.WriteLine($"Finished generating UUID after {time.Elapsed.TotalSeconds} seconds ({iterations} iterations)");
  157.  
  158.             return new string(uuid.Values.ToArray());
  159.         }
  160.     }
  161. }
Add Comment
Please, Sign In to add comment