What's the math behind Google Adwords Promotional Codes and how to replicate them in a custom app?

StackOverflow https://stackoverflow.com/questions/7725383

  •  08-02-2021
  •  | 
  •  

Question

recently i've seen that Google AdWords is sharing promotional codes, which gives you $200 for publishing with them.

The question is this: Obviously, the code is a big combination of chars, something like: 9842 - a251 - b51s - 1250, and if you try any other input but what they give it will fail telling you that the code is not valid. It's of course good because you don't want any "robot" to generate your codes for you.

So, what are the best practices for do something like this? I've been thinking and using a big amount of chars, and generating them in random sequences could it be done, but i think that some "probabilistic" model would fit better.

Do you know how is it properly done?

Thank you all!

Was it helpful?

Solution

The safest way to do this is to use a cryptographic PRNG to generate a sufficiently long random code (at least 128 bits, ideally), and store a list of valid IDs in a database. When someone enters a code, check it against the DB and mark it as used.

OTHER TIPS

The simplest way is:

  1. set an alphabet

    string alpha = "0123456789abcdefghijklmnopqrstuvwxyz";

  2. set a lenght of the final code

    int final = 16; string code="";

  3. generate chars from the alphabet

.

int i = final;
while( i-->0 ){
string += alpha[ Math.random(0,alpha.length) ]
}

Take the hash of an auto-inc number concatenated to a fixed string:

"My long nonsensical string 0000001"

"My long nonsensical string 0000002"

Hashes are good at generating widely different codes from near-identical strings. Throw away duplicates, if you get any.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top