Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.php > #8490

Re: Random function

From "M. Strobel" <sorry_no_mail_here@nowhere.dee>
Newsgroups comp.lang.php
Subject Re: Random function
Date 2013-02-26 11:18 +0100
Message-ID <ap3gf6FepajU1@mid.uni-berlin.de> (permalink)
References <3bbc3c88-ba02-4c72-843a-b87b01bc7c6b@googlegroups.com> <kggpci$1sgb$2@yojimbo.hack>

Show all headers | View raw


Am 25.02.2013 23:42, schrieb Salvatore:
> On 2013-02-25, sonnichjensen@gmail.com <sonnichjensen@gmail.com> wrote:
>> I use the rand function to get 10 items of 1808 current itemes.
> 
> If you want ten random items from an array, you could try the following:
> 
> <?php
> // This is the big array you're pulling something out of.
> $lotsOfItems = array( /* ... */ );
> 
> // This is the empty array that will eventually contain the ten random
> // items.
> $tenRandomItems = array();
> 
> // Generate a range of numbers between 0 and the number of items minus
> // one.
> $range = range(0, count($lotsOfItems) - 1);
> 
> // Shuffle the array of numbers.
> shuffle($range);
> 
> while (count($tenRandomItems) < 10) {
>     $randomOffset = array_shift($range);
>     $tenRandomItems []= $lotsOfItems[$randomOffset];
> }
> ?>
> 
> Using this code, you will never, ever have a duplicate item. However, it
> will be far more computationally expensive than using rand() or
> mt_rand().
> 

Random number generation on computers is a research subject for at least 30 years.

You would never get anywhere near the current state of art with a self written solution.

/Str.

Back to comp.lang.php | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

Random function sonnichjensen@gmail.com - 2013-02-25 12:48 -0800
  Re: Random function Salvatore <sal@yojimbo.hack.invalid> - 2013-02-25 20:57 +0000
    Re: Random function Luuk <luuk@invalid.lan> - 2013-02-25 22:13 +0100
      Re: Random function Jerry Stuckle <jstucklex@attglobal.net> - 2013-02-25 16:42 -0500
      Re: Random function The Natural Philosopher <tnp@invalid.invalid> - 2013-02-25 22:12 +0000
      Re: Random function Robert Heller <heller@deepsoft.com> - 2013-02-25 19:46 -0600
  Re: Random function Jerry Stuckle <jstucklex@attglobal.net> - 2013-02-25 16:39 -0500
  Re: Random function The Natural Philosopher <tnp@invalid.invalid> - 2013-02-25 22:11 +0000
  Re: Random function Salvatore <sal@yojimbo.hack.invalid> - 2013-02-25 22:42 +0000
    Re: Random function "M. Strobel" <sorry_no_mail_here@nowhere.dee> - 2013-02-26 11:18 +0100
      Re: Random function Paul Herber <paul@pherber.com> - 2013-02-26 13:52 +0000
    Re: Random function Markus Grob <snoopy@ilnet.ch> - 2013-02-27 12:17 +0100
      Re: Random function Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2013-02-28 00:22 +0100

csiph-web