Task 1: Reverse String
You are given a string. Write a script to reverse the given string without using the standard reverse function.
Example Output
Input: $str = "weekly"
Output: "ylkeew"
Input: $str = "challenge"
Output: "egnellahc"
Logic
Iterate through the characters of the input string, building a new string by prepending each character sequentially, thus reversing the sequence without utilizing the built-in reverse function.
Perl Solution
ch-1.pl
sub reverse_string ($str) {
my $reversed = "";
for my $char (split //, $str) {
$reversed = $char . $reversed;
}
return $reversed;
}
Python Solution
ch-1.py
def reverse_string(s: str) -> str:
reversed_str = ""
for char in s:
reversed_str = char + reversed_str
return reversed_str
Task 2: Armstrong Number
Find all Armstrong numbers in base $base less than $limit (with the results outputted in base 10).
Example Output
Input: $base = 3, $limit = 20
Output: [0, 1, 2, 5, 8, 17]
Input: $base = 10, $limit = 1000
Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407]
Logic
Convert each base 10 integer N within the range [0, limit-1] to its digits in base base. Raise each digit to the power of the total number of digits, and sum them. If the resulting sum equals N, then N is an Armstrong number in that base.
Perl Solution
ch-2.pl
sub get_digits_base ($num, $base) {
if ($num == 0) {
return (0);
}
my @digits;
my $temp = $num;
while ($temp > 0) {
push @digits, $temp % $base;
$temp = int($temp / $base);
}
return @digits;
}
sub is_armstrong ($num, $base) {
my @digits = get_digits_base($num, $base);
my $k = scalar @digits;
my $sum = 0;
for my $digit (@digits) {
$sum += $digit ** $k;
}
return $sum == $num ? 1 : 0;
}
sub find_armstrongs ($base, $limit) {
my @result;
for my $i (0 .. $limit - 1) {
if (is_armstrong($i, $base)) {
push @result, $i;
}
}
return \@result;
}
Python Solution
ch-2.py
def get_digits_base(num: int, base: int) -> list[int]:
if num == 0:
return [0]
digits = []
temp = num
while temp > 0:
digits.append(temp % base)
temp //= base
return digits
def is_armstrong(num: int, base: int) -> bool:
digits = get_digits_base(num, base)
k = len(digits)
return sum(d**k for d in digits) == num
def find_armstrongs(base: int, limit: int) -> list[int]:
return [i for i in range(limit) if is_armstrong(i, base)]