Robbie Hatley’s Solutions, in Perl, for The Weekly Challenge #357 (“Kaprekar Constant” and “Unique Fraction Generator”)
For those not familiar with "The Weekly Challenge", it is a weekly programming puzzle with two parts, with a new pair of tasks each Monday. You can find it here: The Weekly Challenge
The Weekly Challenge for the week of 2026-01-19 through 2026-01-25 is #357. The tasks for challenge #357 are as follows:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task 357-1: Kaprekar Constant
Submitted by: Mohammad Sajid Anwar
Write a function that takes a 4-digit integer and returns
how many iterations of the following algorithm are required
to reach Kaprekar’s constant (6174). (For more information about
Kaprekar's Constant, see "https://en.wikipedia.org/wiki/6174".)
1. Select any four-digit number that has at least two
different digits (leading zeros are allowed).
2. Create two new four-digit numbers by arranging the
original digits in a.) ascending and b.) descending order
(adding leading zeros if necessary).
3. Subtract the smaller number from the bigger number.
If the result is not 6174, return to step 2 and repeat.
Example inputs: ("3524","6174","9998","1001","9000","1111")
Expected outputs: ( 3 0 5 4 4 -1)
To solve this problem, I just run the calculations expressed on the linked web site and see what happens.
Robbie Hatley's Perl Solution to The Weekly Challenge 357-1
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task 357-2: Unique Fraction Generator
Submitted by: Yary
Given a positive integer N, generate all unique fractions you
can create using integers from 1 to N and follow the rules below:
- Use numbers 1 through N only (no zero)
- Create fractions like numerator/denominator
- List them in ascending order (from smallest to largest)
- If two fractions have the same value (like 1/2 and 2/4),
only show the one with the smallest numerator
Example 1
Input: $int = 3
Output: 1/3, 1/2, 2/3, 1/1, 3/2, 2/1, 3/1
Example 2
Input: $int = 4
Output: 1/4, 1/3, 1/2, 2/3, 3/4, 1/1, 4/3, 3/2, 2/1, 3/1, 4/1
Example 3
Input: $int = 1
Output: 1/1
Example 4
Input: $int = 6
Output: 1/6, 1/5, 1/4, 1/3, 2/5, 1/2, 3/5, 2/3, 3/4,
4/5, 5/6, 1/1, 6/5, 5/4, 4/3, 3/2, 5/3, 2/1,
5/2, 3/1, 4/1, 5/1, 6/1
Example 5
Input: $int = 5
Output: 1/5, 1/4, 1/3, 2/5, 1/2, 3/5, 2/3, 3/4, 4/5, 1/1,
5/4, 4/3, 3/2, 5/3, 2/1, 5/2, 3/1, 4/1, 5/1
We need only include integers (n/1), minimal fractions (1/m), and lowest-form fractions (n/m where 0!=n%m and 0!=m%n), because due to the way the problem is written, if a non-lowest fraction n/m exists, its lowest form will also.
Robbie Hatley's Perl Solution to The Weekly Challenge 357-2
That's it for challenge 357; see you on challenge 358!
Comments
Post a Comment