Uniquely Constant with Raku

11 hours ago 3 views raku-musings.com raku-musings.com

Input: $int = 3524 Output: 3

Iteration 1: 5432 - 2345 = 3087 Iteration 2: 8730 - 0378 = 8352 Iteration 3: 8532 - 2358 = 6174

Input: $int = 6174 Output: 0

Input: $int = 9998 Output: 5

Iteration 1: 9998 - 8999 = 0999 Iteration 2: 9990 - 0999 = 8991 Iteration 3: 9981 - 1899 = 8082 Iteration 4: 8820 - 0288 = 8532 Iteration 5: 8532 - 2358 = 6174

Input: $int = 1001 Output: 4

Iteration 1: 1100 - 0011 = 1089 Iteration 2: 9810 - 0189 = 9621 Iteration 3: 9621 - 1269 = 8352 Iteration 4: 8532 - 2358 = 6174

Input: $int = 1111 Output: -1

The sequence does not converge on 6174, so return -1.

#! /usr/bin/env raku

unit sub MAIN (Int $int is copy where 1000 <= $int <= 9999, # [1] :v(:$verbose));

my $iterations = 0; # [2] constant $target = 6174; # [3]

while $int != $target # [4] { $iterations++; # [5]

my $small = $int.comb.sort.join; # [6] my $large = $small.flip; # [7]

$large *= 10 while $large < 1000; # [8]

$int = $large - $small; # [9]

say ": $iterations: $large - $small = $int" if $verbose;

{ say "-1"; exit; } unless $int; # [10] }

say $iterations; # [11]

$ ./kaprekar-constant 3524 3

$ ./kaprekar-constant 6174 0

$ ./kaprekar-constant 9998 5

$ ./kaprekar-constant 1001 4

$