#!/usr/bin/perl
# Written by JD Baldwin Aug 2014 (in response to a Facebook posting
# about this number). Just a simple demo of walking from any
# four-digit number (not with all the same digits) to Kaprekar's
# constant.
#
# I was a little surprised that I couldn't find sample code to do it,
# so I wrote some.
#
# Email @ panix.com with questions or comments.
use strict;
use warnings;
my $n = 0;
die "Usage: $0 \n" if not defined $ARGV[0];
$n = $ARGV[0];
chomp $n;
$n =~ s/\s//g;
if ( $n !~ m/^[0-9]{4}$/ )
{
die "$n is not a four-digit number\n";
}
if ( $n =~ m/^([0-9])\1\1\1$/ )
{
die "Number cannot have all the same digits"
}
my $i = 1;
printf( "Initial n = %04d ...\n", $n );
while ( 1 ) # It's an odd way to loop, but I find it intuitive.
{
printf( "Iteration %d: ", $i++ );
my @fwrd = sort split( //, sprintf( "%04d", $n ) );
my @rvrs = reverse @fwrd;
my $f = join( '', @fwrd );
my $r = join( '', @rvrs );
my $larger = $f > $r ? $f : $r;
my $smaller = $f > $r ? $r : $f;
my $diff = $larger - $smaller;
printf( "%04d - %04d == %04d\n", $larger, $smaller, $diff );
$n = $diff;
exit 0 if $n == 6174;
}