The Weekly Challenge 026

Stones & Jewels and Mean Angle

Solutions on GitHub

Task 1: Stones and Jewels / Common Characters

Write a script to find the number of common characters between two strings. Specifically, count how many characters in a "jewels" string are present in a "stones" string (case-sensitive).

Example Output

Input: stones = "chancellor", jewels = "chocolate" Output: 8 Input: stones = "abcde", jewels = "fghi" Output: 0

Logic

For each character in the second word/jewels string, check if it exists in the first word/stones string. Increment the count if it matches. In Python, this is optimized by converting the stones string to a set for $O(1)$ lookups.

Perl Solution

ch-1.pl

sub get_common_chars { my ( $word1, $word2 ) = @_; my $count = 0; for ( split //, $word1 ) { $count++ if $word2 =~ /$_/msx; } return $count; }

Python Solution

ch-1.py

def count_matching_letters(stones: str, jewels: str) -> int: stone_set = set(stones) return sum(1 for ch in jewels if ch in stone_set)

Task 2: Mean Angle

Given a list of angles in degrees, compute the circular mean of the angles.

Example Output

Input: 0, 0, 90 Output: 26.6 (degrees)

Logic

We convert the input angles from degrees to radians, then compute the sums of their sines and cosines. Using atan2(y, x) (where $y$ is the sum of sines, and $x$ is the sum of cosines), we calculate the mean angle in radians, and convert it back to degrees. We can normalize the result to be between 0 and 360 degrees using modulo arithmetic.

Perl Solution

ch-2.pl

use Math::Trig; sub get_mean { my @angles = @_; my ( $sin_sum, $cos_sum ); for (@angles) { $sin_sum += sin( deg2rad($_) ); $cos_sum += cos( deg2rad($_) ); } return rad2deg( atan2( $sin_sum, $cos_sum ) ); }

Python Solution

ch-2.py

def mean_angle(degrees: list[float]) -> float: radians = [math.radians(angle) for angle in degrees] x = sum(math.cos(angle) for angle in radians) y = sum(math.sin(angle) for angle in radians) mean = math.degrees(math.atan2(y, x)) return mean % 360.0