【编程之美06期】如何用代码生成激活码(或者优惠券)?

我们在实用app的过程经常能够看到激活码,优惠券,邀请码这些东西,总是感觉自己受制于人,想不想用自己的代码来生成优惠券呢,酷酷的!!



ps(来自ceo叶神的建议):
从产品角度看激活码,一般需要涉及到
1. 要随机,不能简单,否则容易被人爆破
2. 不要有混淆的字母,比如数字零0和字母欧,爱(I)和小写的L,2和Z等等,否则输入容易出错

“编程之美,让你爱上编程的美。”

挑战下面编程题目,

一起体验编程的乐趣!

本期题目:

做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券),如何生成 200 个激活码(或者优惠券)?

之后会每期在回帖中评选一个最佳”代码牛客”并送出牛客大礼包!时间为一周内,也就是说下周四之前的为有效~~

包括:

鼠标垫 +

程序员精美独家贴纸:

+

牛客独家定制T恤:

当然啦,重要的是来练习自己的编程能力,分享代码,交流技术的过程,这个过程中,你提升的不只是一点点~

为了让牛友能够更高效,更好的学习,特意为大家建了一个群:牛客编程之美源码群 595665246,只给真正想参与这个栏目和真正想学习的人开放,会在群里定期分享源码,只让真正想学习的人来参加,所以只有参与栏目(在本栏目下发出自己的代码的)才能加,加的时候备注一下牛客昵称~

栏目介绍

编程之美,是牛客网推出的新栏目,每周推出一个项目供大家练手讨论交流。

如果你有想实现的项目问题,欢迎私信牛妹~

另外!另外!如果有好玩的项目题目可以私信牛妹,一经采用有奖励哦~~

如果你有写博客或者公众号的习惯,也欢迎加牛妹qq:1037532015私信。

参考代码:

 import random, string

f = open('Promo_code.txt', 'wb')
for i in range(200):
    chars = string.letters + string.digits
    s = [random.choice(chars) for i in range(10)]
    f.write(''.join(s) + '\n')
f.close()

