in reply to Reading files sequentially

After you choose your index randomly, you could then just increment it by one to determine the next value.

However since you are doing a website, you may not want the same two ads to always appear next to each other. Therefore, I would do the following:

1. Read all the images in from the file
2. Shuffle the array
3. Pop one image off the end of the array
4. Repeat (3) until array is empty, then goto (1)

Check out (ar0n: Algorithm::Numerical::Shuffle) Re: Randomize an array and Answer: How do I shuffle an array? for code on how to shuffle an array.

Cheers,
Gryn

  • Comment on Random and sequential for the price of one!

Replies are listed 'Best First'.
RE: Random and sequential for the price of one!
by damian (Beadle) on Sep 15, 2000 at 07:09 UTC
    hi grying, thanks for the reply, but is it okay if you could demonstrate you seggestion in my code? thanks, arvin
      sub shuffle { my $array = shift; my $i; for ($i = @$array; --$i; ) { my $j = int rand ($i+1); next if $i == $j; @$array[$i,$j] = @$array[$j,$i]; } } my $counter = 10; # this is the number of images you want open DAT, "ads.dat" or die "Error: cannot open data file!"; my @item; while (my $c=<DAT>) { my ($id,$image,$url)=split(/\|/,$c); push @item, {"image"=>$image,"url"=>$url,"desc"=>$desc}; } close DAT; while ($counter) { my @itemtmp = @item; shuffle(\@itemtmp); while (my $i = pop @itemtmp) { $img = $i->{"image"}; $link = $i->{"url"}; print qq|Set-Cookie: URL=$link\n|; print qq|Location: $img\n\n|; last if --$counter == 0; } }
      Warning, in that I didn't test that code, I only thought about it, and ran it through the syntax checker. Hopefully that is clearer and will help you out!

      Ciao,
      Gryn

        hi, i've tried your code and it's fairly the same.... i think what i am thinking is impossible bec. i'm running the script on the <img src="ad.cgi"> tag. imagine if i have 3 tags that runs the same script simultaneously. it will sure that although you randomly display the image it's 100% that it may display 2 or 3 same images at a time right? thanks anyway