From bc55d00ca1d2896f8f7fe87e7f5b26df1fefcd85 Mon Sep 17 00:00:00 2001 From: Matthew Neleigh Date: Mon, 5 Feb 2024 03:55:41 -0500 Subject: new file: challenge-255/mattneleigh/perl/ch-1.pl new file: challenge-255/mattneleigh/perl/ch-2.pl --- challenge-255/mattneleigh/perl/ch-1.pl | 104 +++++++++++++++++++++++++++++++++ challenge-255/mattneleigh/perl/ch-2.pl | 97 ++++++++++++++++++++++++++++++ 2 files changed, 201 insertions(+) create mode 100755 challenge-255/mattneleigh/perl/ch-1.pl create mode 100755 challenge-255/mattneleigh/perl/ch-2.pl diff --git a/challenge-255/mattneleigh/perl/ch-1.pl b/challenge-255/mattneleigh/perl/ch-1.pl new file mode 100755 index 0000000000..5d10cd0028 --- /dev/null +++ b/challenge-255/mattneleigh/perl/ch-1.pl @@ -0,0 +1,104 @@ +#!/usr/bin/perl + +use strict; +use warnings; +use English; + +################################################################################ +# Begin main execution +################################################################################ + +my @string_pairs = ( + # Given cases + [ "Perl", "Preel" ], + [ "Weekly", "Weeakly" ], + [ "Box", "Boxy" ], + + # Additional test cases + [ "Pizza", "Pizzeria" ], + [ "No", "Match" ], + [ "Peer", "Peerless" ] +); + +print("\n"); +foreach my $string_pair (@string_pairs){ + printf( + "Input: \$s = \"%s\"\n \$t = \"%s\"\nOutput: %s\n\n", + @{$string_pair}, + join( + ", ", + find_additional_characters(@{$string_pair}) + ) + ); +} + +exit(0); +################################################################################ +# End main execution; subroutines follow +################################################################################ + + + +################################################################################ +# Given two strings, find the characters in the second that are NOT present in +# the first, with quantity of characters being taken into account rather than +# mere presence alone (see below) +# Takes two arguments: +# * The first string (e.g. "Peer" ) +# * The second string (e.g. "Peerless" ) +# Returns: +# * A lexicographically sorted list of characters that are present in the +# second string but not in the first (e.g. ( "e", "l", "s", "s" ) ). Note +# that 'e' is included once and 's' is included twice as that represents the +# number of times each appears more in the second string than in the first. +################################################################################ +sub find_additional_characters{ + + my $char; + my %chars; + + # Make a table of character counts from the second + # argument + foreach $char (split('', $ARG[1])){ + if($chars{$char}){ + $chars{$char}++; + } else{ + $chars{$char} = 1; + } + } + + # Decrement (or remove entirely) the counts of + # characters that appear in the first argument + foreach $char (split('', $ARG[0])){ + if(exists($chars{$char})){ + $chars{$char}--; + delete($chars{$char}) + unless($chars{$char}); + } + } + + # Return a lexicographically sorted list of + # remaining characters + return( + sort( + # Make a list of remaining characters + map( + { + $char = $_; + + # Repeat the character the appropriate + # number of times + map( + $char, + 1 .. $chars{$char} + ) + } + keys(%chars) + ) + ) + ); + +} + + + diff --git a/challenge-255/mattneleigh/perl/ch-2.pl b/challenge-255/mattneleigh/perl/ch-2.pl new file mode 100755 index 0000000000..9674ba97d9 --- /dev/null +++ b/challenge-255/mattneleigh/perl/ch-2.pl @@ -0,0 +1,97 @@ +#!/usr/bin/perl + +use strict; +use warnings; +use English; + +################################################################################ +# Begin main execution +################################################################################ + +my @paragraphs_and_words = ( + [ + "Joe hit a ball, the hit ball flew far after it was hit.", + "hit" + ], + [ + "Perl and Raku belong to the same family. Perl is the most popular language in the weekly challenge.", + "the" + ] +); + +print("\n"); +foreach my $paragraph_and_word (@paragraphs_and_words){ + printf( + "Input: \$p = \"%s\"\n \$w = \"%s\"\nOutput: \"%s\"\n\n", + @{$paragraph_and_word}, + most_frequent_permitted_word(@{$paragraph_and_word}) + ); +} + +exit(0); +################################################################################ +# End main execution; subroutines follow +################################################################################ + + + +################################################################################ +# Given a paragraph and a banned word, find the permitted word that appears +# most frequently in the paragraph +# Takes two arguments: +# * The paragraph to examine (e.g. "Joe hit a ball, the hit ball flew far after +# it was hit." ) +# * The word to ban (e.g. "hit") +# Returns: +# * The permitted word that appears most frequently in the paragraph (e.g. +# "ball"). If there are multiple words tied for most frequent, the one that +# sorts first, lexicographically speaking, will be returned +################################################################################ +sub most_frequent_permitted_word{ + + my %words; + + # Get a table of counts of permitted words + foreach my $word (split(' ', $ARG[0])){ + # Stip anything that isn't a letter or number + $word =~ s/[^A-Za-z0-9]//g; + + # If the word isn't the forbidden one, add to + # its count in the word table + if($word ne $ARG[1]){ + if($words{$word}){ + $words{$word}++; + } else{ + $words{$word} = 1; + } + } + } + + return( + # 3: Get the 0th field of the 0th record in + # the sorted list- this will be the most + # frequently observed word + ( + # 2: Sort the list in descending order by + # count, unless the counts are equal, in + # which case sort lexicographically + sort( + { + $b->[1] == $a->[1] ? + $a->[0] cmp $b->[0] + : + $b->[1] <=> $a->[1] + } + # 1: Make a list of words and their counts + map( + [ $_, $words{$_} ], + keys(%words) + ) + ) + )[0][0] + ); + +} + + + -- cgit From 07e12891d5a65f6dad9d73956757c127b1846a3d Mon Sep 17 00:00:00 2001 From: Mark <53903062+andemark@users.noreply.github.com> Date: Mon, 5 Feb 2024 09:38:00 +0000 Subject: Challenge 255 Solutions (Raku) --- challenge-255/mark-anderson/raku/ch-1.raku | 11 +++++++++++ challenge-255/mark-anderson/raku/ch-2.raku | 12 ++++++++++++ 2 files changed, 23 insertions(+) create mode 100644 challenge-255/mark-anderson/raku/ch-1.raku create mode 100644 challenge-255/mark-anderson/raku/ch-2.raku diff --git a/challenge-255/mark-anderson/raku/ch-1.raku b/challenge-255/mark-anderson/raku/ch-1.raku new file mode 100644 index 0000000000..59ed24c2b2 --- /dev/null +++ b/challenge-255/mark-anderson/raku/ch-1.raku @@ -0,0 +1,11 @@ +#!/usr/bin/env raku +use Test; + +is odd-character("Perl", "Preel"), "e"; +is odd-character("Weekly", "Weeakly"), "a"; +is odd-character("Box", "Boxy"), "y"; + +sub odd-character($s, $t) +{ + $t.comb.Bag (-) $s.comb.Bag +} diff --git a/challenge-255/mark-anderson/raku/ch-2.raku b/challenge-255/mark-anderson/raku/ch-2.raku new file mode 100644 index 0000000000..768692ae7f --- /dev/null +++ b/challenge-255/mark-anderson/raku/ch-2.raku @@ -0,0 +1,12 @@ +#!/usr/bin/env raku +use Test; + +is-deeply most-freq-word("Joe hit a ball, the hit ball flew far after it was hit.", "hit"), ("ball",); +is-deeply most-freq-word("Perl and Raku belong to the same family. Perl is the most popular language in the weekly challenge.", "the"), ("Perl",); + +sub most-freq-word($p, $w) +{ + my $b = $p.split(/<[\W]>/, :skip-empty).BagHash; + $b{$w}:delete; + $b.maxpairs>>.key +} -- cgit From 7ae41852c28f903f5821561705eba50147c9c6e4 Mon Sep 17 00:00:00 2001 From: Luca Ferrari Date: Mon, 5 Feb 2024 08:15:45 +0100 Subject: PWC 255 Task 1 Raku done Task 2 Raku done Task 1 PL/Perl done Task 2 PL/perl done Task 1 PL/PgSQL done Task 2 PL/PgSQL done Task 1 Python done Task 2 Python done Task 1 PL/Java done Task 2 PL/Java done --- challenge-255/luca-ferrari/blog-1.txt | 1 + challenge-255/luca-ferrari/blog-10.txt | 1 + challenge-255/luca-ferrari/blog-2.txt | 1 + challenge-255/luca-ferrari/blog-3.txt | 1 + challenge-255/luca-ferrari/blog-4.txt | 1 + challenge-255/luca-ferrari/blog-5.txt | 1 + challenge-255/luca-ferrari/blog-6.txt | 1 + challenge-255/luca-ferrari/blog-7.txt | 1 + challenge-255/luca-ferrari/blog-8.txt | 1 + challenge-255/luca-ferrari/blog-9.txt | 1 + challenge-255/luca-ferrari/pljava/pom.xml | 6 +- .../luca-ferrari/pljava/src/main/java/Task1.java | 74 ++++++++++++++++++++++ .../luca-ferrari/pljava/src/main/java/Task2.java | 62 ++++++++++++++++++ challenge-255/luca-ferrari/plperl/ch-1.plperl | 29 +++++++++ challenge-255/luca-ferrari/plperl/ch-2.plperl | 28 ++++++++ challenge-255/luca-ferrari/plpgsql/ch-1.sql | 18 ++++++ challenge-255/luca-ferrari/plpgsql/ch-2.sql | 35 ++++++++++ challenge-255/luca-ferrari/python/ch-1.python | 26 ++++++-- challenge-255/luca-ferrari/python/ch-2.python | 21 +++--- challenge-255/luca-ferrari/raku/ch-1.raku | 18 ++++++ challenge-255/luca-ferrari/raku/ch-2.raku | 16 +++++ 21 files changed, 322 insertions(+), 21 deletions(-) create mode 100644 challenge-255/luca-ferrari/blog-1.txt create mode 100644 challenge-255/luca-ferrari/blog-10.txt create mode 100644 challenge-255/luca-ferrari/blog-2.txt create mode 100644 challenge-255/luca-ferrari/blog-3.txt create mode 100644 challenge-255/luca-ferrari/blog-4.txt create mode 100644 challenge-255/luca-ferrari/blog-5.txt create mode 100644 challenge-255/luca-ferrari/blog-6.txt create mode 100644 challenge-255/luca-ferrari/blog-7.txt create mode 100644 challenge-255/luca-ferrari/blog-8.txt create mode 100644 challenge-255/luca-ferrari/blog-9.txt create mode 100644 challenge-255/luca-ferrari/pljava/src/main/java/Task1.java create mode 100644 challenge-255/luca-ferrari/pljava/src/main/java/Task2.java create mode 100644 challenge-255/luca-ferrari/plperl/ch-1.plperl create mode 100644 challenge-255/luca-ferrari/plperl/ch-2.plperl create mode 100644 challenge-255/luca-ferrari/plpgsql/ch-1.sql create mode 100644 challenge-255/luca-ferrari/plpgsql/ch-2.sql create mode 100644 challenge-255/luca-ferrari/raku/ch-1.raku create mode 100644 challenge-255/luca-ferrari/raku/ch-2.raku diff --git a/challenge-255/luca-ferrari/blog-1.txt b/challenge-255/luca-ferrari/blog-1.txt new file mode 100644 index 0000000000..936241c6c4 --- /dev/null +++ b/challenge-255/luca-ferrari/blog-1.txt @@ -0,0 +1 @@ +https://fluca1978.github.io/2024/02/05/PerlWeeklyChallenge255.html#task1 diff --git a/challenge-255/luca-ferrari/blog-10.txt b/challenge-255/luca-ferrari/blog-10.txt new file mode 100644 index 0000000000..a21839e412 --- /dev/null +++ b/challenge-255/luca-ferrari/blog-10.txt @@ -0,0 +1 @@ +https://fluca1978.github.io/[= date -%]/PerlWeeklyChallenge255.html#task2pljava diff --git a/challenge-255/luca-ferrari/blog-2.txt b/challenge-255/luca-ferrari/blog-2.txt new file mode 100644 index 0000000000..f829c75fbf --- /dev/null +++ b/challenge-255/luca-ferrari/blog-2.txt @@ -0,0 +1 @@ +https://fluca1978.github.io/2024/02/05/PerlWeeklyChallenge255.html#task2 diff --git a/challenge-255/luca-ferrari/blog-3.txt b/challenge-255/luca-ferrari/blog-3.txt new file mode 100644 index 0000000000..7951fbdfd3 --- /dev/null +++ b/challenge-255/luca-ferrari/blog-3.txt @@ -0,0 +1 @@ +https://fluca1978.github.io/2024/02/05/PerlWeeklyChallenge255.html#task1plperl diff --git a/challenge-255/luca-ferrari/blog-4.txt b/challenge-255/luca-ferrari/blog-4.txt new file mode 100644 index 0000000000..4242e183fd --- /dev/null +++ b/challenge-255/luca-ferrari/blog-4.txt @@ -0,0 +1 @@ +https://fluca1978.github.io/2024/02/05/PerlWeeklyChallenge255.html#task2plperl diff --git a/challenge-255/luca-ferrari/blog-5.txt b/challenge-255/luca-ferrari/blog-5.txt new file mode 100644 index 0000000000..e0e73821c1 --- /dev/null +++ b/challenge-255/luca-ferrari/blog-5.txt @@ -0,0 +1 @@ +https://fluca1978.github.io/2024/02/05/PerlWeeklyChallenge255.html#task1plpgsql diff --git a/challenge-255/luca-ferrari/blog-6.txt b/challenge-255/luca-ferrari/blog-6.txt new file mode 100644 index 0000000000..27c518b72f --- /dev/null +++ b/challenge-255/luca-ferrari/blog-6.txt @@ -0,0 +1 @@ +https://fluca1978.github.io/2024/02/05/PerlWeeklyChallenge255.html#task2plpgsql diff --git a/challenge-255/luca-ferrari/blog-7.txt b/challenge-255/luca-ferrari/blog-7.txt new file mode 100644 index 0000000000..ee88ec0e8d --- /dev/null +++ b/challenge-255/luca-ferrari/blog-7.txt @@ -0,0 +1 @@ +https://fluca1978.github.io/2024/02/05/PerlWeeklyChallenge255.html#task1python diff --git a/challenge-255/luca-ferrari/blog-8.txt b/challenge-255/luca-ferrari/blog-8.txt new file mode 100644 index 0000000000..6929325c63 --- /dev/null +++ b/challenge-255/luca-ferrari/blog-8.txt @@ -0,0 +1 @@ +https://fluca1978.github.io/2024/02/05/PerlWeeklyChallenge255.html#task2python diff --git a/challenge-255/luca-ferrari/blog-9.txt b/challenge-255/luca-ferrari/blog-9.txt new file mode 100644 index 0000000000..2a75b6dad2 --- /dev/null +++ b/challenge-255/luca-ferrari/blog-9.txt @@ -0,0 +1 @@ +https://fluca1978.github.io/2024/02/05/PerlWeeklyChallenge255.html#task1pljava diff --git a/challenge-255/luca-ferrari/pljava/pom.xml b/challenge-255/luca-ferrari/pljava/pom.xml index 8777b204e3..e5ba684e37 100644 --- a/challenge-255/luca-ferrari/pljava/pom.xml +++ b/challenge-255/luca-ferrari/pljava/pom.xml @@ -5,11 +5,11 @@ 4.0.0 PWC - PWC254 + PWC255 1 - Perl Weekly Challenge 254 - Implementation of the tasks in PL/Java for PWC 254 + Perl Weekly Challenge 255 + Implementation of the tasks in PL/Java for PWC 255 US-ASCII diff --git a/challenge-255/luca-ferrari/pljava/src/main/java/Task1.java b/challenge-255/luca-ferrari/pljava/src/main/java/Task1.java new file mode 100644 index 0000000000..ab63904e23 --- /dev/null +++ b/challenge-255/luca-ferrari/pljava/src/main/java/Task1.java @@ -0,0 +1,74 @@ +package PWC255; + +/** + * PL/Java implementation for PWC 255 + * Task 1 + * See + * + * + * To compile on the local machine: + + $ export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64/ # if not already set + $ mvn clean build + $ $ scp target/PWC253-1.jar luca@venkman:/tmp + + + * To install into PostgreSQL execute: + + select sqlj.install_jar( 'file:///tmp/PWC255-1.jar', 'PWC255', true ); + select sqlj.set_classpath( 'public', 'PWC255' ); + + select task1_pljava(); + + and then to redeploy: + + select sqlj.replace_jar( 'file:///tmp/PWC255-1.jar', 'PWC255', true ); + +*/ + +import org.postgresql.pljava.*; +import org.postgresql.pljava.annotation.Function; +import static org.postgresql.pljava.annotation.Function.Effects.IMMUTABLE; +import static org.postgresql.pljava.annotation.Function.OnNullInput.RETURNS_NULL; + +import java.util.*; +import java.sql.SQLException; +import java.util.logging.*; + +public class Task1 { + + private final static Logger logger = Logger.getAnonymousLogger(); + + @Function( onNullInput = RETURNS_NULL, effects = IMMUTABLE ) + public static final String task1_pljava( String origin, String shuffled ) throws SQLException { + logger.log( Level.INFO, "Entering task1_pljava" ); + + if ( origin.length() + 1 != shuffled.length() ) { + throw new SQLException( "Shuffled string should be one character longer than the original one" ); + } + + Map classification = new HashMap(); + for ( String needle : shuffled.split( "" ) ) { + int value = classification.keySet().contains( needle ) + ? classification.get( needle ) + : 0; + + classification.put( needle, ++value ); + } + + + for ( String comparison : origin.split( "" ) ) { + int value = classification.get( comparison ); + value--; + + if ( value > 0 ) + classification.put( comparison, value ); + else + classification.remove( comparison ); + } + + + return classification.keySet().iterator().next(); + + } +} diff --git a/challenge-255/luca-ferrari/pljava/src/main/java/Task2.java b/challenge-255/luca-ferrari/pljava/src/main/java/Task2.java new file mode 100644 index 0000000000..0a8655ca2a --- /dev/null +++ b/challenge-255/luca-ferrari/pljava/src/main/java/Task2.java @@ -0,0 +1,62 @@ +package PWC255; + +/** + * PL/Java implementation for PWC 255 + * Task 1 + * See + * + * + * To compile on the local machine: + + $ export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64/ # if not already set + $ mvn clean build + $ $ scp target/PWC253-1.jar luca@venkman:/tmp + + + * To install into PostgreSQL execute: + + select sqlj.install_jar( 'file:///tmp/PWC255-1.jar', 'PWC255', true ); + select sqlj.set_classpath( 'public', 'PWC255' ); + + select task1_pljava(); + + and then to redeploy: + + select sqlj.replace_jar( 'file:///tmp/PWC255-1.jar', 'PWC255', true ); + +*/ + +import org.postgresql.pljava.*; +import org.postgresql.pljava.annotation.Function; +import static org.postgresql.pljava.annotation.Function.Effects.IMMUTABLE; +import static org.postgresql.pljava.annotation.Function.OnNullInput.RETURNS_NULL; + +import java.util.*; +import java.util.stream.*; +import java.sql.SQLException; +import java.util.logging.*; + +public class Task2 { + private final static Logger logger = Logger.getAnonymousLogger(); + + @Function( onNullInput = RETURNS_NULL, effects = IMMUTABLE ) + public static final String task2_pljava( String paragraph, String banned ) throws SQLException { + logger.log( Level.INFO, "Entering task2_pljava" ); + + Map classification = new HashMap(); + for ( String word : paragraph.split( "\\W+" ) ) { + if ( word.equals( banned ) ) + continue; + + int value = classification.containsKey( word ) ? classification.get( word ) : 0; + classification.put( word, ++value ); + } + + String topValue = classification.entrySet() + .stream() + .sorted( Collections.reverseOrder( Map.Entry.comparingByValue() ) ) + .findFirst().get().getKey(); + + return topValue; + } +} diff --git a/challenge-255/luca-ferrari/plperl/ch-1.plperl b/challenge-255/luca-ferrari/plperl/ch-1.plperl new file mode 100644 index 0000000000..8423dacf63 --- /dev/null +++ b/challenge-255/luca-ferrari/plperl/ch-1.plperl @@ -0,0 +1,29 @@ +-- +-- Perl Weekly Challenge 255 +-- Task 1 +-- See +-- + +CREATE SCHEMA IF NOT EXISTS pwc255; + +CREATE OR REPLACE FUNCTION +pwc255.task1_plperl( text, text ) +RETURNS text +AS $CODE$ + + my ( $origin, $shuffled ) = @_; + die "Shuffled string [$shuffled] should be one char lengther than original [$origin]" + if ( length( $shuffled ) != length( $origin ) + 1 ); + + + my $classification = {}; + $classification->{ $_ }++ for ( split //, $shuffled ); + $classification->{ $_ }-- for ( split //, $origin ); + + for ( keys $classification->%* ) { + return $_ if ( $classification->{ $_ } > 0 ); + } + + return undef; +$CODE$ +LANGUAGE plperl; diff --git a/challenge-255/luca-ferrari/plperl/ch-2.plperl b/challenge-255/luca-ferrari/plperl/ch-2.plperl new file mode 100644 index 0000000000..1f73f3688f --- /dev/null +++ b/challenge-255/luca-ferrari/plperl/ch-2.plperl @@ -0,0 +1,28 @@ +-- +-- Perl Weekly Challenge 255 +-- Task 2 +-- See +-- + +CREATE SCHEMA IF NOT EXISTS pwc255; + +CREATE OR REPLACE FUNCTION +pwc255.task2_plperl( text, text ) +RETURNS text +AS $CODE$ + + my ( $paragraph, $banned ) = @_; + + $paragraph =~ s/\W*$banned\W*/ /g; + + my $classification = {}; + $classification->{ $_ }++ for ( split /\W/, $paragraph ); + my $max = ( reverse sort values $classification->%* )[ 0 ]; + for ( keys $classification->%* ) { + return $_ if ( $classification->{ $_ } == $max ); + } + + return undef; + +$CODE$ +LANGUAGE plperl; diff --git a/challenge-255/luca-ferrari/plpgsql/ch-1.sql b/challenge-255/luca-ferrari/plpgsql/ch-1.sql new file mode 100644 index 0000000000..fba7114f5f --- /dev/null +++ b/challenge-255/luca-ferrari/plpgsql/ch-1.sql @@ -0,0 +1,18 @@ +-- +-- Perl Weekly Challenge 255 +-- Task 1 +-- See +-- + +CREATE SCHEMA IF NOT EXISTS pwc255; + +CREATE OR REPLACE FUNCTION +pwc255.task1_plpgsql( origin text, shuffled text ) +RETURNS char +AS $CODE$ + SELECT s + FROM regexp_split_to_table( shuffled, '' ) s + WHERE s NOT IN ( SELECT v + FROM regexp_split_to_table( origin, '' ) v ); +$CODE$ +LANGUAGE sql; diff --git a/challenge-255/luca-ferrari/plpgsql/ch-2.sql b/challenge-255/luca-ferrari/plpgsql/ch-2.sql new file mode 100644 index 0000000000..33f80c3ddd --- /dev/null +++ b/challenge-255/luca-ferrari/plpgsql/ch-2.sql @@ -0,0 +1,35 @@ +-- +-- Perl Weekly Challenge 255 +-- Task 2 +-- See +-- + +CREATE SCHEMA IF NOT EXISTS pwc255; + +CREATE OR REPLACE FUNCTION +pwc255.task2_plpgsql( p text, b text ) +RETURNS SETOF text +AS $CODE$ +DECLARE + +BEGIN + CREATE TEMPORARY TABLE IF NOT EXISTS classification( w text ); + TRUNCATE TABLE classification; + + INSERT INTO classification + SELECT v + FROM regexp_split_to_table( p, '\W+' ) v; + + RETURN QUERY + SELECT w FROM ( + SELECT w, count(*) AS c + FROM classification + WHERE w <> b + GROUP BY w + ORDER BY c DESC + LIMIT 1 + ); + +END +$CODE$ +LANGUAGE plpgsql; diff --git a/challenge-255/luca-ferrari/python/ch-1.python b/challenge-255/luca-ferrari/python/ch-1.python index a0533551d8..d5e0960574 100644 --- a/challenge-255/luca-ferrari/python/ch-1.python +++ b/challenge-255/luca-ferrari/python/ch-1.python @@ -1,24 +1,36 @@ #!python # -# Perl Weekly Challenge 254 +# Perl Weekly Challenge 255 # Task 1 # # See # import sys -import math # task implementation # the return value will be printed def task_1( args ): - num = int( args[ 0 ] ) - for i in range( 2, int( math.sqrt( num ) ) ): - if ( i ** 3 ) == num: - return True + origin = args[ 0 ] + shuffled = args[ 1 ] + if len( shuffled ) != len( origin ) + 1: + return "Shuffled string must be one character longer than original string" - return False + classification = {} + + for needle in shuffled: + if not needle in classification: + classification[ needle ] = 0 + + classification[ needle ] += 1 + + for needle in origin: + classification[ needle ] -= 1 + if classification[ needle ] <= 0: + del classification[ needle ] + + return list( classification.keys() )[ 0 ] # invoke the main without the command itself diff --git a/challenge-255/luca-ferrari/python/ch-2.python b/challenge-255/luca-ferrari/python/ch-2.python index dc37e2ad93..6493199950 100644 --- a/challenge-255/luca-ferrari/python/ch-2.python +++ b/challenge-255/luca-ferrari/python/ch-2.python @@ -1,7 +1,7 @@ #!python # -# Perl Weekly Challenge 254 +# Perl Weekly Challenge 255 # Task 2 # # See @@ -12,17 +12,16 @@ import sys # task implementation # the return value will be printed def task_2( args ): - word = args[ 0 ].lower() - vowels = list( reversed( list( filter( lambda x: x in ('a','e','i','o','u'), word ) ) ) ) - output = '' - for letter in word: - if letter not in ( 'a', 'e', 'i', 'o', 'u' ) or len( vowels ) == 0 - output += letter - else: - output += vowels.pop( 0 ) - - return output + paragraph = args[ 0 ] + banned = args[ 1 ] + classification = {} + for w in paragraph.split(): + if w != banned: + if not w in classification: + classification[ w ] = 0 + classification[ w ] += 1 + return sorted( classification.items() )[ -1 ][ 0 ] # invoke the main without the command itself if __name__ == '__main__': diff --git a/challenge-255/luca-ferrari/raku/ch-1.raku b/challenge-255/luca-ferrari/raku/ch-1.raku new file mode 100644 index 0000000000..9fe8930de6 --- /dev/null +++ b/challenge-255/luca-ferrari/raku/ch-1.raku @@ -0,0 +1,18 @@ +#!raku + +# +# Perl Weekly Challenge 255 +# Task 1 +# +# See +# + +sub MAIN( Str :$a, Str :$b where { $b.chars == $a.chars + 1 } ) { + my $classification = BagHash.new: $b.comb; + for $a.comb { + $classification{ $_ }--; + $classification{ $_ }:delete if ( $classification{ $_ } <= 0 ); + } + + $classification.keys.head.say; +} diff --git a/challenge-255/luca-ferrari/raku/ch-2.raku b/challenge-255/luca-ferrari/raku/ch-2.raku new file mode 100644 index 0000000000..ab74cfd5d9 --- /dev/null +++ b/challenge-255/luca-ferrari/raku/ch-2.raku @@ -0,0 +1,16 @@ +#!raku + +# +# Perl Weekly Challenge 255 +# Task 2 +# +# See +# + +sub MAIN( Str :$p is copy, Str :$w ) { + + $p ~~ s:g/ \W* $w \W+/ /; + my $classification = Bag.new: $p.split( / \W+ /, :skip-empty ); + $classification.keys.grep( { $classification{ $_ } == $classification.values.max } ).first.say; + +} -- cgit From 4ede8191795f6c20f97942c15ff5a4d488d5de1e Mon Sep 17 00:00:00 2001 From: Michael Manring Date: Mon, 5 Feb 2024 22:17:24 +1100 Subject: pwc255 solution in python --- challenge-255/pokgopun/python/ch-1.py | 49 ++++++++++++++++++++++++++++ challenge-255/pokgopun/python/ch-2.py | 61 +++++++++++++++++++++++++++++++++++ 2 files changed, 110 insertions(+) create mode 100644 challenge-255/pokgopun/python/ch-1.py create mode 100644 challenge-255/pokgopun/python/ch-2.py diff --git a/challenge-255/pokgopun/python/ch-1.py b/challenge-255/pokgopun/python/ch-1.py new file mode 100644 index 0000000000..c48ab19023 --- /dev/null +++ b/challenge-255/pokgopun/python/ch-1.py @@ -0,0 +1,49 @@ +### https://theweeklychallenge.org/blog/perl-weekly-challenge-255/ +""" + +Task 1: Odd Character + +Submitted by: [46]Mohammad Sajid Anwar + __________________________________________________________________ + + You are given two strings, $s and $t. The string $t is generated using + the shuffled characters of the string $s with an additional character. + + Write a script to find the additional character in the string $t.. + +Example 1 + +Input: $s = "Perl" $t = "Preel" +Output: "e" + +Example 2 + +Input: $s = "Weekly" $t = "Weeakly" +Output: "a" + +Example 3 + +Input: $s = "Box" $t = "Boxy" +Output: "y" + +Task 2: Most Frequent Word +""" +### solution by pokgopun@gmail.com + +def oddChar(s,t: str): + for c in s: + t = t.replace(c,"",1) + return t + +import unittest + +class TestOddChar(unittest.TestCase): + def test(self): + for (s,t), otpt in { + ("Perl","Preel"): "e", + ("Weekly","Weeakly"): "a", + ("Box","Boxy"): "y", + }.items(): + self.assertEqual(oddChar(s,t), otpt) + +unittest.main() diff --git a/challenge-255/pokgopun/python/ch-2.py b/challenge-255/pokgopun/python/ch-2.py new file mode 100644 index 0000000000..8a936ca3f2 --- /dev/null +++ b/challenge-255/pokgopun/python/ch-2.py @@ -0,0 +1,61 @@ +### https://theweeklychallenge.org/blog/perl-weekly-challenge-255/ +""" + +Task 2: Most Frequent Word + +Submitted by: [47]Mohammad Sajid Anwar + __________________________________________________________________ + + You are given a paragraph $p and a banned word $w. + + Write a script to return the most frequent word that is not banned. + +Example 1 + +Input: $p = "Joe hit a ball, the hit ball flew far after it was hit." + $w = "hit" +Output: "ball" + +The banned word "hit" occurs 3 times. +The other word "ball" occurs 2 times. + +Example 2 + +Input: $p = "Perl and Raku belong to the same family. Perl is the most popular l +anguage in the weekly challenge." + $w = "the" +Output: "Perl" + +The banned word "the" occurs 3 times. +The other word "Perl" occurs 2 times. + __________________________________________________________________ + + Last date to submit the solution 23:59 (UK Time) Sunday 11th February + 2024. + __________________________________________________________________ + +SO WHAT DO YOU THINK ? +""" +### solution by pokgopun@gmail.com + +import re + +def mostFreqWord(p,w: str): + dct = dict() + for s in ( e.group(0) for e in re.finditer(r'\w+',p) if e.group(0) != w ): + dct[s] = dct.setdefault(s,0) + 1 + mx = max(dct.values()) + for e in dct.items(): + if e[1] == mx: return e[0] + +import unittest + +class TestMostFreqWord(unittest.TestCase): + def test(self): + for (p,w), otpt in { + ("Joe hit a ball, the hit ball flew far after it was hit.","hit"): "ball", + ("Perl and Raku belong to the same family. Perl is the most popular language in the weekly challenge.","the"): "Perl", + }.items(): + self.assertEqual(mostFreqWord(p,w),otpt) + +unittest.main() -- cgit From 9e3bdff8884004b83a1a49209c58e8c966ad413a Mon Sep 17 00:00:00 2001 From: Michael Manring Date: Mon, 5 Feb 2024 23:12:43 +1100 Subject: pwc255 solution in go --- challenge-255/pokgopun/go/ch-1.go | 70 +++++++++++++++++++++++++++++++ challenge-255/pokgopun/go/ch-2.go | 88 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 158 insertions(+) create mode 100644 challenge-255/pokgopun/go/ch-1.go create mode 100644 challenge-255/pokgopun/go/ch-2.go diff --git a/challenge-255/pokgopun/go/ch-1.go b/challenge-255/pokgopun/go/ch-1.go new file mode 100644 index 0000000000..ddba3637e9 --- /dev/null +++ b/challenge-255/pokgopun/go/ch-1.go @@ -0,0 +1,70 @@ +//# https://theweeklychallenge.org/blog/perl-weekly-challenge-255/ +/*# + +Task 1: Odd Character + +Submitted by: [46]Mohammad Sajid Anwar + __________________________________________________________________ + + You are given two strings, $s and $t. The string $t is generated using + the shuffled characters of the string $s with an additional character. + + Write a script to find the additional character in the string $t.. + +Example 1 + +Input: $s = "Perl" $t = "Preel" +Output: "e" + +Example 2 + +Input: $s = "Weekly" $t = "Weeakly" +Output: "a" + +Example 3 + +Input: $s = "Box" $t = "Boxy" +Output: "y" + +Task 2: Most Frequent Word +#*/ +//# solution by pokgopun@gmail.com + +package main + +import ( + "io" + "os" + + "github.com/google/go-cmp/cmp" +) + +type str string + +func (st str) oddChar(s str) rune { + m := make(map[rune]int) + for _, v := range st { + m[v]++ + } + for _, v := range s { + if m[v] > 0 { + m[v]-- + } else { + return v + } + } + return 0 +} + +func main() { + for _, data := range []struct { + s, t str + o rune + }{ + {"Perl", "Preel", 'e'}, + {"Weekly", "Weeakly", 'a'}, + {"Box", "Boxy", 'y'}, + } { + io.WriteString(os.Stdout, cmp.Diff(data.s.oddChar(data.t), data.o)) // blank if ok, otherwise show the difference + } +} diff --git a/challenge-255/pokgopun/go/ch-2.go b/challenge-255/pokgopun/go/ch-2.go new file mode 100644 index 0000000000..127a62dadc --- /dev/null +++ b/challenge-255/pokgopun/go/ch-2.go @@ -0,0 +1,88 @@ +//# https://theweeklychallenge.org/blog/perl-weekly-challenge-255/ +/*# + +Task 2: Most Frequent Word + +Submitted by: [47]Mohammad Sajid Anwar + __________________________________________________________________ + + You are given a paragraph $p and a banned word $w. + + Write a script to return the most frequent word that is not banned. + +Example 1 + +Input: $p = "Joe hit a ball, the hit ball flew far after it was hit." + $w = "hit" +Output: "ball" + +The banned word "hit" occurs 3 times. +The other word "ball" occurs 2 times. + +Example 2 + +Input: $p = "Perl and Raku belong to the same family. Perl is the most popular l +anguage in the weekly challenge." + $w = "the" +Output: "Perl" + +The banned word "the" occurs 3 times. +The other word "Perl" occurs 2 times. + __________________________________________________________________ + + Last date to submit the solution 23:59 (UK Time) Sunday 11th February + 2024. + __________________________________________________________________ + +SO WHAT DO YOU THINK ? +#*/ +//# solution by pokgopun@gmail.com + +package main + +import ( + "io" + "os" + "regexp" + + "github.com/google/go-cmp/cmp" +) + +func mostFreqWord(p, w string) string { + re := regexp.MustCompile(`\w+`) + m := make(map[string]int) + var ( + i, mx int + loc []int + r, v string + ) + l := len(p) + for l-i > 1 { + loc = re.FindStringIndex(p[i:]) + if loc == nil { + break + } + v = p[loc[0]+i : loc[1]+i] + i += loc[1] + if v == w { + continue + } + m[v]++ + if m[v] > mx { + mx = m[v] + r = v + } + } + return r +} + +func main() { + for _, data := range []struct { + p, w, o string + }{ + {"Joe hit a ball, the hit ball flew far after it was hit.", "hit", "ball"}, + {"Perl and Raku belong to the same family. Perl is the most popular language in the weekly challenge.", "the", "Perl"}, + } { + io.WriteString(os.Stdout, cmp.Diff(mostFreqWord(data.p, data.w), data.o)) // blank if ok, otherwise show the difference + } +} -- cgit From 4fd42a03ee91f0da0c7f435078d25a6ed7725582 Mon Sep 17 00:00:00 2001 From: robbie-hatley Date: Mon, 5 Feb 2024 05:21:46 -0800 Subject: Robbie Hatley's solutions in Perl for The Weekly Challenge #255. --- challenge-255/robbie-hatley/blog.txt | 1 + challenge-255/robbie-hatley/perl/ch-1.pl | 112 +++++++++++++++++++++++++++ challenge-255/robbie-hatley/perl/ch-2.pl | 125 +++++++++++++++++++++++++++++++ 3 files changed, 238 insertions(+) create mode 100644 challenge-255/robbie-hatley/blog.txt create mode 100755 challenge-255/robbie-hatley/perl/ch-1.pl create mode 100755 challenge-255/robbie-hatley/perl/ch-2.pl diff --git a/challenge-255/robbie-hatley/blog.txt b/challenge-255/robbie-hatley/blog.txt new file mode 100644 index 0000000000..f43b080607 --- /dev/null +++ b/challenge-255/robbie-hatley/blog.txt @@ -0,0 +1 @@ +https://hatley-software.blogspot.com/2024/02/robbie-hatleys-solutions-to-weekly.html \ No newline at end of file diff --git a/challenge-255/robbie-hatley/perl/ch-1.pl b/challenge-255/robbie-hatley/perl/ch-1.pl new file mode 100755 index 0000000000..9861bcf214 --- /dev/null +++ b/challenge-255/robbie-hatley/perl/ch-1.pl @@ -0,0 +1,112 @@ +#!/usr/bin/perl -CSDA + +=pod + +-------------------------------------------------------------------------------------------------------------- +COLOPHON: +This is a 110-character-wide Unicode UTF-8 Perl-source-code text file with hard Unix line breaks ("\x0A"). +¡Hablo Español! Говорю Русский. Björt skjöldur. ॐ नमो भगवते वासुदेवाय. 看的星星,知道你是爱。麦藁雪、富士川町、山梨県。 + +-------------------------------------------------------------------------------------------------------------- +TITLE BLOCK: +Solutions in Perl for The Weekly Challenge 255-1. +Written by Robbie Hatley on Mon Feb 05, 2024. + +-------------------------------------------------------------------------------------------------------------- +PROBLEM DESCRIPTION: +Task 255-1: Odd Character +Submitted by: Mohammad Sajid Anwar + +You are given two strings, $s and $t. The string $t is generated +using the shuffled characters of the string $s with an +additional character. Write a script to find the additional +character in the string $t. + +Example 1: +Input: $s = "Perl" $t = "Preel" +Output: "e" + +Example 2: +Input: $s = "Weekly" $t = "Weeakly" +Output: "a" + +Example 3: +Input: $s = "Box" $t = "Boxy" +Output: "y" + +-------------------------------------------------------------------------------------------------------------- +PROBLEM NOTES: +Since this problem speaks of "characters" instead of "letters", I'll consider "a" and "A" to be different +"characters", and use a case-sensitive approach. I'll attack this problem by writing a sub which first splits +$s and $t into arrays @s and @t of single characters, then for each character of @s, if that character exists +in @t, splices-out the first occurrence only of that character from @t, then returns @t, which should now +consist of all "additional" characters (if any) which are in $t but not $s. Note that this approach doesn't +care if any of the characters of $s are actually in $t; if given $s="migrant" and $t="buck", the sub will +return ('b','u','c','k') because all of those letters were "added" to "migrant". (The fact that the letters +('m','i','g','r','a','n','t') were also REMOVED is irrelevant and hence ignored.) + +-------------------------------------------------------------------------------------------------------------- +IO NOTES: +Input is via either built-in variables or via @ARGV. If using @ARGV, provide one argument which must be a +single-quoted array of arrays of two double-quoted strings, apostrophes escaped as '"'"', +in proper Perl syntax, like this: +./ch-1.pl '(["trash", "trashy"], ["garbanzo", "gargoyle"]), ["van", "cavern"]' + +Output is to STDOUT and will be each input followed by the corresponding output. + +=cut + +# ------------------------------------------------------------------------------------------------------------ +# PRAGMAS AND MODULES USED: + +use v5.38; +use strict; +use warnings; +use utf8; + +# ------------------------------------------------------------------------------------------------------------ +# SUBROUTINES: + +sub added_characters ($s, $t) { + my @s = split //, $s; + my @t = split //, $t; + for my $char (@s) { + for ( my $i = 0 ; $i <= $#t ; ++$i ) { + if ( $char eq $t[$i] ) { + splice @t, $i, 1; + last; + } + } + } + return @t; +} + +# ------------------------------------------------------------------------------------------------------------ +# MAIN BODY OF PROGRAM: + +# Inputs: +my @pairs = @ARGV ? eval($ARGV[0]) : +( + # Example 1 Input: + ["Perl", "Preel"], + # Expected Output: "e" + + # Example 2 Input: + ["Weekly", "Weeakly"], + # Expected Output: "a" + + # Example 3 Input: + ["Box", "Boxy"], + # Expected Output: "y" +); + +# Main loop: +for my $pair (@pairs) { + say ''; + my $s = $pair->[0]; + my $t = $pair->[1]; + my @added = added_characters($s, $t); + say "\$s = \"$s\""; + say "\$t = \"$t\""; + say 'Added character(s) = ', join(', ', map {"\"$_\""} @added); +} diff --git a/challenge-255/robbie-hatley/perl/ch-2.pl b/challenge-255/robbie-hatley/perl/ch-2.pl new file mode 100755 index 0000000000..5215d6edcd --- /dev/null +++ b/challenge-255/robbie-hatley/perl/ch-2.pl @@ -0,0 +1,125 @@ +#!/usr/bin/perl -CSDA + +=pod + +-------------------------------------------------------------------------------------------------------------- +COLOPHON: +This is a 110-character-wide Unicode UTF-8 Perl-source-code text file with hard Unix line breaks ("\x0A"). +¡Hablo Español! Говорю Русский. Björt skjöldur. ॐ नमो भगवते वासुदेवाय. 看的星星,知道你是爱。麦藁雪、富士川町、山梨県。 + +-------------------------------------------------------------------------------------------------------------- +TITLE BLOCK: +Solutions in Perl for The Weekly Challenge 255-2. +Written by Robbie Hatley on Mon Feb 05, 2024. + +-------------------------------------------------------------------------------------------------------------- +PROBLEM DESCRIPTION: +Task 255-2: Most Frequent Word +Submitted by: Mohammad Sajid Anwar + +You are given a paragraph $p and a banned word $w. Write a script +to return the most frequent word that is not banned. + +Example 1: +Input: + $p = "Joe hit a ball, the hit ball flew far after it was hit." + $w = "hit" +Output: "ball" +The banned word "hit" occurs 3 times. +The other word "ball" occurs 2 times. + +Example 2 + +Input: + $p = "Perl and Raku belong to the same family. Perl is the ". + "most popular language in the weekly challenge." + $w = "the" +Output: "Perl" +The banned word "the" occurs 3 times. +The other word "Perl" occurs 2 times. + +-------------------------------------------------------------------------------------------------------------- +PROBLEM NOTES: +I'll write a sub that first splits each paragraph into words (/[a-zA-Z-]+/), then pushes each non-banned word +to an array called "@words", then makes a frequency hash %freq from @words, then returns the most-frequent +words with their frequency. + +Caveat: This approach will not always handle capitalization and compound words correctly. For example, it +fails to realize that the substrings "Programming" and "programming" are the same word in the following +sentence: "Programming is a science, but programming is also an art." Lower-casing everything won't work +either, because while "Perl" is a name, "perl" is not a word. Also, while "clean-cut" is considered one word +(correct; it's a hyphenated compound), "race baiting" is considered two words (WRONG; it's a single +open-compound word). Oh well; I don't have a month to spend perfecting this, so it will have to do. + +-------------------------------------------------------------------------------------------------------------- +IO NOTES: +Input is via either built-in variables or via @ARGV. If using @ARGV, provide one argument which must be a +single-quoted array of arrays of two double-quoted strings, with each inner array consisting of a paragraph +followed by a banned word, with apostrophes escaped as '"'"', in proper Perl syntax, like this: +./ch-2.pl '(["She cried and cried and cried\!", "cried"], ["She ate rice and beans and rice and beans\!", "and"])' + +Output is to STDOUT and will be each input followed by the corresponding output. + +=cut + +# ------------------------------------------------------------------------------------------------------------ +# PRAGMAS AND MODULES USED: + +use v5.38; +use strict; +use warnings; +use utf8; +use List::Util 'uniq'; + +# ------------------------------------------------------------------------------------------------------------ +# SUBROUTINES: + +sub most ($paragraph, $banned) { + my @words; + for my $word ( split /[^a-zA-Z-]/, $paragraph ) { + $word ne $banned and push @words, $word; + } + my %freq; + for my $word ( @words ) {++$freq{$word};} + my @unique = uniq sort {$freq{$b} <=> $freq{$a}} @words; + my @most; + for my $word ( @unique ) { + last if $freq{$word} < $freq{$unique[0]}; + push @most, $word; + } + push @most, $freq{$unique[0]}; + return @most; +} + +# ------------------------------------------------------------------------------------------------------------ +# MAIN BODY OF PROGRAM: + +# Inputs: +my @arrays = @ARGV ? eval($ARGV[0]) : +( + # Example 1 Input: + [ + "Joe hit a ball, the hit ball flew far after it was hit.", + "hit", + ], + # Expected Output: "ball" + + # Example 2 Input: + [ + "Perl and Raku belong to the same family. Perl is the most popular language in the weekly challenge.", + "the", + ], + # Expected Output: "Perl" +); + +# Main loop: +for my $aref (@arrays) { + say ''; + my $paragraph = $aref->[0]; + my $banned = $aref->[1]; + my @most = most($paragraph, $banned); + my $most = pop @most; + say "Paragraph: \"$paragraph\""; + say "Banned word: \"$banned\""; + say 'Most-common non-banned words = ', join(', ', map {"\"$_\" ($most)"} @most); +} -- cgit From 42b3de759cb5a10aa49c486d32bcbdbae2bc38fa Mon Sep 17 00:00:00 2001 From: Thomas Köhler Date: Mon, 5 Feb 2024 14:45:15 +0100 Subject: Add solution 255. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Thomas Köhler --- challenge-255/jeanluc2020/blog-1.txt | 1 + challenge-255/jeanluc2020/blog-2.txt | 1 + challenge-255/jeanluc2020/perl/ch-1.pl | 62 ++++++++++++++++++++++++++++++++ challenge-255/jeanluc2020/perl/ch-2.pl | 56 +++++++++++++++++++++++++++++ challenge-255/jeanluc2020/python/ch-1.py | 62 ++++++++++++++++++++++++++++++++ challenge-255/jeanluc2020/python/ch-2.py | 60 +++++++++++++++++++++++++++++++ 6 files changed, 242 insertions(+) create mode 100644 challenge-255/jeanluc2020/blog-1.txt create mode 100644 challenge-255/jeanluc2020/blog-2.txt create mode 100755 challenge-255/jeanluc2020/perl/ch-1.pl create mode 100755 challenge-255/jeanluc2020/perl/ch-2.pl create mode 100755 challenge-255/jeanluc2020/python/ch-1.py create mode 100755 challenge-255/jeanluc2020/python/ch-2.py diff --git a/challenge-255/jeanluc2020/blog-1.txt b/challenge-255/jeanluc2020/blog-1.txt new file mode 100644 index 0000000000..589a67eb25 --- /dev/null +++ b/challenge-255/jeanluc2020/blog-1.txt @@ -0,0 +1 @@ +http://gott-gehabt.de/800_wer_wir_sind/thomas/Homepage/Computer/perl/theweeklychallenge-255-1.html diff --git a/challenge-255/jeanluc2020/blog-2.txt b/challenge-255/jeanluc2020/blog-2.txt new file mode 100644 index 0000000000..cfa902820f --- /dev/null +++ b/challenge-255/jeanluc2020/blog-2.txt @@ -0,0 +1 @@ +http://gott-gehabt.de/800_wer_wir_sind/thomas/Homepage/Computer/perl/theweeklychallenge-255-2.html diff --git a/challenge-255/jeanluc2020/perl/ch-1.pl b/challenge-255/jeanluc2020/perl/ch-1.pl new file mode 100755 index 0000000000..6ae4cc6640 --- /dev/null +++ b/challenge-255/jeanluc2020/perl/ch-1.pl @@ -0,0 +1,62 @@ +#!/usr/bin/env perl +# https://theweeklychallenge.org/blog/perl-weekly-challenge-255/#TASK1 +# +# Task 1: Odd Character +# ===================== +# +# You are given two strings, $s and $t. The string $t is generated using the +# shuffled characters of the string $s with an additional character. +# +# Write a script to find the additional character in the string $t.. +# +## Example 1 +## +## Input: $s = "Perl" $t = "Preel" +## Output: "e" +# +## Example 2 +## +## Input: $s = "Weekly" $t = "Weeakly" +## Output: "a" +# +## Example 3 +## +## Input: $s = "Box" $t = "Boxy" +## Output: "y" +# +############################################################ +## +## discussion +## +############################################################ +# +# Split the word into its character, store them in a hash table, then +# count the result for each character in both the table for the original +# word and for the new word. + +use strict; +use warnings; + +odd_character("Perl", "Preel"); +odd_character("Weekly", "Weeakly"); +odd_character("Box", "Boxy"); + +sub odd_character { + my ($s, $t) = @_; + print "Input: '$s', '$t'\n"; + my $s_hash = {}; + my $t_hash = {}; + foreach my $char (split//,$s) { + $s_hash->{$char}++; + } + foreach my $char (split//,$t) { + $t_hash->{$char}++; + } + foreach my $found (keys %$t_hash) { + $s_hash->{$found} //= 0; + if($t_hash->{$found} > $s_hash->{$found}) { + print "Output: $found\n"; + return; + } + } +} diff --git a/challenge-255/jeanluc2020/perl/ch-2.pl b/challenge-255/jeanluc2020/perl/ch-2.pl new file mode 100755 index 0000000000..b3896b9710 --- /dev/null +++ b/challenge-255/jeanluc2020/perl/ch-2.pl @@ -0,0 +1,56 @@ +#!/usr/bin/env perl +# https://theweeklychallenge.org/blog/perl-weekly-challenge-255/#TASK2 +# +# Task 2: Most Frequent Word +# ========================== +# +# You are given a paragraph $p and a banned word $w. +# +# Write a script to return the most frequent word that is not banned. +# +## Example 1 +## +## Input: $p = "Joe hit a ball, the hit ball flew far after it was hit." +## $w = "hit" +## Output: "ball" +## +## The banned word "hit" occurs 3 times. +## The other word "ball" occurs 2 times. +# +## Example 2 +## +## Input: $p = "Perl and Raku belong to the same family. Perl is the most +## popular language in the weekly challenge." +## $w = "the" +## Output: "Perl" +## +## The banned word "the" occurs 3 times. +## The other word "Perl" occurs 2 times. +# +############################################################ +## +## discussion +## +############################################################ +# +# Split the sentence into its words, then count all the words != $w + +use strict; +use warnings; + +most_frequent_word("Joe hit a ball, the hit ball flew far after it was hit.", "hit"); +most_frequent_word("Perl and Raku belong to the same family. Perl is the most" . + " popular language in the weekly challenge.", "the"); + +sub most_frequent_word { + my ($p, $w) = @_; + print "Input: '$p', '$w'\n"; + my $found = {}; + foreach my $word (split/[^\w]/, $p) { + next if $word eq $w; + $found->{$word}++; + } + my @most = sort { $found->{$b} <=> $found->{$a} } keys %$found; + print "Found the most frequent word to be '$most[0]'\n"; +} + diff --git a/challenge-255/jeanluc2020/python/ch-1.py b/challenge-255/jeanluc2020/python/ch-1.py new file mode 100755 index 0000000000..728f307d69 --- /dev/null +++ b/challenge-255/jeanluc2020/python/ch-1.py @@ -0,0 +1,62 @@ +#!/usr/bin/python3 +# https://theweeklychallenge.org/blog/perl-weekly-challenge-255/#TASK1 +# +# Task 1: Odd Character +# ===================== +# +# You are given two strings, $s and $t. The string $t is generated using the +# shuffled characters of the string $s with an additional character. +# +# Write a script to find the additional character in the string $t.. +# +## Example 1 +## +## Input: $s = "Perl" $t = "Preel" +## Output: "e" +# +## Example 2 +## +## Input: $s = "Weekly" $t = "Weeakly" +## Output: "a" +# +## Example 3 +## +## Input: $s = "Box" $t = "Boxy" +## Output: "y" +# +############################################################ +## +## discussion +## +############################################################ +# +# Split the word into its character, store them in a hash table, then +# count the result for each character in both the table for the original +# word and for the new word. + +def odd_character(s: str, t: str) -> None: + print(f"Input: '{s}', '{t}'") + s_hash = {} + t_hash = {} + for char in list(s): + if char in s_hash: + s_hash[char] += 1 + else: + s_hash[char] = 1 + for char in list(t): + if char in t_hash: + t_hash[char] += 1 + else: + t_hash[char] = 1 + for found in t_hash.keys(): + old = 0 + if found in s_hash: + old = s_hash[found] + if t_hash[found] > old: + print(f"Output: {found}") + return + + +odd_character("Perl", "Preel"); +odd_character("Weekly", "Weeakly"); +odd_character("Box", "Boxy"); diff --git a/challenge-255/jeanluc2020/python/ch-2.py b/challenge-255/jeanluc2020/python/ch-2.py new file mode 100755 index 0000000000..ebc9f1edce --- /dev/null +++ b/challenge-255/jeanluc2020/python/ch-2.py @@ -0,0 +1,60 @@ +#!/usr/bin/python3 +# https://theweeklychallenge.org/blog/perl-weekly-challenge-255/#TASK2 +# +# Task 2: Most Frequent Word +# ========================== +# +# You are given a paragraph $p and a banned word $w. +# +# Write a script to return the most frequent word that is not banned. +# +## Example 1 +## +## Input: $p = "Joe hit a ball, the hit ball flew far after it was hit." +## $w = "hit" +## Output: "ball" +## +## The banned word "hit" occurs 3 times. +## The other word "ball" occurs 2 times. +# +## Example 2 +## +## Input: $p = "Perl and Raku belong to the same family. Perl is the most +## popular language in the weekly challenge." +## $w = "the" +## Output: "Perl" +## +## The banned word "the" occurs 3 times. +## The other word "Perl" occurs 2 times. +# +############################################################ +## +## discussion +## +############################################################ +# +# Split the sentence into its words, then count all the words != $w + +import re +from operator import itemgetter + +def most_frequent_word(p: str, w: str) -> None: + print(f"Input: '{p}', '{w}'") + found = {} + for word in re.split('\W+', p): + if word != w: + if word in found: + found[word] += 1 + else: + found[word] = 1 + most = [] + for key in found.keys(): + most.append( (key, found[key]) ) + most.sort(key=itemgetter(1)) + print(most) + print(f"Found the most frequent word to be '{most[-1][0]}'") + +most_frequent_word("Joe hit a ball, the hit ball flew far after it was hit.", "hit"); +most_frequent_word("Perl and Raku belong to the same family. Perl is the most" + + " popular language in the weekly challenge.", "the"); + -- cgit From e3a92ba33f405797167d4646efb4f76c5d23ed7e Mon Sep 17 00:00:00 2001 From: Luis Mochan Date: Mon, 5 Feb 2024 08:53:39 -0600 Subject: Solve PWC255 --- challenge-255/wlmb/blog.txt | 1 + challenge-255/wlmb/perl/ch-1.pl | 19 +++++++++++++++++++ challenge-255/wlmb/perl/ch-2.pl | 16 ++++++++++++++++ 3 files changed, 36 insertions(+) create mode 100644 challenge-255/wlmb/blog.txt create mode 100755 challenge-255/wlmb/perl/ch-1.pl create mode 100755 challenge-255/wlmb/perl/ch-2.pl diff --git a/challenge-255/wlmb/blog.txt b/challenge-255/wlmb/blog.txt new file mode 100644 index 0000000000..fdbdb25e89 --- /dev/null +++ b/challenge-255/wlmb/blog.txt @@ -0,0 +1 @@ +https://wlmb.github.io/2024/02/05/PWC255/ diff --git a/challenge-255/wlmb/perl/ch-1.pl b/challenge-255/wlmb/perl/ch-1.pl new file mode 100755 index 0000000000..b4fd9c7739 --- /dev/null +++ b/challenge-255/wlmb/perl/ch-1.pl @@ -0,0 +1,19 @@ +#!/usr/bin/env perl +# Perl weekly challenge 255 +# Task 1: Odd Character +# +# See https://wlmb.github.io/2024/02/05/PWC255/#task-1-odd-character +use v5.36; +use experimental qw(for_list); +die <<~"FIN" unless @ARGV && @ARGV%2==0; + Usage: $0 S0 T0 [S1 T1...] + to find the odd characters in the string pairs Sn Tn + FIN +for my ($s,$t)(@ARGV){ + warn "Length should differ by one" unless length $t == 1+length $s; + my %count; + ++$count{$_} for split "", fc $s; + --$count{$_}||delete $count{$_} for split "", fc $t; + warn "More than one odd character" unless (keys %count)==1; + say "$t, $s -> ", keys %count; +} diff --git a/challenge-255/wlmb/perl/ch-2.pl b/challenge-255/wlmb/perl/ch-2.pl new file mode 100755 index 0000000000..aabc08ca56 --- /dev/null +++ b/challenge-255/wlmb/perl/ch-2.pl @@ -0,0 +1,16 @@ +#!/usr/bin/env perl +# Perl weekly challenge 255 +# Task 2: Most Frequent Word +# +# See https://wlmb.github.io/2024/02/05/PWC255/#task-2-most-frequent-word +use v5.36; +use List::UtilsBy qw(max_by); +die <<~"FIN" unless @ARGV==2; + Usage: $0 S ¨P + to find the most frequent word in paragraph P excluding the word S + FIN +my ($w, $p)=@ARGV; +my %count; +++$count{fc $_} for split /\W+/, $p; +delete $count{fc $w}; +say "\n$w\n$p\n->\n", max_by{$count{$_}} keys %count; -- cgit From 6527859af4f4317e8e752a405dc3bdd4212862c8 Mon Sep 17 00:00:00 2001 From: Scimon Date: Mon, 5 Feb 2024 15:02:46 +0000 Subject: Week 253 --- challenge-255/simon-proctor/raku/ch-1.raku | 17 +++++++++++++++++ challenge-255/simon-proctor/raku/ch-2.raku | 17 +++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 challenge-255/simon-proctor/raku/ch-1.raku create mode 100644 challenge-255/simon-proctor/raku/ch-2.raku diff --git a/challenge-255/simon-proctor/raku/ch-1.raku b/challenge-255/simon-proctor/raku/ch-1.raku new file mode 100644 index 0000000000..34febe5d43 --- /dev/null +++ b/challenge-255/simon-proctor/raku/ch-1.raku @@ -0,0 +1,17 @@ +#!/usr/bin/env raku + +multi sub MAIN('test') { + use Test; + is odd-character('Perl','Preel'), 'e'; + is odd-character('Weekly','Weeakly'), 'a'; + is odd-character('Box','Boxy'), 'y'; + done-testing; +} + +multi sub MAIN($s, $t) { + odd-character($s, $t).say; +} + +sub odd-character($s, $t) { + return ($s.comb.Bag (^) $t.comb.Bag).keys[0] +} diff --git a/challenge-255/simon-proctor/raku/ch-2.raku b/challenge-255/simon-proctor/raku/ch-2.raku new file mode 100644 index 0000000000..8e9f9cd00a --- /dev/null +++ b/challenge-255/simon-proctor/raku/ch-2.raku @@ -0,0 +1,17 @@ +#!/usr/bin/env raku + +multi sub MAIN('test') { + use Test; + is next-most-frequent(phrase => 'Joe hit a ball, the hit ball flew far after it was hit.', banned => 'hit'), 'ball'; + is next-most-frequent(phrase => 'Perl and Raku belong to the same family. Perl is the most popular language in the weekly challenge.', banned => 'the'), 'Perl'; + done-testing; +} + +multi sub MAIN($banned, *@words) { + next-most-frequent( phrase => @words.join(' '), :$banned ).say; +} + +sub next-most-frequent(:$phrase, :$banned) { + $phrase.words.map( { .trans(["a".."z","A".."Z"] => "", :complement) } ).grep({ $_ ne $banned }).Bag.antipairs.sort({$_.key}).reverse.first.value; +} + -- cgit From 2b4cdf73bee3f5cf609522f16acae2dfe1e50a5e Mon Sep 17 00:00:00 2001 From: Steven Date: Mon, 5 Feb 2024 16:32:18 +0000 Subject: add solutions week 255 in python --- challenge-255/steven-wilson/python/ch-01.py | 34 ++++++++++++++++++++++++++ challenge-255/steven-wilson/python/ch-02.py | 37 +++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 challenge-255/steven-wilson/python/ch-01.py create mode 100644 challenge-255/steven-wilson/python/ch-02.py diff --git a/challenge-255/steven-wilson/python/ch-01.py b/challenge-255/steven-wilson/python/ch-01.py new file mode 100644 index 0000000000..dac2d858ab --- /dev/null +++ b/challenge-255/steven-wilson/python/ch-01.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python3 + +from collections import Counter + + +def odd_character(original, shuffled): + ''' Given two strings, the second string generated using the shuffled + characters of the first string with an additional character. Function + returns the additional character. + >>> odd_character("Perl", "Preel") + 'e' + >>> odd_character("Weekly", "Weeakly") + 'a' + >>> odd_character("Box", "Boxy") + 'y' + ''' + if not original or not shuffled: + raise ValueError("Both strings must be non-empty.") + + original_counter = Counter(x.casefold() for x in original) + shuffled_counter = Counter(x.casefold() for x in shuffled) + + difference_counter = shuffled_counter - original_counter + + if not difference_counter or sum(difference_counter.values()) > 1: + raise ValueError("No unique additional character found.") + + return next(difference_counter.elements()) + + +if __name__ == "__main__": + import doctest + + doctest.testmod() diff --git a/challenge-255/steven-wilson/python/ch-02.py b/challenge-255/steven-wilson/python/ch-02.py new file mode 100644 index 0000000000..2d5fc3ab9c --- /dev/null +++ b/challenge-255/steven-wilson/python/ch-02.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python3 + +from collections import Counter +import string + + +def most_frequent_word(paragraph, banned): + '''Given a paragraph and a banned word. Return the most frequent word that + is not banned + >>> most_frequent_word( + ... "Joe hit a ball, the hit ball flew far after it was hit.", "hit") + 'ball' + >>> most_frequent_word( + ... "Perl and Raku belong to the same family. " + ... "Perl is the most popular language in the weekly challenge.", "the") + 'Perl' + ''' + if not paragraph or not banned: + raise ValueError("Both strings must be non-empty.") + + paragraph_no_punctuation = paragraph.translate( + str.maketrans("", "", string.punctuation)) + paragraph_counter = Counter(paragraph_no_punctuation.split()) + + if banned in paragraph_counter: + del paragraph_counter[banned] + + if not paragraph_counter: + raise ValueError("No words found in the paragraph after removing punctuation and banned word.") + + return paragraph_counter.most_common()[0][0] + + +if __name__ == "__main__": + import doctest + + doctest.testmod() -- cgit From c16e9c1fc0b5b52bab73a19d41ed2c08a2827b26 Mon Sep 17 00:00:00 2001 From: Zapwai Date: Mon, 5 Feb 2024 13:33:19 -0500 Subject: Week 255 --- challenge-255/zapwai/c/ch-1.c | 37 +++++++++++++++++ challenge-255/zapwai/c/ch-2.c | 85 +++++++++++++++++++++++++++++++++++++++ challenge-255/zapwai/perl/ch-1.pl | 36 +++++++++++++++++ challenge-255/zapwai/perl/ch-2.pl | 35 ++++++++++++++++ challenge-255/zapwai/rust/ch-1.rs | 40 ++++++++++++++++++ challenge-255/zapwai/rust/ch-2.rs | 42 +++++++++++++++++++ 6 files changed, 275 insertions(+) create mode 100644 challenge-255/zapwai/c/ch-1.c create mode 100644 challenge-255/zapwai/c/ch-2.c create mode 100644 challenge-255/zapwai/perl/ch-1.pl create mode 100644 challenge-255/zapwai/perl/ch-2.pl create mode 100644 challenge-255/zapwai/rust/ch-1.rs create mode 100644 challenge-255/zapwai/rust/ch-2.rs diff --git a/challenge-255/zapwai/c/ch-1.c b/challenge-255/zapwai/c/ch-1.c new file mode 100644 index 0000000000..474a4d5098 --- /dev/null +++ b/challenge-255/zapwai/c/ch-1.c @@ -0,0 +1,37 @@ +#include +void proc(char*, char*, int, int); +int main() { + + char s[] = "Perl"; + char t[] = "Preel"; + proc(s, t, sizeof(s)/sizeof(char), sizeof(t)/sizeof(char)); + + char s2[] = "Weekly"; + char t2[] = "Weeakly"; + proc(s2, t2, sizeof(s2)/sizeof(char), sizeof(t2)/sizeof(char)); + + char s3[] = "Box"; + char t3[] = "Boxy"; + proc(s3, t3, sizeof(s3)/sizeof(char), sizeof(t3)/sizeof(char)); + +} + +void proc(char *s, char *t, int slen, int tlen) { + int fs[123] = {0}; /* entries 65 to 122 contain freqs of chars */ + int ft[123] = {0}; + + for (int i = 0; i < slen; i++) { + fs[s[i]]++; + } + for (int i = 0; i < tlen; i++) { + ft[t[i]]++; + } + + int ansnum; + for (int i = 0; i < 123; i++) { + if ( (ft[i] == 1) && (fs[i] == 0) ) { ansnum = i; break; } + else if ( ft[i] > fs[i] ) { ansnum = i; break; } + } + + printf("Input: s: %s t: %s\nOutput: %c\n", s, t, ansnum); +} \ No newline at end of file diff --git a/challenge-255/zapwai/c/ch-2.c b/challenge-255/zapwai/c/ch-2.c new file mode 100644 index 0000000000..7a49b28886 --- /dev/null +++ b/challenge-255/zapwai/c/ch-2.c @@ -0,0 +1,85 @@ +#include +const int M = 20; /* upper bound on number of words in the sentence */ +void proc(char *p, char *wor, int plen, int worlen) { + printf("Input: "); + printf("s: %s ", p); + printf("\n\tw: %s\n", wor); + /* w is a list of strings, were splitting on ' ' */ + char w[M][20]; + int wlen[M] = {0}; /* length of words in list */ + int skip[M] = {0}; /* entries to skip bc they match wor */ + int freq[M] = {0}; /* a cumulative count of each word */ + + int entry = 0; + int j = 0; + /* copy words into w, skip punctuation */ + for (int i = 0; i < plen; i++) { + if (p[i] == ' ') { + wlen[entry] = j; + entry++; + j = 0; + continue; + } else if ( (p[i] < 65) || (p[i] > 122) ) { + continue; + } else { + w[entry][j] = p[i]; + j++; + } + } + wlen[entry] = j; /* entry is now the number of words - 1 */ + /* find which words to skip bc they match wor */ + for (int i = 0; i <= entry; i++) { + int cnt = 0; + for (int k = 0; k < wlen[i]; k++) { + if (wor[k] == w[i][k]) { + cnt++; + } +