14 Ekim 2021

6 Karakterli Unique Key Üretme

 using System;

using System.Collections.Generic;
using System.Text;

namespace ConsoleApp14
{
    class Program
    {
       
        static void Main(string[] args)
        {
            var generatedKeys = new List<string>();
            for (int i = 0; i < 100000; i++)
            {
                var key = KeyGenerator.Generate(i);
                if (generatedKeys.Contains(key))
                    throw new Exception("Tekrar eden numaralar var");
                Console.WriteLine(key);
                generatedKeys.Add(key);
            }
        }
    }

    public static class KeyGenerator
    {
        // chars count must be prime number
        // (mine are 31 i also shuffled them you can re shuffle your letters)
        private static readonly char[] chars = {
                'C', 'V', 'M', 'J', '4', 'E', 'Y','L','R','N','9','5','Z','3','X',
                'D','8','G','T','6','K','W','P','B','S','U','F','H','A','2','7'
            };
        private static int Mod(int a, int b)
           => ((a % b) + b) % b;

        /// <summary>
        /// Generates Unique 6 Character Key By Id
        /// </summary>
        /// <param name="index"> Min 0 Max 887,503,680</param>
        /// <returns></returns>
        public static string Generate(int index)
        {
            // I am calculating 6 digit which means 31^6 = 887503681 possible number
            // I multiplied with 2 different very big prime numbers to prevent similar generated keys
            var number = Mod((index * 8969 * 10457), 887503681);
            var sb = new StringBuilder();
            while (number > 30)
            {
                var letter = chars[(number % 31)];
                sb.Append(letter);
                number = number / 31;
            }
            sb.Append(chars[number]);
            // if it's shorter than 6 character we add last character example (1 =>001)
            while (sb.Length < 6)
            {
                sb.Insert(0, chars[30]);
            }

            return sb.ToString();
        }
    } 
}


SQL User Defined Function

create function [dbo].[udf_GenerateSixCharacterKey] 
(@index int)
returns varchar(6)  as
begin 
declare @a int, 
@b int
set @a = @index * 8969 * 10457
set @b = 887503681

declare @number int
set @number = ((@a % @b) + @b) % @b

declare @chars varchar(31)
set @chars = 'CVMJ4EYLRN95Z3XD8GT6KWPBSUFHA27'

declare @key varchar(6)
set @key = ''

while @number > 30
begin 
set @key = @key + substring(@chars, (@number % 31) + 1, 1)
set @number = @number / 31
end

set @key = @key + substring(@chars, @number + 1, 1)

while len(@key) < 6
begin
set @key = substring(@chars, 31, 1) + @key
end

return @key

end