diff options
| author | Nicolas Mendoza <mendoza@pvv.ntnu.no> | 2025-09-29 13:44:24 +0200 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2025-09-29 13:44:24 +0200 |
| commit | 93bc75642d46b64d1afa127317c14fc968776827 (patch) | |
| tree | 4c15d2eb3c31dd96b2247c5c460fae47e28c5e58 | |
| parent | f3d59ebde11006c172e4da77a9cb8fa7fe6a9e30 (diff) | |
| parent | 9eb997933caae9aea353f9b2859ca9bb4e1cf432 (diff) | |
| download | perlweeklychallenge-club-93bc75642d46b64d1afa127317c14fc968776827.tar.gz perlweeklychallenge-club-93bc75642d46b64d1afa127317c14fc968776827.tar.bz2 perlweeklychallenge-club-93bc75642d46b64d1afa127317c14fc968776827.zip | |
Merge branch 'manwar:master' into 341
25 files changed, 980 insertions, 71 deletions
diff --git a/challenge-341/ash/raku/ch-1.raku b/challenge-341/ash/raku/ch-1.raku new file mode 100644 index 0000000000..ccd63a5848 --- /dev/null +++ b/challenge-341/ash/raku/ch-1.raku @@ -0,0 +1,18 @@ +# Task 1 of the Weekly Challenge 341 +# https://theweeklychallenge.org/blog/perl-weekly-challenge-341/#TASK1 + +say count-words('Hello World', ['d']); # 1 +say count-words('apple banana cherry', ['a', 'e']); # 0 +say count-words('Coding is fun', []); # 3 +say count-words('The Weekly Challenge', ['a','b']); # 2 +say count-words('Perl and Python', ['p']); # 1 + +sub count-words($string, @broken-keys) { + my @words = $string.lc.words; + my $possible-words = @words.elems; + for @words -> $word { + $possible-words-- if $word.comb (&) @broken-keys; + } + + return $possible-words; +} diff --git a/challenge-341/ash/raku/ch-2.raku b/challenge-341/ash/raku/ch-2.raku new file mode 100644 index 0000000000..1375a3ec4d --- /dev/null +++ b/challenge-341/ash/raku/ch-2.raku @@ -0,0 +1,14 @@ +# Task 2 of the Weekly Challenge 341 +# https://theweeklychallenge.org/blog/perl-weekly-challenge-341/#TASK2 + +say reverse-prefix('programming', 'g'); # gorpramming +say reverse-prefix('hello', 'h'); # hello +say reverse-prefix('abcdefghij', 'h'); # hgfedcbaij +say reverse-prefix('reverse', 's'); # srevere +say reverse-prefix('perl', 'r'); # repl + +sub reverse-prefix($word, $char) { + $word ~~ /^ (.*? $char) (.*) $/; + + return $/[0].flip ~ $/[1]; +} diff --git a/challenge-341/bob-lied/README.md b/challenge-341/bob-lied/README.md index ea96334263..e3e8ac2801 100644 --- a/challenge-341/bob-lied/README.md +++ b/challenge-341/bob-lied/README.md @@ -1,5 +1,5 @@ -# Solutions to weekly challenge 340 by Bob Lied +# Solutions to weekly challenge 341 by Bob Lied -## [PWC](https://perlweeklychallenge.org/blog/perl-weekly-challenge-340/) -## [GitHub](https://github.com/boblied/perlweeklychallenge-club/tree/master/challenge-340/bob-lied) +## [PWC](https://perlweeklychallenge.org/blog/perl-weekly-challenge-341/) +## [GitHub](https://github.com/boblied/perlweeklychallenge-club/tree/master/challenge-341/bob-lied) [Blog](https://dev.to/boblied/) diff --git a/challenge-341/bob-lied/perl/ch-1.pl b/challenge-341/bob-lied/perl/ch-1.pl new file mode 100644 index 0000000000..9215b554a0 --- /dev/null +++ b/challenge-341/bob-lied/perl/ch-1.pl @@ -0,0 +1,80 @@ +#!/usr/bin/env perl +# vim:set ts=4 sw=4 sts=4 et ai wm=0 nu: +#============================================================================= +# Copyright (c) 2025, Bob Lied +#============================================================================= +# ch-1.pl Perl Weekly Challenge 341 Task 1 Broken Keyboard +#============================================================================= +# You are given a string containing English letters only and also you +# are given broken keys. Write a script to return the total words in the +# given sentence can be typed completely. +# Example 1 Input: $str = 'Hello World', @keys = ('d') +# Output: 1 +# Example 2 Input: $str = 'apple banana cherry', @keys = ('a', 'e') +# Output: 0 +# Example 3 Input: $str = 'Coding is fun', @keys = () +# Output: 3 +# Example 4 Input: $str = 'The Weekly Challenge', @keys = ('a','b') +# Output: 2 +# Example 5 Input: $str = 'Perl and Python', @keys = ('p') +# Output: 1 +#============================================================================= + +use v5.42; + + +use Getopt::Long; +my $Verbose = false; +my $DoTest = false; +my $Benchmark = 0; + +GetOptions("test" => \$DoTest, "verbose" => \$Verbose, "benchmark:i" => \$Benchmark); +my $logger; +{ + use Log::Log4perl qw(:easy); + Log::Log4perl->easy_init({ level => ($Verbose ? $DEBUG : $INFO ), + layout => "%d{HH:mm:ss.SSS} %p{1} %m%n" }); + $logger = Log::Log4perl->get_logger(); +} +#============================================================================= + +exit(!runTest()) if $DoTest; +exit( runBenchmark($Benchmark) ) if $Benchmark; + +say $_ for @ARGV; # TODO command line processing here + +#============================================================================= +sub broken($str, @keys) +{ + my $re = '[' . join("", @keys) . ']'; + $re = '^$' if @keys == 0; + scalar grep !/$re/i, split(" ", $str); +} + +sub runTest +{ + use Test2::V0; + + my $str; my @keys; + $str = 'Hello World', @keys = ('d'); + is( broken($str, @keys), 1, "Example 1"); + $str = 'apple banana cherry', @keys = ('a', 'e'); + is( broken($str, @keys), 0, "Example 2"); + $str = 'Coding is fun', @keys = (); + is( broken($str, @keys), 3, "Example 3"); + $str = 'The Weekly Challenge', @keys = ('a','b'); + is( broken($str, @keys), 2, "Example 4"); + $str = 'Perl and Python', @keys = ('p'); + is( broken($str, @keys), 1, "Example 5"); + + done_testing; +} + +sub runBenchmark($repeat) +{ + use Benchmark qw/cmpthese/; + + cmpthese($repeat, { + label => sub { }, + }); +} diff --git a/challenge-341/bob-lied/perl/ch-2.pl b/challenge-341/bob-lied/perl/ch-2.pl new file mode 100644 index 0000000000..e001c7b4cf --- /dev/null +++ b/challenge-341/bob-lied/perl/ch-2.pl @@ -0,0 +1,75 @@ +#!/usr/bin/env perl +# vim:set ts=4 sw=4 sts=4 et ai wm=0 nu: +#============================================================================= +# Copyright (c) 2025, Bob Lied +#============================================================================= +# ch-2.pl Perl Weekly Challenge 341 Task 2 Reverse Prefix +#============================================================================= +# You are given a string, $str and a character in the given string, $char. +# Write a script to reverse the prefix upto the first occurrence of the +# given $char in the given string $str and return the new string. +# Example 1 Input: $str = "programming", $char = "g" +# Output: "gorpramming" +# Example 2 Input: $str = "hello", $char = "h" +# Output: "hello" +# Example 3 Input: $str = "abcdefghij", $char = "h" +# Output: "hgfedcbaij" +# Example 4 Input: $str = "reverse", $char = "s" +# Output: "srevere" +# Example 5 Input: $str = "perl", $char = "r" +# Output: "repl" +#============================================================================= + +use v5.42; + + +use Getopt::Long; +my $Verbose = false; +my $DoTest = false; +my $Benchmark = 0; + +GetOptions("test" => \$DoTest, "verbose" => \$Verbose, "benchmark:i" => \$Benchmark); +my $logger; +{ + use Log::Log4perl qw(:easy); + Log::Log4perl->easy_init({ level => ($Verbose ? $DEBUG : $INFO ), + layout => "%d{HH:mm:ss.SSS} %p{1} %m%n" }); + $logger = Log::Log4perl->get_logger(); +} +#============================================================================= + +exit(!runTest()) if $DoTest; +exit( runBenchmark($Benchmark) ) if $Benchmark; + +say $_ for @ARGV; # TODO command line processing here + +#============================================================================= +sub revPrefix($str, $char) +{ + my $upto = index($str, $char); + # my $prefix = substr($str, 0, 1+$upto); + # substr($str, 0, length($prefix)) = reverse($prefix); + return reverse( substr($str, 0, 1+$upto) ) . substr($str, $upto+1); +} + +sub runTest +{ + use Test2::V0; + + is( revPrefix("programming", "g"), 'gorpramming', "Example 1"); + is( revPrefix("hello", "h"), 'hello', "Example 2"); + is( revPrefix("abcdefghij", "h"), 'hgfedcbaij', "Example 3"); + is( revPrefix("reverse", "s"), 'srevere', "Example 4"); + is( revPrefix("perl", "r"), 'repl', "Example 5"); + + done_testing; +} + +sub runBenchmark($repeat) +{ + use Benchmark qw/cmpthese/; + + cmpthese($repeat, { + label => sub { }, + }); +} diff --git a/challenge-341/e-choroba/perl/ch-1.pl b/challenge-341/e-choroba/perl/ch-1.pl new file mode 100755 index 0000000000..473871cfa8 --- /dev/null +++ b/challenge-341/e-choroba/perl/ch-1.pl @@ -0,0 +1,20 @@ +#!/usr/bin/perl +use warnings; +use strict; +use experimental qw( signatures ); + +sub broken_keyboard($str, @keys) { + my @words = split ' ', $str; + return scalar @words unless @keys; + + my $regex = join "", @keys; + return grep ! /[\Q$regex\E]/i, @words +} + +use Test::More tests => 5; + +is broken_keyboard('Hello World', 'd'), 1, 'Example 1'; +is broken_keyboard('apple banana cherry', 'a', 'e'), 0, 'Example 2'; +is broken_keyboard('Coding is fun'), 3, 'Example 3'; +is broken_keyboard('The Weekly Challenge', 'a','b'), 2, 'Example 4'; +is broken_keyboard('Perl and Python', 'p'), 1, 'Example 5'; diff --git a/challenge-341/e-choroba/perl/ch-2.pl b/challenge-341/e-choroba/perl/ch-2.pl new file mode 100755 index 0000000000..063cbf7614 --- /dev/null +++ b/challenge-341/e-choroba/perl/ch-2.pl @@ -0,0 +1,20 @@ +#!/usr/bin/perl +use warnings; +use strict; +use experimental qw( signatures ); + +sub reverse_prefix($str, $char) { + my $i = 1 + index $str, $char; + return $str if 1 >= $i; + + substr $str, 0, $i, reverse substr $str, 0, $i; + return $str +} + +use Test::More tests => 5; + +is reverse_prefix('programming', 'g'), 'gorpramming', 'Example 1'; +is reverse_prefix('hello', 'h'), 'hello', 'Example 2'; +is reverse_prefix('abcdefghij', 'h'), 'hgfedcbaij', 'Example 3'; +is reverse_prefix('reverse', 's'), 'srevere', 'Example 4'; +is reverse_prefix('perl', 'r'), 'repl', 'Example 5'; diff --git a/challenge-341/feng-chang/raku/ch-1.raku b/challenge-341/feng-chang/raku/ch-1.raku new file mode 100755 index 0000000000..01b2cd6502 --- /dev/null +++ b/challenge-341/feng-chang/raku/ch-1.raku @@ -0,0 +1,5 @@ +#!/bin/env raku + +unit sub MAIN(Str:D $snt, *@keys); + +put +$snt.lc.words.grep(!*.contains(@keys.any)); diff --git a/challenge-341/feng-chang/raku/ch-2.raku b/challenge-341/feng-chang/raku/ch-2.raku new file mode 100755 index 0000000000..d775624c4c --- /dev/null +++ b/challenge-341/feng-chang/raku/ch-2.raku @@ -0,0 +1,7 @@ +#!/bin/env raku + +unit sub MAIN(Str:D $w, Str:D $c where *.chars == 1); + +with $w.index($c) + 1 -> $i { + put $w.substr(0,$i).flip, $w.substr($i); +} diff --git a/challenge-341/feng-chang/raku/test.raku b/challenge-341/feng-chang/raku/test.raku new file mode 100755 index 0000000000..9281ae83e4 --- /dev/null +++ b/challenge-341/feng-chang/raku/test.raku @@ -0,0 +1,28 @@ +#!/bin/env raku + +# The Weekly Challenge 341 +use Test; + +sub pwc-test(Str:D $script, Bool :$deeply? = False, *@input) { + my ($expect, $assertion) = @input.splice(*-2, 2); + my $p = run $script, |@input, :out; + if $deeply { + is-deeply $p.out.slurp(:close).chomp.words.Bag, $expect, $assertion; + } else { + is $p.out.slurp(:close).chomp, $expect, $assertion; + } +} + +# Task 1, Broken Keyboard +pwc-test './ch-1.raku', 'Hello World', <d>, 1, 'Broken Keyboard: "Hello World", @keys=<d> => 1'; +pwc-test './ch-1.raku', 'apple banana cherry', <a e>, 0, 'Broken Keyboard: "apple banana cherry", @keys=<a e> => 0'; +pwc-test './ch-1.raku', 'Coding is fun', 3, 'Broken Keyboard: "Coding is fun", @keys=<> => 3'; +pwc-test './ch-1.raku', 'The Weekly Challenge', <a b>, 2, 'Broken Keyboard: "The Weekly Challenge", @keys=<a b> => 2'; +pwc-test './ch-1.raku', 'Perl and Python', <p>, 1, 'Broken Keyboard: "Perl and Python", @keys=<p> => 1'; + +# Task 2, Reverse Prefix +pwc-test './ch-2.raku', 'programming', 'g', 'gorpramming', 'Reverse Prefix: programming g => gorpramming'; +pwc-test './ch-2.raku', 'hello', 'h', 'hello', 'Reverse Prefix: hello h => hello'; +pwc-test './ch-2.raku', 'abcdefghij', 'h', 'hgfedcbaij', 'Reverse Prefix: abcdefghij h => hgfedcbaij'; +pwc-test './ch-2.raku', 'reverse', 's', 'srevere', 'Reverse Prefix: reverse s => srevere'; +pwc-test './ch-2.raku', 'perl', 'r', 'repl', 'Reverse Prefix: perl r => repl'; diff --git a/challenge-341/lubos-kolouch/README b/challenge-341/lubos-kolouch/README index 7035227f5b..2e275f9d57 100644 --- a/challenge-341/lubos-kolouch/README +++ b/challenge-341/lubos-kolouch/README @@ -1,79 +1,33 @@ -Solutions by Lubos Kolouch. +# Perl Weekly Challenge: Broken Keyboard and Reverse Prefix -# The Weekly Challenge - 339 - -## Task 1: Max Diff +## Task 1: Broken Keyboard ### Description - -Given an array of at least four integers, find two disjoint pairs whose product -difference is as large as possible. The difference for pairs (a, b) and (c, d) -is `(a * b) - (c * d)`, and we are interested in the maximum absolute value of -this difference across all pair selections. +Given a string containing English letters and a list of broken keys, return the count of words that can be typed completely without using any broken keys. The check is case-insensitive. ### Solution +- **Perl (ch-1.pl)**: The `broken_keyboard` function splits the input string into words and checks each word against a hash of broken keys. If a word contains no broken keys, it increments a counter. The function uses `split` for word separation and a hash for O(1) key lookup. +- **Python (ch-1.py)**: The `broken_keyboard` function uses a set for broken keys lookup, splits the string into words, and counts words that don't contain any broken keys. It uses `str.split()` and a set for efficient lookup. -#### Perl (ch-1.pl) - -Enumerates every combination of four numbers, evaluates the three possible -pairings, and keeps the maximum absolute difference between the resulting -products. Input validation ensures the list has at least four elements, with -unit tests covering the provided examples. - -#### Python (ch-1.py) - -Uses `itertools.combinations` to iterate through all quadruples of integers and -checks the three pairings of each quadruple. Tracks the maximum absolute -product difference. Type hints and `unittest` cases cover the supplied -scenarios. +### Test Cases +1. Input: "Hello World", ['d'] → Output: 1 +2. Input: "apple banana cherry", ['a', 'e'] → Output: 0 +3. Input: "Coding is fun", [] → Output: 3 +4. Input: "The Weekly Challenge", ['a', 'b'] → Output: 2 +5. Input: "Perl and Python", ['p'] → Output: 1 -### Examples - -- Example 1: `[5, 9, 3, 4, 6]` → `42` -- Example 2: `[1, -2, 3, -4]` → `10` -- Example 3: `[-3, -1, -2, -4]` → `10` -- Example 4: `[10, 2, 0, 5, 1]` → `50` -- Example 5: `[7, 8, 9, 10, 10]` → `44` - -## Task 2: Peak Point +## Task 2: Reverse Prefix ### Description - -Given a list of altitude gains, starting from altitude zero compute the running -sum and report the highest altitude reached at any step. +Given a string and a character, reverse the prefix of the string up to and including the first occurrence of the character, and return the new string. If the character is not found, return the original string. ### Solution - -#### Perl (ch-2.pl) - -Processes the gains sequentially, maintaining the cumulative altitude and the -highest value encountered. Embedded tests verify the challenge examples. - -#### Python (ch-2.py) - -Updates the running altitude for each gain and retains the maximum altitude -seen. Includes type annotations and unit tests mirroring the provided cases. - -### Examples - -- Example 1: `[-5, 1, 5, -9, 2]` → `1` -- Example 2: `[10, 10, 10, -25]` → `30` -- Example 3: `[3, -4, 2, 5, -6, 1]` → `6` -- Example 4: `[-1, -2, -3, -4]` → `0` -- Example 5: `[-10, 15, 5]` → `10` - -## Running the Code - -### Perl - -```bash -perl ch-1.pl -perl ch-2.pl -``` - -### Python - -```bash -python3 ch-1.py -python3 ch-2.py -``` +- **Perl (ch-2.pl)**: The `reverse_prefix` function uses `index` to find the character's position, extracts the prefix with `substr`, reverses it, and appends the remaining string. +- **Python (ch-2.py)**: The `reverse_prefix` function uses `str.find` to locate the character, slices the prefix, reverses it using slice notation `[::-1]`, and concatenates the rest of the string. + +### Test Cases +1. Input: "programming", "g" → Output: "gorpramming" +2. Input: "hello", "h" → Output: "hello" +3. Input: "abcdefghij", "h" → Output: "hgfedcbaij" +4. Input: "reverse", "s" → Output: "srevere" +5. Input: "perl", "r" → Output: "repl" diff --git a/challenge-341/lubos-kolouch/perl/ch-1.pl b/challenge-341/lubos-kolouch/perl/ch-1.pl new file mode 100644 index 0000000000..a241d752c2 --- /dev/null +++ b/challenge-341/lubos-kolouch/perl/ch-1.pl @@ -0,0 +1,45 @@ +#!/usr/bin/env perl + +use strict; +use warnings; +use v5.10; + +# Module docstring +# Task 1: Broken Keyboard +# Given a string and a list of broken keys, returns the count of words that can be typed completely. + +sub broken_keyboard { + my ( $str, @broken_keys ) = @_; + + # Convert broken keys to a hash for O(1) lookup + my %broken = map { $_ => 1 } @broken_keys; + + # Split string into words + my @words = split /\s+/, $str; + my $count = 0; + + # Check each word + foreach my $word (@words) { + my $can_type = 1; + + # Check if word contains any broken key + foreach my $char ( split //, lc($word) ) { + if ( exists $broken{$char} ) { + $can_type = 0; + last; + } + } + $count++ if $can_type; + } + + return $count; +} + +# Unit tests +use Test::More tests => 5; + +is( broken_keyboard( 'Hello World', 'd' ), 1, 'Example 1: Hello World, d broken' ); +is( broken_keyboard( 'apple banana cherry', 'a', 'e' ), 0, 'Example 2: apple banana cherry, a,e broken' ); +is( broken_keyboard( 'Coding is fun', () ), 3, 'Example 3: Coding is fun, no broken keys' ); +is( broken_keyboard( 'The Weekly Challenge', 'a', 'b' ), 2, 'Example 4: The Weekly Challenge, a,b broken' ); +is( broken_keyboard( 'Perl and Python', 'p' ), 1, 'Example 5: Perl and Python, p broken' ); diff --git a/challenge-341/lubos-kolouch/perl/ch-2.pl b/challenge-341/lubos-kolouch/perl/ch-2.pl new file mode 100644 index 0000000000..a4f52e6cbe --- /dev/null +++ b/challenge-341/lubos-kolouch/perl/ch-2.pl @@ -0,0 +1,34 @@ +#!/usr/bin/env perl + +use strict; +use warnings; +use v5.10; + +# Module docstring +# Task 2: Reverse Prefix +# Given a string and a character, reverses the prefix up to the first occurrence of the character. + +sub reverse_prefix { + my ( $str, $char ) = @_; + + # Find position of first occurrence of char + my $pos = index( $str, $char ); + + # If char not found, return original string + return $str if $pos == -1; + + # Get prefix up to and including char + my $prefix = substr( $str, 0, $pos + 1 ); + + # Reverse prefix and append rest of string + return reverse($prefix) . substr( $str, $pos + 1 ); +} + +# Unit tests +use Test::More tests => 5; + +is( reverse_prefix( 'programming', 'g' ), 'gorpramming', 'Example 1: programming, g' ); +is( reverse_prefix( 'hello', 'h' ), 'hello', 'Example 2: hello, h' ); +is( reverse_prefix( 'abcdefghij', 'h' ), 'hgfedcbaij', 'Example 3: abcdefghij, h' ); +is( reverse_prefix( 'reverse', 's' ), 'srevere', 'Example 4: reverse, s' ); +is( reverse_prefix( 'perl', 'r' ), 'repl', 'Example 5: perl, r' ); diff --git a/challenge-341/lubos-kolouch/python/ch-1.py b/challenge-341/lubos-kolouch/python/ch-1.py new file mode 100644 index 0000000000..6c28d3106d --- /dev/null +++ b/challenge-341/lubos-kolouch/python/ch-1.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +""" +Task 1: Broken Keyboard +Given a string and a list of broken keys, returns the count of words that can be typed completely. +""" + +import unittest + + +def broken_keyboard(str_input: str, broken_keys: list[str]) -> int: + """ + Count words that can be typed with broken keys. + + Args: + str_input: Input string containing words + broken_keys: List of broken key characters + + Returns: + Number of words that can be typed completely + """ + # Convert broken keys to set for O(1) lookup + broken_set = set(broken_keys) + + # Split string into words + words = str_input.split() + count = 0 + + # Check each word + for word in words: + can_type = True + # Check if word contains any broken key + for char in word.lower(): + if char in broken_set: + can_type = False + break + if can_type: + count += 1 + + return count + + +# Unit tests + + +class TestBrokenKeyboard(unittest.TestCase): + + def test_example1(self): + """Test Example 1: Hello World, d broken""" + self.assertEqual(broken_keyboard("Hello World", ["d"]), 1) + + def test_example2(self): + """Test Example 2: apple banana cherry, a,e broken""" + self.assertEqual(broken_keyboard("apple banana cherry", ["a", "e"]), 0) + + def test_example3(self): + """Test Example 3: Coding is fun, no broken keys""" + self.assertEqual(broken_keyboard("Coding is fun", []), 3) + + def test_example4(self): + """Test Example 4: The Weekly Challenge, a,b broken""" + self.assertEqual(broken_keyboard("The Weekly Challenge", ["a", "b"]), + 2) + + def test_example5(self): + """Test Example 5: Perl and Python, p broken""" + self.assertEqual(broken_keyboard("Perl and Python", ["p"]), 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/challenge-341/lubos-kolouch/python/ch-2.py b/challenge-341/lubos-kolouch/python/ch-2.py new file mode 100644 index 0000000000..5a6e46156e --- /dev/null +++ b/challenge-341/lubos-kolouch/python/ch-2.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 +""" +Task 2: Reverse Prefix +Given a string and a character, reverses the prefix up to the first occurrence of the character. +""" + +import unittest + + +def reverse_prefix(str_input: str, char: str) -> str: + """ + Reverse prefix up to first occurrence of given character. + + Args: + str_input: Input string + char: Character to find + + Returns: + String with prefix reversed up to first occurrence of char + """ + # Find position of first occurrence of char + pos = str_input.find(char) + + # If char not found, return original string + if pos == -1: + return str_input + + # Get prefix up to and including char + prefix = str_input[:pos + 1] + + # Reverse prefix and append rest of string + return prefix[::-1] + str_input[pos + 1:] + + +# Unit tests + + +class TestReversePrefix(unittest.TestCase): + + def test_example1(self): + """Test Example 1: programming, g""" + self.assertEqual(reverse_prefix("programming", "g"), "gorpramming") + + def test_example2(self): + """Test Example 2: hello, h""" + self.assertEqual(reverse_prefix("hello", "h"), "hello") + + def test_example3(self): + """Test Example 3: abcdefghij, h""" + self.assertEqual(reverse_prefix("abcdefghij", "h"), "hgfedcbaij") + + def test_example4(self): + """Test Example 4: reverse, s""" + self.assertEqual(reverse_prefix("reverse", "s"), "srevere") + + def test_example5(self): + """Test Example 5: perl, r""" + self.assertEqual(reverse_prefix("perl", "r"), "repl") + + +if __name__ == "__main__": + unittest.main() diff --git a/challenge-341/mark-anderson/raku/ch-1.raku b/challenge-341/mark-anderson/raku/ch-1.raku new file mode 100644 index 0000000000..52cea38299 --- /dev/null +++ b/challenge-341/mark-anderson/raku/ch-1.raku @@ -0,0 +1,13 @@ +#!/usr/bin/env raku +use Test; + +is broken-keyboard("Hello World", [< d >] ), 1; +is broken-keyboard("apple banana cherry", [< a e >]), 0; +is broken-keyboard("Coding is fun", Empty), 3; +is broken-keyboard("The Weekly Challenge", [< a b >]), 2; +is broken-keyboard("Perl and Python", [< p >]), 1; + +sub broken-keyboard($str, @keys) +{ + $str.words.grep({ none /:i @keys/ }).elems +} diff --git a/challenge-341/mark-anderson/raku/ch-2.raku b/challenge-341/mark-anderson/raku/ch-2.raku new file mode 100644 index 0000000000..d7e2dd24db --- /dev/null +++ b/challenge-341/mark-anderson/raku/ch-2.raku @@ -0,0 +1,13 @@ +#!/usr/bin/env raku +use Test; + +is reverse-prefix("programming", "g"), "gorpramming"; +is reverse-prefix("hello", "h"), "hello"; +is reverse-prefix("abcdefghij", "h"), "hgfedcbaij"; +is reverse-prefix("reverse", "s"), "srevere"; +is reverse-prefix("perl", "r"), "repl"; + +sub reverse-prefix($str, $char) +{ + $str.subst(/(.*? $char)/, {$0.flip}) +} diff --git a/challenge-341/perlboy1967/perl/ch1.pl b/challenge-341/perlboy1967/perl/ch1.pl new file mode 100755 index 0000000000..a59ba86df6 --- /dev/null +++ b/challenge-341/perlboy1967/perl/ch1.pl @@ -0,0 +1,34 @@ +#!/bin/perl + +=pod + +L<https://theweeklychallenge.org/blog/perl-weekly-challenge-341#TASK1> + +Author: Niels 'PerlBoy' van Dijke + +Task 1: Broken Keyboard +Submitted by: Mohammad Sajid Anwar + +You are given a string containing English letters only and also you are given broken keys. + +Write a script to return the total words in the given sentence can be typed completely. + +=cut + +use Test2::V0 qw(-no_srand); +use exact 'v5.32', -signatures; + +sub brokenKeyboard ($str,@keys) { + my @w = split /\s+/,$str; + return scalar @w if (@keys == 0); + my $re = '['.join('',@keys).']'; + scalar grep !/$re/i, @w; +} + +is(brokenKeyboard('Hello World',qw(d)),1,'Example 1'); +is(brokenKeyboard('apple banana cherry',qw(a e)),0,'Example 2'); +is(brokenKeyboard('Coding is fun',qw()),3,'Example 3'); +is(brokenKeyboard('The Weekly Challenge',qw(ab)),2,'Example 4'); +is(brokenKeyboard('Perl and Python',qw(p)),1,'Example 5'); + +done_testing; diff --git a/challenge-341/perlboy1967/perl/ch2.pl b/challenge-341/perlboy1967/perl/ch2.pl new file mode 100755 index 0000000000..f3dbfcc126 --- /dev/null +++ b/challenge-341/perlboy1967/perl/ch2.pl @@ -0,0 +1,33 @@ +#!/bin/perl + +=pod + +L<https://theweeklychallenge.org/blog/perl-weekly-challenge-341#TASK2> + +Author: Niels 'PerlBoy' van Dijke + +Task 2: Reverse Prefix +Submitted by: Mohammad Sajid Anwar + +You are given a string, $str and a character in the given string, $char. + +Write a script to reverse the prefix upto the first occurrence of the given +$char in the given string $str and return the new string. + +=cut + +use Test2::V0 qw(-no_srand); +use exact 'v5.32', -signatures; + +sub reversePrefix ($str,$char) { + return reverse($1).$2 if ($str =~ m#^(.+?$char)(.*)#); + return $str; +} + +is(reversePrefix('programming','g'),'gorpramming','Example 1'); +is(reversePrefix('hello','h'),'hello','Example 2'); +is(reversePrefix('abcdefghij','h'),'hgfedcbaij','Example 3'); +is(reversePrefix('reverse','s'),'srevere','Example 4'); +is(reversePrefix('perl','r'),'repl','Example 5'); + +done_testing; diff --git a/challenge-341/pokgopun/go/ch-1.go b/challenge-341/pokgopun/go/ch-1.go new file mode 100644 index 0000000000..14a99c38f8 --- /dev/null +++ b/challenge-341/pokgopun/go/ch-1.go @@ -0,0 +1,88 @@ +//# https://theweeklychallenge.org/blog/perl-weekly-challenge-341/ +/*# + +Task 1: Broken Keyboard + +Submitted by: [39]Mohammad Sajid Anwar + __________________________________________________________________ + + You are given a string containing English letters only and also you are + given broken keys. + + Write a script to return the total words in the given sentence can be + typed completely. + +Example 1 + +Input: $str = |
