skip to Main Content

I need 10 random ids at time. I need to get a new set of random ids every time I ask for a new set, but the new ones must not include any of the ones I already got from any number of previous times I asked for a new set Unless the process is reset. I may have a total of 100 or 1million ids in my database. I plan to use the ids to show 10 items on a webpage, with next and previous buttons. The pages already shown have to be consistent with the original items shown if the users goes back to any previously shown page

I have an idea that I select random numbers with seed 1000 times ,store it on redis server and pop out every 10 rows when a user enter the page. Are there any different ideas?

2

Answers


  1. You are looking for a repeatable random sort. In MySQL, you can do this by passing a seed to mathematical function rand(), as explained in the documentation:

    for equal argument values, RAND(N) returns the same value each time, and thus produces a repeatable sequence of column values.

    This gives you the first 10 records:

    select t.*
    from mytable t
    order by rand(12345)
    limit 10
    

    You can then paginate; to get the "next" 10 records, you use the same seed to rand(), and offset the result:

    select t.*
    from mytable t
    order by rand(12345)
    limit 10 offset 10
    
    Login or Signup to reply.
  2. For a large set of non-repeating ‘random’ numbers you are probably better off using encryption. If numbers do not repeat, then they are not truly random because they are constrained not to repeat. Every time you pick a number the pool of available numbers shrinks. Hence the output is not truly random.

    To implement, set up a counter: 0, 1, 2, 3, … Pick a constant key. Then encrypt the counter using the key to get a non-repeating output. Then increment the counter ready to generate the next output. Because encryption is reversible then different inputs using the same key are guaranteed to give different outputs. Encryption is a one-to-one process.

    AES will give you 128 non-repeating bits, DES only goes to 64 bits. If 128 bits are not enough then you will have to do some research on larger block ciphers, such as Rijndael.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search