全部评论
从产品角度看激活码,一般需要涉及到 1. 要随机,不能简单,否则容易被人爆破 2. 不要有混淆的字母,比如数字零0和字母欧,爱(I)和小写的L,2和Z等等,否则输入容易出错
点赞 回复 分享
发布于 2016-12-02 14:56
import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Random; public class Key { private String time; private String custormId; private SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd"); public Key(String custormId) { super(); Date date = new Date(); this.time = format.format(date); this.custormId = custormId; } /** * 计算激活码 * @return */ public String getKey(){ //对时间和用户id计算md5值 String md5 = Utils.md5(time+custormId); //取md5的前2位 String header= md5.substring(0, 2); //用于验证激活码的正确性 String verify= String.valueOf(md5.substring(10,15)); //取md5的3-5位 String footer= md5.substring(2, 5); return header+verify+footer; } public static void main(String[] args) { //产生随机用户id Random random = new Random(); List<String> id = new ArrayList<String>(); for(int i=0;i<200;i++){ id.add(String.valueOf(random.nextInt(1000000))); } //产生激活码 for (String string : id) { Key key = new Key(string); System.out.println(key.getKey()); } } } import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * 工具类 用于计算md5 * @author Matrix42 * */ public class Utils { public static String md5(String src) { try { MessageDigest mDigest = MessageDigest.getInstance("MD5"); mDigest.update(src.getBytes()); byte b[] = mDigest.digest(); int i; StringBuffer buffer = new StringBuffer(""); for(int offset = 0; offset < b.length; offset++) { i=b[offset]; if(i<0) i+=256; if(i<16) buffer.append("0"); buffer.append(Integer.toHexString(i)); } return buffer.toString(); }catch(NoSuchAlgorithmException e){ e.printStackTrace(); return null; } } }
点赞 回复 分享
发布于 2016-12-08 15:51
package years.year2016.months12; import java.util.Random; public class Day02 { public static void main(String []args){ String s1 = getActivationCode("string", 80); System.out.println(s1); String s2 = getActivationCode("number", 50); System.out.println(s2); String s3 = getActivationCode("string-number", 10); System.out.println(s3); } private static final char[] LETTER = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; private static final int LETTER_LENGTH =LETTER.length; private static final char[] NUMBER = {'0','1','2','3','4','5','6','7','8','9'}; private static final int NUMBER_LENGTH =NUMBER.length; private static final char[] LETTER_NUMBER = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; private static final int LETTER_NUMBER_LENGTH =LETTER_NUMBER.length; /** * 返回激活码 * @param type 返回激活码类型 [string,number,string-number] * @param length 返回激活码长度 * @return */ public static String getActivationCode(String type,int length){ StringBuilder code=new StringBuilder(length); int state=0; //判定生成何种类型的验证码 if("string".equals(type)){ state=0; }else if("number".equals(type)){ state=1; }else if("string-number".equals(type)){ state=2; }else { new RuntimeException("传入的type值不符合标准,请从新传入,string,number,string-number,中的一个座位type"); } if(length<=0||length>=100){ new RuntimeException("传入生成激活码长度异常请重新传递,激活码长度范围1到99"); } //获取随机数 Random r = new Random(); for(int i=0;i<length;i++){ if(state==0){ code.append(LETTER[r.nextInt(LETTER_LENGTH)]); }else if(state==1){ code.append(NUMBER[r.nextInt(NUMBER_LENGTH)]); }else if(state==2){ code.append(LETTER_NUMBER[r.nextInt(LETTER_NUMBER_LENGTH)]); } } return code.toString(); } }
点赞 回复 分享
发布于 2016-12-02 14:27
没事做... 我来补上之前没做的编程之美。 这个比较复杂,先 生成一个随机字符串,再将字符串使用MD5加密,生成32位的激活码。 参考了一点前面的大神的。 public class MD5Util { public static void main(String[] args) { final int ACTIVATECODENUM = 200; Random random = new Random(); String candicateCode = "abcdefghijklmnopqrstuvwxyz"; candicateCode += candicateCode.toUpperCase(); candicateCode += "1234567890"; for (int i = 0; i < ACTIVATECODENUM; i++) { String res = ""; for (int j = 0; j < 6; j++) { res += candicateCode.charAt(random.nextInt(candicateCode .length())); } String pwd = MD5Util.getMD5(MD5Util.getMD5(res)); System.out.println(pwd); } } private static String byteHEX(byte ib) { char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; char[] ob = new char[2]; ob[0] = Digit[(ib >>> 4) & 0X0F]; ob[1] = Digit[ib & 0X0F]; String s = new String(ob); return s; } // 字符串加密 public static String getMD5(String source) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } messageDigest.update(source.getBytes()); byte[] b = messageDigest.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < b.length; i++) { sb.append(byteHEX(b[i])); } // sb.setCharAt(sb.length()-1, (char)(sb.charAt(sb.length()-1)+1)); return sb.toString(); } } 运行效果:
点赞 回复 分享
发布于 2017-01-21 02:27
本周是这位牛友获得编程之星,记得私信牛妹领取大礼包哦~
点赞 回复 分享
发布于 2016-12-09 10:23
/* * 生成优惠码 * @author dragonlogin * @time 2016/12/8/15:43 * 实话实说,我是参看了贴友的代码,谁知一看,如此简单,我还是太蠢了点啊! */ import java.util.Random; public class Main{ private static int maxL=20; public static void main(String[] args) { String str="abcdefghijklmnopqrstuvwxyz"; str+=str.toUpperCase(); str+="1234567890"; Random random= new Random(); for(int i=0; i<maxL; i++){ String res=""; for(int j=0; j<20; j++){ res+=str.charAt(random.nextInt(str.length())); } System.out.println(res); } } }
点赞 回复 分享
发布于 2016-12-08 15:47
package bianchengzhimei6; import java.util.HashSet; import java.util.Set; /** * Created by stella.yang on 2016/12/6. */ public class RandomSecurityCode { //生成激活码的个数 private static int size=200; //除去易混淆的字符,数字0,字符O,o,l, private static final char[] charCode={ '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; //生成6位激活码 public static Set<char[]> activateCode(){ Set<char[]> result=new HashSet<>(); for(int i=0;i<size;i++){ char []chars=new char[6]; char []code=charCode; int n=charCode.length; //生成激活码 for(int j=0;j<4;j++){ int r= (int) (Math.random()*n); //将激活码中的第j位设置成code中的第r位 chars[j]=code[r]; // 必须确保不会再次抽取到那个字符,因为所有抽取的字符必须不相同。 // 因此,这里用数组中的最后一个字符改写code[r],并将n减1 code[r]=code[n-1]; n--; } //如果检测到有生成重复的激活码,就重新生成这个激活码 if(!result.add(chars)){ i--; } } return result; } public static void main(String []args){ Set<char[]> set=RandomSecurityCode.activateCode(); for(char[] s:set){ System.out.println(s); } } }
点赞 回复 分享
发布于 2016-12-06 15:52
/* * @author yixingu *生成八位激活码 * * 利用62个可打印字符,通过随机生成32位UUID; * 由于UUID都为十六进制,所以将UUID分成8组,每4个为一组; * 然后通过模62操作,结果作为索引取出字符; * */ import java.util.ArrayList; import java.util.UUID; public class RandomStrUtil { public static final String[] CHARS = new String[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }; /* * count表示要生成的个数 */ public static ArrayList<String> getRandStr(final int count) { ArrayList<String> list = new ArrayList<String>(); if (count < 1) { return list; } StringBuilder sb = new StringBuilder(); String uuid = UUID.randomUUID().toString().replace("-", ""); for (int i = 0; i < count; i++) { for (int j = 0; j < 8; j++) { String str = uuid.substring(i * 4, i * 4 + 4); sb.append(CHARS[Integer.parseInt(str, 16) % 0x3E]); } list.add(sb.toString()); } return list; } }
点赞 回复 分享
发布于 2016-12-05 18:54
CEO的建议: 从产品角度看激活码,一般需要涉及到 1. 要随机,不能简单,否则容易被人爆破 2. 不要有混淆的字母,比如数字零0和字母欧,爱(I)和小写的L,2和Z等等,否则输入容易出错
点赞 回复 分享
发布于 2016-12-05 18:23
JavaScript实现 //给定范围随机数生成 //from:生成的最小数,to:生成的最大数 function randBetween(from,to){ return parseInt(Math.random()*(to-from+1))%(to-from+1)+from; } //激活码生成 //num:激活码数量,length:激活码长度 function genCode(num,length){ var rtn=[]; var new_code; length=(Math.pow(62,length)>num )?length:parseInt(Math.log(num)/Math.log(62))+1; //如果激活码长度太短,导致无法生成给定数量的不重复激活码,则增长激活码长度 for(var i=0;i<num;++i){ do{ ascii_arr=[]; for(var j=0;j<length;++j){ switch(randBetween(0,2)){ case 0: ascii_arr[j]=randBetween(48,57); break; case 1: ascii_arr[j]=randBetween(65,90); break; case 2: ascii_arr[j]=randBetween(97,122); break; } } new_code=String.fromCharCode.apply(null,ascii_arr); }while( rtn.indexOf(new_code)!=-1 ); //确保生产随机数不会重复 rtn[i]=new_code; } return rtn; } genCode(200,12);
点赞 回复 分享
发布于 2016-12-04 21:47
一进来就萌我一脸血!
点赞 回复 分享
发布于 2016-12-04 17:59
import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * 描述:工具类 生成激活码 * @author 尧先生 * */ public class ActiveCode { //存储激活码的容器 private static List<String> activeList; //激活码个数 private static final int SIZE=200; //激活码长度 private static final int LENGTH=8; /** * 描述:初始化容器 */ static{ activeList=new ArrayList<String>(); } /** * 描述:工具方法,私有构造方法 */ private ActiveCode(){}; /** * 描述:使用UUID,生成激活码 * @return List<String> 生成的激活码集合 */ public static List<String> getActiceCode(){ for (int i = 0; i < SIZE; i++) { String randomStr=UUID.randomUUID().toString(); activeList.add(randomStr.substring(0, LENGTH)); } return activeList; } }
点赞 回复 分享
发布于 2016-12-02 11:09
生成6位激活码 import java.util.Random; import java.util.TreeSet; public class Test{ private static final String allChars= "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; private static int codeNum = 200; private static int codeLength = 6; private static int allLength = allChars.length(); private TreeSet<String> set = new TreeSet<String>(); public static String generator(){ StringBuffer buf = new StringBuffer(); Random rand = new Random(); for(int i = 0; i < codeLength; i++){ int index = rand.nextInt(allLength); buf.append(allChars.charAt(index)); } return buf.toString(); } public void addEle(){ for(int i = 0; i < codeNum; i++) { String str = generator(); while(set.contains(str)){ str = generator(); } set.add(str); } } public void print(){ for(Object s:set){ System.out.println(s); } } public static void main(String[] args){ Test test = new Test(); test.addEle(); test.print(); } }
点赞 回复 分享
发布于 2016-12-02 11:07
java实现,生成8位激活码 import java.util.Random; /** * Created by CAD on 2016/12/2. */ public class ActivateCode { public static void main(String[] args){ final int ACTIVATECODENUM = 200; Random random = new Random(); String candicateCode = "abcdefghijklmnopqrstuvwxyz"; candicateCode += candicateCode.toUpperCase(); candicateCode += "1234567890"; for(int i = 0; i < ACTIVATECODENUM; i++){ String res = ""; for(int j = 0; j < 8; j++){ res += candicateCode.charAt(random.nextInt(candicateCode.length())); } System.out.println(res); } } }
点赞 回复 分享
发布于 2016-12-02 09:49
import java.util.Set; import java.util.TreeSet; public class Generator { public static final String numbersAndChars = "1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm"; public static void main(String[] args) { int maxNumber = 200; Set set = new TreeSet<String>(); int strSize = numbersAndChars.length(); String result; int lengthOfGoal = 20; while (set.size() < maxNumber) { result = ""; for(int i = 0; i < lengthOfGoal; i++) { result += numbersAndChars.charAt((int)(Math.random() * strSize)); } if(!set.contains(result)) { set.add(result); } } int count = 0; for(Object o : set) { count ++; System.out.println((String)o + " " + count); } } }
点赞 回复 分享
发布于 2016-12-01 23:04
这个激活码有啥要求么
点赞 回复 分享
发布于 2016-12-01 22:07
#!/usr/bin/env python # -*- encoding: utf-8 -*- # @Date : 2015-02-18 10:41:10 # @Author : NSSimacer # @Email : wuxiaoqiang1020@gmail.com # @Version : 1.0 import string import random COUPON_NUM = 200 COUPON_LENGTH = 8 if __name__ == '__main__': coupon_character_list = list(string.uppercase + string.digits) for i in xrange(COUPON_NUM): coupon_str = '' for j in xrange(COUPON_LENGTH): coupon_str += random.choice(coupon_character_list) print coupon_str
点赞 回复 分享
发布于 2016-12-01 18:38

相关推荐

06-27 12:30
延安大学 C++
实习+外包,这两个公司底层融为一体了,如何评价呢?
一表renzha:之前面了一家外包的大模型,基本上都能答出来,那面试官感觉还没我懂,然后把我挂了,我都还没嫌弃他是外包,他把我挂了……
第一份工作能做外包吗?
点赞 评论 收藏
分享
程序员牛肉:主要是因为小厂的资金本来就很吃紧,所以更喜欢有实习经历的同学。来了就能上手。 而大厂因为钱多,实习生一天三四百的就不算事。所以愿意培养你,在面试的时候也就不在乎你有没有实习(除非是同级别大厂的实习。) 按照你的简历来看,同质化太严重了。项目也很烂大街。 要么换项目,要么考研。 你现在选择工作的话,前景不是很好了。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务