doupang5433 2015-08-01 11:53
浏览 326
已采纳

PHP - 从键生成指定范围内的随机整数

I have a set of questions with unique IDs in a MySQL database. Users also have a unique ID and are to answer these questions and their answers are saved in the database.

Now, I want users to get 5 non-repeating uniquely and randomly picked questions from the pool of available ones (let's say 50) based on users ID. So when a user with id 10 starts answering his questions, but stops and wants to return later to the same page, he will get the same questions as before. A user with id 11 will get a different random set of questions, but it will always be the same for him and different from all other users.

I found that random.org can generate exactly what I need with their sequence generator that generates a random sequence of numbers based on provided ID: https://www.random.org/sequences/?min=1&max=50&col=1&format=plain&rnd=id.10 But I would like the generation to be done locally instead of relying random.org API.

So, I need to generate 'X' unique random integers, within specified range 'Y' that are generated based on supplied integer 'Z'. I should be able to call a function with 'Z' as parameter and receive back the same 'X' integers every time.

I need to know how to replicate this generation with PHP code or at least a push or hint in a direction of a PHP function, pseudo-code or code snippet that will allow me to do it myself. Thank you in advance!

  • 写回答

5条回答 默认 最新

  • doujiao3016 2015-08-01 12:42
    关注

    Why reinvent the wheel

    mt_srand(44);
    for ($i=0; $i < 10; $i++) echo mt_rand(). "
    ";
    echo "
    
    ";
    mt_srand(44);
    for ($i=0; $i < 10; $i++) echo mt_rand(). "
    ";
    

    result

    362278652
    928876241
    1914830862
    68235862
    1599103261
    790008503
    1366233414
    1758526812
    771614145
    1520717825
    
    
    362278652
    928876241
    1914830862
    68235862
    1599103261
    790008503
    1366233414
    1758526812
    771614145
    1520717825
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?