Random number generation without duplicates

I need to show some banners on a web page. The number of banners will be from 10 (maximum 10). I can set the number of banners and each banner folder in the database. Banner images are stored in separate server folders depending on the category. Banners are displayed in columns.

My code, Here long1, long2, ... long10 are the directory names from the database

$array=array(); for($n=1;$n<=$long;$n++) { $files = array(); $dir=${'long'.$n}; if(is_dir($dir)) { $openDir = opendir($dir); while (false !== ($file = readdir($openDir))) { if ($file != "." && $file != "..") { $files[] = $file; } } closedir($openDir); } mt_srand((double) microtime()*1000000); $randnum = mt_rand(0,(sizeof($files)-1)); $arraycount=count($array); for($index=0;$index<=$arraycount;$index++) { if(!in_array($array,$randnum)) { $array[]=$randnum; } } $img = $dir."/".$files[$randnum]; <input type="image" class="advt_image" src="<?=$img;?>" alt="" name=""/> } 

ex: if 7 banners are installed in the database, I have to show 7 banners from another or the same folder (some banners will be from the same folder). I need to avoid duplicating banners every time I display a web page.

I assigned an array to store each random number. Do I need to change something in the code? any thought / idea?

Thanks!

+4
source share
3 answers

You can remove the image displayed from the $ files array in a loop. this means that you will also need to check the length of the array in the loop. you can use array_diff for this.

 $files = array(...); // this holds the files in the directory $banners = array(); // this will hold the files to display $count = 7; for($i=0;$i<$count;$i++) { $c = mt_rand(0,count($files)); $banners[] = $files[$c]; $files = array_diff($files, array($files[$c])); } // now go ahead and display the $banners 
0
source
  • put the identifiers of your banner in an array. Each time will happen once.
  • shuffle this array using Knuth shuffle
  • emit the first 10 in HTML output
+1
source

An easy way to solve this problem is to create an array to store a list of banners than before displaying them.

I have not read your code (Sorry), but here is the basic concept with which this is possible.

 $bannerList = array(); //Now, check if the list contains the banner before adding it while($rows) { //your big list of banners if(!in_array($rows['bannerpath'])) { $bannerList[] = $rows['bannerpath']; } } 
0
source

All Articles