perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 357 - Task 1: Kaprekar Constant

  1 #!/usr/bin/env perl
  2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-357/#TASK1
  3 #
  4 # Task 1: Kaprekar Constant
  5 # =========================
  6 #
  7 # Write a function that takes a 4-digit integer and returns how many iterations are required to reach Kaprekar’s constant (6174). For more information about Kaprekar's Constant please follow the wikipedia page.
  8 ## Example 1
  9 ##
 10 ## Input: $int = 3524
 11 ## Output: 3
 12 ##
 13 ## Iteration 1: 5432 - 2345 = 3087
 14 ## Iteration 2: 8730 - 0378 = 8352
 15 ## Iteration 3: 8532 - 2358 = 6174
 16 #
 17 #
 18 ## Example 2
 19 ##
 20 ## Input: $int = 6174
 21 ## Output: 0
 22 #
 23 #
 24 ## Example 3
 25 ##
 26 ## Input: $int = 9998
 27 ## Output: 5
 28 ##
 29 ## Iteration 1: 9998 - 8999 = 0999
 30 ## Iteration 2: 9990 - 0999 = 8991
 31 ## Iteration 3: 9981 - 1899 = 8082
 32 ## Iteration 4: 8820 - 0288 = 8532
 33 ## Iteration 5: 8532 - 2358 = 6174
 34 #
 35 #
 36 ## Example 4
 37 ##
 38 ## Input: $int = 1001
 39 ## Output: 4
 40 ##
 41 ## Iteration 1: 1100 - 0011 = 1089
 42 ## Iteration 2: 9810 - 0189 = 9621
 43 ## Iteration 3: 9621 - 1269 = 8352
 44 ## Iteration 4: 8532 - 2358 = 6174
 45 #
 46 #
 47 ## Example 5
 48 ##
 49 ## Input: $int = 9000
 50 ## Output: 4
 51 ##
 52 ## Iteration 1: 9000 - 0009 = 8991
 53 ## Iteration 2: 9981 - 1899 = 8082
 54 ## Iteration 3: 8820 - 0288 = 8532
 55 ## Iteration 4: 8532 - 2358 = 6174
 56 #
 57 #
 58 ## Example 6
 59 ##
 60 ## Input: $int = 1111
 61 ## Output: -1
 62 ##
 63 ## The sequence does not converge on 6174, so return -1.
 64 #
 65 ############################################################
 66 ##
 67 ## discussion
 68 ##
 69 ############################################################
 70 #
 71 # First, we check a few basic parameters and catch the case of
 72 # 6174 as input. Then we run through a loop where we calculate
 73 # the next number until we finally reach 6174, keeping track
 74 # of the amount of steps until we reach that point.
 75 #
 76 use v5.36;
 77 
 78 kaprekar_constant(3524);
 79 kaprekar_constant(6174);
 80 kaprekar_constant(9998);
 81 kaprekar_constant(1001);
 82 kaprekar_constant(9000);
 83 kaprekar_constant(1111);
 84 
 85 sub kaprekar_constant($int) {
 86     say "Input: $int";
 87     return say "Not 4 digits: $int" unless length($int) == 4;
 88     return say "Output: 0" if $int == 6174;
 89     my $count = 0;
 90     while($int != 6174) {
 91         my @sorted = sort {$a <=> $b} split //, $int;
 92         my @sorted_r = reverse @sorted;
 93         my $s = join("", @sorted);
 94         my $s_r = join("", @sorted_r);
 95         # by sort order, $s is <= $s_r
 96         return say "Output: -1: $s = $s_r" if $s eq $s_r;
 97         $s =~ s/^0*//;
 98         $int = sprintf("%04d", $s_r - $s);
 99         $count++;
100     }
101     say "Output: $count";
102 }