一佳一

记录像1+1一样简洁的代码

导航

高性能(无需判重)批量生成优惠券码生成方案

Posted on 2022-10-10 13:52  一佳一  阅读(104)  评论(0编辑  收藏  举报
using System.Text;

namespace xxxxxx
{
    public class CouponCodeUtilV2
    {
        private static readonly char[] _codePool = { 'z', 'N', 'x', '5', 'h', 'g', 'W', 'b', 'S', '4', 'q', 'X', '7', 'K', 'L', '3', 'a', 'n', 'J', 'P', 'D', 't', 'Z', 'C', 'E', 'A', 'e', 'H', 'M', 'G', 'j', 'Q', 'V', 'Y', 'w', '8', 'f', '2', 'y', 'p', 'u', 'c', 'U', 's', 'd', 'k', 'm', 'B', 'r', 'v', 'T', '6', 'F', 'R', '9' };
        private static readonly int _poolSize = _codePool.Length;
        private static readonly int[] _weights = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
        private static readonly int _weightSize = _weights.Length;

        public static string GenerateCode()
        {
            long uniqueId = BitConverter.ToInt64(Guid.NewGuid().ToByteArray(), 0);

            StringBuilder codeBuilder = new StringBuilder();
            int sum = 0;
            int position = -1;

            char currentChar;
            int weight;
            while (uniqueId >= _poolSize)
            {
                long poolPosition = uniqueId % _poolSize;
                uniqueId /= _poolSize;
                currentChar = _codePool[poolPosition];
                codeBuilder.Append(currentChar);

                position++;
                weight = _weights[position % _weightSize];
                sum += weight * currentChar;
            }

            currentChar = _codePool[uniqueId];
            codeBuilder.Append(currentChar);

            position++;
            weight = _weights[position % _weightSize];
            sum += weight * currentChar;

            position = sum % _poolSize;
            codeBuilder.Append(_codePool[position]);

            return codeBuilder.ToString();
        }

        public static bool Verify(string code)
        {
            if (string.IsNullOrWhiteSpace(code) || code.Length < 2) return false;

            char[] parts = code.ToCharArray();
            int sum = 0;
            int weight;
            char part;

            for (int i = 0; i < parts.Length - 1; i++)
            {
                part = parts[i];
                weight = _weights[i % _weightSize];
                sum += weight * part;
            }

            int position = sum % _poolSize;
            return parts[parts.Length - 1] == _codePool[position];
        }
    }
}

var code = CouponCodeUtilV2.GenerateCode();

var verify = CouponCodeUtilV2.Verify(code);

Console.WriteLine($"{code}\t{verify}");