From cbfdd589185f2e68e08b3542e519cd35578e7724 Mon Sep 17 00:00:00 2001 From: Alexander Pankoff Date: Mon, 5 Oct 2020 14:14:03 +0200 Subject: reset README --- challenge-081/alexander-pankoff/README | 9 --------- 1 file changed, 9 deletions(-) (limited to 'challenge-081') diff --git a/challenge-081/alexander-pankoff/README b/challenge-081/alexander-pankoff/README index a74e2fd1ec..41f67807ac 100644 --- a/challenge-081/alexander-pankoff/README +++ b/challenge-081/alexander-pankoff/README @@ -1,10 +1 @@ Solution by Alexander Pankoff - -# Run the Haskell solution - -With a `ghc` installation you can run the haskell solution with `runghc` - -``` -$ runghc haskell/ch-1.hs 1 2 3 -1 4 -5 -``` -- cgit From 8968a5ff21e13aecd34c6a0697358cfe1fd30a4d Mon Sep 17 00:00:00 2001 From: boblied Date: Tue, 6 Oct 2020 07:26:56 -0500 Subject: Set up challenge 081 --- challenge-081/bob-lied/README | 4 +- challenge-081/bob-lied/perl/ch-1.pl | 46 ++++++++++++++++++++++ challenge-081/bob-lied/perl/ch-2.pl | 46 ++++++++++++++++++++++ .../bob-lied/perl/lib/CommonBaseString.pm | 39 ++++++++++++++++++ challenge-081/bob-lied/perl/lib/FrequencySort.pm | 39 ++++++++++++++++++ challenge-081/bob-lied/perl/t/CommonBaseString.t | 16 ++++++++ challenge-081/bob-lied/perl/t/FrequencySort.t | 16 ++++++++ challenge-081/bob-lied/perl/t/input | 13 ++++++ 8 files changed, 217 insertions(+), 2 deletions(-) create mode 100755 challenge-081/bob-lied/perl/ch-1.pl create mode 100755 challenge-081/bob-lied/perl/ch-2.pl create mode 100644 challenge-081/bob-lied/perl/lib/CommonBaseString.pm create mode 100644 challenge-081/bob-lied/perl/lib/FrequencySort.pm create mode 100644 challenge-081/bob-lied/perl/t/CommonBaseString.t create mode 100644 challenge-081/bob-lied/perl/t/FrequencySort.t create mode 100644 challenge-081/bob-lied/perl/t/input (limited to 'challenge-081') diff --git a/challenge-081/bob-lied/README b/challenge-081/bob-lied/README index 026576bd98..e698fa656a 100644 --- a/challenge-081/bob-lied/README +++ b/challenge-081/bob-lied/README @@ -1,3 +1,3 @@ -Solutions to weekly challenge 79 by Bob Lied. +Solutions to weekly challenge 81 by Bob Lied. -https://perlweeklychallenge.org/blog/perl-weekly-challenge-079/ +https://perlweeklychallenge.org/blog/perl-weekly-challenge-081/ diff --git a/challenge-081/bob-lied/perl/ch-1.pl b/challenge-081/bob-lied/perl/ch-1.pl new file mode 100755 index 0000000000..3aa9ff13fe --- /dev/null +++ b/challenge-081/bob-lied/perl/ch-1.pl @@ -0,0 +1,46 @@ +#!/usr/bin/env perl +# vim:set ts=4 sw=4 sts=4 et ai wm=0 nu: +#============================================================================= +# ch-1.pl +#============================================================================= +# Copyright (c) 2020, Bob Lied +#============================================================================= +# Perl Weekly Challenge 081 Task #1 > Common Base String +#============================================================================= +# You are given 2 strings, $A and $B. +# Write a script to find out common base strings in $A and $B. +# A substring of a string $S is called base string if repeated concatenation +# of the substring results in the string. +# Example 1: Input: $A = "abcdabcd" +# $B = "abcdabcdabcdabcd" +# Output: ("abcd", "abcdabcd") +# +# Example 2: Input: $A = "aaa" +# $B = "aa" +# Output: ("a") + +use strict; +use warnings; +use v5.30; + +use feature qw/ signatures /; +no warnings qw/ experimental::signatures /; + +use Getopt::Long; + +use lib "lib"; +use CommonBaseString; + +sub Usage { "Usage: $0 astring bstring" }; + +my $Verbose = 0; +GetOptions('verbose' => \$Verbose); + +my (@A, @B) = @ARGV; + +die Usage() unless $A; +die Usage() unless $B; + +my $cbs = CommonBaseString->new($A, $B); +my $result = $cbs->run(); +say $result; diff --git a/challenge-081/bob-lied/perl/ch-2.pl b/challenge-081/bob-lied/perl/ch-2.pl new file mode 100755 index 0000000000..5ed37221ff --- /dev/null +++ b/challenge-081/bob-lied/perl/ch-2.pl @@ -0,0 +1,46 @@ +#!/usr/bin/env perl +# vim:set ts=4 sw=4 sts=4 et ai wm=0 nu: +#============================================================================= +# ch-2.pl +#============================================================================= +# Copyright (c) 2020, Bob Lied +#============================================================================= +# Perl Weekly Challenge 081 Task #2 > Frequency Sort +#============================================================================= +# You are given file named input. +# Write a script to find the frequency of all the words. +# It should print the result as first column of each line should be the +# frequency of the the word followed by all the words of that frequency +# arranged in lexicographical order. Also sort the words in the ascending +# order of frequency. +# For the sake of this task, please ignore the following in the input file: +# . " ( ) , 's -- +# Keep hyphenated words and contractions, but reduce possessives to their base +# (e.g., "award-winning" and "doesn't" are words, but "Joe's" becomes "Joe" + +use strict; +use warnings; +use v5.30; + +use feature qw/ signatures /; +no warnings qw/ experimental::signatures /; + +use Getopt::Long; + +use lib "lib"; +use FrequencySort; + +sub Usage { "Usage: $0 args" }; + +my $Verbose = 0; +GetOptions('verbose' => \$Verbose); + +my $arg = shift; +my @list = @ARGV; + +die Usage() unless $arg; +die Usage() unless @list; + +my $task = FrequencySort->new(); +my $result = $task->run(); +say $result; diff --git a/challenge-081/bob-lied/perl/lib/CommonBaseString.pm b/challenge-081/bob-lied/perl/lib/CommonBaseString.pm new file mode 100644 index 0000000000..b67ecfa948 --- /dev/null +++ b/challenge-081/bob-lied/perl/lib/CommonBaseString.pm @@ -0,0 +1,39 @@ +# vim:set ts=4 sw=4 sts=4 et ai wm=0 nu: +#============================================================================= +# CommonBaseString.pm +#============================================================================= +# Copyright (c) 2020, Bob Lied +#============================================================================= +# Description: +#============================================================================= + +package CommonBaseString; + +use strict; +use warnings; +use v5.30; + +use feature qw/ signatures /; +no warnings qw/ experimental::signatures /; + +require Exporter; +our @ISA = qw(Exporter); +our @EXPORT = qw(); +our @EXPORT_OK = qw(); + +sub new($class, $name1) +{ + $class = ref($class) || $class; + my $self = { + _name1 => $name1, + }; + bless $self, $class; + return $self; +} + +sub run($self) +{ + return undef; +} + +1; diff --git a/challenge-081/bob-lied/perl/lib/FrequencySort.pm b/challenge-081/bob-lied/perl/lib/FrequencySort.pm new file mode 100644 index 0000000000..177e28ace9 --- /dev/null +++ b/challenge-081/bob-lied/perl/lib/FrequencySort.pm @@ -0,0 +1,39 @@ +# vim:set ts=4 sw=4 sts=4 et ai wm=0 nu: +#============================================================================= +# FrequencySort.pm +#============================================================================= +# Copyright (c) 2020, Bob Lied +#============================================================================= +# Description: +#============================================================================= + +package FrequencySort; + +use strict; +use warnings; +use v5.30; + +use feature qw/ signatures /; +no warnings qw/ experimental::signatures /; + +require Exporter; +our @ISA = qw(Exporter); +our @EXPORT = qw(); +our @EXPORT_OK = qw(); + +sub new($class, $name1) +{ + $class = ref($class) || $class; + my $self = { + _name1 => $name1, + }; + bless $self, $class; + return $self; +} + +sub run($self) +{ + return undef; +} + +1; diff --git a/challenge-081/bob-lied/perl/t/CommonBaseString.t b/challenge-081/bob-lied/perl/t/CommonBaseString.t new file mode 100644 index 0000000000..81d4345b76 --- /dev/null +++ b/challenge-081/bob-lied/perl/t/CommonBaseString.t @@ -0,0 +1,16 @@ +# vim:set ts=4 sw=4 sts=4 et ai wm=0 nu: +# +#=============================================================================== +# FILE: CommonBaseString.t +# DESCRIPTION: Unit test for CommonBaseString +#=============================================================================== + +use strict; +use warnings; +use v5.30; + +use Test2::V0; + +use CommonBaseString; + +done_testing(); diff --git a/challenge-081/bob-lied/perl/t/FrequencySort.t b/challenge-081/bob-lied/perl/t/FrequencySort.t new file mode 100644 index 0000000000..794fd04750 --- /dev/null +++ b/challenge-081/bob-lied/perl/t/FrequencySort.t @@ -0,0 +1,16 @@ +# vim:set ts=4 sw=4 sts=4 et ai wm=0 nu: +# +#=============================================================================== +# FILE: FrequencySort.t +# DESCRIPTION: Unit test for FrequencySort +#=============================================================================== + +use strict; +use warnings; +use v5.30; + +use Test2::V0; + +use FrequencySort; + +done_testing(); diff --git a/challenge-081/bob-lied/perl/t/input b/challenge-081/bob-lied/perl/t/input new file mode 100644 index 0000000000..5905c36971 --- /dev/null +++ b/challenge-081/bob-lied/perl/t/input @@ -0,0 +1,13 @@ +West Side Story + +The award-winning adaptation of the classic romantic tragedy "Romeo and +Juliet". The feuding families become two warring New York City gangs, the +white Jets led by Riff and the Latino Sharks, led by Bernardo. Their hatred +escalates to a point where neither can coexist with any form of understanding. +But when Riff's best friend (and former Jet) Tony and Bernardo's younger +sister Maria meet at a dance, no one can do anything to stop their love. Maria +and Tony begin meeting in secret, planning to run away. Then the Sharks and +Jets plan a rumble under the highway--whoever wins gains control of the +streets. Maria sends Tony to stop it, hoping it can end the violence. It goes +terribly wrong, and before the lovers know what's happened, tragedy strikes +and doesn't stop until the climactic and heartbreaking ending. -- cgit From 4b6202a6507cb1e1e3854fa643fc25714dc930a2 Mon Sep 17 00:00:00 2001 From: Walt Mankowski Date: Tue, 6 Oct 2020 19:34:55 -0400 Subject: perl solution to challenge 81 task 1 --- challenge-081/walt-mankowski/perl/ch-1.pl | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 challenge-081/walt-mankowski/perl/ch-1.pl (limited to 'challenge-081') diff --git a/challenge-081/walt-mankowski/perl/ch-1.pl b/challenge-081/walt-mankowski/perl/ch-1.pl new file mode 100644 index 0000000000..9a91c9d8db --- /dev/null +++ b/challenge-081/walt-mankowski/perl/ch-1.pl @@ -0,0 +1,28 @@ +#!/usr/bin/env perl +use strict; +use warnings; +use feature qw(:5.32); +use experimental qw(signatures); +use List::Util qw(min); + +# You are given 2 strings, $A and $B. +# +# Write a script to find out common base strings in $A and $B. +# +# A substring of a string $S is called base string if repeated +# concatenation of the substring results in the string. + +my ($A, $B) = @ARGV; +my $max_base_len = min(length($A), length($B)); + +for my $i (1 .. $max_base_len) { + if (is_base(substr($A, 0, $i), $A) && is_base(substr($B, 0, $i), $B)) { + say substr($A, 0, $i); + } +} + +sub is_base($prefix, $s) { + my $cnt = length($s) / length($prefix); + return $prefix x $cnt eq $s; +} + -- cgit From 6c58dba68670dfc7c703bb4a39455196eb3dbd97 Mon Sep 17 00:00:00 2001 From: Walt Mankowski Date: Tue, 6 Oct 2020 19:40:07 -0400 Subject: cleaned up the code a bit --- challenge-081/walt-mankowski/perl/ch-1.pl | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'challenge-081') diff --git a/challenge-081/walt-mankowski/perl/ch-1.pl b/challenge-081/walt-mankowski/perl/ch-1.pl index 9a91c9d8db..130a121916 100644 --- a/challenge-081/walt-mankowski/perl/ch-1.pl +++ b/challenge-081/walt-mankowski/perl/ch-1.pl @@ -16,8 +16,9 @@ my ($A, $B) = @ARGV; my $max_base_len = min(length($A), length($B)); for my $i (1 .. $max_base_len) { - if (is_base(substr($A, 0, $i), $A) && is_base(substr($B, 0, $i), $B)) { - say substr($A, 0, $i); + my $prefix = substr($A, 0, $i); + if (is_base($prefix, $A) && is_base($prefix, $B)) { + say $prefix; } } -- cgit From fb9bee1b7c989e55ca10b43bc2553700f558aabd Mon Sep 17 00:00:00 2001 From: Walt Mankowski Date: Tue, 6 Oct 2020 19:57:20 -0400 Subject: perl code for challenge 81 task 2 --- challenge-081/walt-mankowski/perl/ch-2.pl | 44 +++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 challenge-081/walt-mankowski/perl/ch-2.pl (limited to 'challenge-081') diff --git a/challenge-081/walt-mankowski/perl/ch-2.pl b/challenge-081/walt-mankowski/perl/ch-2.pl new file mode 100644 index 0000000000..68e2900945 --- /dev/null +++ b/challenge-081/walt-mankowski/perl/ch-2.pl @@ -0,0 +1,44 @@ +#!/usr/bin/env perl +use strict; +use warnings; +use feature qw(:5.32); +use experimental qw(signatures); + +# You are given file named input. +# +# Write a script to find the frequency of all the words. +# +# It should print the result as first column of each line should be +# the frequency of the the word followed by all the words of that +# frequency arranged in lexicographical order. Also sort the words in +# the ascending order of frequency. +# +# For the sake of this task, please ignore the following in the input file: +# +# . " ( ) , 's -- + +my %h; + +while (<>) { + chomp; + s/--/ /; + my @tok = split / /; + for my $tok (@tok) { + $tok =~ s/[."(),]//g; + $tok =~ s/'s$//; + $h{$tok}++; + } +} + +my $last = 0; +for my $k (sort { $h{$a} <=> $h{$b} || $a cmp $b } keys %h) { + if ($h{$k} != $last) { + print "\n" unless $last == 0; + print $h{$k}; + $last = $h{$k}; + } + print " $k"; +} + +print "\n"; + -- cgit From 7af4d2a5a2c40a060f78972bd974af2ee836c631 Mon Sep 17 00:00:00 2001 From: Walt Mankowski Date: Tue, 6 Oct 2020 19:57:27 -0400 Subject: input file for challenge 81 task 2 --- challenge-081/walt-mankowski/perl/input.txt | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 challenge-081/walt-mankowski/perl/input.txt (limited to 'challenge-081') diff --git a/challenge-081/walt-mankowski/perl/input.txt b/challenge-081/walt-mankowski/perl/input.txt new file mode 100644 index 0000000000..649cf57770 --- /dev/null +++ b/challenge-081/walt-mankowski/perl/input.txt @@ -0,0 +1,15 @@ +West Side Story + +The award-winning adaptation of the classic romantic tragedy "Romeo +and Juliet". The feuding families become two warring New York City +gangs, the white Jets led by Riff and the Latino Sharks, led by +Bernardo. Their hatred escalates to a point where neither can coexist +with any form of understanding. But when Riff's best friend (and +former Jet) Tony and Bernardo's younger sister Maria meet at a dance, +no one can do anything to stop their love. Maria and Tony begin +meeting in secret, planning to run away. Then the Sharks and Jets plan +a rumble under the highway--whoever wins gains control of the +streets. Maria sends Tony to stop it, hoping it can end the +violence. It goes terribly wrong, and before the lovers know what's +happened, tragedy strikes and doesn't stop until the climactic and +heartbreaking ending. -- cgit From 293c72bd0be6f09dba088d564d92d6820357bb3e Mon Sep 17 00:00:00 2001 From: Walt Mankowski Date: Tue, 6 Oct 2020 21:08:46 -0400 Subject: python solutions to challenge 81 --- challenge-081/walt-mankowski/python/ch-1.py | 13 +++++++++++++ challenge-081/walt-mankowski/python/ch-2.py | 29 +++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 challenge-081/walt-mankowski/python/ch-1.py create mode 100644 challenge-081/walt-mankowski/python/ch-2.py (limited to 'challenge-081') diff --git a/challenge-081/walt-mankowski/python/ch-1.py b/challenge-081/walt-mankowski/python/ch-1.py new file mode 100644 index 0000000000..a268b371f5 --- /dev/null +++ b/challenge-081/walt-mankowski/python/ch-1.py @@ -0,0 +1,13 @@ +from sys import argv + +def is_base(prefix, s): + cnt = int(len(s) / len(prefix)) + return prefix * cnt == s + +a, b = argv[1:] +max_base_len = min(len(a), len(b)) + +for i in range(1, max_base_len+1): + prefix = a[0:i] + if is_base(prefix, a) and is_base(prefix, b): + print(prefix) diff --git a/challenge-081/walt-mankowski/python/ch-2.py b/challenge-081/walt-mankowski/python/ch-2.py new file mode 100644 index 0000000000..2b6c400b45 --- /dev/null +++ b/challenge-081/walt-mankowski/python/ch-2.py @@ -0,0 +1,29 @@ +from sys import argv +from collections import defaultdict +import re + +d = defaultdict(int) +fname = argv[1] +with open(fname) as f: + for line in f: + line = line.rstrip() + line = re.sub('--', ' ', line) + if line == '': + continue + toks = line.split(' ') + for tok in toks: + tok = re.sub('[."(),]', '', tok); + tok = re.sub("'s$", '', tok) + d[tok] += 1 + +last = 0 +for k in sorted(d, key=lambda k:(d[k], k)): + if d[k] != last: + if last != 0: + print() + print(d[k], end='') + last = d[k] + print(f" {k}", end = '') + +print() + -- cgit From ad08b2b87cc19ab0320df5ed8f72cb7471edb078 Mon Sep 17 00:00:00 2001 From: Nuno Vieira Date: Thu, 8 Oct 2020 00:21:23 +0100 Subject: Add nunovieira220 perl solution to challenge 081 --- challenge-081/nunovieira220/perl/ch-1.pl | 22 ++++++++++++++++++ challenge-081/nunovieira220/perl/ch-2.pl | 36 ++++++++++++++++++++++++++++++ challenge-081/nunovieira220/perl/input.txt | 3 +++ 3 files changed, 61 insertions(+) create mode 100644 challenge-081/nunovieira220/perl/ch-1.pl create mode 100644 challenge-081/nunovieira220/perl/ch-2.pl create mode 100644 challenge-081/nunovieira220/perl/input.txt (limited to 'challenge-081') diff --git a/challenge-081/nunovieira220/perl/ch-1.pl b/challenge-081/nunovieira220/perl/ch-1.pl new file mode 100644 index 0000000000..1c33299ac0 --- /dev/null +++ b/challenge-081/nunovieira220/perl/ch-1.pl @@ -0,0 +1,22 @@ +#!/usr/bin/perl + +use strict; +use warnings; +use List::Util qw[min max]; + +# Input +my $A = "abcdabcd"; +my $B = "abcdabcdabcdabcd"; + +# Common Base String +my @res = (); +my $len = min(length($A), length($B)); + +for (my $i = 0; $i < $len; $i++) { + my $base = substr($A, 0, $i+1); + + push(@res, $base) if($A =~ /^($base)+$/ && $B =~ /^($base)+$/); +} + +# Output +print join(', ', @res); \ No newline at end of file diff --git a/challenge-081/nunovieira220/perl/ch-2.pl b/challenge-081/nunovieira220/perl/ch-2.pl new file mode 100644 index 0000000000..5bb3b73619 --- /dev/null +++ b/challenge-081/nunovieira220/perl/ch-2.pl @@ -0,0 +1,36 @@ +#!/usr/bin/perl + +use strict; +use warnings; +use File::Basename; + +# Input +open(my $fh, "<", dirname(__FILE__)."/input.txt") or die "Can't open < input.txt: $!"; + +my %sums = (); +my %freqs = (); + +# Get word frenquencies from file +while(<$fh>) { + chomp; + s/--/ /g; + my @words = split(/ /, $_); + + for(@words) { + $_ =~ s/\.|"|'s|,|\(|\)//g; + $sums{$_} = $sums{$_} ? $sums{$_} + 1 : 1; + } +} + +# Join words by frequency +for(sort keys %sums) { + $freqs{$sums{$_}} = () if(!$freqs{$sums{$_}}); + + push @{$freqs{$sums{$_}}}, $_; +} + +# Output +for(sort keys %freqs) { + my $res = join(', ', @{$freqs{$_}}); + print $_.": ".$res."\n"; +} \ No newline at end of file diff --git a/challenge-081/nunovieira220/perl/input.txt b/challenge-081/nunovieira220/perl/input.txt new file mode 100644 index 0000000000..d2bb45d308 --- /dev/null +++ b/challenge-081/nunovieira220/perl/input.txt @@ -0,0 +1,3 @@ +West Side Story + +The award-winning adaptation of the classic romantic tragedy "Romeo and Juliet". The feuding families become two warring New York City gangs, the white Jets led by Riff and the Latino Sharks, led by Bernardo. Their hatred escalates to a point where neither can coexist with any form of understanding. But when Riff's best friend (and former Jet) Tony and Bernardo's younger sister Maria meet at a dance, no one can do anything to stop their love. Maria and Tony begin meeting in secret, planning to run away. Then the Sharks and Jets plan a rumble under the highway--whoever wins gains control of the streets. Maria sends Tony to stop it, hoping it can end the violence. It goes terribly wrong, and before the lovers know what's happened, tragedy strikes and doesn't stop until the climactic and heartbreaking ending. \ No newline at end of file -- cgit From 1c2a38e61c7dcf97185d5835b9f08e9dbf17179b Mon Sep 17 00:00:00 2001 From: Nuno Vieira Date: Thu, 8 Oct 2020 00:21:39 +0100 Subject: Add nunovieira220 js solution to challenge 081 --- challenge-081/nunovieira220/js/ch-1.js | 17 +++++++++++++++++ challenge-081/nunovieira220/js/ch-2.js | 25 +++++++++++++++++++++++++ challenge-081/nunovieira220/js/input.txt | 3 +++ 3 files changed, 45 insertions(+) create mode 100644 challenge-081/nunovieira220/js/ch-1.js create mode 100644 challenge-081/nunovieira220/js/ch-2.js create mode 100644 challenge-081/nunovieira220/js/input.txt (limited to 'challenge-081') diff --git a/challenge-081/nunovieira220/js/ch-1.js b/challenge-081/nunovieira220/js/ch-1.js new file mode 100644 index 0000000000..2582e1b9a3 --- /dev/null +++ b/challenge-081/nunovieira220/js/ch-1.js @@ -0,0 +1,17 @@ +// Input +const A = 'abcdabcd'; +const B = 'abcdabcdabcdabcd'; + +// Common Base String +const res = []; +const len = Math.min(A.length, B.length); + +for (let i = 0; i < len; i++) { + const base = A.substring(0, i + 1); + const regex = new RegExp(`^(${base})+$`); + + if(A.match(regex) && B.match(regex)) res.push(base); +} + +// Output +console.log(res); \ No newline at end of file diff --git a/challenge-081/nunovieira220/js/ch-2.js b/challenge-081/nunovieira220/js/ch-2.js new file mode 100644 index 0000000000..9d76ffd1a5 --- /dev/null +++ b/challenge-081/nunovieira220/js/ch-2.js @@ -0,0 +1,25 @@ +const fs = require('fs'); + +// Input +const sums = {}; +const freqs = {}; +const data = fs.readFileSync(`${__dirname}/input.txt`, { encoding: 'utf8' }); +const words = data.replace(/--|\n/g, ' ').split(/ /); + +// Get word frenquencies from word list +words.forEach(token => { + if(token) { + const word = token.replace(/\.|"|'s|,|\(|\)/g, ''); + sums[word] = sums[word] ? sums[word] + 1 : 1; + } +}); + +// Join words by frequency +Object.keys(sums).sort().forEach(word => { + if(!freqs[sums[word]]) freqs[sums[word]] = []; + + freqs[sums[word]].push(word); +}); + +// Output +Object.keys(freqs).sort().forEach(freq => console.log(freq + ': ' + freqs[freq].join(', '))); \ No newline at end of file diff --git a/challenge-081/nunovieira220/js/input.txt b/challenge-081/nunovieira220/js/input.txt new file mode 100644 index 0000000000..d2bb45d308 --- /dev/null +++ b/challenge-081/nunovieira220/js/input.txt @@ -0,0 +1,3 @@ +West Side Story + +The award-winning adaptation of the classic romantic tragedy "Romeo and Juliet". The feuding families become two warring New York City gangs, the white Jets led by Riff and the Latino Sharks, led by Bernardo. Their hatred escalates to a point where neither can coexist with any form of understanding. But when Riff's best friend (and former Jet) Tony and Bernardo's younger sister Maria meet at a dance, no one can do anything to stop their love. Maria and Tony begin meeting in secret, planning to run away. Then the Sharks and Jets plan a rumble under the highway--whoever wins gains control of the streets. Maria sends Tony to stop it, hoping it can end the violence. It goes terribly wrong, and before the lovers know what's happened, tragedy strikes and doesn't stop until the climactic and heartbreaking ending. \ No newline at end of file -- cgit From a3d7d532eab68e3edde77df48b701485ef6f38ad Mon Sep 17 00:00:00 2001 From: "Markus \"Holli\" Holzer" Date: Thu, 8 Oct 2020 15:11:46 +0200 Subject: bugfix and optimization --- challenge-081/markus-holzer/raku/ch-1.raku | 14 +++++++++----- challenge-081/markus-holzer/raku/ch-2.raku | 2 +- 2 files changed, 10 insertions(+), 6 deletions(-) (limited to 'challenge-081') diff --git a/challenge-081/markus-holzer/raku/ch-1.raku b/challenge-081/markus-holzer/raku/ch-1.raku index ee685600da..f3b9e8c8e6 100644 --- a/challenge-081/markus-holzer/raku/ch-1.raku +++ b/challenge-081/markus-holzer/raku/ch-1.raku @@ -1,10 +1,14 @@ unit sub MAIN( Str, Str ); -my Str $A = @*ARGS.min; -my Str $B = @*ARGS.max; +my Str $A = @*ARGS.min(*.chars); +my Str $B = @*ARGS.max(*.chars); # Custom operator, just for fun -multi sub infix:<%%>( Str $n, Str $d ) { - $n eq $d x $n.chars div $d.chars } +multi sub infix:<%%>( Str $n, Str $d ) returns Bool { + #will always be a Rat + given $n.chars / $d.chars { + .denominator == 1 + ?? $n eq $d x $_ + !! False }} -.say for grep $B %% *, [\~] $A.comb \ No newline at end of file +.say for grep all($A, $B) %% *, [\~] $A.comb \ No newline at end of file diff --git a/challenge-081/markus-holzer/raku/ch-2.raku b/challenge-081/markus-holzer/raku/ch-2.raku index 7f6ab7aadc..c9d0bad20c 100644 --- a/challenge-081/markus-holzer/raku/ch-2.raku +++ b/challenge-081/markus-holzer/raku/ch-2.raku @@ -11,4 +11,4 @@ my $words = $file .classify( *.value ); say "{$_} : {sort $words{$_}>>.key}" - for sort $words.keys; \ No newline at end of file + for sort keys $words; \ No newline at end of file -- cgit From 1cdbe1caf321faa72362f4a6c2c8ba5ec0c36ba0 Mon Sep 17 00:00:00 2001 From: "Markus \"Holli\" Holzer" Date: Thu, 8 Oct 2020 15:17:22 +0200 Subject: bugfix and optimization --- challenge-081/markus-holzer/raku/ch-1.raku | 1 - 1 file changed, 1 deletion(-) (limited to 'challenge-081') diff --git a/challenge-081/markus-holzer/raku/ch-1.raku b/challenge-081/markus-holzer/raku/ch-1.raku index f3b9e8c8e6..db9c216af9 100644 --- a/challenge-081/markus-holzer/raku/ch-1.raku +++ b/challenge-081/markus-holzer/raku/ch-1.raku @@ -5,7 +5,6 @@ my Str $B = @*ARGS.max(*.chars); # Custom operator, just for fun multi sub infix:<%%>( Str $n, Str $d ) returns Bool { - #will always be a Rat given $n.chars / $d.chars { .denominator == 1 ?? $n eq $d x $_ -- cgit From 9817474c0b7f76d936b16a38a836c13bf6d69ab3 Mon Sep 17 00:00:00 2001 From: "Markus \"Holli\" Holzer" Date: Thu, 8 Oct 2020 15:38:00 +0200 Subject: bugfix and optimization --- challenge-081/markus-holzer/raku/ch-1.raku | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) (limited to 'challenge-081') diff --git a/challenge-081/markus-holzer/raku/ch-1.raku b/challenge-081/markus-holzer/raku/ch-1.raku index db9c216af9..d29156c0bb 100644 --- a/challenge-081/markus-holzer/raku/ch-1.raku +++ b/challenge-081/markus-holzer/raku/ch-1.raku @@ -6,8 +6,6 @@ my Str $B = @*ARGS.max(*.chars); # Custom operator, just for fun multi sub infix:<%%>( Str $n, Str $d ) returns Bool { given $n.chars / $d.chars { - .denominator == 1 - ?? $n eq $d x $_ - !! False }} + .denominator == 1 && $n eq $d x $_ }} -.say for grep all($A, $B) %% *, [\~] $A.comb \ No newline at end of file +.say for grep all($A, $B) %% *, [\~] $A.comb; -- cgit From 94fb7bfc97525637029b22a4727db362edde6374 Mon Sep 17 00:00:00 2001 From: "Markus \"Holli\" Holzer" Date: Thu, 8 Oct 2020 15:40:30 +0200 Subject: avoid $_ --- challenge-081/markus-holzer/raku/ch-1.raku | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'challenge-081') diff --git a/challenge-081/markus-holzer/raku/ch-1.raku b/challenge-081/markus-holzer/raku/ch-1.raku index d29156c0bb..e9a18dd53e 100644 --- a/challenge-081/markus-holzer/raku/ch-1.raku +++ b/challenge-081/markus-holzer/raku/ch-1.raku @@ -6,6 +6,6 @@ my Str $B = @*ARGS.max(*.chars); # Custom operator, just for fun multi sub infix:<%%>( Str $n, Str $d ) returns Bool { given $n.chars / $d.chars { - .denominator == 1 && $n eq $d x $_ }} + .denominator == 1 && $n eq $d x .numerator }} .say for grep all($A, $B) %% *, [\~] $A.comb; -- cgit From f5e4a7bc97c2642cf5cc3650a062c37bb8b4dbc7 Mon Sep 17 00:00:00 2001 From: Tyler Wardhaugh Date: Thu, 8 Oct 2020 13:27:25 -0700 Subject: Ch81/Task 2: optimize and add comments We just need a count of the words, which can be achieved by summing (via x/reduce +) 1 for every instance we find. Add comments to clarify what the algorithm is doing at each step. --- challenge-081/tyler-wardhaugh/clojure/src/tw/weekly/c81/t2.clj | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'challenge-081') diff --git a/challenge-081/tyler-wardhaugh/clojure/src/tw/weekly/c81/t2.clj b/challenge-081/tyler-wardhaugh/clojure/src/tw/weekly/c81/t2.clj index 543a1f54b6..c126e053b3 100644 --- a/challenge-081/tyler-wardhaugh/clojure/src/tw/weekly/c81/t2.clj +++ b/challenge-081/tyler-wardhaugh/clojure/src/tw/weekly/c81/t2.clj @@ -18,10 +18,10 @@ [source] (let [cleaner (fn [s] (str/replace s #"(?:[.\"\(\),]|'s|--|\n)" " ")) splitter (fn [s] (str/split s #" ")) - xf (comp (mapcat (comp splitter cleaner)) - (remove #{""}) - (x/by-key identity (x/into [])) - (x/by-key (comp count second) first (x/into (sorted-set))))] + xf (comp (mapcat (comp splitter cleaner)) ; wordify + (remove #{""}) ; discard empty strings + (x/by-key identity (constantly 1) (x/reduce +)) ; hash (word => count) + (x/by-key second first (x/into (sorted-set))))] ; invert hash, combine words (into (sorted-map) xf source))) (defn -main -- cgit From 973c66cd12ed324880767de16c4788e376ff778f Mon Sep 17 00:00:00 2001 From: Lubos Kolouch Date: Fri, 9 Oct 2020 10:55:06 +0200 Subject: Challenge 081 Task 1 LK Perl --- challenge-081/lubos-kolouch/perl/ch-1.pl | 50 ++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 challenge-081/lubos-kolouch/perl/ch-1.pl (limited to 'challenge-081') diff --git a/challenge-081/lubos-kolouch/perl/ch-1.pl b/challenge-081/lubos-kolouch/perl/ch-1.pl new file mode 100644 index 0000000000..6aed6bb23b --- /dev/null +++ b/challenge-081/lubos-kolouch/perl/ch-1.pl @@ -0,0 +1,50 @@ +#!/usr/bin/perl +#=============================================================================== +# +# FILE: ch-1.pl +# +# USAGE: ./ch-1.pl +# +# DESCRIPTION: Perl Weekly Challenge 081 +# https://perlweeklychallenge.org/blog/perl-weekly-challenge-081/ +# Task 1 - Common base string +# +# OPTIONS: --- +# REQUIREMENTS: --- +# BUGS: --- +# NOTES: --- +# AUTHOR: YOUR NAME (), +# ORGANIZATION: +# VERSION: 1.0 +# CREATED: 10/09/2020 10:43:10 AM +# REVISION: --- +#=============================================================================== + +use strict; +use warnings; + + +sub get_common_strings { + my $arg = shift; + + my $str1 = $arg->{str1}; + my $str2 = $arg->{str2}; + + my @result; + + my ($res1) = $str1 =~ /(.*)\1+/; + push @result, $res1; + + my ($res2) = $str2 =~ /(.*)\1+/; + push @result, $res2 unless $res1 eq $res2; + + return \@result; + +} + +use Test::More; + +is_deeply(get_common_strings({str1 => 'abcdabcd', str2 => 'abcdabcdabcdabcd'} ),['abcd','abcdabcd']); +is_deeply(get_common_strings({str1 => 'aaa', str2 => 'aa'} ),['a']); +is_deeply(get_common_strings({str1 => 'abc', str2 => 'aa'} ),['','a']); + -- cgit From 0b0246ec4c2367a968b49aeb3f876e34e448344c Mon Sep 17 00:00:00 2001 From: Lubos Kolouch Date: Fri, 9 Oct 2020 11:59:28 +0200 Subject: Challenge 2 Perl --- challenge-081/lubos-kolouch/perl/ch-1.pl | 1 + challenge-081/lubos-kolouch/perl/ch-2.pl | 56 ++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 challenge-081/lubos-kolouch/perl/ch-2.pl (limited to 'challenge-081') diff --git a/challenge-081/lubos-kolouch/perl/ch-1.pl b/challenge-081/lubos-kolouch/perl/ch-1.pl index 6aed6bb23b..9890053c01 100644 --- a/challenge-081/lubos-kolouch/perl/ch-1.pl +++ b/challenge-081/lubos-kolouch/perl/ch-1.pl @@ -48,3 +48,4 @@ is_deeply(get_common_strings({str1 => 'abcdabcd', str2 => 'abcdabcdabcdabcd'} ), is_deeply(get_common_strings({str1 => 'aaa', str2 => 'aa'} ),['a']); is_deeply(get_common_strings({str1 => 'abc', str2 => 'aa'} ),['','a']); +done_testing; diff --git a/challenge-081/lubos-kolouch/perl/ch-2.pl b/challenge-081/lubos-kolouch/perl/ch-2.pl new file mode 100644 index 0000000000..c8d93d17f8 --- /dev/null +++ b/challenge-081/lubos-kolouch/perl/ch-2.pl @@ -0,0 +1,56 @@ +#!/usr/bin/perl +#=============================================================================== +# +# FILE: ch-1.pl +# +# USAGE: ./ch-1.pl +# +# DESCRIPTION: Perl Weekly Challenge 081 +# https://perlweeklychallenge.org/blog/perl-weekly-challenge-081/ +# Task 2 - Frequency Sort +# +# AUTHOR: Lubos Kolouch +# CREATED: 10/09/2020 10:43:10 AM +#=============================================================================== + +use strict; +use warnings; +use Data::Dumper; + +sub frequency_sort { + my $arg = shift; + + # sanitize the input as per the challenge + $arg =~ s/[."\(\)--]/ /g; + $arg =~ s/(?:'s)/ /g; + + my %count; + # I'm sure it can be done in one-liner with map, but I took the longer approach + + # First split the array and create hash of counts of each word + for (split ' ', $arg) { + $count{$_}++; + } + + my %rev_count; + + # create reverse hash with counts as key and the words as array + my @result; + for my $key (keys %count) { + push @{$rev_count{$count{$key}}}, $key; + } + + # sort the arrays and put them to the result output + for my $key (keys %rev_count) { + push @result, $key.' '.join(' ', sort @{$rev_count{$key}}); + } + + return [sort @result]; + +} + +use Test::More; + +is_deeply(frequency_sort("West Side Story The award-winning adaptation of the classic romantic tragedy \"Romeo and Juliet\". The feuding families become two warring New York City gangs, the white Jets led by Riff and the Latino Sharks, led by Bernardo. Their hatred escalates to a point where neither can coexist with any form of understanding. But when Riff\'s best friend (and former Jet) Tony and Bernardo\'s younger sister Maria meet at a dance, no one can do anything to stop their love. Maria and Tony begin meeting in secret, planning to run away. Then the Sharks and Jets plan a rumble under the highway--whoever wins gains control of the streets. Maria sends Tony to stop it, hoping it can end the violence. It goes terribly wrong, and before the lovers know what\'s happened, tragedy strikes and doesn\'t stop until the climactic and heartbreaking ending." ),['1 But City It Jet Juliet Latino New Romeo Side Story Their Then West York adaptation any anything at award away become before begin best classic climactic coexist control dance do doesn\'t end ending escalates families feuding form former friend gains gangs goes happened hatred heartbreaking highway hoping in know love lovers meet meeting neither no one plan planning point romantic rumble run secret sends sister streets strikes terribly their two under understanding until violence warring what when where white whoever winning wins with wrong younger', '2 Bernardo Jets Riff Sharks The by it led tragedy','3 Maria Tony a can of stop','4 to','9 and the']); + +done_testing; -- cgit From 57a96cc9711fbab23187d8b1d10a1ad55a030d3e Mon Sep 17 00:00:00 2001 From: Frank Oosterhuis Date: Fri, 9 Oct 2020 15:15:41 +0200 Subject: WordCount --- challenge-081/frankivo/README | 1 + challenge-081/frankivo/scala/WestSideStory.txt | 3 +++ challenge-081/frankivo/scala/WordCount.scala | 22 ++++++++++++++++++++++ 3 files changed, 26 insertions(+) create mode 100644 challenge-081/frankivo/README create mode 100644 challenge-081/frankivo/scala/WestSideStory.txt create mode 100644 challenge-081/frankivo/scala/WordCount.scala (limited to 'challenge-081') diff --git a/challenge-081/frankivo/README b/challenge-081/frankivo/README new file mode 100644 index 0000000000..681b15b36c --- /dev/null +++ b/challenge-081/frankivo/README @@ -0,0 +1 @@ +Solution by Frank Oosterhuis. diff --git a/challenge-081/frankivo/scala/WestSideStory.txt b/challenge-081/frankivo/scala/WestSideStory.txt new file mode 100644 index 0000000000..7c77fa54a9 --- /dev/null +++ b/challenge-081/frankivo/scala/WestSideStory.txt @@ -0,0 +1,3 @@ +West Side Story + +The award-winning adaptation of the classic romantic tragedy "Romeo and Juliet". The feuding families become two warring New York City gangs, the white Jets led by Riff and the Latino Sharks, led by Bernardo. Their hatred escalates to a point where neither can coexist with any form of understanding. But when Riff's best friend (and former Jet) Tony and Bernardo's younger sister Maria meet at a dance, no one can do anything to stop their love. Maria and Tony begin meeting in secret, planning to run away. Then the Sharks and Jets plan a rumble under the highway--whoever wins gains control of the streets. Maria sends Tony to stop it, hoping it can end the violence. It goes terribly wrong, and before the lovers know what's happened, tragedy strikes and doesn't stop until the climactic and heartbreaking ending. \ No newline at end of file diff --git a/challenge-081/frankivo/scala/WordCount.scala b/challenge-081/frankivo/scala/WordCount.scala new file mode 100644 index 0000000000..c9917146d4 --- /dev/null +++ b/challenge-081/frankivo/scala/WordCount.scala @@ -0,0 +1,22 @@ +object WordCount { + + def main(args: Array[String]): Unit = { + println(getCounts("WestSideStory.txt")) + } + + def getCounts(filename: String): String = { + scala.io.Source.fromFile(filename) + .getLines + .mkString(" ") + .replaceAll("(\\.|\"|\\(|\\)|,|'s|--)", "") + .split(" ") + .filter(_.length > 0) + .groupMapReduce(identity)(_ => 1)(_ + _) + .groupBy(c => c._2) + .map(x => (x._1, x._2.keys)) + .toList + .sortBy(_._1) + .map(x => s"${x._1} ${x._2.mkString(" ")}") + .mkString("\n\n") + } +} \ No newline at end of file -- cgit From 92ec88f28334de0e18d3bbeaf314b170078cf475 Mon Sep 17 00:00:00 2001 From: Lubos Kolouch Date: Fri, 9 Oct 2020 15:59:10 +0200 Subject: Python solution Task 1 LK --- challenge-081/lubos-kolouch/perl/ch-1.pl | 8 +------ challenge-081/lubos-kolouch/python/ch-1.py | 36 ++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 7 deletions(-) create mode 100644 challenge-081/lubos-kolouch/python/ch-1.py (limited to 'challenge-081') diff --git a/challenge-081/lubos-kolouch/perl/ch-1.pl b/challenge-081/lubos-kolouch/perl/ch-1.pl index 9890053c01..fe05fd99fd 100644 --- a/challenge-081/lubos-kolouch/perl/ch-1.pl +++ b/challenge-081/lubos-kolouch/perl/ch-1.pl @@ -9,15 +9,9 @@ # https://perlweeklychallenge.org/blog/perl-weekly-challenge-081/ # Task 1 - Common base string # -# OPTIONS: --- -# REQUIREMENTS: --- -# BUGS: --- -# NOTES: --- -# AUTHOR: YOUR NAME (), -# ORGANIZATION: +# AUTHOR: Lubos Kolouch # VERSION: 1.0 # CREATED: 10/09/2020 10:43:10 AM -# REVISION: --- #=============================================================================== use strict; diff --git a/challenge-081/lubos-kolouch/python/ch-1.py b/challenge-081/lubos-kolouch/python/ch-1.py new file mode 100644 index 0000000000..e3b1b080ce --- /dev/null +++ b/challenge-081/lubos-kolouch/python/ch-1.py @@ -0,0 +1,36 @@ +#!/bin/env python +""" =============================================================================== +# +# FILE: ch-1.py +# +# USAGE: ./ch-1.py +# +# DESCRIPTION: Perl Weekly Challenge 081 +# https://perlweeklychallenge.org/blog/perl-weekly-challenge-081/ +# Task 1 - Common base string +# +# AUTHOR: Lubos Kolouch +# CREATED: 10/09/2020 10:43:10 AM +#=============================================================================== +""" +import re + + +def get_common_strings(str1, str2): + """ Find and return the common strings """ + + result = [] + res1 = re.match(r'(.*)\1+', str1) + + result.append(res1.group(1)) + + res2 = re.match(r'(.*)\1+', str2) + if res1.group(1) != res2.group(1): + result.append(res2.group(1)) + + return result + + +assert get_common_strings('abcdabcd', 'abcdabcdabcdabcd') == ['abcd','abcdabcd'] +assert get_common_strings('aaa', 'aa') == ['a'] +assert get_common_strings('abc', 'aa') == ['','a'] -- cgit From 9b1d06e752e91bb03f909b4305e5c1a19d5f27a4 Mon Sep 17 00:00:00 2001 From: Lubos Kolouch Date: Fri, 9 Oct 2020 21:42:53 +0200 Subject: Perl regex fixes and Python solution --- challenge-081/lubos-kolouch/perl/ch-2.pl | 5 +-- challenge-081/lubos-kolouch/python/ch-2.py | 55 ++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 2 deletions(-) create mode 100644 challenge-081/lubos-kolouch/python/ch-2.py (limited to 'challenge-081') diff --git a/challenge-081/lubos-kolouch/perl/ch-2.pl b/challenge-081/lubos-kolouch/perl/ch-2.pl index c8d93d17f8..0a6e16b0ef 100644 --- a/challenge-081/lubos-kolouch/perl/ch-2.pl +++ b/challenge-081/lubos-kolouch/perl/ch-2.pl @@ -21,8 +21,9 @@ sub frequency_sort { my $arg = shift; # sanitize the input as per the challenge - $arg =~ s/[."\(\)--]/ /g; + $arg =~ s/[."\(\),]/ /g; $arg =~ s/(?:'s)/ /g; + $arg =~ s/(?:--)/ /g; my %count; # I'm sure it can be done in one-liner with map, but I took the longer approach @@ -51,6 +52,6 @@ sub frequency_sort { use Test::More; -is_deeply(frequency_sort("West Side Story The award-winning adaptation of the classic romantic tragedy \"Romeo and Juliet\". The feuding families become two warring New York City gangs, the white Jets led by Riff and the Latino Sharks, led by Bernardo. Their hatred escalates to a point where neither can coexist with any form of understanding. But when Riff\'s best friend (and former Jet) Tony and Bernardo\'s younger sister Maria meet at a dance, no one can do anything to stop their love. Maria and Tony begin meeting in secret, planning to run away. Then the Sharks and Jets plan a rumble under the highway--whoever wins gains control of the streets. Maria sends Tony to stop it, hoping it can end the violence. It goes terribly wrong, and before the lovers know what\'s happened, tragedy strikes and doesn\'t stop until the climactic and heartbreaking ending." ),['1 But City It Jet Juliet Latino New Romeo Side Story Their Then West York adaptation any anything at award away become before begin best classic climactic coexist control dance do doesn\'t end ending escalates families feuding form former friend gains gangs goes happened hatred heartbreaking highway hoping in know love lovers meet meeting neither no one plan planning point romantic rumble run secret sends sister streets strikes terribly their two under understanding until violence warring what when where white whoever winning wins with wrong younger', '2 Bernardo Jets Riff Sharks The by it led tragedy','3 Maria Tony a can of stop','4 to','9 and the']); +is_deeply(frequency_sort("West Side Story The award-winning adaptation of the classic romantic tragedy \"Romeo and Juliet\". The feuding families become two warring New York City gangs, the white Jets led by Riff and the Latino Sharks, led by Bernardo. Their hatred escalates to a point where neither can coexist with any form of understanding. But when Riff\'s best friend (and former Jet) Tony and Bernardo\'s younger sister Maria meet at a dance, no one can do anything to stop their love. Maria and Tony begin meeting in secret, planning to run away. Then the Sharks and Jets plan a rumble under the highway--whoever wins gains control of the streets. Maria sends Tony to stop it, hoping it can end the violence. It goes terribly wrong, and before the lovers know what\'s happened, tragedy strikes and doesn\'t stop until the climactic and heartbreaking ending." ),['1 But City It Jet Juliet Latino New Romeo Side Story Their Then West York adaptation any anything at award-winning away become before begin best classic climactic coexist control dance do doesn\'t end ending escalates families feuding form former friend gains gangs goes happened hatred heartbreaking highway hoping in know love lovers meet meeting neither no one plan planning point romantic rumble run secret sends sister streets strikes terribly their two under understanding until violence warring what when where white whoever wins with wrong younger', '2 Bernardo Jets Riff Sharks The by it led tragedy','3 Maria Tony a can of stop','4 to','9 and the']); done_testing; diff --git a/challenge-081/lubos-kolouch/python/ch-2.py b/challenge-081/lubos-kolouch/python/ch-2.py new file mode 100644 index 0000000000..8160fc3593 --- /dev/null +++ b/challenge-081/lubos-kolouch/python/ch-2.py @@ -0,0 +1,55 @@ +#!/bin/env python +""" +#=============================================================================== +# +# FILE: ch-1.py +# +# USAGE: ./ch-1.py +# +# DESCRIPTION: Perl Weekly Challenge 081 +# https://perlweeklychallenge.org/blog/perl-weekly-challenge-081/ +# Task 2 - Frequency Sort +# +# AUTHOR: Lubos Kolouch +# CREATED: 10/09/2020 10:43:10 AM +#=============================================================================== +""" +import re + + +def frequency_sort(arg): + """ Do the frequency sorting """ + + # sanitize the input as per the challenge + arg = re.sub(r'[."\(\),]', ' ', arg) + arg = re.sub(r'(?:\'s)', ' ', arg) + arg = re.sub(r'(?:--)', ' ', arg) + + count = {} + # I'm sure it can be done in one-liner with map, but I took the longer approach + # First split the array and create hash of counts of each word + for item in re.split(r'\s+', arg): + if not item: + continue + try: + count[item] += 1 + except KeyError: + count[item] = 1 + + rev_count = {} + # create reverse hash with counts as key and the words as array + for key in count.keys(): + try: + rev_count[count[key]].append(key) + except KeyError: + rev_count[count[key]] = [key] + + result = [] + for key in rev_count.keys(): + # sort the arrays and put them to the result output + result.append(str(key)+' '+' '.join(sorted(rev_count[key]))) + + return sorted(result) + + +assert frequency_sort("West Side Story The award-winning adaptation of the classic romantic tragedy \"Romeo and Juliet\". The feuding families become two warring New York City gangs, the white Jets led by Riff and the Latino Sharks, led by Bernardo. Their hatred escalates to a point where neither can coexist with any form of understanding. But when Riff's best friend (and former Jet) Tony and Bernardo's younger sister Maria meet at a dance, no one can do anything to stop their love. Maria and Tony begin meeting in secret, planning to run away. Then the Sharks and Jets plan a rumble under the highway--whoever wins gains control of the streets. Maria sends Tony to stop it, hoping it can end the violence. It goes terribly wrong, and before the lovers know what's happened, tragedy strikes and doesn't stop until the climactic and heartbreaking ending.") == ["1 But City It Jet Juliet Latino New Romeo Side Story Their Then West York adaptation any anything at award-winning away become before begin best classic climactic coexist control dance do doesn't end ending escalates families feuding form former friend gains gangs goes happened hatred heartbreaking highway hoping in know love lovers meet meeting neither no one plan planning point romantic rumble run secret sends sister streets strikes terribly their two under understanding until violence warring what when where white whoever wins with wrong younger", '2 Bernardo Jets Riff Sharks The by it led tragedy', '3 Maria Tony a can of stop', '4 to', '9 and the'] -- cgit From d0579dfc12bbc9d3878bd2aab8525e9b3140824b Mon Sep 17 00:00:00 2001 From: boblied Date: Fri, 9 Oct 2020 15:34:05 -0500 Subject: Solutions for PWC 081 --- challenge-081/bob-lied/perl/ch-1.pl | 4 +- challenge-081/bob-lied/perl/ch-2.pl | 49 ++++++++++++++++------ .../bob-lied/perl/lib/CommonBaseString.pm | 48 +++++++++++++++++++-- challenge-081/bob-lied/perl/lib/FrequencySort.pm | 39 ----------------- challenge-081/bob-lied/perl/t/CommonBaseString.t | 12 +++++- challenge-081/bob-lied/perl/t/FrequencySort.t | 16 ------- 6 files changed, 93 insertions(+), 75 deletions(-) delete mode 100644 challenge-081/bob-lied/perl/lib/FrequencySort.pm delete mode 100644 challenge-081/bob-lied/perl/t/FrequencySort.t (limited to 'challenge-081') diff --git a/challenge-081/bob-lied/perl/ch-1.pl b/challenge-081/bob-lied/perl/ch-1.pl index 3aa9ff13fe..032b1efc8d 100755 --- a/challenge-081/bob-lied/perl/ch-1.pl +++ b/challenge-081/bob-lied/perl/ch-1.pl @@ -36,11 +36,11 @@ sub Usage { "Usage: $0 astring bstring" }; my $Verbose = 0; GetOptions('verbose' => \$Verbose); -my (@A, @B) = @ARGV; +my ($A, $B) = @ARGV; die Usage() unless $A; die Usage() unless $B; my $cbs = CommonBaseString->new($A, $B); my $result = $cbs->run(); -say $result; +say "@$result"; diff --git a/challenge-081/bob-lied/perl/ch-2.pl b/challenge-081/bob-lied/perl/ch-2.pl index 5ed37221ff..76c3ba067d 100755 --- a/challenge-081/bob-lied/perl/ch-2.pl +++ b/challenge-081/bob-lied/perl/ch-2.pl @@ -25,22 +25,45 @@ use v5.30; use feature qw/ signatures /; no warnings qw/ experimental::signatures /; -use Getopt::Long; +use File::Slurper qw/ read_text /; -use lib "lib"; -use FrequencySort; -sub Usage { "Usage: $0 args" }; +sub Usage { "Usage: $0 filename" }; -my $Verbose = 0; -GetOptions('verbose' => \$Verbose); +my $InFile = shift; -my $arg = shift; -my @list = @ARGV; +# It would be friendlier to allow stdin, but the spec says use a file. +die Usage() unless $InFile; -die Usage() unless $arg; -die Usage() unless @list; +# Slurp input file into one long string. +my $input = read_text($InFile); + +# Split on word separators, and convienently get rid of them. +# That might leave some empty strings, so filter those. +my @words = grep !/^$/, split(/\s|[\n\r."(),]/, $input); + +# These next two cleanups could be chained to make one pass, +# but let's keep it readable for now. +# +# Phrases separated by long dashes turn into multiple words. +@words = map { if (/--/) { split(/--/) } else { $_ } } @words; + +# Possessives reduce to the base noun. +@words = map { s/'s//; $_ } @words; + +my %counts; +$counts{$_}++ foreach @words; + +# Invert the hash to have counts as keys to lists of words. +my %countList; +for my $word ( keys %counts ) +{ + push @{$countList{ $counts{$word} }}, $word; +} + +# Numeric sort ascending on the counts. +for my $n ( sort { $a <=> $b } keys %countList ) +{ + say "$n\t", join " ", sort @{$countList{$n}} +} -my $task = FrequencySort->new(); -my $result = $task->run(); -say $result; diff --git a/challenge-081/bob-lied/perl/lib/CommonBaseString.pm b/challenge-081/bob-lied/perl/lib/CommonBaseString.pm index b67ecfa948..4c6f98901c 100644 --- a/challenge-081/bob-lied/perl/lib/CommonBaseString.pm +++ b/challenge-081/bob-lied/perl/lib/CommonBaseString.pm @@ -19,21 +19,61 @@ no warnings qw/ experimental::signatures /; require Exporter; our @ISA = qw(Exporter); our @EXPORT = qw(); -our @EXPORT_OK = qw(); +our @EXPORT_OK = qw(commonPrefix); -sub new($class, $name1) +sub new($class, $a, $b) { $class = ref($class) || $class; my $self = { - _name1 => $name1, + _a => $a, + _b => $b, }; bless $self, $class; return $self; } +# +sub commonPrefix($s, $t) +{ + my @s1 = split("", $s); + my @s2 = split("", $t); + my $prefix = ""; + my @possiblePrefixes = (); + + while ( @s1 && @s2 && ($s = shift @s1) eq ($t = shift @s2) ) + { + $prefix .= $s; + push @possiblePrefixes, $prefix; + } + return \@possiblePrefixes; +} + sub run($self) { - return undef; + my ($A, $B) = @{$self}{qw(_a _b)}; + my ($lenA, $lenB) = ( length($A), length($B) ); + my @thisWorks = (); + + my $prefixes = commonPrefix($A, $B); + + for my $prefix ( @$prefixes ) + { + my $lenP = length($prefix); + # Only prefixes that can be repeated to the length of both strings + # are candidates. + next unless $lenA % $lenP == 0; + next unless $lenB % $lenP == 0; + + # Number of repetitions required for each string. + my $repA = $lenA / $lenP; + my $repB = $lenB / $lenP; + + my $buildsA = ( ($prefix x $repA) eq $A ); + my $buildsB = ( ($prefix x $repB) eq $B ); + push @thisWorks, $prefix if ( $buildsA && $buildsB ); + } + + return \@thisWorks; } 1; diff --git a/challenge-081/bob-lied/perl/lib/FrequencySort.pm b/challenge-081/bob-lied/perl/lib/FrequencySort.pm deleted file mode 100644 index 177e28ace9..0000000000 --- a/challenge-081/bob-lied/perl/lib/FrequencySort.pm +++ /dev/null @@ -1,39 +0,0 @@ -# vim:set ts=4 sw=4 sts=4 et ai wm=0 nu: -#============================================================================= -# FrequencySort.pm -#============================================================================= -# Copyright (c) 2020, Bob Lied -#============================================================================= -# Description: -#============================================================================= - -package FrequencySort; - -use strict; -use warnings; -use v5.30; - -use feature qw/ signatures /; -no warnings qw/ experimental::signatures /; - -require Exporter; -our @ISA = qw(Exporter); -our @EXPORT = qw(); -our @EXPORT_OK = qw(); - -sub new($class, $name1) -{ - $class = ref($class) || $class; - my $self = { - _name1 => $name1, - }; - bless $self, $class; - return $self; -} - -sub run($self) -{ - return undef; -} - -1; diff --git a/challenge-081/bob-lied/perl/t/CommonBaseString.t b/challenge-081/bob-lied/perl/t/CommonBaseString.t index 81d4345b76..8c7108c572 100644 --- a/challenge-081/bob-lied/perl/t/CommonBaseString.t +++ b/challenge-081/bob-lied/perl/t/CommonBaseString.t @@ -10,7 +10,17 @@ use warnings; use v5.30; use Test2::V0; +use lib "lib"; + +use CommonBaseString qw/ commonPrefix /; + +is( commonPrefix("abc", "def"), [ ], "commonPrefix length 0" ); +is( commonPrefix("aaa", "abc"), [ "a" ], "commonPrefix length 1" ); +is( commonPrefix("aaa", "aac"), [ "a", "aa" ], "commonPrefix length 2" ); +is( commonPrefix("abab", "abababab"), [ "a", "ab", "aba", "abab" ], "commonPrefix 2 possibilities" ); + +is( CommonBaseString->new("abcdabcd", "abcdabcdabcdabcd")->run, [ "abcd", "abcdabcd" ], "Example 1"); +is( CommonBaseString->new("aaa", "a")->run, [ "a" ], "Example 2"); -use CommonBaseString; done_testing(); diff --git a/challenge-081/bob-lied/perl/t/FrequencySort.t b/challenge-081/bob-lied/perl/t/FrequencySort.t deleted file mode 100644 index 794fd04750..0000000000 --- a/challenge-081/bob-lied/perl/t/FrequencySort.t +++ /dev/null @@ -1,16 +0,0 @@ -# vim:set ts=4 sw=4 sts=4 et ai wm=0 nu: -# -#=============================================================================== -# FILE: FrequencySort.t -# DESCRIPTION: Unit test for FrequencySort -#=============================================================================== - -use strict; -use warnings; -use v5.30; - -use Test2::V0; - -use FrequencySort; - -done_testing(); -- cgit From d37a9263d9436a4f38818bd2afccdc1d4623a5e8 Mon Sep 17 00:00:00 2001 From: PerlMonk Athanasius Date: Sat, 10 Oct 2020 18:54:35 +1000 Subject: Perl & Raku solutions to Tasks 1 & 2 of the Perl Weekly Challenge #081 On branch branch-for-challenge-081 Changes to be committed: new file: challenge-081/athanasius/perl/WestSideStory.txt new file: challenge-081/athanasius/perl/ch-1.pl new file: challenge-081/athanasius/perl/ch-2.pl new file: challenge-081/athanasius/raku/WestSideStory.txt new file: challenge-081/athanasius/raku/ch-1.raku new file: challenge-081/athanasius/raku/ch-2.raku --- challenge-081/athanasius/perl/WestSideStory.txt | 3 + challenge-081/athanasius/perl/ch-1.pl | 130 ++++++++++++++++++ challenge-081/athanasius/perl/ch-2.pl | 174 ++++++++++++++++++++++++ challenge-081/athanasius/raku/WestSideStory.txt | 3 + challenge-081/athanasius/raku/ch-1.raku | 138 +++++++++++++++++++ challenge-081/athanasius/raku/ch-2.raku | 148 ++++++++++++++++++++ 6 files changed, 596 insertions(+) create mode 100644 challenge-081/athanasius/perl/WestSideStory.txt create mode 100644 challenge-081/athanasius/perl/ch-1.pl create mode 100644 challenge-081/athanasius/perl/ch-2.pl create mode 100644 challenge-081/athanasius/raku/WestSideStory.txt create mode 100644 challenge-081/athanasius/raku/ch-1.raku create mode 100644 challenge-081/athanasius/raku/ch-2.raku (limited to 'challenge-081') diff --git a/challenge-081/athanasius/perl/WestSideStory.txt b/challenge-081/athanasius/perl/WestSideStory.txt new file mode 100644 index 0000000000..37001629ad --- /dev/null +++ b/challenge-081/athanasius/perl/WestSideStory.txt @@ -0,0 +1,3 @@ +West Side Story + +The award-winning adaptation of the classic romantic tragedy "Romeo and Juliet". The feuding families become two warring New York City gangs, the white Jets led by Riff and the Latino Sharks, led by Bernardo. Their hatred escalates to a point where neither can coexist with any form of understanding. But when Riff's best friend (and former Jet) Tony and Bernardo's younger sister Maria meet at a dance, no one can do anything to stop their love. Maria and Tony begin meeting in secret, planning to run away. Then the Sharks and Jets plan a rumble under the highway--whoever wins gains control of the streets. Maria sends Tony to stop it, hoping it can end the violence. It goes terribly wrong, and before the lovers know what's happened, tragedy strikes and doesn't stop until the climactic and heartbreaking ending. diff --git a/challenge-081/athanasius/perl/ch-1.pl b/challenge-081/athanasius/perl/ch-1.pl new file mode 100644 index 0000000000..d3e22ee5f6 --- /dev/null +++ b/challenge-081/athanasius/perl/ch-1.pl @@ -0,0 +1,130 @@ +#!perl + +############################################################################### +=comment + +Perl Weekly Challenge 081 +========================= + +Task #1 +------- +*Common Base String* + +Submitted by: Mohammad S Anwar + +You are given 2 strings, $A and $B. + +Write a script to find out common base strings in $A and $B. + + A substring of a string $S is called base string if repeated concatenation + of the substring results in the string. + +Example 1: + + Input: + $A = "abcdabcd" + $B = "abcdabcdabcdabcd" + + Output: + ("abcd", "abcdabcd") + +Example 2: + + Input: + $A = "aaa" + $B = "aa" + + Output: + ("a") + +=cut +############################################################################### + +#--------------------------------------# +# Copyright © 2020 PerlMonk Athanasius # +#--------------------------------------# + + # Exports: +use strict; +use warnings; +use Const::Fast; # const() +use Math::Prime::Util qw( divisors ); +use Set::Scalar; # infix "*" (overloaded for set inter- + # section), members(), new() + +const my $USAGE => +"Usage: + perl $0 + + First string + Second string\n"; + +#------------------------------------------------------------------------------ +BEGIN +#------------------------------------------------------------------------------ +{ + $| = 1; + print "\nChallenge 081, Task #1: Common Base String (Perl)\n\n"; +} + +#============================================================================== +MAIN: +#============================================================================== +{ + my ($A, $B) = parse_command_line(); + + # (1) Display the input + + print qq[Input:\n \$A = "$A"\n \$B = "$B"\n\n]; + + # (2) Find the *lengths* of all possible base strings common to $A and $B + + my $A_lengths = Set::Scalar->new( divisors(length $A) ); + my $B_lengths = Set::Scalar->new( divisors(length $B) ); + my @lengths = sort { $a <=> $b } ($A_lengths * $B_lengths)->members; + + # (3) Find the base strings common to $A and $B using the substring lengths + # just calculated + + my $A_bases = Set::Scalar->new( find_base_strings($A, \@lengths) ); + my $B_bases = Set::Scalar->new( find_base_strings($B, \@lengths) ); + my @bases = sort +($A_bases * $B_bases)->members; + + # (4) Display the common base strings + + printf "Output:\n (%s)\n", join ', ', map { qq["$_"] } @bases; +} + +#------------------------------------------------------------------------------ +sub find_base_strings +#------------------------------------------------------------------------------ +{ + my ($string, $lengths) = @_; + my $total_length = length $string; + my @base_strings; + + for my $length (@$lengths) + { + my $substring = substr $string, 0, $length; + my $new_string = $substring x int($total_length / $length); + + push @base_strings, $substring if $new_string eq $string; + } + + return @base_strings; +} + +#------------------------------------------------------------------------------ +sub parse_command_line +#------------------------------------------------------------------------------ +{ + my $args = scalar @ARGV; + + $args == 2 + or die "ERROR: Incorrect number ($args) of command-line arguments\n" . + $USAGE; + + return @ARGV; +} + +############################################################################### diff --git a/challenge-081/athanasius/perl/ch-2.pl b/challenge-081/athanasius/perl/ch-2.pl new file mode 100644 index 0000000000..c32157c2bb --- /dev/null +++ b/challenge-081/athanasius/perl/ch-2.pl @@ -0,0 +1,174 @@ +#!perl + +############################################################################### +=comment + +Perl Weekly Challenge 081 +========================= + +Task #2 +------- +*Frequency Sort* + +Submitted by: Mohammad S Anwar + +You are given file named input. + +Write a script to find the frequency of all the words. + +It should print the result as first column of each line should be the frequency +of the the word followed by all the words of that frequency arranged in lexico- +graphical order. Also sort the words in the ascending order of frequency. + +INPUT file + + West Side Story + + The award-winning adaptation of the classic romantic tragedy "Romeo and + Juliet". The feuding families become two warring New York City gangs, the + white Jets led by Riff and the Latino Sharks, led by Bernardo. Their hatred + escalates to a point where neither can coexist with any form of understanding. + But when Riff's best friend (and former Jet) Tony and Bernardo's younger + sister Maria meet at a dance, no one can do anything to stop their love. Maria + and Tony begin meeting in secret, planning to run away. Then the Sharks and + Jets plan a rumble under the highway--whoever wins gains control of the + streets. Maria sends Tony to stop it, hoping it can end the violence. It goes + terribly wrong, and before the lovers know what's happened, tragedy strikes + and doesn't stop until the climactic and heartbreaking ending. + +NOTE + +For the sake of this task, please ignore the following in the input file: + + . " ( ) , 's -- + +OUTPUT + + 1 But City It Jet Juliet Latino New Romeo Side Story Their Then West York + adaptation any anything at award-winning away become before begin best classic + climactic coexist control dance do doesn't end ending escalates families + feuding form former friend gains gangs goes happened hatred heartbreaking + highway hoping in know love lovers meet meeting neither no one plan planning +