From ac0f1ea3cf12fe316d222dde948d8dacb5c84b99 Mon Sep 17 00:00:00 2001 From: Thomas Köhler Date: Mon, 25 Dec 2023 10:03:27 +0100 Subject: Add solution 249 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Thomas Köhler --- challenge-249/jeanluc2020/blog-1.txt | 1 + challenge-249/jeanluc2020/blog-2.txt | 1 + challenge-249/jeanluc2020/perl/ch-1.pl | 79 ++++++++++++++++++++++++++++++++ challenge-249/jeanluc2020/perl/ch-2.pl | 62 +++++++++++++++++++++++++ challenge-249/jeanluc2020/python/ch-1.py | 72 +++++++++++++++++++++++++++++ challenge-249/jeanluc2020/python/ch-2.py | 59 ++++++++++++++++++++++++ 6 files changed, 274 insertions(+) create mode 100644 challenge-249/jeanluc2020/blog-1.txt create mode 100644 challenge-249/jeanluc2020/blog-2.txt create mode 100755 challenge-249/jeanluc2020/perl/ch-1.pl create mode 100755 challenge-249/jeanluc2020/perl/ch-2.pl create mode 100755 challenge-249/jeanluc2020/python/ch-1.py create mode 100755 challenge-249/jeanluc2020/python/ch-2.py (limited to 'challenge-249') diff --git a/challenge-249/jeanluc2020/blog-1.txt b/challenge-249/jeanluc2020/blog-1.txt new file mode 100644 index 0000000000..7d29922b0c --- /dev/null +++ b/challenge-249/jeanluc2020/blog-1.txt @@ -0,0 +1 @@ +http://gott-gehabt.de/800_wer_wir_sind/thomas/Homepage/Computer/perl/theweeklychallenge-249-1.html diff --git a/challenge-249/jeanluc2020/blog-2.txt b/challenge-249/jeanluc2020/blog-2.txt new file mode 100644 index 0000000000..1606e86db7 --- /dev/null +++ b/challenge-249/jeanluc2020/blog-2.txt @@ -0,0 +1 @@ +http://gott-gehabt.de/800_wer_wir_sind/thomas/Homepage/Computer/perl/theweeklychallenge-249-2.html diff --git a/challenge-249/jeanluc2020/perl/ch-1.pl b/challenge-249/jeanluc2020/perl/ch-1.pl new file mode 100755 index 0000000000..fe6d982d7a --- /dev/null +++ b/challenge-249/jeanluc2020/perl/ch-1.pl @@ -0,0 +1,79 @@ +#!/usr/bin/env perl +# https://theweeklychallenge.org/blog/perl-weekly-challenge-249/#TASK1 +# +# Task 1: Shortest Distance +# ========================= +# +# You are given an array of integers with even number of elements. +# +# Write a script to divide the given array into equal pairs such that: +# +# a) Each element belongs to exactly one pair. +# b) The elements present in a pair are equal. +# +# +## Example 1 +## +## Input: @ints = (3, 2, 3, 2, 2, 2) +## Output: (2, 2), (3, 3), (2, 2) +## +## There are 6 elements in @ints. +## They should be divided into 6 / 2 = 3 pairs. +## @ints is divided into the pairs (2, 2), (3, 3), and (2, 2) satisfying all the +## conditions. +# +## Example 2 +## +## Input: @ints = (1, 2, 3, 4) +## Output: () +## +## There is no way to divide @ints 2 pairs such that the pairs satisfy every +## condition. +# +############################################################ +## +## discussion +## +############################################################ +# +# We use the elements of the array as keys for a hash in which we +# count the amount of elements of this value in the array. +# If in the end, all values in the hash are even, we can spit out the +# correct number of arrays, otherwise we can only return an empty array. + +use strict; +use warnings; + +shortest_distance(3, 2, 3, 2, 2, 2); +shortest_distance(1, 2, 3, 4); + +sub shortest_distance { + my @ints = @_; + print "Input: (" . join(", ", @ints) . ")\n"; + my $map; + map { $map->{$_}++ } @ints; + my @result = (); + foreach my $key (keys %$map) { + if($map->{$key} % 2) { + print "Output: ()\n"; + return; + } + my $i = int( $map->{$key} / 2 ); + foreach my $elem (1..$i) { + push @result, [ $key, $key ]; + } + } + my $first = 1; + print "Output: "; + foreach my $elem (@result) { + if($first) { + $first = 0; + } else { + print ", "; + } + print "(" . join(", ", @$elem) . ")"; + } + print "\n"; +} + + diff --git a/challenge-249/jeanluc2020/perl/ch-2.pl b/challenge-249/jeanluc2020/perl/ch-2.pl new file mode 100755 index 0000000000..7407eaacbe --- /dev/null +++ b/challenge-249/jeanluc2020/perl/ch-2.pl @@ -0,0 +1,62 @@ +#!/usr/bin/env perl +# https://theweeklychallenge.org/blog/perl-weekly-challenge-249/#TASK2 +# +# Task 2: DI String Match +# ======================= +# +# You are given a string s, consisting of only the characters "D" and "I". +# +# Find a permutation of the integers [0 .. length(s)] such that for each +# character s[i] in the string: +# +# s[i] == 'I' ⇒ perm[i] < perm[i + 1] +# s[i] == 'D' ⇒ perm[i] > perm[i + 1] +# +## Example 1 +## +## Input: $str = "IDID" +## Output: (0, 4, 1, 3, 2) +# +## Example 2 +## +## Input: $str = "III" +## Output: (0, 1, 2, 3) +# +## Example 3 +## +## Input: $str = "DDI" +## Output: (3, 2, 0, 1) +# +############################################################ +## +## discussion +## +############################################################ +# +# We just count from 0 to length(s) for each "I" and from +# length(s) to 0 for each "D", and in the end add the last +# element we didn't use up yet. + +use strict; +use warnings; + +DI_string_match("IDID"); +DI_string_match("III"); +DI_string_match("DDI"); + +sub DI_string_match { + my $str = shift; + print "Input: '$str'\n"; + my $upper = length($str); + my $lower = 0; + my @result = (); + foreach my $char (split//,$str) { + if($char eq "I") { + push @result, $lower++; + } else { + push @result, $upper--; + } + } + push @result, $lower; + print "Output: (", join(", ", @result), ")\n"; +} diff --git a/challenge-249/jeanluc2020/python/ch-1.py b/challenge-249/jeanluc2020/python/ch-1.py new file mode 100755 index 0000000000..d187c0ca7d --- /dev/null +++ b/challenge-249/jeanluc2020/python/ch-1.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +# https://theweeklychallenge.org/blog/perl-weekly-challenge-249/#TASK1 +# +# Task 1: Shortest Distance +# ========================= +# +# You are given an array of integers with even number of elements. +# +# Write a script to divide the given array into equal pairs such that: +# +# a) Each element belongs to exactly one pair. +# b) The elements present in a pair are equal. +# +# +## Example 1 +## +## Input: @ints = (3, 2, 3, 2, 2, 2) +## Output: (2, 2), (3, 3), (2, 2) +## +## There are 6 elements in @ints. +## They should be divided into 6 / 2 = 3 pairs. +## @ints is divided into the pairs (2, 2), (3, 3), and (2, 2) satisfying all the +## conditions. +# +## Example 2 +## +## Input: @ints = (1, 2, 3, 4) +## Output: () +## +## There is no way to divide @ints 2 pairs such that the pairs satisfy every +## condition. +# +############################################################ +## +## discussion +## +############################################################ +# +# We use the elements of the array as keys for a hash in which we +# count the amount of elements of this value in the array. +# If in the end, all values in the hash are even, we can spit out the +# correct number of arrays, otherwise we can only return an empty array. + +def shortest_distance(ints: list) -> list: + print("Input: (", ", ".join([str(x) for x in ints]), ")") + result = [] + map = {} + for i in ints: + if i in map: + map[i] += 1 + else: + map[i] = 1 + for key in map.keys(): + if map[key] % 2 != 0: + print("Output: ()") + return () + i = int( map[key] / 2 ) + for j in range(1,i+1): + result.append( [key, key] ) + first = True + print("Output: ", end="") + for elem in result: + if first: + first = False + else: + print(", ", end="") + print(", ".join([str(x) for x in elem]), end="") + print("") + +shortest_distance([3, 2, 3, 2, 2, 2]) +shortest_distance([1, 2, 3, 4]) + diff --git a/challenge-249/jeanluc2020/python/ch-2.py b/challenge-249/jeanluc2020/python/ch-2.py new file mode 100755 index 0000000000..504e70a26d --- /dev/null +++ b/challenge-249/jeanluc2020/python/ch-2.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +# https://theweeklychallenge.org/blog/perl-weekly-challenge-249/#TASK2 +# +# Task 2: DI String Match +# ======================= +# +# You are given a string s, consisting of only the characters "D" and "I". +# +# Find a permutation of the integers [0 .. length(s)] such that for each +# character s[i] in the string: +# +# s[i] == 'I' ⇒ perm[i] < perm[i + 1] +# s[i] == 'D' ⇒ perm[i] > perm[i + 1] +# +## Example 1 +## +## Input: $str = "IDID" +## Output: (0, 4, 1, 3, 2) +# +## Example 2 +## +## Input: $str = "III" +## Output: (0, 1, 2, 3) +# +## Example 3 +## +## Input: $str = "DDI" +## Output: (3, 2, 0, 1) +# +############################################################ +## +## discussion +## +############################################################ +# +# We just count from 0 to length(s) for each "I" and from +# length(s) to 0 for each "D", and in the end add the last +# element we didn't use up yet. + +def DI_string_match(string: str) -> list: + print("Input: '", string, "'", sep="") + upper = len(string) + lower = 0 + result = [] + for char in list(string): + if char == "I": + result.append(lower) + lower += 1 + else: + result.append(upper) + upper -= 1 + result.append(lower) + print("Output: (", ", ".join([str(x) for x in result]), ")") + return result + +DI_string_match("IDID"); +DI_string_match("III"); +DI_string_match("DDI"); + -- cgit From fe7c62233cb5309173a1f5744a522635f7448131 Mon Sep 17 00:00:00 2001 From: Michael Manring Date: Mon, 25 Dec 2023 23:05:34 +1100 Subject: pwc249 solution in python --- challenge-249/pokgopun/python/ch-1.py | 57 +++++++++++++++++++++++++++ challenge-249/pokgopun/python/ch-2.py | 73 +++++++++++++++++++++++++++++++++++ 2 files changed, 130 insertions(+) create mode 100644 challenge-249/pokgopun/python/ch-1.py create mode 100644 challenge-249/pokgopun/python/ch-2.py (limited to 'challenge-249') diff --git a/challenge-249/pokgopun/python/ch-1.py b/challenge-249/pokgopun/python/ch-1.py new file mode 100644 index 0000000000..cef9601557 --- /dev/null +++ b/challenge-249/pokgopun/python/ch-1.py @@ -0,0 +1,57 @@ +### https://theweeklychallenge.org/blog/perl-weekly-challenge-249/ +""" + +Task 1: Shortest Distance + +Submitted by: [66]Mohammad S Anwar + __________________________________________________________________ + + You are given an array of integers with even number of elements. + + Write a script to divide the given array into equal pairs such that: +a) Each element belongs to exactly one pair. +b) The elements present in a pair are equal. + +Example 1 + +Input: @ints = (3, 2, 3, 2, 2, 2) +Output: (2, 2), (3, 3), (2, 2) + +There are 6 elements in @ints. +They should be divided into 6 / 2 = 3 pairs. +@ints is divided into the pairs (2, 2), (3, 3), and (2, 2) satisfying all the co +nditions. + +Example 2 + +Input: @ints = (1, 2, 3, 4) +Output: () + +There is no way to divide @ints 2 pairs such that the pairs satisfy every condit +ion. + +Task 2: DI String Match +""" +### solution by pokgopun@gmail.com + +from itertools import chain + +def equalPairs(tup: tuple): + return tuple( + chain.from_iterable( + ( (e,e) for c in range(tup.count(e)//2 ) ) + for e in set(tup) + ) + ) + +import unittest + +class TestEqualPairs(unittest.TestCase): + def test1(self): + for inpt,otpt in { + (3, 2, 3, 2, 2, 2): ((2, 2), (3, 3), (2, 2)), + (1, 2, 3, 4): (), + }.items(): + self.assertEqual(sorted(equalPairs(inpt)),sorted(otpt)) + +unittest.main() diff --git a/challenge-249/pokgopun/python/ch-2.py b/challenge-249/pokgopun/python/ch-2.py new file mode 100644 index 0000000000..f535069d2e --- /dev/null +++ b/challenge-249/pokgopun/python/ch-2.py @@ -0,0 +1,73 @@ +### https://theweeklychallenge.org/blog/perl-weekly-challenge-249/ +""" + +Task 2: DI String Match + +Submitted by: [67]Mohammad S Anwar + __________________________________________________________________ + + You are given a string s, consisting of only the characters "D" and + "I". + + Find a permutation of the integers [0 .. length(s)] such that for each + character s[i] in the string: +s[i] == 'I' ⇒ perm[i] < perm[i + 1] +s[i] == 'D' ⇒ perm[i] > perm[i + 1] + +Example 1 + +Input: $str = "IDID" +Output: (0, 4, 1, 3, 2) + +Example 2 + +Input: $str = "III" +Output: (0, 1, 2, 3) + +Example 3 + +Input: $str = "DDI" +Output: (3, 2, 0, 1) + __________________________________________________________________ + + Last date to submit the solution 23:59 (UK Time) Sunday 31st December + 2023. + __________________________________________________________________ + +SO WHAT DO YOU THINK ? +""" +### solution by pokgopun@gmail.com + +from itertools import permutations + +def dism(s: str): + t = tuple() + l = len(s) + for perm in permutations(tuple(range(l+1)),l+1): + #print(perm) + for i in range(l): + #print(f"{s[i]},{perm[i]},{perm[i+1]}") + if s[i]=="I": + if perm[i] >= perm[i+1]: + break + elif s[i]=="D": + if perm[i] <= perm[i+1]: + break + else: + #print("=>",perm) + t += (perm,) + #print(t) + return t + +import unittest + +class TestDism(unittest.TestCase): + def test(self): + for inpt,otpt in { + "IDID": (0, 4, 1, 3, 2), + "III": (0, 1, 2, 3), + "DDI": (3, 2, 0, 1), + }.items(): + self.assertEqual(dism(inpt).count(otpt)>0,True) + +unittest.main() -- cgit From 06399d1731e8a64bc5d5f4070e96c218dc3212ce Mon Sep 17 00:00:00 2001 From: Mark <53903062+andemark@users.noreply.github.com> Date: Mon, 25 Dec 2023 12:20:55 +0000 Subject: Challenge 249 Solutions (Raku) --- challenge-249/mark-anderson/raku/ch-1.raku | 12 ++++++++++++ challenge-249/mark-anderson/raku/ch-2.raku | 22 ++++++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 challenge-249/mark-anderson/raku/ch-1.raku create mode 100644 challenge-249/mark-anderson/raku/ch-2.raku (limited to 'challenge-249') diff --git a/challenge-249/mark-anderson/raku/ch-1.raku b/challenge-249/mark-anderson/raku/ch-1.raku new file mode 100644 index 0000000000..d3b772effb --- /dev/null +++ b/challenge-249/mark-anderson/raku/ch-1.raku @@ -0,0 +1,12 @@ +#!/usr/bin/env raku +use Test; + +is-deeply equal-pairs(3,2,3,2,2,2), ((2,2),(2,2),(3,3)); +nok equal-pairs(1,2,3,4); + +sub equal-pairs(+@a where * %% 2) +{ + my $b = @a.Bag; + return False unless all($b.values) %% 2; + $b.kxxv.sort.rotor(2) +} diff --git a/challenge-249/mark-anderson/raku/ch-2.raku b/challenge-249/mark-anderson/raku/ch-2.raku new file mode 100644 index 0000000000..c1d73452a2 --- /dev/null +++ b/challenge-249/mark-anderson/raku/ch-2.raku @@ -0,0 +1,22 @@ +#!/usr/bin/env raku +use Test; + +is-deeply DI("IDID"), (0,4,1,3,2); +is-deeply DI("III"), (0,1,2,3); +is-deeply DI("DDI"), (3,2,0,1); +is-deeply DI("DDID"), (4,3,0,2,1); +is-deeply DI("IDDID"), (0,5,4,1,3,2); +is-deeply DI("DDD"), (3,2,1,0); +is-deeply DI("IDDIIDIIIDIIDDIDIDDI"), (0,20,19,1,2,18,3,4,5,17,6,7,16,15,8,14,9,13,12,10,11); + +sub DI($str) +{ + my @a = flat $str.comb, "I"; + my %h := { :I(0), :D(@a.end) } + + gather while @a.shift -> $a + { + take %h{$a}.abs; + %h{$a}-- + } +} -- cgit From 6fe6b26d3e03f849c61d1425968b68d2e0ab4d31 Mon Sep 17 00:00:00 2001 From: Mark <53903062+andemark@users.noreply.github.com> Date: Mon, 25 Dec 2023 12:25:40 +0000 Subject: Challenge 249 Solutions (Raku) --- challenge-249/mark-anderson/raku/ch-1.raku | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'challenge-249') diff --git a/challenge-249/mark-anderson/raku/ch-1.raku b/challenge-249/mark-anderson/raku/ch-1.raku index d3b772effb..8b84602374 100644 --- a/challenge-249/mark-anderson/raku/ch-1.raku +++ b/challenge-249/mark-anderson/raku/ch-1.raku @@ -2,11 +2,11 @@ use Test; is-deeply equal-pairs(3,2,3,2,2,2), ((2,2),(2,2),(3,3)); -nok equal-pairs(1,2,3,4); +is-deeply equal-pairs(1,2,3,4), (); sub equal-pairs(+@a where * %% 2) { my $b = @a.Bag; - return False unless all($b.values) %% 2; + return () unless all($b.values) %% 2; $b.kxxv.sort.rotor(2) } -- cgit From 18fe1cc9bbde79fa195f77c4806e1cb69a8d0501 Mon Sep 17 00:00:00 2001 From: Mark <53903062+andemark@users.noreply.github.com> Date: Mon, 25 Dec 2023 12:33:37 +0000 Subject: Challenge 249 Solutions (Raku) --- challenge-249/mark-anderson/raku/ch-1.raku | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'challenge-249') diff --git a/challenge-249/mark-anderson/raku/ch-1.raku b/challenge-249/mark-anderson/raku/ch-1.raku index 8b84602374..992e315b1d 100644 --- a/challenge-249/mark-anderson/raku/ch-1.raku +++ b/challenge-249/mark-anderson/raku/ch-1.raku @@ -8,5 +8,5 @@ sub equal-pairs(+@a where * %% 2) { my $b = @a.Bag; return () unless all($b.values) %% 2; - $b.kxxv.sort.rotor(2) + $b.kxxv.sort.batch(2) } -- cgit From 413aea80198685a15518411388b4ae622dad5cfb Mon Sep 17 00:00:00 2001 From: Mark <53903062+andemark@users.noreply.github.com> Date: Mon, 25 Dec 2023 12:48:52 +0000 Subject: Challenge 249 Solutions (Raku) --- challenge-249/mark-anderson/raku/ch-1.raku | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'challenge-249') diff --git a/challenge-249/mark-anderson/raku/ch-1.raku b/challenge-249/mark-anderson/raku/ch-1.raku index 992e315b1d..8adcd9f766 100644 --- a/challenge-249/mark-anderson/raku/ch-1.raku +++ b/challenge-249/mark-anderson/raku/ch-1.raku @@ -8,5 +8,5 @@ sub equal-pairs(+@a where * %% 2) { my $b = @a.Bag; return () unless all($b.values) %% 2; - $b.kxxv.sort.batch(2) + $b.kxxv.batch(2).sort } -- cgit From 25544ece2cc3a152d5e91b0971fec10538b72b56 Mon Sep 17 00:00:00 2001 From: "E. Choroba" Date: Mon, 25 Dec 2023 16:43:17 +0100 Subject: Add solutions to 249: Equal Pairs & DI String Match by E. Choroba --- challenge-249/e-choroba/perl/ch-1.pl | 75 ++++++++++++++++++++++++++++++++++++ challenge-249/e-choroba/perl/ch-2.pl | 53 +++++++++++++++++++++++++ 2 files changed, 128 insertions(+) create mode 100755 challenge-249/e-choroba/perl/ch-1.pl create mode 100755 challenge-249/e-choroba/perl/ch-2.pl (limited to 'challenge-249') diff --git a/challenge-249/e-choroba/perl/ch-1.pl b/challenge-249/e-choroba/perl/ch-1.pl new file mode 100755 index 0000000000..41f1d964ab --- /dev/null +++ b/challenge-249/e-choroba/perl/ch-1.pl @@ -0,0 +1,75 @@ +#!/usr/bin/perl +use warnings; +use strict; +use experimental qw( signatures ); + +sub equal_pairs_count(@ints) { + my %seen; + ++$seen{$_} for @ints; + return [map $seen{$_} % 2 ? return [] + : ([$_, $_]) x ($seen{$_} / 2), + keys %seen] +} + +sub equal_pairs_odd(@ints) { + my %odd; + my @pairs; + for my $i (@ints) { + if (exists $odd{$i}) { + delete $odd{$i}; + push @pairs, [$i, $i]; + } else { + undef $odd{$i}; + } + } + return keys %odd ? [] : \@pairs +} + + +use Test2::V0 -srand => srand; +plan 2 + 1; + +my $type = 'count'; +*equal_pairs = *equal_pairs_count{CODE}; +for (1, 2) { + subtest $type => sub { + plan 5; + + is equal_pairs(3, 2, 3, 2, 2, 2), + bag { item $_ for [2, 2], [2, 2], [3, 3]; }, + 'Example 1'; + + is equal_pairs(1, 2, 3, 4), [], 'Example 2'; + + + is equal_pairs(-1, -1, -2, -2), + bag { item $_ for [-1, -1], [-2, -2]; }, + 'Negative numbers'; + + is equal_pairs(1, 1, 1, 1, 2, 2, 2, 2), + bag { item $_ for [1, 1], [1, 1], [2, 2], [2, 2]; }, + 'More than once'; + + is equal_pairs(1, 1, 1, 1, 2, 2, 2, 2, 1), + [], + 'More than once odd'; + }; + + no warnings 'redefine'; + $type = 'odd'; + *equal_pairs = *equal_pairs_odd{CODE}; +} + +use Benchmark qw{ cmpthese }; + +my @l = map int rand 1000, 1 .. 100_000; +is equal_pairs_odd(@l), equal_pairs_count(@l), 'same'; +cmpthese(-3, { + odd => sub { equal_pairs_odd(@l) }, + count => sub { equal_pairs_count(@l) }, +}); + +__END__ + Rate odd count +odd 9.97/s -- -82% +count 55.5/s 456% -- diff --git a/challenge-249/e-choroba/perl/ch-2.pl b/challenge-249/e-choroba/perl/ch-2.pl new file mode 100755 index 0000000000..e498008452 --- /dev/null +++ b/challenge-249/e-choroba/perl/ch-2.pl @@ -0,0 +1,53 @@ +#!/usr/bin/perl +use warnings; +use strict; +use feature qw{ say }; + +use Test2::V0; +use experimental qw( signatures ); + +sub DI_string_match($str) { + my @p = (0); + my $max = 1; + my %DISPATCH = (I => sub { + push @p, $max++; + }, + D => sub { + $_++ for @p, $max; + push @p, 0; + }); + $DISPATCH{$_}() for split //, $str; + return \@p +} + +{ my %DISPATCH = (D => sub($perm, $i) { $perm->[$i - 1] > $perm->[$i] }, + I => sub($perm, $i) { $perm->[$i - 1] < $perm->[$i] }); + sub matches($s, $perm) { + return unless @$perm - 1 == length $s; + my %used; + @used{@$perm} = (); + exists $used{$_} or return for 0 .. length $s; + + for my $i (1 .. length $s) { + my $char = substr $s, $i - 1, 1; + return unless $DISPATCH{$char}($perm, $i); + } + return 1 + } +} + +plan 3 + 5 + 3; + +is matches('IDID', [0, 4, 1, 3, 2]), 1, 'matches() correct for Example 1'; +is matches('III', [0, 1, 2, 3]), 1, 'matches() correct for Example 2'; +is matches('DDI', [3, 2, 0, 1]), 1, 'matches() correct for Example 3'; + +is matches('I', [1, 0]), undef, 'matches() detects wrong order'; +is matches('D', [0, 1]), undef, 'matches() detects wrong order'; +is matches('I', [0, 2]), undef, 'matches() checks the range'; +is matches('III', [0, 1, 2]), undef, 'matches() rejects shorter'; +is matches('III', [0, 1, 2, 3, 4]), undef, 'matches() rejects longer'; + +is matches('IDID', DI_string_match('IDID')), 1, 'Example 1'; +is matches('III', DI_string_match('III')), 1, 'Example 2'; +is matches('DDI', DI_string_match('DDI')), 1, 'Example 3'; -- cgit From 993b8be6de0c326497f7cd7d51e1c4f6664fb2a1 Mon Sep 17 00:00:00 2001 From: "E. Choroba" Date: Mon, 25 Dec 2023 16:45:16 +0100 Subject: Add Python solutions to 249 by E. Choroba --- challenge-249/e-choroba/python/ch-1.py | 20 ++++++++++++++++++++ challenge-249/e-choroba/python/ch-2.py | 23 +++++++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100755 challenge-249/e-choroba/python/ch-1.py create mode 100755 challenge-249/e-choroba/python/ch-2.py (limited to 'challenge-249') diff --git a/challenge-249/e-choroba/python/ch-1.py b/challenge-249/e-choroba/python/ch-1.py new file mode 100755 index 0000000000..8804c18a26 --- /dev/null +++ b/challenge-249/e-choroba/python/ch-1.py @@ -0,0 +1,20 @@ +#! /usr/bin/python3 +from collections import Counter + +def equal_pairs(*ints): + seen = Counter(ints) + pairs = [] + for c in seen: + if seen[c] % 2 == 1: + return [] + else: + pairs += map(lambda _i: [c, c], range(seen[c] // 2)) + return pairs + +assert equal_pairs(3, 2, 3, 2, 2, 2) == [[3, 3], [2, 2], [2, 2]], 'Example 1' +assert equal_pairs(1, 2, 3, 4) == [], 'Example 2' +assert equal_pairs(-1, -1, -2, -2) == [[-1, -1], [-2, -2]], 'Negative numbers' +assert equal_pairs(1, 1, 1, 1, 2, 2, 2, 2) == [ + [1, 1], [1, 1], [2, 2], [2, 2]], \ + 'More than once' +assert equal_pairs(1, 1, 1, 1, 2, 2, 2, 2, 1) == [], 'More than once odd'; diff --git a/challenge-249/e-choroba/python/ch-2.py b/challenge-249/e-choroba/python/ch-2.py new file mode 100755 index 0000000000..9cff6bee20 --- /dev/null +++ b/challenge-249/e-choroba/python/ch-2.py @@ -0,0 +1,23 @@ +#! /usr/bin/python3 +class DiStringMatch: + def __init__(self): + self.p = [0] + self.mx = 1 + + def process(self, s): + def inc(): + self.p.append(self.mx) + self.mx += 1 + + def dec(): + self.p = [x + 1 for x in self.p] + self.mx += 1 + self.p.append(0) + + for ch in s: + inc() if ch == 'I' else dec() + return self.p + +assert DiStringMatch().process('IDID') == [2, 3, 1, 4, 0] +assert DiStringMatch().process('III') == [0, 1, 2, 3] +assert DiStringMatch().process('DDI') == [2, 1, 0, 3] -- cgit From 8dde5fc3043bfad8ad700801206b460b0d52e59c Mon Sep 17 00:00:00 2001 From: pme Date: Mon, 25 Dec 2023 21:52:28 +0100 Subject: challenge-249 --- challenge-249/peter-meszaros/perl/ch-1.pl | 68 ++++++++++++++++++++++++ challenge-249/peter-meszaros/perl/ch-2.pl | 86 +++++++++++++++++++++++++++++++ 2 files changed, 154 insertions(+) create mode 100755 challenge-249/peter-meszaros/perl/ch-1.pl create mode 100755 challenge-249/peter-meszaros/perl/ch-2.pl (limited to 'challenge-249') diff --git a/challenge-249/peter-meszaros/perl/ch-1.pl b/challenge-249/peter-meszaros/perl/ch-1.pl new file mode 100755 index 0000000000..0caeece62f --- /dev/null +++ b/challenge-249/peter-meszaros/perl/ch-1.pl @@ -0,0 +1,68 @@ +#!/usr/bin/env perl +# +# You are given an array of integers with even number of elements. +# +# Write a script to divide the given array into equal pairs such that: +# +# a) Each element belongs to exactly one pair. +# b) The elements present in a pair are equal. +# +# Example 1 +# +# Input: @ints = (3, 2, 3, 2, 2, 2) +# Output: (2, 2), (3, 3), (2, 2) +# +# There are 6 elements in @ints. +# They should be divided into 6 / 2 = 3 pairs. +# @ints is divided into the pairs (2, 2), (3, 3), and (2, 2) satisfying all the +# conditions. +# +# Example 2 +# +# Input: @ints = (1, 2, 3, 4) +# Output: () +# +# There is no way to divide @ints 2 pairs such that the pairs satisfy every +# condition. +# + +use strict; +use warnings; +use Test::More; +use Data::Dumper; +use Algorithm::Combinatorics qw/partitions/; + +my $cases = [ + [3, 2, 3, 2, 2, 2], + [1, 2, 3, 4], +]; + +sub equal_pairs +{ + my $l = shift; + + return undef if @$l % 2; + my @res; + my $len = @$l / 2; + my $iter = partitions($l, $len); + PARTITION: while (my $p = $iter->next) { + undef @res; + for (0..$len-1) { + my @tuple = $p->[$_]->@*; + next PARTITION unless @tuple == 2 and $tuple[0] == $tuple[1]; + push @res, \@tuple; + } + if (@res == $len ) { + @res = sort {$a->[0] <=> $b->[0]} @res; + last; + } + } + + return \@res; +} + +is_deeply(equal_pairs($cases->[0]), [[2, 2], [2, 2], [3, 3]], '[3, 2, 3, 2, 2, 2]'); +is_deeply(equal_pairs($cases->[1]), [] , '[1, 2, 3, 4]'); +done_testing(); + +exit 0; diff --git a/challenge-249/peter-meszaros/perl/ch-2.pl b/challenge-249/peter-meszaros/perl/ch-2.pl new file mode 100755 index 0000000000..9698c19525 --- /dev/null +++ b/challenge-249/peter-meszaros/perl/ch-2.pl @@ -0,0 +1,86 @@ +#!/usr/bin/env perl +# +# You are given a string s, consisting of only the characters "D" and "I". +# +# Find a permutation of the integers [0 .. length(s)] such that for each +# character s[i] in the string: +# +# s[i] == 'I' ⇒ perm[i] < perm[i + 1] +# s[i] == 'D' ⇒ perm[i] > perm[i + 1] +# +# Example 1 +# +# Input: $str = "IDID" +# Output: (0, 4, 1, 3, 2) +# +# Example 2 +# +# Input: $str = "III" +# Output: (0, 1, 2, 3) +# +# Example 3 +# +# Input: $str = "DDI" +# Output: (3, 2, 0, 1) +# + +use strict; +use warnings; +use Test::More; +use Data::Dumper; +use Algorithm::Combinatorics qw/permutations/; + +my $cases = [ + 'IDID', + 'III', + 'DDI', +]; + +sub di_string_match +{ + my $str = shift; + + my @str = split('', $str); + + my @res; + my $iter = permutations([0..length($str)]); + PERMUTATION: while (my $p = $iter->next) { + for my $i (0..$#str) { + next PERMUTATION unless $str[$i] eq 'I' and $p->[$i] < $p->[$i+1] or + $str[$i] eq 'D' and $p->[$i] > $p->[$i+1]; + } + push @res, $p; + } + @res = sort {join('-', @$a) cmp join('-', @$b)} @res; + + return \@res; +} + +is_deeply(di_string_match($cases->[0]), [[ 0, 2, 1, 4, 3 ], + [ 0, 3, 1, 4, 2 ], + [ 0, 3, 2, 4, 1 ], + [ 0, 4, 1, 3, 2 ], + [ 0, 4, 2, 3, 1 ], + [ 1, 2, 0, 4, 3 ], + [ 1, 3, 0, 4, 2 ], + [ 1, 3, 2, 4, 0 ], + [ 1, 4, 0, 3, 2 ], + [ 1, 4, 2, 3, 0 ], + [ 2, 3, 0, 4, 1 ], + [ 2, 3, 1, 4, 0 ], + [ 2, 4, 0, 3, 1 ], + [ 2, 4, 1, 3, 0 ], + [ 3, 4, 0, 2, 1 ], + [ 3, 4, 1, 2, 0 ], + ], 'IDID'); +is_deeply(di_string_match($cases->[1]), [[ 0, 1, 2, 3 ], + ], 'III'); +is_deeply(di_string_match($cases->[2]), [[ 2, 1, 0, 3 ], + [ 3, 1, 0, 2 ], + [ 3, 2, 0, 1 ], + ], 'DDI'); +done_testing(); + +exit 0; + + -- cgit From f52c911f9ada18fd83cda2b5651a63741b714e81 Mon Sep 17 00:00:00 2001 From: David Ferrone Date: Mon, 25 Dec 2023 16:00:51 -0500 Subject: Week 249 --- challenge-249/zapwai/perl/ch-1.pl | 23 +++++++++++++++++++++++ challenge-249/zapwai/perl/ch-2.pl | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 challenge-249/zapwai/perl/ch-1.pl create mode 100644 challenge-249/zapwai/perl/ch-2.pl (limited to 'challenge-249') diff --git a/challenge-249/zapwai/perl/ch-1.pl b/challenge-249/zapwai/perl/ch-1.pl new file mode 100644 index 0000000000..6550ba4305 --- /dev/null +++ b/challenge-249/zapwai/perl/ch-1.pl @@ -0,0 +1,23 @@ +use v5.30; +my @ints = (3, 2, 3, 2, 2, 2); +#my @ints = (1, 2, 3, 4); +say "Input: @ints"; +print "Output: "; +my %h; +$h{$_}++ for (@ints); +my $cnt = 0; +for my $k ( values %h ) { + if ($k % 2 != 0) { + say "()"; + last; + } else { + $cnt++; + } +} +if ($cnt == scalar keys %h) { + foreach my $k ( keys %h ) { + my $d = $h{$k} / 2; + print "($k, $k) " x $d; + } + print "\n"; +} diff --git a/challenge-249/zapwai/perl/ch-2.pl b/challenge-249/zapwai/perl/ch-2.pl new file mode 100644 index 0000000000..7b6c161aa9 --- /dev/null +++ b/challenge-249/zapwai/perl/ch-2.pl @@ -0,0 +1,34 @@ +use v5.30; +my $str = "IDID"; +# my $str = "III"; +# my $str = "DDI"; +my @s = split "", $str; +my @p = (0 .. @s); +say "Input: \$str = $str"; +print "Output: "; +my $cnt; +do { + $cnt = 0; + for my $i (0 .. $#s) { + if ($s[$i] eq 'I') { + if ($p[$i] > $p[$i+1]) { + swap($i, \@p); + $cnt++; + } + } else { + if ($p[$i] < $p[$i+1]) { + swap($i, \@p); + $cnt++; + } + } + } +} while ($cnt != 0); + +say "@p"; + +sub swap { + my ($i, $ref) = @_; + my $val = $$ref[$i]; + $$ref[$i] = $$ref[$i + 1]; + $$ref[$i + 1] = $val; +} -- cgit From a8e8a75796d9be05a2fc4ce38db216141b8aea5b Mon Sep 17 00:00:00 2001 From: Packy Anderson Date: Mon, 25 Dec 2023 18:58:47 -0500 Subject: Challenge 249 solutions by Packy Anderson * Raku * Perl * Python 1 Blog post --- challenge-249/packy-anderson/README.md | 82 ++++++++++++----------------- challenge-249/packy-anderson/blog.txt | 1 + challenge-249/packy-anderson/perl/ch-1.pl | 47 +++++++++++++++++ challenge-249/packy-anderson/perl/ch-2.pl | 39 ++++++++++++++ challenge-249/packy-anderson/python/ch-1.py | 47 +++++++++++++++++ challenge-249/packy-anderson/python/ch-2.py | 36 +++++++++++++ challenge-249/packy-anderson/raku/ch-1.raku | 46 ++++++++++++++++ challenge-249/packy-anderson/raku/ch-2.raku | 39 ++++++++++++++ 8 files changed, 288 insertions(+), 49 deletions(-) create mode 100644 challenge-249/packy-anderson/blog.txt create mode 100755 challenge-249/packy-anderson/perl/ch-1.pl create mode 100755 challenge-249/packy-anderson/perl/ch-2.pl create mode 100755 challenge-249/packy-anderson/python/ch-1.py create mode 100755 challenge-249/packy-anderson/python/ch-2.py create mode 100755 challenge-249/packy-anderson/raku/ch-1.raku create mode 100755 challenge-249/packy-anderson/raku/ch-2.raku (limited to 'challenge-249') diff --git a/challenge-249/packy-anderson/README.md b/challenge-249/packy-anderson/README.md index f08eb862a3..6682f66637 100644 --- a/challenge-249/packy-anderson/README.md +++ b/challenge-249/packy-anderson/README.md @@ -8,12 +8,16 @@ Sample output ``` $ raku/ch-1.raku Example 1: -Input: $str = "loveleetcode", $char = "e" -Output: (3,2,1,0,1,0,0,1,2,2,1,0) +Input: @ints = (3, 2, 3, 2, 2, 2) +Output: (3, 3), (2, 2), (2, 2) Example 2: -Input: $str = "aaab", $char = "b" -Output: (3,2,1,0) +Input: @ints = (1, 2, 3, 4) +Output: () + +Example 3: +Input: @ints = (1, 2, 3, 4, 4, 3, 2, 1) +Output: (1, 1), (4, 4), (3, 3), (2, 2) ``` * [Task 2](raku/ch-2.raku) @@ -22,28 +26,16 @@ Sample output ``` $ raku/ch-2.raku Example 1: -Input: $a = [ - [1, 2, 3, 4], - [5, 6, 7, 8], - [9, 10, 11, 12] - ] -Output: $b = [ - [14, 18, 22], - [30, 34, 38] - ] +Input: $str = 'IDID' +Output: (0, 4, 1, 3, 2) Example 2: -Input: $a = [ - [1, 0, 0, 0], - [0, 1, 0, 0], - [0, 0, 1, 0], - [0, 0, 0, 1] - ] -Output: $b = [ - [2, 1, 0], - [1, 2, 1], - [0, 1, 2] - ] +Input: $str = 'III' +Output: (0, 1, 2, 3) + +Example 3: +Input: $str = 'DDI' +Output: (3, 2, 0, 1) ``` ## Perl @@ -54,12 +46,16 @@ Sample output ``` $ perl/ch-1.pl Example 1: -Input: $str = "loveleetcode", $char = "e" -Output: (3,2,1,0,1,0,0,1,2,2,1,0) +Input: @ints = (3, 2, 3, 2, 2, 2) +Output: (2, 2), (2, 2), (3, 3) Example 2: -Input: $str = "aaab", $char = "b" -Output: (3,2,1,0) +Input: @ints = (1, 2, 3, 4) +Output: () + +Example 3: +Input: @ints = (1, 2, 3, 4, 4, 3, 2, 1) +Output: (4, 4), (3, 3), (2, 2), (1, 1) ``` * [Task 2](perl/ch-2.pl) @@ -68,28 +64,16 @@ Sample output ``` $ perl/ch-2.pl Example 1: -Input: $a = [ - [1, 2, 3, 4], - [5, 6, 7, 8], - [9, 10, 11, 12] - ] -Output: $b = [ - [14, 18, 22], - [30, 34, 38] - ] +Input: $str = 'IDID' +Output: (0, 4, 1, 3, 2) Example 2: -Input: $a = [ - [1, 0, 0, 0], - [0, 1, 0, 0], - [0, 0, 1, 0], - [0, 0, 0, 1] - ] -Output: $b = [ - [2, 1, 0], - [1, 2, 1], - [0, 1, 2] - ] +Input: $str = 'III' +Output: (0, 1, 2, 3) + +Example 3: +Input: $str = 'DDI' +Output: (3, 2, 0, 1) ``` ## Guest Language: Python @@ -98,4 +82,4 @@ Output: $b = [ ## Blog Post -[Perl Weekly Challenge: The Shortest Distance between Submatrix Sums](https://packy.dardan.com/b/Ff) +[Perl Weekly Challenge: Stringy DI and Paired Equals](https://packy.dardan.com/b/Fv) diff --git a/challenge-249/packy-anderson/blog.txt b/challenge-249/packy-anderson/blog.txt new file mode 100644 index 0000000000..1adcf62852 --- /dev/null +++ b/challenge-249/packy-anderson/blog.txt @@ -0,0 +1 @@ +https://packy.dardan.com/b/Fv \ No newline at end of file diff --git a/challenge-249/packy-anderson/perl/ch-1.pl b/challenge-249/packy-anderson/perl/ch-1.pl new file mode 100755 index 0000000000..ec399a13e6 --- /dev/null +++ b/challenge-249/packy-anderson/perl/ch-1.pl @@ -0,0 +1,47 @@ +#!/usr/bin/env perl +use v5.38; + +sub equalPairs(@ints) { + my @pairs; + my %num_count; + # count how many of each int we have + foreach my $num ( @ints ) { + $num_count{$num}++; + } + # first, make sure we have even numbers of each integer + foreach my $k ( keys %num_count ) { + my $v = $num_count{$k}; + next if $v % 2 == 0; # it's even, we can make pairs + return @pairs; # we have an odd number, can't make pairs + } + # now make pairs from those integers + foreach my $k ( keys %num_count ) { + my $count = $num_count{$k}; + while ($count > 0) { + push @pairs, [$k, $k]; + $count -= 2; + } + } + return @pairs; +} + +sub solution(@ints) { + say 'Input: @ints = (' . join(', ', @ints) . ')'; + my @pairs = equalPairs(@ints); + if (@pairs == 0) { + say 'Output: ()'; + } + else { + @pairs = map { qq{($_->[0], $_->[1])} } @pairs; + say 'Output: ' . join(', ', @pairs); + } +} + +say "Example 1:"; +solution(3, 2, 3, 2, 2, 2); + +say "\nExample 2:"; +solution(1, 2, 3, 4); + +say "\nExample 3:"; +solution(1, 2, 3, 4, 4, 3, 2, 1); \ No newline at end of file diff --git a/challenge-249/packy-anderson/perl/ch-2.pl b/challenge-249/packy-anderson/perl/ch-2.pl new file mode 100755 index 0000000000..e24b164ac9 --- /dev/null +++ b/challenge-249/packy-anderson/perl/ch-2.pl @@ -0,0 +1,39 @@ +#!/usr/bin/env perl +use v5.38; + +sub diStringMatch($str) { + my @permutation; + # first, generate the list of integers + # we're making permutations of + my @nums = 0 .. length($str); + # now let's generate our permutation + foreach my $c ( split(//, $str) ) { + if ($c eq 'D') { + # take the largest number available + push @permutation, pop(@nums); + } + else { + # take the smallest number available + push @permutation, shift(@nums); + } + } + # add last remaining number + push @permutation, $nums[0]; + + return @permutation; +} + +sub solution($str) { + say qq{Input: \$str = '$str'}; + my @permutation = diStringMatch($str); + say 'Output: (' . join(', ', @permutation) . ')'; +} + +say "Example 1:"; +solution("IDID"); + +say "\nExample 2:"; +solution("III"); + +say "\nExample 3:"; +solution("DDI"); \ No newline at end of file diff --git a/challenge-249/packy-anderson/python/ch-1.py b/challenge-249/packy-anderson/python/ch-1.py new file mode 100755 index 0000000000..228bb47da3 --- /dev/null +++ b/challenge-249/packy-anderson/python/ch-1.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python + +from collections import Counter + +def equalPairs(nums): + pairs = [] + num_count = Counter() + # count how many of each int we have + for num in nums: + num_count[num] += 1 + + # first, make sure we have even numbers of each integer + for k, v in dict(num_count).items(): + if v % 2 == 0: # it's even, we can make pairs + continue + else: + return pairs # we have an odd number, no pairs + + # now make pairs from those integers + for k, v in dict(num_count).items(): + count = v # the values k, v are read-only + while count > 0: + pairs.append( [k, k] ) + count -= 2 + + return pairs + +def comma_join(arr): + return ', '.join(map(lambda i: str(i), arr)) + +def solution(nums): + print(f'Input: @ints = ({comma_join(nums)})') + pairs = equalPairs(nums) + if len(pairs) == 0: + print('Output: ()') + else: + pairs = [ f'({x[0]}, {x[1]})' for x in pairs ] + print(f"Output: { ', '.join(pairs) }") + +print('Example 1:') +solution([3, 2, 3, 2, 2, 2]) + +print('\nExample 2:') +solution([1, 2, 3, 4]) + +print('\nExample 3:') +solution([1, 2, 3, 4, 4, 3, 2, 1]) \ No newline at end of file diff --git a/challenge-249/packy-anderson/python/ch-2.py b/challenge-249/packy-anderson/python/ch-2.py new file mode 100755 index 0000000000..8c3750f195 --- /dev/null +++ b/challenge-249/packy-anderson/python/ch-2.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python + +def diStringMatch(str): + permutation = [] + # first, generate the list of integers + # we're making permutations of + nums = list(range(len(str)+1)) + # now let's generate our permutation + for c in str: + if c == 'D': + # take the largest number available + permutation.append( nums.pop(-1) ) + else: + # take the smallest number available + permutation.append( nums.pop(0) ) + # add last remaining number + permutation.append( nums[0] ) + + return permutation + +def comma_join(arr): + return ', '.join(map(lambda i: str(i), arr)) + +def solution(str): + print(f'Input: $str = ({comma_join(str)})') + permutations = diStringMatch(str) + print(f'Output: ({comma_join(permutations)})') + +print('Example 1:') +solution("IDID") + +print('\nExample 2:') +solution("III") + +print('\nExample 3:') +solution("DDI") \ No newline at end of file diff --git a/challenge-249/packy-anderson/raku/ch-1.raku b/challenge-249/packy-anderson/raku/ch-1.raku new file mode 100755 index 0000000000..6daec9c767 --- /dev/null +++ b/challenge-249/packy-anderson/raku/ch-1.raku @@ -0,0 +1,46 @@ +#!/usr/bin/env raku +use v6; + +sub equalPairs(@ints) { + my @pairs; + my %num_count; + # count how many of each int we have + for @ints -> $num { + %num_count{$num}++; + } + # first, make sure we have even numbers of each integer + for %num_count.kv -> $k, $v { + next if $v % 2 == 0; # it's even, we can make pairs + return @pairs; # we have an odd number, can't make pairs + } + # now make pairs from those integers + for %num_count.kv -> $k, $v { + my $count = $v; # the values $k, $v are read-only + while ($count > 0) { + @pairs.push( [$k, $k] ); + $count -= 2; + } + } + return @pairs; +} + +sub solution(@ints) { + say 'Input: @ints = (' ~ @ints.join(', ') ~ ')'; + my @pairs = equalPairs(@ints); + if (@pairs == 0) { + say 'Output: ()'; + } + else { + @pairs = @pairs.map({ qq{($_[0], $_[1])} }); + say 'Output: ' ~ @pairs.join(', '); + } +} + +say "Example 1:"; +solution([3, 2, 3, 2, 2, 2]); + +say "\nExample 2:"; +solution([1, 2, 3, 4]); + +say "\nExample 3:"; +solution([1, 2, 3, 4, 4, 3, 2, 1]); diff --git a/challenge-249/packy-anderson/raku/ch-2.raku b/challenge-249/packy-anderson/raku/ch-2.raku new file mode 100755 index 0000000000..44b853efd2 --- /dev/null +++ b/challenge-249/packy-anderson/raku/ch-2.raku @@ -0,0 +1,39 @@ +#!/usr/bin/env raku +use v6; + +sub diStringMatch($str) { + my @permutation; + # first, generate the list of integers + # we're making permutations of + my @nums = 0 .. $str.chars; + # now let's generate our permutation + for $str.split('', :skip-empty) -> $c { + if ($c eq 'D') { + # take the largest number available + @permutation.push( @nums.pop() ); + } + else { + # take the smallest number available + @permutation.push( @nums.shift() ); + } + } + # add last remaining number + @permutation.push( @nums[0] ); + + return @permutation; +} + +sub solution($str) { + say qq{Input: \$str = '$str'}; + my @permutation = diStringMatch($str); + say 'Output: (' ~ @permutation.join(', ') ~ ')'; +} + +say "Example 1:"; +solution("IDID"); + +say "\nExample 2:"; +solution("III"); + +say "\nExample 3:"; +solution("DDI"); \ No newline at end of file -- cgit From 665fcbc151ec9abb919bfed2495d789e53e61e74 Mon Sep 17 00:00:00 2001 From: Peter Campbell Smith Date: Tue, 26 Dec 2023 12:52:23 +0000 Subject: Week 249 - last one for 2023 --- challenge-249/peter-campbell-smith/blog.txt | 1 + challenge-249/peter-campbell-smith/perl/ch-1.pl | 35 +++++++++++ challenge-249/peter-campbell-smith/perl/ch-2.pl | 77 +++++++++++++++++++++++++ 3 files changed, 113 insertions(+) create mode 100644 challenge-249/peter-campbell-smith/blog.txt create mode 100755 challenge-249/peter-campbell-smith/perl/ch-1.pl create mode 100755 challenge-249/peter-campbell-smith/perl/ch-2.pl (limited to 'challenge-249') diff --git a/challenge-249/peter-campbell-smith/blog.txt b/challenge-249/peter-campbell-smith/blog.txt new file mode 100644 index 0000000000..489402b764 --- /dev/null +++ b/challenge-249/peter-campbell-smith/blog.txt @@ -0,0 +1 @@ +http://ccgi.campbellsmiths.force9.co.uk/challenge/249 diff --git a/challenge-249/peter-campbell-smith/perl/ch-1.pl b/challenge-249/peter-campbell-smith/perl/ch-1.pl new file mode 100755 index 0000000000..8a3c5d8bb4 --- /dev/null +++ b/challenge-249/peter-campbell-smith/perl/ch-1.pl @@ -0,0 +1,35 @@ +#!/usr/bin/perl + +use v5.26; # The Weekly Challenge - 2023-12-25 +use utf8; # Week 249 task 1 - Equal pairs +use strict; # Peter Campbell Smith +use warnings; # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge + +equal_pairs(1, 2, 3, 4, 1, 2, 3, 4); +equal_pairs(1, 2, 3, 4, 1, 2, 3); +equal_pairs(77, 23, 45, 12, 23, 99, 99, 12, 77, 45, 12, 12); + +sub equal_pairs { + + my ($j, %seen, $result); + %seen = (); + + # loop over supplied integers + for $j (@_) { + + # seen one unpaired already, so this is an answer + if ($seen{$j}) { + $result .= qq[($j, $j), ]; + delete $seen{$j}; + + # note that we are looking for a mate + } else { + $seen{$j} = 1; + } + } + + # output answers: if success then %seen will be empty + say qq[\nInput: \@ints = (] . join(', ', @_) . ')'; + say qq[Output: ] . (scalar keys %seen ? 'not possible' : substr($result, 0, -2)); +} + \ No newline at end of file diff --git a/challenge-249/peter-campbell-smith/perl/ch-2.pl b/challenge-249/peter-campbell-smith/perl/ch-2.pl new file mode 100755 index 0000000000..903792bd1b --- /dev/null +++ b/challenge-249/peter-campbell-smith/perl/ch-2.pl @@ -0,0 +1,77 @@ +#!/usr/bin/perl + +use v5.26; # The Weekly Challenge - 2023-12-25 +use utf8; # Week 249 task 2 - DI string match +use strict; # Peter Campbell Smith +use warnings; # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge +no warnings 'recursion'; + +my (@di); + +di_string_match('IDID'); +di_string_match('III'); +di_string_match('DDI'); +di_string_match('DDIIDIDDIIIDDIDIIDIIIIDD'); +di_string_match('DIDIDIDIDI'); + +sub di_string_match { + + my ($str, @nums, @perm, @new_nums, $i, $good); + + # initialise + $str = $_[0]; + say qq[\nInput: \$str = '$str']; + @di = split('', $str); + $nums[$_] = 1 for 0 .. @di; + + # try all possible initial numbers + for $i (0 .. @di) { + @perm = ($i); + @new_nums = @nums; + @new_nums[$i] = -1; + $good = get_next(1, \@new_nums, \@perm); + last if $good; + } + + say qq[Output: no valid permutation] unless $good; +} + +sub get_next { + + my ($i, @perm, $this_di, $n, @nums, @new_nums, @new_perm, $good); + + $i = $_[0]; # looking for $perm[$i]; + @nums = @{$_[1]}; # numbers still unused + @perm = @{$_[2]}; # answer so far + $this_di = $di[$i - 1]; # D or I at position $i + + # find numbers valid at this position + for $n (0 .. @nums - 1) { + + # number already used + next unless $nums[$n] >= 0; + + # number not < or > as required by D or I + next if ($this_di eq 'D' and $n > $perm[$i - 1]); + next if ($this_di eq 'I' and $n < $perm[$i - 1]); + + # good so far and if we've reached the end of $str we have an answer + @new_perm = @perm; + $new_perm[$i] = $n; + if ($i == @di) { + say qq[Output: (] . join(', ', @new_perm) . ')'; + return 1; + } + + # else recurse to get next value in @perm + @new_nums = @nums; + $new_nums[$n] = -1; + $good = get_next($i + 1, \@new_nums, \@new_perm); + + # finished + return 1 if $good; + } + + # no valid perm - but I don't think that can happen + return 0; +} -- cgit From ec34f3232c555c181a086cd46e0c439c84764588 Mon Sep 17 00:00:00 2001 From: Michael Manring Date: Tue, 26 Dec 2023 23:44:30 +1100 Subject: pwc249 solution in go --- challenge-249/pokgopun/go/ch-1.go | 88 +++++++++++++++++++++ challenge-249/pokgopun/go/ch-2.go | 159 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 247 insertions(+) create mode 100644 challenge-249/pokgopun/go/ch-1.go create mode 100644 challenge-249/pokgopun/go/ch-2.go (limited to 'challenge-249') diff --git a/challenge-249/pokgopun/go/ch-1.go b/challenge-249/pokgopun/go/ch-1.go new file mode 100644 index 0000000000..c6f505180e --- /dev/null +++ b/challenge-249/pokgopun/go/ch-1.go @@ -0,0 +1,88 @@ +//# https://theweeklychallenge.org/blog/perl-weekly-challenge-249/ +/*# + +Task 1: Shortest Distance + +Submitted by: [66]Mohammad S Anwar + __________________________________________________________________ + + You are given an array of integers with even number of elements. + + Write a script to divide the given array into equal pairs such that: +a) Each element belongs to exactly one pair. +b) The elements present in a pair are equal. + +Example 1 + +Input: @ints = (3, 2, 3, 2, 2, 2) +Output: (2, 2), (3, 3), (2, 2) + +There are 6 elements in @ints. +They should be divided into 6 / 2 = 3 pairs. +@ints is divided into the pairs (2, 2), (3, 3), and (2, 2) satisfying all the co +nditions. + +Example 2 + +Input: @ints = (1, 2, 3, 4) +Output: () + +There is no way to divide @ints 2 pairs such that the pairs satisfy every condit +ion. + +Task 2: DI String Match +#*/ +//# solution by pokgopun@gmail.com + +package main + +import ( + "cmp" + "fmt" + "slices" + + gocmp "github.com/google/go-cmp/cmp" +) + +type duo [2]int + +type duos []duo + +func (ds duos) sort() duos { + if len(ds) == 0 { + return nil + } + slices.SortFunc(ds, func(a, b duo) int { + return cmp.Compare(a[0], b[0]) + }) + return ds +} + +type ints []int + +func (is ints) equalPairs() duos { + var ds duos + slices.Sort(is) + m := make(map[int]int) + for _, v := range is { + m[v]++ + if m[v] == 2 { + ds = append(ds, duo{v, v}) + m[v] = 0 + } + } + //return ds.sort() + return ds +} + +func main() { + for _, data := range []struct { + input ints + output duos + }{ + {ints{3, 2, 3, 2, 2, 2}, duos{duo{2, 2}, duo{3, 3}, duo{2, 2}}}, + {ints{1, 2, 3, 4}, duos{}}, + } { + fmt.Println(gocmp.Diff(data.input.equalPairs(), data.output.sort())) //output nothing if ok, otherise show the difference + } +} diff --git a/challenge-249/pokgopun/go/ch-2.go b/challenge-249/pokgopun/go/ch-2.go new file mode 100644 index 0000000000..b9e687a641 --- /dev/null +++ b/challenge-249/pokgopun/go/ch-2.go @@ -0,0 +1,159 @@ +//# https://theweeklychallenge.org/blog/perl-weekly-challenge-249/ +/*# + +Task 2: DI String Match + +Submitted by: [67]Mohammad S Anwar + __________________________________________________________________ + + You are given a string s, consisting of only the characters "D" and + "I". + + Find a permutation of the integers [0 .. length(s)] such that for each + character s[i] in the string: +s[i] == 'I' ⇒ perm[i] < perm[i + 1] +s[i] == 'D' ⇒ perm[i] > perm[i + 1] + +Example 1 + +Input: $str = "IDID" +Output: (0, 4, 1, 3, 2) + +Example 2 + +Input: $str = "III" +Output: (0, 1, 2, 3) + +Example 3 + +Input: $str = "DDI" +Output: (3, 2, 0, 1) + __________________________________________________________________ + + Last date to submit the solution 23:59 (UK Time) Sunday 31st December + 2023. + __________________________________________________________________ + +SO WHAT DO YOU THINK ? +#*/ +//# solution by pokgopun@gmail.com + +package main + +import ( + "fmt" + + "github.com/google/go-cmp/cmp" +) + +func main() { + for _, data := range []struct { + input DI + output permute + }{ + {newDI("IDID"), permute{0, 4, 1, 3, 2}}, + {newDI("III"), permute{0, 1, 2, 3}}, + {newDI("DDI"), permute{3, 2, 0, 1}}, + } { + fmt.Println(data.input.match(data.output)) + } +} + +type DI []bool + +func newDI(s string) DI { + di := make(DI, len(s)) + for i, v := range s { + switch v { + case 'I': + di[i] = false + case 'D': + di[i] = true + default: + return DI{} + } + } + return di +} + +func (di DI) match(p permute) bool { + l := len(di) + //fmt.Println("l=", l) + pmtt := newPermutation(byte(l + 1)) + for pm := range pmtt.ch { + //fmt.Println("-----") + var ( + i int + v bool + ) + for _, v = range di { + if v { + if pm[i] > pm[i+1] { + //fmt.Println("D", pm[i], pm[i+1]) + i++ + continue + } + } else { + if pm[i] < pm[i+1] { + //fmt.Println("I", pm[i], pm[i+1]) + i++ + continue + } + } + break + } + //fmt.Println("i=", i) + if i == l { + //fmt.Println(pm, p, cmp.Diff(pm, p)) + if cmp.Diff(pm, p) == "" { + close(pmtt.done) + return true + } + } + } + return false +} + +type permute []byte + +type permutation struct { + ch chan permute + done chan struct{} +} + +func newPermutation(n byte) permutation { + pmtt := permutation{make(chan permute), make(chan struct{})} + go func() { + s := pmString(n) + pmtt.output(s, "") + close(pmtt.ch) + }() + return pmtt +} + +func (pmtt permutation) output(s, t string) { + select { + case <-pmtt.done: + default: + if len(s) > 0 { + for i, v := range []byte(s) { + pmtt.output(s[:i]+s[i+1:], t+string(v)) + } + } else { + select { + case <-pmtt.done: + case pmtt.ch <- permute(t): + } + } + } +} + +func pmString(n byte) string { + bs := make([]byte, n) + for n > 0 { + n-- + bs[n] = n + } + //fmt.Println(bs) + return string(bs) +} -- cgit From 057e65c8cdea0ae55a2094b855acf80da1f5dec0 Mon Sep 17 00:00:00 2001 From: arnesom Date: Tue, 26 Dec 2023 18:43:14 +0100 Subject: Arne Sommer --- challenge-249/arne-sommer/blog.txt | 1 + challenge-249/arne-sommer/raku/ch-1.raku | 28 ++++++++++++++++++++++++++ challenge-249/arne-sommer/raku/ch-2.raku | 25 +++++++++++++++++++++++ challenge-249/arne-sommer/raku/di-string-match | 25 +++++++++++++++++++++++ challenge-249/arne-sommer/raku/equal-pairs | 28 ++++++++++++++++++++++++++ 5 files changed, 107 insertions(+) create mode 100644 challenge-249/arne-sommer/blog.txt create mode 100755 challenge-249/arne-sommer/raku/ch-1.raku create mode 100755 challenge-249/arne-sommer/raku/ch-2.raku create mode 100755 challenge-249/arne-sommer/raku/di-string-match create mode 100755 challenge-249/arne-sommer/raku/equal-pairs (limited to 'challenge-249') diff --git a/challenge-249/arne-sommer/blog.txt b/challenge-249/arne-sommer/blog.txt new file mode 100644 index 0000000000..9c3ec53f8a --- /dev/null +++ b/challenge-249/arne-sommer/blog.txt @@ -0,0 +1 @@ +https://raku-musings.com/equal-di.html diff --git a/challenge-249/arne-sommer/raku/ch-1.raku b/challenge-249/arne-sommer/raku/ch-1.raku new file mode 100755 index 0000000000..96989560ee --- /dev/null +++ b/challenge-249/arne-sommer/raku/ch-1.raku @@ -0,0 +1,28 @@ +#! /usr/bin/env raku + +unit sub MAIN (*@ints where @ints.elems %% 2 && @ints.elems > 0 && all(@ints) ~~ Int, :v(:$verbose)); + +my @output; +my @sorted = @ints>>.Int.sort; + +say ":Sorted: { @sorted.join(",") }" if $verbose; + +while @sorted +{ + my $first = @sorted.shift; + my $second = @sorted.shift; + + if $first == $second + { + @output.push: ($first, $second); + say ":Pair: $first,$second" if $verbose; + } + else + { + say ":Non-pair: $first,$second" if $verbose; + say "()"; + exit; + } +} + +say @output.map({ "($_[0], $_[1])"}).join(", "); diff --git a/challenge-249/arne-sommer/raku/ch-2.raku b/challenge-249/arne-sommer/raku/ch-2.raku new file mode 100755 index 0000000000..9f90401bc1 --- /dev/null +++ b/challenge-249/arne-sommer/raku/ch-2.raku @@ -0,0 +1,25 @@ +#! /usr/bin/env raku + +unit sub MAIN ($s where $s ~~ /^<[ID]>+$/, :v(:$verbose)); + +my @output; +my @integers = (0 .. $s.chars); + +for $s.comb -> $char +{ + if $char eq "I" + { + @output.push: @integers.shift; + say ":I -> lowest integer { @output.tail }" if $verbose; + } + else + { + @output.push: @integers.pop; + say ":D -> highest integer { @output.tail }" if $verbose; + } +} + +@output.push: @integers[0]; +say ": -> remaining integer { @output.tail }" if $verbose; + +say "({ @output.join(", ") })"; diff --git a/challenge-249/arne-sommer/raku/di-string-match b/challenge-249/arne-sommer/raku/di-string-match new file mode 100755 index 0000000000..9f90401bc1 --- /dev/null +++ b/challenge-249/arne-sommer/raku/di-string-match @@ -0,0 +1,25 @@ +#! /usr/bin/env raku + +unit sub MAIN ($s where $s ~~ /^<[ID]>+$/, :v(:$verbose)); + +my @output; +my @integers = (0 .. $s.chars); + +for $s.comb -> $char +{ + if $char eq "I" + { + @output.push: @integers.shift; + say ":I -> lowest integer { @output.tail }" if $verbose; + } + else + { + @output.push: @integers.pop; + say ":D -> highest integer { @output.tail }" if $verbose; + } +} + +@output.push: @integers[0]; +say ": -> remaining integer { @output.tail }" if $verbose; + +say "({ @output.join(", ") })"; diff --git a/challenge-249/arne-sommer/raku/equal-pairs b/challenge-249/arne-sommer/raku/equal-pairs new file mode 100755 index 0000000000..96989560ee --- /dev/null +++ b/challenge-249/arne-sommer/raku/equal-pairs @@ -0,0 +1,28 @@ +#! /usr/bin/env raku + +unit sub MAIN (*@ints where @ints.elems %% 2 && @ints.elems > 0 && all(@ints) ~~ Int, :v(:$verbose)); + +my @output; +my @sorted = @ints>>.Int.sort; + +say ":Sorted: { @sorted.join(",") }" if $verbose; + +while @sorted +{ + my $first = @sorted.shift; + my $second = @sorted.shift; + + if $first == $second + { + @output.push: ($first, $second); + say ":Pair: $first,$second" if $verbose; + } + else + { + say ":Non-pair: $first,$second" if $verbose; + say "()"; + exit; + } +} + +say @output.map({ "($_[0], $_[1])"}).join(", "); -- cgit From 858a5a78afbe2f51d389af1d6f4dd5d4e28d9710 Mon Sep 17 00:00:00 2001 From: Roger Bell_West Date: Tue, 26 Dec 2023 19:56:14 +0000 Subject: RogerBW solutions for challenge no. 249 --- challenge-249/roger-bell-west/javascript/ch-1.js | 59 +++++ challenge-249/roger-bell-west/javascript/ch-2.js | 71 ++++++ challenge-249/roger-bell-west/kotlin/ch-1.kt | 32 +++ challenge-249/roger-bell-west/kotlin/ch-2.kt | 45 ++++ challenge-249/roger-bell-west/lua/ch-1.lua | 61 +++++ challenge-249/roger-bell-west/lua/ch-2.lua | 79 +++++++ challenge-249/roger-bell-west/perl/ch-1.pl | 25 ++ challenge-249/roger-bell-west/perl/ch-2.pl | 29 +++ challenge-249/roger-bell-west/postscript/ch-1.ps | 215 ++++++++++++++++++ challenge-249/roger-bell-west/postscript/ch-2.ps | 276 +++++++++++++++++++++++ challenge-249/roger-bell-west/python/ch-1.py | 25 ++ challenge-249/roger-bell-west/python/ch-2.py | 35 +++ challenge-249/roger-bell-west/raku/ch-1.p6 | 23 ++ challenge-249/roger-bell-west/raku/ch-2.p6 | 27 +++ challenge-249/roger-bell-west/ruby/ch-1.rb | 30 +++ challenge-249/roger-bell-west/ruby/ch-2.rb | 39 ++++ challenge-249/roger-bell-west/rust/ch-1.rs | 31 +++ challenge-249/roger-bell-west/rust/ch-2.rs | 39 ++++ challenge-249/roger-bell-west/scala/ch-1.scala | 33 +++ challenge-249/roger-bell-west/scala/ch-2.scala | 46 ++++ challenge-249/roger-bell-west/tests.yaml | 44 ++++ 21 files changed, 1264 insertions(+) create mode 100755 challenge-249/roger-bell-west/javascript/ch-1.js create mode 100755 challenge-249/roger-bell-west/javascript/ch-2.js create mode 100644 challenge-249/roger-bell-west/kotlin/ch-1.kt create mode 100644 challenge-249/roger-bell-west/kotlin/ch-2.kt create mode 100755 challenge-249/roger-bell-west/lua/ch-1.lua create mode 100755 challenge-249/roger-bell-west/lua/ch-2.lua create mode 100755 challenge-249/roger-bell-west/perl/ch-1.pl create mode 100755 challenge-249/roger-bell-west/perl/ch-2.pl create mode 100644 challenge-249/roger-bell-west/postscript/ch-1.ps create mode 100644 challenge-249/roger-bell-west/postscript/ch-2.ps create mode 100755 challenge-249/roger-bell-west/python/ch-1.py create mode 100755 challenge-249/roger-bell-west/python/ch-2.py create mode 100755 challenge-249/roger-bell-west/raku/ch-1.p6 create mode 100755 challenge-249/roger-bell-west/raku/ch-2.p6 create mode 100755 challenge-249/roger-bell-west/ruby/ch-1.rb create mode 100755 challenge-249/roger-bell-west/ruby/ch-2.rb create mode 100755 challenge-249/roger-bell-west/rust/ch-1.rs create mode 100755 challenge-249/roger-bell-west/rust/ch-2.rs create mode 100644 challenge-249/roger-bell-west/scala/ch-1.scala create mode 100644 challenge-249/roger-bell-west/scala/ch-2.scala create mode 100644 challenge-249/roger-bell-west/tests.yaml (limited to 'challenge-249') diff --git a/challenge-249/roger-bell-west/javascript/ch-1.js b/challenge-249/roger-bell-west/javascript/ch-1.js new file mode 100755 index 0000000000..6b39470cdd --- /dev/null +++ b/challenge-249/roger-bell-west/javascript/ch-1.js @@ -0,0 +1,59 @@ +#! /usr/bin/node + +"use strict" + +// by Frank Tan +// https://stackoverflow.com/questions/38400594/javascript-deep-comparison +function deepEqual(a,b) +{ + if( (typeof a == 'object' && a != null) && + (typeof b == 'object' && b != null) ) + { + var count = [0,0]; + for( var key in a) count[0]++; + for( var key in b) count[1]++; + if( count[0]-count[1] != 0) {return false;} + for( var key in a) + { + if(!(key in b) || !deepEqual(a[key],b[key])) {return false;} + } + for( var key in b) + { + if(!(key in a) || !deepEqual(b[key],a[key])) {return false;} + } + return true; + } + else + { + return a === b; + } +} + +function shortestdistance(a0) { + if (a0.length % 2 != 0) { + return []; + } + let a = a0; + a.sort(); + let out = []; + for (let i = 0; i < a.length; i += 2) { + if (a[i] != a[i + 1]) { + return []; + } + out.push([a[i], a[i]]); + } + return out; +} + +if (deepEqual(shortestdistance([3, 2, 3, 2, 2, 2]), [[2, 2], [2, 2], [3, 3]])) { + process.stdout.write("Pass"); +} else { + process.stdout.write("FAIL"); +} +process.stdout.write(" "); +if (deepEqual(shortestdistance([1, 2, 3, 4]), [])) { + process.stdout.write("Pass"); +} else { + process.stdout.write("FAIL"); +} +process.stdout.write("\n"); diff --git a/challenge-249/roger-bell-west/javascript/ch-2.js b/challenge-249/roger-bell-west/javascript/ch-2.js new file mode 100755 index 0000000000..4dd1690970 --- /dev/null +++ b/challenge-249/roger-bell-west/javascript/ch-2.js @@ -0,0 +1,71 @@ +#! /usr/bin/node + +"use strict" + +// by Frank Tan +// https://stackoverflow.com/questions/38400594/javascript-deep-comparison +function deepEqual(a,b) +{ + if( (typeof a == 'object' && a != null) && + (typeof b == 'object' && b != null) ) + { + var count = [0,0]; + for( var key in a) count[0]++; + for( var key in b) count[1]++; + if( count[0]-count[1] != 0) {return false;} + for( var key in a) + { + if(!(key in b) || !deepEqual(a[key],b[key])) {return false;} + } + for( var key in b) + { + if(!(key in a) || !deepEqual(b[key],a[key])) {return false;} + } + return true; + } + else + { + return a === b; + } +} + +function distringmatch(a) { + let v = 1 << (a.length - 1); + let wv = v << 1; + let out = [wv]; + for (const c of a) { + if (c == 'I') { + wv += v; + } else { + wv -= v; + } + v >>= 1; + out.push(wv); + } + let q = [...out]; + q.sort(function(a,b) { + return a-b; + }); + let c = new Map; + q.forEach((v, i) => {c.set(v, i)}); + return out.map(x => c.get(x)); +} + +if (deepEqual(distringmatch('IDID'), [0, 4, 1, 3, 2])) { + process.stdout.write("Pass"); +} else { + process.stdout.write("FAIL"); +} +process.stdout.write(" "); +if (deepEqual(distringmatch('III'), [0, 1, 2, 3])) { + process.stdout.write("Pass"); +} else { + process.stdout.write("FAIL"); +} +process.stdout.write(" "); +if (deepEqual(distringmatch('DDI'), [3, 2, 0, 1])) { + process.stdout.write("Pass"); +} else { + process.stdout.write("FAIL"); +} +process.stdout.write("\n"); diff --git a/challenge-249/roger-bell-west/kotlin/ch-1.kt b/challenge-249/roger-bell-west/kotlin/ch-1.kt new file mode 100644 index 0000000000..c0bae85bf8 --- /de