Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Random while statement does not exit

Status
Not open for further replies.

NateBro

Programmer
Sep 1, 2004
233
US
i'm trying to write a script that will generate 95 random numbers. basically i have a file that has 95 lines in it and i want it to randomly mix them up. i tried writing the below code, but it does not exit and keeps crashing.

Code:
open(FILE, "Format.txt");
@Coded = <FILE>;
close(FILE);

@MyUsed;
$NumberCheck;
for($i=0;$i<=$#Regulare;$i++){
# $Regulare[$i] =~ s/\n//g;
$lower=0;
$upper=$#Coded;
$random = int(rand( $upper-$lower+1 ) ) + $lower; 
	while (! $NumberCheck){
	CheckRandom($random);
	}
@MyUsed = (@MyUsed, "$random");
}
open(FILE, "> DoneCode.txt");
print FILE "@MyUsed";
close(FILE);


sub CheckRandom(){
    my ($rand) = @_;
    for($n=0;$n<=$#MyUsed;$n++){
    $myNumber = $MyUsed[$n];
    if ($myNumber == $rand){
    $random = int(rand( $upper-$lower+1 ) ) + $lower;
    } else {
    $NumberCheck = 1;
    }
    }
}

if there is another way to do this please let me know,
thanks so much for your time!

~ Nate_Bro
 
I'd start by using strict.

What is @Regulare, and where is it created?

--Paul

Spend an hour a week on CPAN, helps cure all known programming ailments ;-)
 
I concur.

Not using strict is flirting with the devil... but be careful, he has a nasty bite!
 
Just for fun, try this and see if it's any use:
Code:
perl -lne 'print sort { rand() <=> rand() } <>;' file_to_mix


Trojan.
 
Here's another one-liner:
Code:
perl -MList::Util -le  "map {chomp; print} List::Util::shuffle(<>)" file_to_mix
 
thats what the module rharsh used is for, along with a few other options:

List::Util

I'm pretty sure it's a core module so you should hopefully have it in your perl installation.
 
ok, very nice, I'll try those!
thanks for your help! :D
 
Ok, this was exactly was i was looking for!

Code:
my @MyRandSort = sort { rand() <=> rand() } @Regulare;

Thank you soooooo much!
 
perl -lne 'print sort { rand() <=> rand() } <>;' file_to_mix

when I looked at that I thought it would generate duplictes in the new list, but it doesn't.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top