Last active
June 18, 2016 21:23
-
-
Save colinvh/388d39d0b41527c23600d602876034c0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
# PRAGMA | |
use warnings; | |
use strict; | |
# DECLARE | |
sub kaprekar_distance(_); | |
sub fmt(_); | |
# CONFIGURE | |
$, = " "; | |
$\ = "\n"; | |
our $DEBUG = 0; | |
# MAIN | |
if (@ARGV) { | |
print @$_ for map {[fmt, kaprekar_distance]} @ARGV; | |
} else { | |
print map kaprekar_distance, 0 .. 9999; | |
} | |
# DEFINE | |
sub fmt(_) { sprintf "%04d", $_[0] } | |
sub kaprekar_distance(_) { | |
my $n = int shift; | |
return "X" if $n > 9999; | |
return "Z" if $n < 0; | |
return 0 if $n == 6174; # Kaprekar's constant | |
my $n = fmt $n; | |
return "*" if $n =~ /(\d)\1{3}/; # quads make 0 instead of converging to K | |
my $sorted = join "", sort split //, $n; | |
my $reversed = reverse $sorted; | |
my $new = $reversed - $sorted; | |
print STDERR "$reversed - $sorted = $new" if $DEBUG; | |
return 1 + kaprekar_distance $new; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment