生成随机数不重复 [英] Generating random numbers without repeats

查看:149
本文介绍了生成随机数不重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要建一个网站,将随机显示一个Yelp的上市,每次刷新页面。在Yelp的搜索API返回数组中的20上市。现在,我使用PHP的函数rand(0,19)每次页面刷新时间来生成一个随机的上市($企业[兰特(0,19)])。

有人可以参考我一个更聪明的方法来随机?我想告诉所有20个目录前一次其中的任何重复。什么是preferred方法来处理这​​个问题呢?

下面的答案不起作用,因为数字是我每次刷新页面重新创建。我猜我需要存储哪些号码我已经用?

  $数=范围(0,19);

洗牌($号);
 


  //处理Yelp的响应数据
$响应= json_de code($的数据);
$ RANDOM =兰特(1,19);
$业务= $响应 - >企业;

回声< IMG的边界= 0 SRC =$事业[$ RANDOM]  - > IMAGE_URL'>< BR />中;
回声$事业[$ RANDOM]  - >名称< BR />中。
回声< IMG的边界= 0 SRC =$事业[$ RANDOM]  - > rating_img_url_large'>< BR />中;

?>
 

解决方案

最简单的方法:

  $数=范围(1,20);
洗牌($号);
 

另一种方法:

 < PHP

功能randomGen($分,$最大,$数量){
    $数=范围($分,$最大值);
    洗牌($号);
    返回array_slice($数字,0,$量);
}

的print_r(randomGen(0,20,20)); //生成20个独特的随机数

?>
 

类似的问题:#5612656

codePAD: HTTP://$c$cpad.org/cBaGHxFU

更新:

你得到所有房源中称为数组 $企业

  1. 生成使用上面给出的方法随机上市的ID,然后将其存储数据库表。
  2. 在每一页刷新,随机生成一个列表ID,并检查它是否在你的数据库中的值相匹配。如果不是,显示上市和值添加到您的餐桌。
  3. 转到步骤1。

准备工作完成后,你会立即显示所有的20个目录。

希望这有助于!

I'm building a website that will randomly display a yelp listing each time the page is refreshed. The yelp search api returns 20 listings in an array. Right now, I am using PHP's function rand(0,19) to generate a random listing every time the page is refreshed ( $businesses[rand(0,19)] ).

Can someone refer me to a smarter method to randomize? I want to show all 20 listings once before any of them are repeated. What is the preferred method to handle this problem?

the below answer doesn't work because the numbers are recreated every time I refresh the page. I'm guessing I need to store which numbers I've used already?

$numbers = range(0, 19);

shuffle($numbers);


// Handle Yelp response data
$response = json_decode($data);
$RANDOM = rand(1,19);
$business = $response->businesses;

echo "<img border=0 src='".$business[$RANDOM]->image_url."'><br/>";
echo $business[$RANDOM]->name."<br/>";
echo "<img border=0 src='".$business[$RANDOM]->rating_img_url_large."'><br/>";

?>

解决方案

Easiest solution:

$numbers = range(1, 20);
shuffle($numbers);

Alternative:

<?php

function randomGen($min, $max, $quantity) {
    $numbers = range($min, $max);
    shuffle($numbers);
    return array_slice($numbers, 0, $quantity);
}

print_r(randomGen(0,20,20)); //generates 20 unique random numbers

?>

Similar question: #5612656

Codepad: http://codepad.org/cBaGHxFU

Update:

You're getting all the listings in an array called $businesses.

  1. Generate a random listing ID using the method given above, and then store it your database table.
  2. On each page refresh, generate a random listing ID, and check if it matches the value in your database. If not, display that listing and add that value to your table.
  3. Go to step 1.

When this is completed, you will have displayed all the 20 listings at once.

Hope this helps!

这篇关于生成随机数不重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