How to select randomly M different banners out of N

If you participate in affiliate programs, you may want to put several ads of your advertisers in some standard area of your pages, like a bottom bar or side area. However if you have more advertisers to put there than space you may want to rotate their banners This is also a good idea, because if banners change with each reload, they get more attention.

A simple solution to that would be to select randomly M (how many fits into area) different banners out of N (how many advertisers you have). That's not a rocket science, but still a need to make them different makes it a bit more complex than just to shoot M times random number generator. Here is a simple solution which will work for up to 32 advertisers. If you have more, you'll have to replace bit mask with a boolean array.

Notice that though this page shows Javascript solution, you can do it as well in C or Perl (drop me a notice if you want to see solution in one of these language here). Which way to choose depends on many factors. First, if you have paid advertisers with a promised number of impressions, you may want to have it server-based, because only this way you can record how many impressions the ad made. However just for affiliate programs it is usually not necesary. Then server-side Javascript solution works fine. Because you will keep Javascript and ad HTML code in a separate *.js file, it will be loaded only once. So with client-side solution you trade a bit longer load time when visitor comes to your site first for a server-side smaller delays for CGI (or servlet/ASP, whatever) each time the page is requested.

And here is an example how to do that:


Reload this page and see the numbers change. We specially kept border for this table, so you'll see it. In your real-life bar you may want to sent "border=0".


And here is the code to implement this:

<script language="JavaScript"> function getRand(n) { var r = Math.round(Math.random()*n-0.5); if ( r < 0 ) { r=0; } return r; } var adBtns = new Array( // Button1 '<font size=+2 color=blue>1</font>', // Button2 '<font size=+2 color=green>2</font>', // Button3 '<font size=+2 color=yellow>3</font>', // Button4 '<font size=+2 color=red>4</font>', // Button5 '<font size=+2 color=gray>5</font>', // Button6 '<font size=+2 color=cyan>6</font>', // Button7 '<font size=+2 color=magenta>7</font>', // Button8 '<font size=+2 color=black>8</font>', // Button9 '<font size=+2 color=teal>9</font>', // Button10 '<font size=+2 color=pink>0</font>' ); function bottomBarAds() { var i, k, f = 0; document.write('<hr><table border="1" width="100%"><tr>'); for ( i=0; i<5; ) { k = getRand(adBtns.length); if ( ! (f & (1<<k)) ) { f |= 1<<k; i++; document.write('<td align="center">'+adBtns[k]+'</td>'); } } document.write('</tr></table>'); } </script> ... <script language=javascript> bottomBarAds(); </script>