问题描述
我需要生成一个优惠券代码[5〜10位]仅一次使用。什么是生成并检查所使用的最佳方法
I need to generate a voucher code[ 5 to 10 digit] for one time use only. what is the best way to generate and check if been used?
编辑:?我宁愿字母数字字符 - 亚马逊样的礼品券代码必须是唯一的
edited: I would prefer alpha-numeric characters - amazon like gift voucher codes that must be unique.
推荐答案
在生成优惠券代码 - 你应该考虑有一个序列是可以预见的是你要真的是。
When generating voucher codes - you should consider whether having a sequence which is predictable is really what you want.
例如,优惠券代码:ABC101,ABC102,ABC103等都是相当的可预见性。用户可以很轻易地猜到优惠券代码。
For example, Voucher Codes: ABC101, ABC102, ABC103 etc are fairly predictable. A user could quite easily guess voucher codes.
要防止这一点 - 你需要防止随机猜测,从工作的一些方法。
To protect against this - you need some way of preventing random guesses from working.
有两种方法:
-
嵌入您的优惠券代码校验。
Embed a checksum in your voucher codes.
信用卡上的最后一个数字是校验(校验位) - 当你以某种方式加起来的对方号码,可以让你确保有人输入的数字正确。请参阅:(第一链接出谷歌)为如何为信用卡完成。
The last number on a credit card is a checksum (Check digit) - when you add up the other numbers in a certain way, lets you ensure someone has entered a number correctly. See: http://www.beachnet.com/~hstiles/cardtype.html (first link out of google) for how this is done for credit cards.
有一个大的密钥空间,这只是人烟稀少。
Have a large key-space, that is only sparsely populated.
例如,如果要生成凭证1000 - 然后1,000,000关键空间意味着你应该能够使用随机生成(有重复和顺序检查),以确保它是很难猜测另一个券代码。
For example, if you want to generate 1,000 vouchers - then a key-space of 1,000,000 means you should be able to use random-generation (with duplicate and sequential checking) to ensure it's difficult to guess another voucher code.
下面是一个使用的大型骨干空间方法一个示例应用程序:
Here's a sample app using the large key-space approach:
static Random random = new Random();
static void Main(string[] args)
{
int vouchersToGenerate = 10;
int lengthOfVoucher = 10;
List<string> generatedVouchers = new List<string>();
char[] keys = "ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890".ToCharArray();
Console.WriteLine("Vouchers: ");
while(generatedVouchers.Count < vouchersToGenerate)
{
var voucher = GenerateVoucher(keys, lengthOfVoucher);
if (!generatedVouchers.Contains(voucher))
{
generatedVouchers.Add(voucher);
Console.WriteLine("\t[#{0}] {1}", generatedVouchers.Count, voucher);
}
}
Console.WriteLine("done");
Console.ReadLine();
}
private static string GenerateVoucher(char[] keys, int lengthOfVoucher)
{
return Enumerable
.Range(1, lengthOfVoucher) // for(i.. )
.Select(k => keys[random.Next(0, keys.Length - 1)]) // generate a new random char
.Aggregate("", (e, c) => e + c); // join into a string
}
这篇关于如何生成在C#中的优惠券代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!