The Weekly Challenge 034

Array/Hash Slices and Dispatch Table

Solutions on GitHub

Task 1: Array and Hash Slices

Write a script to demonstrate using array slices and hash slices.

Example Output

First three elements: 1, 2, 3 Last five elements: 6, 7, 8, 9, 10 Ages: 27, 32, 24

Logic

An array slice allows extracting multiple elements from an array at once using a list of indices. A hash slice allows extracting multiple values from a hash/dictionary by specifying a list of keys.

Perl Solution

ch-1.pl

my @numbers = ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ); print "First three elements: ", join( ", ", @numbers[ 0 .. 2 ] ), "\n"; print "Last five elements: ", join( ", ", @numbers[ -5 .. -1 ] ), "\n"; my @names = ( "Alice", "Bob", "Charlie", "Dave", "Emily" ); my %ages = ( "Alice" => 27, "Charlie" => 32, "Emily" => 24 ); print "Ages: ", join( ", ", @ages{ @names[ 0, 2, 4 ] } ), "\n";

Python Solution

ch-1.py

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(f"First three elements: {numbers[:3]}") print(f"Last five elements: {numbers[-5:]}") ages = {"Alice": 27, "Bob": 31, "Charlie": 32, "Dave": 29, "Emily": 24} names = ["Alice", "Charlie", "Emily"] print(f"Ages: {[ages[name] for name in names]}")

Task 2: Dispatch Table

Write a script to demonstrate using a dispatch table. A dispatch table is a table (or hash) of subroutine references.

Example Output

5 4 24 5

Logic

Map operation names (e.g. "add", "subtract") to their corresponding function references in a hash/dictionary. To perform an operation dynamically, look up the operation key in the table and invoke the mapped function with the given arguments.

Perl Solution

ch-2.pl

sub add { $_[0] + $_[1] } sub subtract { $_[0] - $_[1] } sub multiply { $_[0] * $_[1] } sub divide { $_[0] / $_[1] } my %operation_table = ( "add" => \&add, "subtract" => \&subtract, "multiply" => \&multiply, "divide" => \÷ ); sub perform_operation { my ( $operation, $a, $b ) = @_; if ( exists $operation_table{$operation} ) { return $operation_table{$operation}->( $a, $b ); } die "Unknown operation '$operation'"; }

Python Solution

ch-2.py

def add(a, b): return a + b def subtract(a, b): return a - b def multiply(a, b): return a * b def divide(a, b): return a / b operation_table = { "add": add, "subtract": subtract, "multiply": multiply, "divide": divide, } def perform_operation(operation, a, b): if operation in operation_table: return operation_table[operation](a, b) raise ValueError(f"Unknown operation '{operation}'")