Determine if a string is a rotation a given string using Perl

Input Sample:

Hello, lloHe

Output Sample:

true

Script:

open(INFILE, "$ARGV[0]") or die("Cannot open file $_[0] for reading: $!");

    while(my $line = <INFILE>) {
	chomp($line);
	my $i=0,$position,$count=0,$j,$flag = 1;
	my @arg = split(/,/,$line);
	my @word1 = split(//,$arg[0]);
	my @word2 = split(//,$arg[1]);
	my $len1 = scalar(@word1) - 1;
	my $len2 = scalar(@word2) - 1;
	if($len1 != $len2){
		print "False\n";
		next;
	}

	foreach(@word2){
		if($_ eq $word1[0]){
			$position = $count;
			last;
		}
		$count++;
	}

	for($i=0;$i <= $len1;$i++){
		if($position > $len2){
			$position = 0;
		}
		if($word1[$i] eq $word2[$position]){
			$position++;
			next;
		}else{
			print "False\n";
			$flag = 0;
			last;
		}
	}
	if($flag eq 1){
		print "True\n";
	}

}

close(INFILE);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s