0 Replies - 1504 Views - Last Post: 31 May 2009 - 06:30 PM

#1 Ed_Bighead   User is offline

  • D.I.C Head
  • member icon

Reputation: 14
  • View blog
  • Posts: 178
  • Joined: 26-April 09

Kaprekar's Process for 3-digit numbers

Posted 31 May 2009 - 06:30 PM

Description: To exit, enter a negative number.This snippet determines the number of steps needed to complete Kaprekar's Process for any valid 3-digit number.
#!/usr/bin/perl
use warnings;
use strict;

# Prompt user and display number of steps
while(1) {
	print "ENTER A 3-DIGIT NUMBER: ";
	my $input = <>;
	chomp($input);

	if($input <= 0) {
		last;
	}
	elsif(isValidNumber($input)) {
		print "THE NUMBER $input TAKES ".getKap($input)." STEP(S) TO REACH 495.n";
	}
	print "n";
}

print "nGOODBYE.n";
exit;

# -- isValidNumber() ----------------
# Verifies that $num is 3-digits and
# does not have repeating digits.
# -----------------------------------
sub isValidNumber {
	my ($num) = @_;
	my @numDigits = split //, $num."";

	if (($num < 100 or $num > 999)
	  or ($numDigits[0] eq $numDigits[1] and $numDigits[1] eq $numDigits[2])) {
		print "INVALID NUMBER ENTEREDn";
		return 0;
	}
	else {
		return 1;
	}
}

# -- getKap() -----------------------
# Calls recursiveKap() to obtain the
# number of steps needed to complete
# Kaprekar's Process
# -----------------------------------
sub getKap {
	my ($num) = @_;
	my $numReverse;

	$num = join "", sort {$a <=> $b} (split //, $num);
	$numReverse = reverse "".$num;
	return recursiveKap($num,$numReverse,0);
}

# -- recursiveKap() ------------------
# Recursively obtains the number of
# steps needed to complete Kaprekar's
# Process.
# ------------------------------------
sub recursiveKap {
	my ($num,$numReverse,$count) = @_;
	my $diff = $numReverse - $num;
	my $diffReverse;

	print "$numReverse - $num = $diffn";

	$count++;
	if($diff == 495) {
		return $count;
	}
	else {
		$diff = join "", sort {$a <=> $b} (split //, $diff);
		$diffReverse = reverse "".$diff ;

		if(isValidNumber($diff)) {
			return recursiveKap($diff,$diffReverse,$count);
		}
		else {
			return "#";
		}
	}
}


Is This A Good Question/Topic? 0
  • +

Page 1 of 1