1

I want to generate 6-digit numeric coupon codes in JavaScript.

I'd like to use something like Preshing's algorithm.

This is what I have so far,

const p = 1000003;

function permuteQPR(x) {
  const residue = x * x % p;
  return (x <= p/2) ? residue : p - residue;
}

function next() {
  return permuteQPR(
    (permuteQPR(m_index++) + m_intermediateOffset) ^ 0x5bf03635
  );
};

const seedBase = 123456;
const seedOffset = 44;
m_index = permuteQPR(permuteQPR(seedBase) + 0x682f0161);
m_intermediateOffset = permuteQPR(
  permuteQPR(seedOffset) + 0x46790905
);

for (i = 0; i < 20; i++) {
  document.body.innerHTML += ('000000' + next()).substr(-6) + "<br>";
}

There is also a jsfiddle.

Bob Gilmore
  • 12,608
  • 13
  • 46
  • 53
Obiwahn
  • 2,677
  • 2
  • 26
  • 36
  • 1
    Convert it to JavaScript yourself? Although in reality, all you need to do is shuffle an ordered array. See http://stackoverflow.com/questions/3746725/create-a-javascript-array-containing-1-n and http://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array-in-javascript. – James Donnelly Nov 28 '16 at 15:36
  • 1
    Your all very helpful.. To me this seems a valid question, and it's certainly not asking the same question as shuffling an array. The link the OP posted was for generating unique random numbers without the overhead of an Array. – Keith Nov 28 '16 at 15:57
  • 1
    @obiwahn,.. I've just done a quick convert of the source code from your link, and it appears to work fine. Tested by creating 10 million random numbers, and checking there is no duplicate. If this question gets taken of hold I could post here. – Keith Nov 28 '16 at 16:04
  • 1
    @Keith You could also post a link to a jsfiddle in a comment here – JstnPwll Nov 28 '16 at 16:31
  • Sorry guys. Could someone please explain to me why this is on hold? I am rather new to JavaScript and I asked this question because I am not able to convert it by myself. Plus I think this would be really useful for many other members of this community. – Obiwahn Nov 29 '16 at 09:27
  • 1
    @obiwahn It was put on hold (I presume) because the original wording sounded like you were looking for someone to point you to an off-site resource. I re-worded your question to ask specifically for help rewriting the algorithm in JS and then flagged it for reopen. – JstnPwll Nov 29 '16 at 16:10

1 Answers1

0

This one works and is unique:

const p = 1000003;
const seed1 = 123456;
const seed2 = 123457;


function calculateResidue(x) {
    const residue = x * x % p;
  return (x <= p/2) ? residue : p - residue;
}


function valueForIndex(index) {
        const first = calculateResidue((index + seed1) % p);
        return result = calculateResidue((first + seed2) % p);
};

let codes = [];
for(i=0;i<1000000;i++) {
    const code = valueForIndex(i);
  if(codes.indexOf(code)==-1) codes.push(code);
};


document.body.innerHTML += "Unique codes: " + codes.length;
Obiwahn
  • 2,677
  • 2
  • 26
  • 36