Task 1: Excel Column
Write a script that accepts a positive integer and converts it to its corresponding Excel column title, and vice versa.
Example Output
Input Number: 28 => Output: AB
Input Column Name: AD => Output: 30
Logic
For number-to-column, repeatedly subtract 1, take modulo 26 to map to letters A-Z, and divide by 26. For column-to-number, iterate through characters and accumulate using base 26 conversion (num = num * 26 + (ord(char) - ord('A') + 1)).
Perl Solution
ch-1.pl
sub number_to_excel_column {
my $num = shift;
my $column = '';
while ( $num > 0 ) {
$num--;
$column = chr( ( $num % 26 ) + ord('A') ) . $column;
$num = int( $num / 26 );
}
return $column;
}
sub excel_column_to_number {
my $column = shift;
my $num = 0;
for my $char ( split //, $column ) {
$num = $num * 26 + ( ord($char) - ord('A') + 1 );
}
return $num;
}
Python Solution
ch-1.py
def number_to_excel_column(num: int) -> str:
column = ""
while num > 0:
num -= 1
column = chr((num % 26) + ord("A")) + column
num //= 26
return column
def excel_column_to_number(column: str) -> int:
num = 0
for char in column:
num = num * 26 + (ord(char) - ord("A") + 1)
return num
Task 2: Find Numbers
Given a set of digits L, length X, and an integer Y, write a script to find all X-digit numbers formed using digits from L that are strictly less than Y.
Example Output
Input: L = [0, 1, 2, 5], X = 2, Y = 21
Output: 0, 1, 2, 5, 10, 11, 12, 15, 20
Logic
Recursively build all numbers of length X from digits in L. Once length X is reached, keep numbers strictly less than Y.
Perl Solution
ch-2.pl
sub generate_numbers {
my ( $list, $x, $y, $current ) = @_;
if ( $x == 0 ) {
return int($current) < $y ? ( int($current) ) : ();
}
my @result;
for my $num (@$list) {
push @result, generate_numbers( $list, $x - 1, $y, $current . $num );
}
return @result;
}
Python Solution
ch-2.py
def generate_numbers(numbers: List[int], x: int, y: int, current: str) -> List[int]:
if x == 0:
return [int(current)] if int(current) < y else []
result = []
for num in numbers:
result.extend(generate_numbers(numbers, x - 1, y, current + str(num)))
return result