From 76c022a8dd82c194b2f2c879e0e127d5a66f411a Mon Sep 17 00:00:00 2001 From: Magnus Markling Date: Mon, 6 Nov 2023 08:03:44 +0100 Subject: add 242 --- challenge-242/memark/uiua/ch-1.ua | 10 ++++++++++ challenge-242/memark/uiua/ch-2.ua | 9 +++++++++ 2 files changed, 19 insertions(+) create mode 100644 challenge-242/memark/uiua/ch-1.ua create mode 100644 challenge-242/memark/uiua/ch-2.ua diff --git a/challenge-242/memark/uiua/ch-1.ua b/challenge-242/memark/uiua/ch-1.ua new file mode 100644 index 0000000000..90e8d2408a --- /dev/null +++ b/challenge-242/memark/uiua/ch-1.ua @@ -0,0 +1,10 @@ +# https://theweeklychallenge.org/blog/perl-weekly-challenge-242/#TASK1 + +# Uiua 0.1.0 + +MissingMembers ← ▽>0≡⧻. ⊟∩□⊝ ⊃(▽¬∊,∶)(▽¬∊,) + +--- +⍤. ≍{[1 3][4 6]} MissingMembers [1 2 3] [2 4 6] +⍤. ≍{[3]} MissingMembers [1 2 3 3] [1 1 2 2] +--- diff --git a/challenge-242/memark/uiua/ch-2.ua b/challenge-242/memark/uiua/ch-2.ua new file mode 100644 index 0000000000..0a94498d51 --- /dev/null +++ b/challenge-242/memark/uiua/ch-2.ua @@ -0,0 +1,9 @@ +# https://theweeklychallenge.org/blog/perl-weekly-challenge-242/#TASK2 + +# Uiua 0.1.0 + +FlipMatrix ← ¬≡⇌ +--- +⍤. ≍[[1 0 0] [0 1 0] [1 1 1]] FlipMatrix [[1 1 0] [1 0 1] [0 0 0]] +⍤. ≍[[1 1 0 0] [0 1 1 0] [0 0 0 1] [1 0 1 0]] FlipMatrix [[1 1 0 0] [1 0 0 1] [0 1 1 1] [1 0 1 0]] +--- -- cgit From 5e686655fd92a70e0b05a792552c06735bfe6c34 Mon Sep 17 00:00:00 2001 From: irifkin Date: Tue, 7 Nov 2023 08:41:42 -0500 Subject: perl submissions for challenge 242 and blog post in README --- challenge-242/ianrifkin/README.md | 173 ++++++++++++++++------------------- challenge-242/ianrifkin/blog.txt | 1 + challenge-242/ianrifkin/perl/ch-1.pl | 95 +++++++++++++++++++ challenge-242/ianrifkin/perl/ch-2.pl | 70 ++++++++++++++ 4 files changed, 244 insertions(+), 95 deletions(-) create mode 100644 challenge-242/ianrifkin/blog.txt create mode 100644 challenge-242/ianrifkin/perl/ch-1.pl create mode 100644 challenge-242/ianrifkin/perl/ch-2.pl diff --git a/challenge-242/ianrifkin/README.md b/challenge-242/ianrifkin/README.md index ece05ca910..a6148b3413 100644 --- a/challenge-242/ianrifkin/README.md +++ b/challenge-242/ianrifkin/README.md @@ -1,140 +1,123 @@ -# Math is hard? +# ??? -Challenge 241: https://theweeklychallenge.org/blog/perl-weekly-challenge-241/ +Challenge 242: https://theweeklychallenge.org/blog/perl-weekly-challenge-242/ -Some of The Weekly Challenges are more intimidating for me based on how math-heavy the task feels. The first task seemed overwhelming but was pretty quick to create a solution, yet the second task took me much longer. - -## Task 1: Arithmetic Triplets +This week's challenge is pretty fun because it's one of those types of problems that seems really easy but you can end up spending a bunch of time trying to figure out how to solve it in a way that makes some sense. +## Task 1: Missing Members ``` -You are given an array (3 or more members) of integers in increasing order and a positive integer. +You are given two arrays of integers. -Write a script to find out the number of unique Arithmetic Triplets satisfying the following rules: +Write a script to find out the missing members in each other arrays. -a) i < j < k -b) nums[j] - nums[i] == diff -c) nums[k] - nums[j] == diff Example 1 -Input: @nums = (0, 1, 4, 6, 7, 10) - $diff = 3 -Output: 2 +Input: @arr1 = (1, 2, 3) + @arr2 = (2, 4, 6) +Output: ([1, 3], [4, 6]) -Index (1, 2, 4) is an arithmetic triplet because both 7 - 4 == 3 and 4 - 1 == 3. -Index (2, 4, 5) is an arithmetic triplet because both 10 - 7 == 3 and 7 - 4 == 3. +(1, 2, 3) has 2 members (1, 3) missing in the array (2, 4, 6). +(2, 4, 6) has 2 members (4, 6) missing in the array (1, 2, 3). Example 2 -Input: @nums = (4, 5, 6, 7, 8, 9) - $diff = 2 -Output: 2 +Input: @arr1 = (1, 2, 3, 3) + @arr2 = (1, 1, 2, 2) +Output: ([3]) -(0, 2, 4) is an arithmetic triplet because both 8 - 6 == 2 and 6 - 4 == 2. -(1, 3, 5) is an arithmetic triplet because both 9 - 7 == 2 and 7 - 5 == 2. +(1, 2, 3, 3) has 2 members (3, 3) missing in the array (1, 1, 2, 2). Since they are same, keep just one. +(1, 1, 2, 2) has 0 member missing in the array (1, 2, 3, 3). ``` -A quick read of this task was overwhelming to me because it sounded like it was going to be more math than I could handle, but upon closer inspection the answer is in the description. - -I kept it simple and just explicitely created the three loops with the three specified iterators. It's very helpful to match the incrementor names in my code with the task's description. +My command-line knowledge makes me think of just having two files and `diff`'ing them. If I needed to solve this for a real purpose I would probably look to using List::Compare to get it done. But for the challenges I like to think about how else I could go about solving for it. -I started by looping through the input array with an incrementer `$i`. We know that `$i` is needed for the first value so the max `$i` is going to be 2 less than the total array length: `for (my $i = 0; $i < $nums_length - 2; $i++)` -Within this loop I just make the next loop with `$j` which is 1 more than `$i` to 1 less than the array length: `for (my $j = $i + 1; $j < $nums_length - 1; $j++)` +I call a sub `find_members` passing it the two arrays as references. The sub starts by creating an output string and defaulting it to "Everything matches" in case the two arrays have all the same numbers. -Finally within that loop I create the loop with `$k` which is going to be 1 more than `$j` to the end of the array: `for (my $k = $j + 1; $k < $nums_length; $k++)` +Here's where I got a little silly for fun. I needed to compare array1 to array2 then also compare array2 to array1. A sane person would probably just call a sub twice e.g. `get_diffs(@array1, @array2)` then `get_diffs(@array2, @array1)`. I decided to get "creative." -Now that I have my loops I go back to the instructions which stated: +The sub starts by accepting an array of array refs. I can loop through the array `@_` to run through the process twice (`for (my $i = 0; $i < @arrays; $i++)`). The first time I run it I will be on item 0 so I know I'll be comparing it to item 1: `my $other_arr = 1;` So in the loop, just for clarity I set: ``` -nums[j] - nums[i] == diff -and -nums[k] - nums[j] == diff +my $arr = $arrays[$i]; +my $arr_other = $arrays[$other_arr]; ``` -which in my Perl code is literally that same thing: `$nums[$j] - $nums[$i] == $diff && $nums[$k] - $nums[$j] == $diff` - -Anytime the above is true it increments a counter `$total_finds`. After the loops are complete it prints the `$total_finds` counter. - -The complete `sub find_triplets` is as follows: +To find the actual differences between arrays I create a hash mapping the array I'm in to the other array: `my %arr_hash = map {$_=>1} @{$arr_other};` then create an array of differences by `grep`'ing the hash for the values in the current array: `my @diffs = grep { !$arr_hash{$_} } @{$arr};` +This finds the differences but I noticed in the example two output that it should not duplicate the same number multiple times. I think the best way to do that would be with List::MoreUtils but I decided to write out a little loop to create an array of those unique values using a new hash just to keep track: ``` -sub find_triplets { - my ($diff, $nums) = @_; - my $nums_length = scalar @{$nums}; - my $total_finds = 0; - for (my $i = 0; $i < $nums_length - 2; $i++) { - for (my $j = $i + 1; $j < $nums_length - 1; $j++) { - for (my $k = $j + 1; $k < $nums_length; $k++) { - if (@{$nums}[$j] - @{$nums}[$i] eq $diff && @{$nums}[$k] - @{$nums}[$j] eq $diff) { - $total_finds++; - } - } - } +my @unique; +my %seen; +foreach my $value (@diffs) { + if (! $seen{$value}) { + push @unique, $value; + $seen{$value} = 1; } - print "$total_finds\n"; } ``` -Full script with comments available at https://github.com/ianrifkin/perlweeklychallenge-club/blob/ianrifkin-challenge-241/challenge-241/ianrifkin/perl/ch-1.pl - +At this point I want to update the `$output` variable. If there are no differences found it leaves the ouput variable with the default text, otherwise it sets it to the value of the `@unique` differences array. Note that it also checks if the value of `$output` was the default string so it knows if it is setting or appending the new text: -## Task 2: Prime Order ``` -You are given an array of unique positive integers greater than 2. - -Write a script to sort them in ascending order of the count of their prime factors, tie-breaking by ascending value. +# Creating output text if applicable +if ($output eq 'Everything matches') { + $output = '[' . join(',', @unique) . ']' if @diffs; +} +else { + $output .= ', [' . join(',', @unique) . ']' if @diffs; +} +# now switch to comparing the other direction +$other_arr = 0; + } + # Return output to be printed with paranthesis to match task instructions + return '(' . $output . ')'; +} +``` -Example 1 -Input: @int = (11, 8, 27, 4) -Output: (11, 4, 8, 27)) +## Task 2: Flip Matrix -Prime factors of 11 => 11 -Prime factors of 4 => 2, 2 -Prime factors of 8 => 2, 2, 2 -Prime factors of 27 => 3, 3, 3 ``` +You are given n x n binary matrix. -This one sounded simple enough but I needed to write WAY more code to accomplish. Though to be fair, part of the length is a lot more code comments and documentation -- critial because this quickly got confusing for me! After I completed it and it was working, I wasn't happy with how long the code got and how I was handling the looping so I refactored it a bit. The main different is the first attempt I really started by trying to find the prime factors and then counting them up. This was useful because it allowed me to check as I went along to make sure I was counting the right things appropriately. But once I got a good sense of it I realized it could be done quicker -- though mostly it's to reduce what felt like messy extra loops in code. +Write a script to flip the given matrix as below. -I split up the work into 2 subroutines. +1 1 0 +0 1 1 +0 0 1 +a) Reverse each row -The main sub, `prime_order()`, accepts an array of integers. It loops through the array to create a hash where the key is the input number from the array and the value is number of prime factors for that number. It generates the count of prime factors by calling a sub `prime_finder()`. +0 1 1 +1 1 0 +1 0 0 -```prime_finder``` +b) Invert each member -After the loop is complete `prime_order()` will create and print a sorted array based on the hash results. -``` - foreach my $ordered_num (sort { $results{$a} <=> $results{$b} or $a <=> $b } keys %results) { - push(@sorted_output, $ordered_num); - } +1 0 0 +0 0 1 +0 1 1 - # Finally, print the sorted output - say "(" . join(", ", @sorted_output) . ")"; +Example 1 +Input: @matrix = ([1, 1, 0], [1, 0, 1], [0, 0, 0]) +Output: ([1, 0, 0], [0, 1, 0], [1, 1, 1]) +Example 2 +Input: @matrix = ([1, 1, 0, 0], [1, 0, 0, 1], [0, 1, 1, 1], [1, 0, 1, 0]) +Output: ([1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 0, 1], [1, 0, 1, 0]) ``` -The sub `prime_finder()` is what actually cacluates the number of prime factors for a given input number. - +This was a fun task becasuse it's really simple to just look at the examples to know the output (especially with short array lenghts). Reversing numbers and flipping 0's and 1's is easy to do in your head. But how to do it in code? It ends up that it doesn't have to be very tricky either. -I start by having a while loop set to repeat endlessly with a manual condition flag. This will be important based on my approach. - -Within the while loop I have a for loop that will find the biggest prime factor for a given number. The loop starts at the square root of the number `$i = int(sqrt($num))` and checks if a prime is found by seeing if dividing the number by the iterator has a remainder: `if ($num % $i == 0)` - -Some examples: - -input is 11 --> int of square root is 3 --> first prime factor found is 1 (meaning 11 is a prime number). In this case it increments the counter by 1 then exits the parent while loop. - -input is 27 --> int of square root is 5 --> first prime factor found is 3. The counter gets incremented to 1. To determine how many other prime factors it would take, I set the `$num` variable to `27 / 3` which is 9 and I exit the `for` loop, restarting it with the new `$num`. In this next iteration the prime found is 3. I increment the counter. Then it goes one more time where it determines that 3 is a prime number and does the final increment. +I solved this task by passing the matrix array to a sub `matrix_flip` which just uses Perl's native `reverse` to put the array in backwards order then a simple conditional `map` that sets 1's to 0 and 0's to 1. Other than that is just some parentheses and commas for output readability. ``` - while ($calculating) { - for (my $i = int(sqrt($num)); $i >= 1; $i--) { - #looping backwards to find biggest prime factor first - if ($num % $i == 0) { #if prime factor found - $counter++; #increment that we found a prime factor - $calculating = 0 if ($i == 1); #if the prime factor is 1 stop the parent while loop - $num = $num / $i; #otherwise reset num lower to search for the next prime factor - last; #and restart for loop with new number - } - - } +sub matrix_flip { + my @matrix_rows = @_; + my @new_matrix = (); + + foreach my $row (@matrix_rows) { + #the actual flipping - use reverse to swap order and the map to flip values + my @new_row = '[' . join (", ", reverse map {$_ == 0 ? 1 : 0} @{$row}) . ']'; + push (@new_matrix, @new_row); } + return '(' . join (", ", @new_matrix) . ')'; +} ``` -The full code with comments is available at https://github.com/ianrifkin/perlweeklychallenge-club/blob/ianrifkin-challenge-241/challenge-241/ianrifkin/perl/ch-2.pl \ No newline at end of file +The full code with comments is available at https://github.com/manwar/perlweeklychallenge-club/tree/master/challenge-242/ianrifkin \ No newline at end of file diff --git a/challenge-242/ianrifkin/blog.txt b/challenge-242/ianrifkin/blog.txt new file mode 100644 index 0000000000..7e5837dddf --- /dev/null +++ b/challenge-242/ianrifkin/blog.txt @@ -0,0 +1 @@ +https://github.com/manwar/perlweeklychallenge-club/tree/master/challenge-242/ianrifkin#readme diff --git a/challenge-242/ianrifkin/perl/ch-1.pl b/challenge-242/ianrifkin/perl/ch-1.pl new file mode 100644 index 0000000000..93aa61db37 --- /dev/null +++ b/challenge-242/ianrifkin/perl/ch-1.pl @@ -0,0 +1,95 @@ +use v5.30.3; +use warnings; +use strict; +use Getopt::Long; +use Pod::Usage; + +# You are given two arrays of integers. +# Write a script to find out the missing members in each other arrays. + +my $man = 0; +my $help = 0; +GetOptions ('help|?' => \$help, man => \$man) + or pod2usage(2); + +pod2usage(1) if $help; +pod2usage(-exitstatus => 0, -verbose => 2) if $man; + +# Example 1 +my @arr1 = (1, 2, 3); +my @arr2 = (2, 4, 6); +say find_members(\@arr1, \@arr2); + +#Example 2 +@arr1 = (1, 2, 3, 3); +@arr2 = (1, 1, 2, 2); +say find_members(\@arr1, \@arr2); + +sub find_members { + my (@arrays) = @_; + + my $output = 'Everything matches'; #default output string + my $other_arr = 1; #b/c I need to diff both directions + for (my $i = 0; $i < @arrays; $i++) { + my $arr = $arrays[$i]; + my $arr_other = $arrays[$other_arr]; + + # Checking what numbers are only in $arr + my %arr_hash = map {$_=>1} @{$arr_other}; + my @diffs = grep { !$arr_hash{$_} } @{$arr}; + # Making sure each item in array is unique + my @unique; + my %seen; + foreach my $value (@diffs) { + if (! $seen{$value}) { + push @unique, $value; + $seen{$value} = 1; + } + } + # Creating output text if applicable + if ($output eq 'Everything matches') { + $output = '[' . join(',', @unique) . ']' if @diffs; + } + else { + $output .= ', [' . join(',', @unique) . ']' if @diffs; + } + # now switch to comparing the other direction + $other_arr = 0; + } + # Return output to be printed with paranthesis to match task instructions + return '(' . $output . ')'; +} + +__END__ + +=head1 Challenge 242, Task 1, by IanRifkin: Missing Members + +Given an input of two arrays, this script will find the missing members from each input array. + +Example 1 inputs: (1, 2, 3) and (2, 4, 6) + +Example 2 inputs: (1, 2, 3, 3) and (1, 1, 2, 2) + +See https://theweeklychallenge.org/blog/perl-weekly-challenge-241/#TASK1 for more information on this challenge + +=head1 SYNOPSIS + +perl ./ch-1.pl + +=head1 OPTIONS + +=over 8 + +=item B<-help> + +Print a brief help message and exits. + +=item B<-man> + +Prints the manual page and exits. + +=back + + + + diff --git a/challenge-242/ianrifkin/perl/ch-2.pl b/challenge-242/ianrifkin/perl/ch-2.pl new file mode 100644 index 0000000000..be6601d695 --- /dev/null +++ b/challenge-242/ianrifkin/perl/ch-2.pl @@ -0,0 +1,70 @@ +use v5.30.3; +use warnings; +use strict; + +use Getopt::Long; +use Pod::Usage; + +# You are given two arrays of integers. +# Write a script to find out the missing members in each other arrays. + +my $man = 0; +my $help = 0; +GetOptions ('help|?' => \$help, man => \$man) + or pod2usage(2); + +pod2usage(1) if $help; +pod2usage(-exitstatus => 0, -verbose => 2) if $man; + + +# Example 1 +my @matrix = ([1, 1, 0], [1, 0, 1], [0, 0, 0]); +say matrix_flip(@matrix); + +# Example 2 +@matrix = ([1, 1, 0, 0], [1, 0, 0, 1], [0, 1, 1, 1], [1, 0, 1, 0]); +say matrix_flip(@matrix); + +sub matrix_flip { + my @matrix_rows = @_; + my @new_matrix = (); + + foreach my $row (@matrix_rows) { + #the actual flipping - use reverse to swap order and the map to flip values + my @new_row = '[' . join (", ", reverse map {$_ == 0 ? 1 : 0} @{$row}) . ']'; + push (@new_matrix, @new_row); + } + return '(' . join (", ", @new_matrix) . ')'; +} + + +__END__ + +=head1 Challenge 242, Task 2, by IanRifkin: Flip Matrix + +Given a "n x n" binary matrix, this script will flip the given matrix by revering each row then inverting each member. + +See https://theweeklychallenge.org/blog/perl-weekly-challenge-241/#TASK2 for more information on this challenge + +=head1 SYNOPSIS + +perl ./ch-2.pl + +=head1 OPTIONS + +=over 8 + +=item B<-help> + +Print a brief help message and exits. + +=item B<-man> + +Prints the manual page and exits. + +=back + + + + + -- cgit From 4d132885b421c95decf38f5691fb9b8c78e859b4 Mon Sep 17 00:00:00 2001 From: irifkin Date: Tue, 7 Nov 2023 13:28:12 -0500 Subject: refactoring task 1 --- challenge-242/ianrifkin/README.md | 70 ++++++++++++++++++++---------------- challenge-242/ianrifkin/perl/ch-1.pl | 63 ++++++++++++++++---------------- 2 files changed, 72 insertions(+), 61 deletions(-) diff --git a/challenge-242/ianrifkin/README.md b/challenge-242/ianrifkin/README.md index a6148b3413..a519c9fd16 100644 --- a/challenge-242/ianrifkin/README.md +++ b/challenge-242/ianrifkin/README.md @@ -1,4 +1,4 @@ -# ??? +# I'm a Map Challenge 242: https://theweeklychallenge.org/blog/perl-weekly-challenge-242/ @@ -28,47 +28,55 @@ Output: ([3]) My command-line knowledge makes me think of just having two files and `diff`'ing them. If I needed to solve this for a real purpose I would probably look to using List::Compare to get it done. But for the challenges I like to think about how else I could go about solving for it. +When I first started writing code I tried to: +1) create an hash for each array +2) create an array using the hash to grep values in the other array +3) process the output array to de-duplicate +4) parse the de-duped output array for pretty printing -I call a sub `find_members` passing it the two arrays as references. The sub starts by creating an output string and defaulting it to "Everything matches" in case the two arrays have all the same numbers. +It worked but it felt messy. Taking a step back to refactor I realized that I could create an array of hashes for the output, very succicintly: -Here's where I got a little silly for fun. I needed to compare array1 to array2 then also compare array2 to array1. A sane person would probably just call a sub twice e.g. `get_diffs(@array1, @array2)` then `get_diffs(@array2, @array1)`. I decided to get "creative." - -The sub starts by accepting an array of array refs. I can loop through the array `@_` to run through the process twice (`for (my $i = 0; $i < @arrays; $i++)`). The first time I run it I will be on item 0 so I know I'll be comparing it to item 1: `my $other_arr = 1;` So in the loop, just for clarity I set: ``` -my $arr = $arrays[$i]; -my $arr_other = $arrays[$other_arr]; +my @result_hashes = ( + {map { $_ => check_if_exists($_, $arr2) } @{$arr1}}, + {map { $_ => check_if_exists($_, $arr1) } @{$arr2}} + ); ``` -To find the actual differences between arrays I create a hash mapping the array I'm in to the other array: `my %arr_hash = map {$_=>1} @{$arr_other};` then create an array of differences by `grep`'ing the hash for the values in the current array: `my @diffs = grep { !$arr_hash{$_} } @{$arr};` - -This finds the differences but I noticed in the example two output that it should not duplicate the same number multiple times. I think the best way to do that would be with List::MoreUtils but I decided to write out a little loop to create an array of those unique values using a new hash just to keep track: +This sets each hash's key to the the value from the array. Then `check_if_exists` just `grep`s the other array for the value and returns true or false: ``` -my @unique; -my %seen; -foreach my $value (@diffs) { - if (! $seen{$value}) { - push @unique, $value; - $seen{$value} = 1; - } +sub check_if_exists { + my ($k, $arr) = @_; + return 1 if grep /$k/, @{$arr}; + return 0; } ``` -At this point I want to update the `$output` variable. If there are no differences found it leaves the ouput variable with the default text, otherwise it sets it to the value of the `@unique` differences array. Note that it also checks if the value of `$output` was the default string so it knows if it is setting or appending the new text: +That's it! Since the `@result_hashes` array contains hashes it is de-duped by naturely. The only remaining step is printing. Interestingly I expended more lines of code to get the printing in the desired format. + +Parse hashed results into an @output array where the output array will end up having two values (one for each input). + +I loop through the array of hashed results putting the key from the hash in an array if the hash key's value is false (meaning the number was not found in the other array): ``` -# Creating output text if applicable -if ($output eq 'Everything matches') { - $output = '[' . join(',', @unique) . ']' if @diffs; -} -else { - $output .= ', [' . join(',', @unique) . ']' if @diffs; -} -# now switch to comparing the other direction -$other_arr = 0; - } - # Return output to be printed with paranthesis to match task instructions - return '(' . $output . ')'; -} +foreach (@result_hashes) { + my %h = %{$_}; + my @tmp_out = (); + + foreach my $key ( keys %h ) { + push(@tmp_out, $key) unless $h{$key}; + } +``` +Then I put that output into the @output array. Note that that point of having the @tmp_out step is solely to have separation between the two inputs. e.g. I want the output from example 1 to be `(['3','1'],['4','6'])` and not `('3','1','4','6')`: +``` +push(@output, \@tmp_out) if @tmp_out; +``` + +For the final step (and not to make this any longer) I used `Data::Dumper` to return the `@output` array in the desired format: +``` +$Data::Dumper::Terse = 1; #don't print VAR names +$Data::Dumper::Indent = 0; #keep output on one line +return '(' . join(',', Dumper(@output)) . ')'; ``` ## Task 2: Flip Matrix diff --git a/challenge-242/ianrifkin/perl/ch-1.pl b/challenge-242/ianrifkin/perl/ch-1.pl index 93aa61db37..91f34050d8 100644 --- a/challenge-242/ianrifkin/perl/ch-1.pl +++ b/challenge-242/ianrifkin/perl/ch-1.pl @@ -3,6 +3,7 @@ use warnings; use strict; use Getopt::Long; use Pod::Usage; +use Data::Dumper; # You are given two arrays of integers. # Write a script to find out the missing members in each other arrays. @@ -26,38 +27,40 @@ say find_members(\@arr1, \@arr2); say find_members(\@arr1, \@arr2); sub find_members { - my (@arrays) = @_; - - my $output = 'Everything matches'; #default output string - my $other_arr = 1; #b/c I need to diff both directions - for (my $i = 0; $i < @arrays; $i++) { - my $arr = $arrays[$i]; - my $arr_other = $arrays[$other_arr]; - - # Checking what numbers are only in $arr - my %arr_hash = map {$_=>1} @{$arr_other}; - my @diffs = grep { !$arr_hash{$_} } @{$arr}; - # Making sure each item in array is unique - my @unique; - my %seen; - foreach my $value (@diffs) { - if (! $seen{$value}) { - push @unique, $value; - $seen{$value} = 1; - } + my ($arr1, $arr2) = @_; + + my @result_hashes = ( + {map { $_ => check_if_exists($_, $arr2) } @{$arr1}}, + {map { $_ => check_if_exists($_, $arr1) } @{$arr2}} + ); + + # Parse hashed results into an @output array + # output array will have two values (one for each input) + my @output = (); + foreach (@result_hashes) { + my %h = %{$_}; + my @tmp_out = (); + # Select the hash key if the value is false + # --meaning that the number did not exist in the other array + foreach my $key ( keys %h ) { + push(@tmp_out, $key) unless $h{$key}; } - # Creating output text if applicable - if ($output eq 'Everything matches') { - $output = '[' . join(',', @unique) . ']' if @diffs; - } - else { - $output .= ', [' . join(',', @unique) . ']' if @diffs; - } - # now switch to comparing the other direction - $other_arr = 0; + # The step of putting \@tmp_out into @output + # -- is so we have separation from results of + # -- the two inputs + push(@output, \@tmp_out) if @tmp_out; } - # Return output to be printed with paranthesis to match task instructions - return '(' . $output . ')'; + + # Return the @output array in the desired format + $Data::Dumper::Terse = 1; #don't print VAR names + $Data::Dumper::Indent = 0; #keep output on one line + return '(' . join(',', Dumper(@output)) . ')'; +} + +sub check_if_exists { + my ($k, $arr) = @_; + return 1 if grep /$k/, @{$arr}; + return 0; } __END__ -- cgit From 9518d58f43543361c49af92b9d919d8b8c4c10f0 Mon Sep 17 00:00:00 2001 From: Humberto Massa Date: Wed, 8 Nov 2023 19:43:03 -0300 Subject: Some more oneliners --- challenge-242/massa/raku/ch-1.raku | 64 ++++++++++++++++++++++++++++++++ challenge-242/massa/raku/ch-2.raku | 75 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 139 insertions(+) create mode 100644 challenge-242/massa/raku/ch-1.raku create mode 100644 challenge-242/massa/raku/ch-2.raku diff --git a/challenge-242/massa/raku/ch-1.raku b/challenge-242/massa/raku/ch-1.raku new file mode 100644 index 0000000000..7691ced71b --- /dev/null +++ b/challenge-242/massa/raku/ch-1.raku @@ -0,0 +1,64 @@ +#! /usr/bin/env raku + +# Perl Weekly Challenge +# © 2023 Shimon Bollinger. All rights reserved. +# Last modified: Mon 15 May 2023 09:17:32 PM EDT +# Version 0.0.1 + +=begin pod +=TITLE +=head2 Task 1: Missing Members + +=SUBTITLE +=head2 Submitted by massa + +=CHALLENGE +=head2 + +You are given two arrays of integers. + +Write a script to find out the missing members in each other arrays. + +=head3 Example 1: + + Input: @arr1 = (1, 2, 3) + @arr2 = (2, 4, 6) + Output: ([1, 3], [4, 6]) + + (1, 2, 3) has 2 members (1, 3) missing in the array (2, 4, 6). + (2, 4, 6) has 2 members (4, 6) missing in the array (1, 2, 3). + +=head3 Example 2: + + Input: @arr1 = (1, 2, 3, 3) + @arr2 = (1, 1, 2, 2) + Output: ([3]) + + (1, 2, 3, 3) has 2 members (3, 3) missing in the array (1, 1, 2, 2). Since they are same, keep just one. + (1, 1, 2, 2) has 0 member missing in the array (1, 2, 3, 3). + +=SOLUTION + +=end pod + +# always use the latest version of Raku +use v6.*; + +sub SOLUTION(@a, @b) { + keys(@a ∖ @b).sort.Array, keys(@b ∖ @a).sort.Array +} + +multi MAIN (Bool :$test!) { + use Test; + + my @tests = [ + %{ input => ([1, 2, 3], [2, 4, 6]), output => ([1, 3], [4, 6]) }, + %{ input => ([1, 2, 3, 3], [1, 1, 2, 2]), output => ([3], []) }, + ]; + + for @tests { + SOLUTION( |. ).&is-deeply: ., .; + } # end of for @tests +} # end of multi MAIN (Bool :$test!) + + diff --git a/challenge-242/massa/raku/ch-2.raku b/challenge-242/massa/raku/ch-2.raku new file mode 100644 index 0000000000..58801dd5e4 --- /dev/null +++ b/challenge-242/massa/raku/ch-2.raku @@ -0,0 +1,75 @@ +#! /usr/bin/env raku + +# Perl Weekly Challenge +# © 2023 Shimon Bollinger. All rights reserved. +# Last modified: Mon 15 May 2023 09:17:32 PM EDT +# Version 0.0.1 + +=begin pod +=TITLE +=head2 Task 2: Flip Matrix + +=SUBTITLE +=head2 Submitted by massa + +=CHALLENGE +=head2 + +You are given n x n binary matrix. + +Write a script to flip the given matrix as below. + + 1 1 0 + 0 1 1 + 0 0 1 + + a) Reverse each row + + 0 1 1 + 1 1 0 + 1 0 0 + + b) Invert each member + + 1 0 0 + 0 0 1 + 0 1 1 + +=head3 Example 1: + + Input: @matrix = ([1, 1, 0], [1, 0, 1], [0, 0, 0]) + Output: ([1, 0, 0], [0, 1, 0], [1, 1, 1]) + +=head3 Example 2: + + Input: @matrix = ([1, 1, 0, 0], [1, 0, 0, 1], [0, 1, 1, 1], [1, 0, 1, 0]) + Output: ([1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 0, 1], [1, 0, 1, 0]) + +=SOLUTION + +=end pod + +# always use the latest version of Raku +use v6.*; + +sub SOLUTION(@_) { + @_».reverse».map({ $_ ?? 0 !! 1 })».Array +} + +multi MAIN (Bool :$test!) { + use Test; + + my @tests = [ + %{ input => ([1, 1, 0], [1, 0, 1], [0, 0, 0]), + output => ([1, 0, 0], [0, 1, 0], [1, 1, 1]) }, + %{ input => ([1, 1, 0, 0], [1, 0, 0, 1], [0, 1, 1, 1], [1, 0, 1, 0]), + output => ([1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 0, 1], [1, 0, 1, 0]) }, + ]; + + for @tests { + SOLUTION( . ).&is-deeply: ., .; + + } # end of for @tests +} # end of multi MAIN (:$test!) + + -- cgit From 03383778501c07642e5fa3d0e5202793fb237929 Mon Sep 17 00:00:00 2001 From: Paulo Custodio Date: Wed, 8 Nov 2023 23:48:12 +0000 Subject: Add C solution --- challenge-242/paulo-custodio/c/ch-1.c | 130 +++++++++++++++ challenge-242/paulo-custodio/c/ch-2.c | 149 ++++++++++++++++++ challenge-242/paulo-custodio/c/utarray.h | 252 ++++++++++++++++++++++++++++++ challenge-242/paulo-custodio/perl/ch-2.pl | 41 ++--- 4 files changed, 554 insertions(+), 18 deletions(-) create mode 100644 challenge-242/paulo-custodio/c/ch-1.c create mode 100644 challenge-242/paulo-custodio/c/ch-2.c create mode 100644 challenge-242/paulo-custodio/c/utarray.h diff --git a/challenge-242/paulo-custodio/c/ch-1.c b/challenge-242/paulo-custodio/c/ch-1.c new file mode 100644 index 0000000000..2b00d9ceed --- /dev/null +++ b/challenge-242/paulo-custodio/c/ch-1.c @@ -0,0 +1,130 @@ +/* +Challenge 242 + +Task 1: Missing Members +Submitted by: Mohammad S Anwar +You are given two arrays of integers. + +Write a script to find out the missing members in each other arrays. + +Example 1 +Input: @arr1 = (1, 2, 3) + @arr2 = (2, 4, 6) +Output: ([1, 3], [4, 6]) + +(1, 2, 3) has 2 members (1, 3) missing in the array (2, 4, 6). +(2, 4, 6) has 2 members (4, 6) missing in the array (1, 2, 3). +Example 2 +Input: @arr1 = (1, 2, 3, 3) + @arr2 = (1, 1, 2, 2) +Output: ([3]) + +(1, 2, 3, 3) has 2 members (3, 3) missing in the array (1, 1, 2, 2). Since they are same, keep just one. +(1, 1, 2, 2) has 0 member missing in the array (1, 2, 3, 3). +*/ + +#include "utarray.h" +#include +#include +#include +#include + +#define DELIMS "[](),; \t" + +void die(const char* message, ...) { + va_list ap; + va_start(ap, message); + vfprintf(stderr, message, ap); + fprintf(stderr, "\n"); + va_end(ap); + exit(EXIT_FAILURE); +} + +void* check_mem(void* p) { + if (!p) + die("Out of memory"); + return p; +} + +int compare(const void* a, const void* b) { + return *(int*)a - *(int*)b; +} + +UT_array* parse_list(const char* text_) { + UT_array* arr; + utarray_new(arr, &ut_int_icd); + + char* text = check_mem(strdup(text_)); + char* token = strtok(text, DELIMS); + while (token) { + int n = atoi(token); + utarray_push_back(arr, &n); + token = strtok(NULL, DELIMS); + } + utarray_sort(arr, compare); + + free(text); + return arr; +} + +UT_array* find_not_in(UT_array* arr1, UT_array* arr2) { + UT_array* result; + utarray_new(result, &ut_int_icd); + + for (int *p = NULL; (p = utarray_next(arr1, p)) != NULL; ) { + if (!utarray_find(arr2, p, compare)) { + if (!utarray_find(result, p, compare)) { + utarray_push_back(result, p); + } + } + } + + return result; +} + +void print_list(UT_array* arr) { + printf("["); + const char* sep = ""; + for (int *p = NULL; (p = utarray_next(arr, p)) != NULL; ) { + printf("%s%d", sep, *p); + sep = ", "; + } + printf("]"); +} + +void print_result(UT_array* arr1, UT_array* arr2) { + printf("("); + const char* sep = ""; + + if (utarray_len(arr1) > 0) { + printf("%s", sep); + print_list(arr1); + sep = ", "; + } + + if (utarray_len(arr2) > 0) { + printf("%s", sep); + print_list(arr2); + sep = ", "; + } + + printf(")"); +} + +int main(int argc, char* argv[]) { + if (argc != 3) + die("Usage: ch-1 '(a,b,c)' '(d,e,f)'"); + + UT_array* arr1 = parse_list(argv[1]); + UT_array* arr2 = parse_list(argv[2]); + + UT_array* not_in1 = find_not_in(arr1, arr2); + UT_array* not_in2 = find_not_in(arr2, arr1); + + print_result(not_in1, not_in2); + + utarray_free(arr1); + utarray_free(arr2); + utarray_free(not_in1); + utarray_free(not_in2); +} diff --git a/challenge-242/paulo-custodio/c/ch-2.c b/challenge-242/paulo-custodio/c/ch-2.c new file mode 100644 index 0000000000..75c09c908c --- /dev/null +++ b/challenge-242/paulo-custodio/c/ch-2.c @@ -0,0 +1,149 @@ +/* +Task 2: Flip Matrix +Submitted by: Mohammad S Anwar +You are given n x n binary matrix. + +Write a script to flip the given matrix as below. + + +1 1 0 +0 1 1 +0 0 1 + +a) Reverse each row + +0 1 1 +1 1 0 +1 0 0 + +b) Invert each member + +1 0 0 +0 0 1 +0 1 1 + +Example 1 +Input: @matrix = ([1, 1, 0], [1, 0, 1], [0, 0, 0]) +Output: ([1, 0, 0], [0, 1, 0], [1, 1, 1]) +Example 2 +Input: @matrix = ([1, 1, 0, 0], [1, 0, 0, 1], [0, 1, 1, 1], [1, 0, 1, 0]) +Output: ([1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 0, 1], [1, 0, 1, 0]) +*/ + +#include "utarray.h" +#include +#include +#include +#include + +#define DELIMS "[](),; \t" + +void die(const char* message, ...) { + va_list ap; + va_start(ap, message); + vfprintf(stderr, message, ap); + fprintf(stderr, "\n"); + va_end(ap); + exit(EXIT_FAILURE); +} + +void* check_mem(void* p) { + if (!p) + die("Out of memory"); + return p; +} + +UT_array* parse_list(const char* text_) { + UT_array* arr; + utarray_new(arr, &ut_int_icd); + + char* text = check_mem(strdup(text_)); + char* token = strtok(text, DELIMS); + while (token) { + int n = atoi(token); + utarray_push_back(arr, &n); + token = strtok(NULL, DELIMS); + } + + free(text); + return arr; +} + +UT_array* parse_matrix(const char* text_) { + char* text = check_mem(malloc(strlen(text_) + 2 + 1)); + sprintf(text, "%s],", text_); + + UT_array* matrix; + utarray_new(matrix, &ut_ptr_icd); + + char* row_delim; + char* p = text; + while ((row_delim = strstr(p, "],")) != NULL) { + *row_delim = '\0'; + UT_array* row = parse_list(p); + utarray_push_back(matrix, &row); + p = row_delim + 1; + } + + free(text); + return matrix; +} + +void process_matrix(UT_array* matrix) { + for (UT_array** p = NULL; (p = utarray_next(matrix, p)) != NULL; ) { + UT_array* row = *p; + // a) Reverse each row + for (size_t i = 0; i < utarray_len(row) / 2; i++) { + int a = *(int*)utarray_eltptr(row, i); + int b = *(int*)utarray_eltptr(row, utarray_len(row) - 1 - i); + *(int*)utarray_eltptr(row, i) = b; + *(int*)utarray_eltptr(row, utarray_len(row) - 1 - i) = a; + } + + // b) Invert each member + for (size_t i = 0; i < utarray_len(row); i++) { + int a = *(int*)utarray_eltptr(row, i); + *(int*)utarray_eltptr(row, i) = 1 - a; + } + } +} + +void print_list(UT_array* arr) { + printf("["); + const char* sep = ""; + for (int* p = NULL; (p = utarray_next(arr, p)) != NULL; ) { + printf("%s%d", sep, *p); + sep = ", "; + } + printf("]"); +} + +void print_matrix(UT_array* matrix) { + printf("("); + const char* sep = ""; + for (UT_array** p = NULL; (p = utarray_next(matrix, p)) != NULL; ) { + printf("%s", sep); + print_list(*p); + sep = ", "; + } + printf(")"); +} + +void free_matrix(UT_array* matrix) { + for (UT_array** p = NULL; (p = utarray_next(matrix, p)) != NULL; ) { + utarray_free(*p); + *p = NULL; + } +} + +int main(int argc, char* argv[]) { + if (argc != 2) + die("Usage: ch-2 '([a, b, c], [d, e, f], [g, h, i])'"); + + UT_array* matrix = parse_matrix(argv[1]); + process_matrix(matrix); + print_matrix(matrix); + free_matrix(matrix); + + utarray_free(matrix); +} diff --git a/challenge-242/paulo-custodio/c/utarray.h b/challenge-242/paulo-custodio/c/utarray.h new file mode 100644 index 0000000000..1fe8bc1c74 --- /dev/null +++ b/challenge-242/paulo-custodio/c/utarray.h @@ -0,0 +1,252 @@ +/* +Copyright (c) 2008-2022, Troy D. Hanson https://troydhanson.github.io/uthash/ +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/* a dynamic array implementation using macros + */ +#ifndef UTARRAY_H +#define UTARRAY_H + +#define UTARRAY_VERSION 2.3.0 + +#include /* size_t */ +#include /* memset, etc */ +#include /* exit */ + +#ifdef __GNUC__ +#define UTARRAY_UNUSED __attribute__((__unused__)) +#else +#define UTARRAY_UNUSED +#endif + +#ifndef utarray_oom +#define utarray_oom() exit(-1) +#endif + +typedef void (ctor_f)(void *dst, const void *src); +typedef void (dtor_f)(void *elt); +typedef void (init_f)(void *elt); +typedef struct { + size_t sz; + init_f *init; + ctor_f *copy; + dtor_f *dtor; +} UT_icd; + +typedef struct { + unsigned i,n;/* i: index of next available slot, n: num slots */ + UT_icd icd; /* initializer, copy and destructor functions */ + char *d; /* n slots of size icd->sz*/ +} UT_array; + +#define utarray_init(a,_icd) do { \ + memset(a,0,sizeof(UT_array)); \ + (a)->icd = *(_icd); \ +} while(0) + +#define utarray_done(a) do { \ + if ((a)->n) { \ + if ((a)->icd.dtor) { \ + unsigned _ut_i; \ + for(_ut_i=0; _ut_i < (a)->i; _ut_i++) { \ + (a)->icd.dtor(utarray_eltptr(a,_ut_i)); \ + } \ + } \ + free((a)->d); \ + } \ + (a)->n=0; \ +} while(0) + +#define utarray_new(a,_icd) do { \ + (a) = (UT_array*)malloc(sizeof(UT_array)); \ + if ((a) == NULL) { \ + utarray_oom(); \ + } \ + utarray_init(a,_icd); \ +} while(0) + +#define utarray_free(a) do { \ + utarray_done(a); \ + free(a); \ +} while(0) + +#define utarray_reserve(a,by) do { \ + if (((a)->i+(by)) > (a)->n) { \ + char *utarray_tmp; \ + while (((a)->i+(by)) > (a)->n) { (a)->n = ((a)->n ? (2*(a)->n) : 8); } \ + utarray_tmp=(char*)realloc((a)->d, (a)->n*(a)->icd.sz); \ + if (utarray_tmp == NULL) { \ + utarray_oom(); \ + } \ + (a)->d=utarray_tmp; \ + } \ +} while(0) + +#define utarray_push_back(a,p) do { \ + utarray_reserve(a,1); \ + if ((a)->icd.copy) { (a)->icd.copy( _utarray_eltptr(a,(a)->i++), p); } \ + else { memcpy(_utarray_eltptr(a,(a)->i++), p, (a)->icd.sz); }; \ +} while(0) + +#define utarray_pop_back(a) do { \ + if ((a)->icd.dtor) { (a)->icd.dtor( _utarray_eltptr(a,--((a)->i))); } \ + else { (a)->i--; } \ +} while(0) + +#define utarray_extend_back(a) do { \ + utarray_reserve(a,1); \ + if ((a)->icd.init) { (a)->icd.init(_utarray_eltptr(a,(a)->i)); } \ + else { memset(_utarray_eltptr(a,(a)->i),0,(a)->icd.sz); } \ + (a)->i++; \ +} while(0) + +#define utarray_len(a) ((a)->i) + +#define utarray_eltptr(a,j) (((j) < (a)->i) ? _utarray_eltptr(a,j) : NULL) +#define _utarray_eltptr(a,j) ((void*)((a)->d + ((a)->icd.sz * (j)))) + +#define utarray_insert(a,p,j) do { \ + if ((j) > (a)->i) utarray_resize(a,j); \ + utarray_reserve(a,1); \ + if ((j) < (a)->i) { \ + memmove( _utarray_eltptr(a,(j)+1), _utarray_eltptr(a,j), \ + ((a)->i - (j))*((a)->icd.sz)); \ + } \ + if ((a)->icd.copy) { (a)->icd.copy( _utarray_eltptr(a,j), p); } \ + else { memcpy(_utarray_eltptr(a,j), p, (a)->icd.sz); }; \ + (a)->i++; \ +} while(0) + +#define utarray_inserta(a,w,j) do { \ + if (utarray_len(w) == 0) break; \ + if ((j) > (a)->i) utarray_resize(a,j); \ + utarray_reserve(a,utarray_len(w)); \ + if ((j) < (a)->i) { \ + memmove(_utarray_eltptr(a,(j)+utarray_len(w)), \ + _utarray_eltptr(a,j), \ + ((a)->i - (j))*((a)->icd.sz)); \ + } \ + if ((a)->icd.copy) { \ + unsigned _ut_i; \ + for(_ut_i=0;_ut_i<(w)->i;_ut_i++) { \ + (a)->icd.copy(_utarray_eltptr(a, (j) + _ut_i), _utarray_eltptr(w, _ut_i)); \ + } \ + } else { \ + memcpy(_utarray_eltptr(a,j), _utarray_eltptr(w,0), \ + utarray_len(w)*((a)->icd.sz)); \ + } \ + (a)->i += utarray_len(w); \ +} while(0) + +#define utarray_resize(dst,num) do { \ + unsigned _ut_i; \ + if ((dst)->i > (unsigned)(num)) { \ + if ((dst)->icd.dtor) { \ + for (_ut_i = (num); _ut_i < (dst)->i; ++_ut_i) { \ + (dst)->icd.dtor(_utarray_eltptr(dst, _ut_i)); \ + } \ + } \ + } else if ((dst)->i < (unsigned)(num)) { \ + utarray_reserve(dst, (num) - (dst)->i); \ + if ((dst)->icd.init) { \ + for (_ut_i = (dst)->i; _ut_i < (unsigned)(num); ++_ut_i) { \ + (dst)->icd.init(_utarray_eltptr(dst, _ut_i)); \ + } \ + } else { \ + memset(_utarray_eltptr(dst, (dst)->i), 0, (dst)->icd.sz*((num) - (dst)->i)); \ + } \ + } \ + (dst)->i = (num); \ +} while(0) + +#define utarray_concat(dst,src) do { \ + utarray_inserta(dst, src, utarray_len(dst)); \ +} while(0) + +#define utarray_erase(a,pos,len) do { \ + if ((a)->icd.dtor) { \ + unsigned _ut_i; \ + for (_ut_i = 0; _ut_i < (len); _ut_i++) { \ + (a)->icd.dtor(utarray_eltptr(a, (pos) + _ut_i)); \ + } \ + } \ + if ((a)->i > ((pos) + (len))) { \ + memmove(_utarray_eltptr(a, pos), _utarray_eltptr(a, (pos) + (len)), \ + ((a)->i - ((pos) + (len))) * (a)->icd.sz); \ + } \ + (a)->i -= (len); \ +} while(0) + +#define utarray_renew(a,u) do { \ + if (a) utarray_clear(a); \ + else utarray_new(a, u); \ +} while(0) + +#define utarray_clear(a) do { \ + if ((a)->i > 0) { \ + if ((a)->icd.dtor) { \ + unsigned _ut_i; \ + for(_ut_i=0; _ut_i < (a)->i; _ut_i++) { \ + (a)->icd.dtor(_utarray_eltptr(a, _ut_i)); \ + } \ + } \ + (a)->i = 0; \ + } \ +} while(0) + +#define utarray_sort(a,cmp) do { \ + qsort((a)->d, (a)->i, (a)->icd.sz, cmp); \ +} while(0) + +#define utarray_find(a,v,cmp) bsearch((v),(a)->d,(a)->i,(a)->icd.sz,cmp) + +#define utarray_front(a) (((a)->i) ? (_utarray_eltptr(a,0)) : NULL) +#define utarray_next(a,e) (((e)==NULL) ? utarray_front(a) : (((a)->i != utarray_eltidx(a,e)+1) ? _utarray_eltptr(a,utarray_eltidx(a,e)+1) : NULL)) +#define utarray_prev(a,e) (((e)==NULL) ? utarray_back(a) : ((utarray_eltidx(a,e) != 0) ? _utarray_eltptr(a,utarray_eltidx(a,e)-1) : NULL)) +#define utarray_back(a) (((a)->i) ? (_utarray_eltptr(a,(a)->i-1)) : NULL) +#define utarray_eltidx(a,e) (((char*)(e) - (a)->d) / (a)->icd.sz) + +/* last we pre-define a few icd for common utarrays of ints and strings */ +static void utarray_str_cpy(void *dst, const void *src) { + char *const *srcc = (char *const *)src; + char **dstc = (char**)dst; + if (*srcc == NULL) { + *dstc = NULL; + } else { + *dstc = (char*)malloc(strlen(*srcc) + 1); + if (*dstc == NULL) { + utarray_oom(); + } else { + strcpy(*dstc, *srcc); + } + } +} +static void utarray_str_dtor(void *elt) { + char **eltc = (char**)elt; + if (*eltc != NULL) free(*eltc); +} +static const UT_icd ut_str_icd UTARRAY_UNUSED = {sizeof(char*),NULL,utarray_str_cpy,utarray_str_dtor}; +static const UT_icd ut_int_icd UTARRAY_UNUSED = {sizeof(int),NULL,NULL,NULL}; +static const UT_icd ut_ptr_icd UTARRAY_UNUSED = {sizeof(void*),NULL,NULL,NULL}; + + +#endif /* UTARRAY_H */ diff --git a/challenge-242/paulo-custodio/perl/ch-2.pl b/challenge-242/paulo-custodio/perl/ch-2.pl index 530091d6b5..69ff12386c 100644 --- a/challenge-242/paulo-custodio/perl/ch-2.pl +++ b/challenge-242/paulo-custodio/perl/ch-2.pl @@ -2,26 +2,34 @@ # Challenge 242 # -# Task 1: Missing Members +# Task 2: Flip Matrix # Submitted by: Mohammad S Anwar -# You are given two arrays of integers. +# You are given n x n binary matrix. # -# Write a script to find out the missing members in each other arrays. +# Write a script to flip the given matrix as below. # -# Example 1 -# Input: @arr1 = (1, 2, 3) -# @arr2 = (2, 4, 6) -# Output: ([1, 3], [4, 6]) +# 1 1 0 +# 0 1 1 +# 0 0 1 # -# (1, 2, 3) has 2 members (1, 3) missing in the array (2, 4, 6). -# (2, 4, 6) has 2 members (4, 6) missing in the array (1, 2, 3). -# Example 2 -# Input: @arr1 = (1, 2, 3, 3) -# @arr2 = (1, 1, 2, 2) -# Output: ([3]) +# a) Reverse each row +# +# 0 1 1 +# 1 1 0 +# 1 0 0 +# +# b) Invert each member # -# (1, 2, 3, 3) has 2 members (3, 3) missing in the array (1, 1, 2, 2). Since they are same, keep just one. -# (1, 1, 2, 2) has 0 member missing in the array (1, 2, 3, 3). +# 1 0 0 +# 0 0 1 +# 0 1 1 +# +# Example 1 +# Input: @matrix = ([1, 1, 0], [1, 0, 1], [0, 0, 0]) +# Output: ([1, 0, 0], [0, 1, 0], [1, 1, 1]) +# Example 2 +# Input: @matrix = ([1, 1, 0, 0], [1, 0, 0, 1], [0, 1, 1, 1], [1, 0, 1, 0]) +# Output: ([1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 0, 1], [1, 0, 1, 0]) use Modern::Perl; @@ -38,10 +46,8 @@ for (@m) { } } - say output(@m); - sub parse { my($text) = @_; my @m; @@ -62,4 +68,3 @@ sub output { } return "(".join(", ", @elems).")"; } - -- cgit From c7cd3e2ea5883404c6ae18ef6621a075e24210d4 Mon Sep 17 00:00:00 2001 From: Humberto Massa Date: Thu, 9 Nov 2023 06:35:35 -0300 Subject: unifying test syntax --- challenge-242/massa/raku/ch-1.raku | 18 +++++++++--------- challenge-242/massa/raku/ch-2.raku | 21 +++++++++------------ 2 files changed, 18 insertions(+), 21 deletions(-) diff --git a/challenge-242/massa/raku/ch-1.raku b/challenge-242/massa/raku/ch-1.raku index 7691ced71b..6f66804868 100644 --- a/challenge-242/massa/raku/ch-1.raku +++ b/challenge-242/massa/raku/ch-1.raku @@ -44,21 +44,21 @@ Write a script to find out the missing members in each other arrays. # always use the latest version of Raku use v6.*; -sub SOLUTION(@a, @b) { - keys(@a ∖ @b).sort.Array, keys(@b ∖ @a).sort.Array +sub SOLUTION(@ (@a, @b)) { + (@a ∖ @b, @b ∖ @a)».keys».sort } multi MAIN (Bool :$test!) { use Test; - my @tests = [ - %{ input => ([1, 2, 3], [2, 4, 6]), output => ([1, 3], [4, 6]) }, - %{ input => ([1, 2, 3, 3], [1, 1, 2, 2]), output => ([3], []) }, - ]; + my @tests = + %{ input => ((1, 2, 3), (2, 4, 6)), + output => ((1, 3), (4, 6)) }, + %{ input => ((1, 2, 3, 3), (1, 1, 2, 2)), + output => ((3,), ()) }, + ; - for @tests { - SOLUTION( |. ).&is-deeply: ., .; - } # end of for @tests + ..&SOLUTION.gist.&is: ..gist, . for @tests } # end of multi MAIN (Bool :$test!) diff --git a/challenge-242/massa/raku/ch-2.raku b/challenge-242/massa/raku/ch-2.raku index 58801dd5e4..bb3033c7a2 100644 --- a/challenge-242/massa/raku/ch-2.raku +++ b/challenge-242/massa/raku/ch-2.raku @@ -53,23 +53,20 @@ Write a script to flip the given matrix as below. use v6.*; sub SOLUTION(@_) { - @_».reverse».map({ $_ ?? 0 !! 1 })».Array + @_».reverse».map: 1 - * } multi MAIN (Bool :$test!) { use Test; - my @tests = [ - %{ input => ([1, 1, 0], [1, 0, 1], [0, 0, 0]), - output => ([1, 0, 0], [0, 1, 0], [1, 1, 1]) }, - %{ input => ([1, 1, 0, 0], [1, 0, 0, 1], [0, 1, 1, 1], [1, 0, 1, 0]), - output => ([1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 0, 1], [1, 0, 1, 0]) }, - ]; + my @tests = + %{ input => ((1, 1, 0), (1, 0, 1), (0, 0, 0)), + output => ((1, 0, 0), (0, 1, 0), (1, 1, 1)) }, + %{ input => ((1, 1, 0, 0), (1, 0, 0, 1), (0, 1, 1, 1), (1, 0, 1, 0)), + output => ((1, 1, 0, 0), (0, 1, 1, 0), (0, 0, 0, 1), (1, 0, 1, 0)) }, + ; - for @tests { - SOLUTION( . ).&is-deeply: ., .; - - } # end of for @tests -} # end of multi MAIN (:$test!) + ..&SOLUTION.gist.&is: ..gist, . for @tests +} # end of multi MAIN (Bool :$test!) -- cgit From df3151eb4b96d34e7c23a99fa9cd4cffe29839cd Mon Sep 17 00:00:00 2001 From: Humberto Massa Date: Thu, 9 Nov 2023 06:48:13 -0300 Subject: unifying test syntax (quirk in is-deeply) --- challenge-242/massa/raku/ch-1.raku | 2 +- challenge-242/massa/raku/ch-2.raku | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/challenge-242/massa/raku/ch-1.raku b/challenge-242/massa/raku/ch-1.raku index 6f66804868..fd3b1ccefd 100644 --- a/challenge-242/massa/raku/ch-1.raku +++ b/challenge-242/massa/raku/ch-1.raku @@ -58,7 +58,7 @@ multi MAIN (Bool :$test!) { output => ((3,), ()) }, ; - ..&SOLUTION.gist.&is: ..gist, . for @tests + ..&SOLUTION».cache.&is-deeply: .».cache, . for @tests } # end of multi MAIN (Bool :$test!) diff --git a/challenge-242/massa/raku/ch-2.raku b/challenge-242/massa/raku/ch-2.raku index bb3033c7a2..997ddd791b 100644 --- a/challenge-242/massa/raku/ch-2.raku +++ b/challenge-242/massa/raku/ch-2.raku @@ -66,7 +66,7 @@ multi MAIN (Bool :$test!) { output => ((1, 1, 0, 0), (0, 1, 1, 0), (0, 0, 0, 1), (1, 0, 1, 0)) }, ; - ..&SOLUTION.gist.&is: ..gist, . for @tests + ..&SOLUTION».cache.&is-deeply: .».cache, . for @tests } # end of multi MAIN (Bool :$test!) -- cgit From c59c47a9c3579f4edfd0bf7d736a25e845a8a1aa Mon Sep 17 00:00:00 2001 From: Humberto Massa Date: Thu, 9 Nov 2023 06:58:13 -0300 Subject: unifying test syntax (a more perfect workaround) --- challenge-242/massa/raku/ch-1.raku | 2 +- challenge-242/massa/raku/ch-2.raku | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/challenge-242/massa/raku/ch-1.raku b/challenge-242/massa/raku/ch-1.raku index fd3b1ccefd..9eacb018ce 100644 --- a/challenge-242/massa/raku/ch-1.raku +++ b/challenge-242/massa/raku/ch-1.raku @@ -58,7 +58,7 @@ multi MAIN (Bool :$test!) { output => ((3,), ()) }, ; - ..&SOLUTION».cache.&is-deeply: .».cache, . for @tests + ..&SOLUTION.deepmap({$_}).&is-deeply: ., . for @tests } # end of multi MAIN (Bool :$test!) diff --git a/challenge-242/massa/raku/ch-2.raku b/challenge-242/massa/raku/ch-2.raku index 997ddd791b..3241fa21c6 100644 --- a/challenge-242/massa/raku/ch-2.raku +++ b/challenge-242/massa/raku/ch-2.raku @@ -66,7 +66,7 @@ multi MAIN (Bool :$test!) { output => ((1, 1, 0, 0), (0, 1, 1, 0), (0, 0, 0, 1), (1, 0, 1, 0)) }, ; - ..&SOLUTION».cache.&is-deeply: .».cache, . for @tests + ..&SOLUTION.deepmap({$_}).&is-deeply: ., . for @tests } # end of multi MAIN (Bool :$test!) -- cgit From 9e9430d291601777c065ab8f34fc0bbf162bcd50 Mon Sep 17 00:00:00 2001 From: pme Date: Thu, 9 Nov 2023 18:23:50 +0100 Subject: challenge-242 --- challenge-242/peter-meszaros/perl/ch-1.pl | 67 +++++++++++++++++++++++++++++++ challenge-242/peter-meszaros/perl/ch-2.pl | 58 ++++++++++++++++++++++++++ 2 files changed, 125 insertions(+) create mode 100755 challenge-242/peter-meszaros/perl/ch-1.pl create mode 100755 challenge-242/peter-meszaros/perl/ch-2.pl diff --git a/challenge-242/peter-meszaros/perl/ch-1.pl b/challenge-242/peter-meszaros/perl/ch-1.pl new file mode 100755 index 0000000000..27f1c152a4 --- /dev/null +++ b/challenge-242/peter-meszaros/perl/ch-1.pl @@ -0,0 +1,67 @@ +#!/usr/bin/env perl +# +# You are given two arrays of integers. +# +# Write a script to find out the missing members in each other arrays. +# Example 1 +# +# Input: @arr1 = (1, 2, 3) +# @arr2 = (2, 4, 6) +# Output: ([1, 3], [4, 6]) +# +# (1, 2, 3) has 2 members (1, 3) missing in the array (2, 4, 6). +# (2, 4, 6) has 2 members (4, 6) missing in the array (1, 2, 3). +# +# Example 2 +# +# Input: @arr1 = (1, 2, 3, 3) +# @arr2 = (1, 1, 2, 2) +# Output: ([3]) +# +# (1, 2, 3, 3) has 2 members (3, 3) missing in the array (1, 1, 2, 2). Since +# they are same, keep just one. +# (1, 1, 2, 2) has 0 member missing in the array (1, 2, 3, 3). +# + +use strict; +use warnings; +use Test::More; +use Data::Dumper; + +my $cases = [ + [[1, 2, 3], [2, 4, 6]], + [[1, 2, 3, 3], [1, 1, 2, 2]], +]; + +sub missing_members +{ + my $l1 = $_[0]->[0]; + my $l2 = $_[0]->[1]; + + my (%h1, %h2); + $h1{$_} = 1 for @$l1; + $h2{$_} = 1 for @$l2; + + --$h2{$_} for @$l1; + --$h1{$_} for @$l2; + + my $ret = [[], []]; + + for (sort keys %h1) { + push @{$ret->[0]}, $_ if $h1{$_} > 0; + } + for (sort keys %h2) { + push @{$ret->[1]}, $_ if $h2{$_} > 0; + } + + return $ret; +} + +is_deeply(missing_members($cases->[0]), [[1, 3], [4, 6]], '[[1, 2, 3], [2, 4, 6]]'); +is_deeply(missing_members($cases->[1]), [[3],[]], '[[1, 2, 3, 3], [1, 1, 2, 2]]'); + +done_testing(); + +exit 0; + + diff --git a/challenge-242/peter-meszaros/perl/ch-2.pl b/challenge-242/peter-meszaros/perl/ch-2.pl new file mode 100755 index 0000000000..fcbce3bc49 --- /dev/null +++ b/challenge-242/peter-meszaros/perl/ch-2.pl @@ -0,0 +1,58 @@ +#!/usr/bin/env perl +# +# You are given n x n binary matrix. +# +# Write a script to flip the given matrix as below. +# 1 1 0 +# 0 1 1 +# 0 0 1 +# +# a) Reverse each row +# 0 1 1 +# 1 1 0 +# 1 0 0 +# +# b) Invert each member +# 1 0 0 +# 0 0 1 +# 0 1 1 +# +# Example 1 +# Input: @matrix = ([1, 1, 0], [1, 0, 1], [0, 0, 0]) +# Output: ([1, 0, 0], [0, 1, 0], [1, 1, 1]) +# +# Example 2 +# Input: @matrix = ([1, 1, 0, 0], [1, 0, 0, 1], [0, 1, 1, 1], [1, 0, 1, 0]) +# Output: ([1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 0, 1], [1, 0, 1, 0]) +# + +use strict; +use warnings; +use Test::More; +use Data::Dumper; + +my $cases = [ + [[1, 1, 0], [0, 1, 1], [0, 0, 1]], + [[1, 1, 0, 0], [1, 0, 0, 1], [0, 1, 1, 1], [1, 0, 1, 0]], +]; + +sub flip_matrix +{ + my $m = shift; + + for my $row (@$m) { + @$row = map { $_ ? 0 : 1 } reverse @$row; + } + + return $m; +} + +is_deeply(flip_matrix($cases->[0]), + [[1, 0, 0], [0, 0, 1], [0, 1, 1]], + '[[1, 1, 0], [1, 0, 1], [0, 0, 1]]'); +is_deeply(flip_matrix($cases->[1]), + [[1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 0, 1], [1, 0, 1, 0]], + '[[1, 1, 0, 0], [1, 0, 0, 1], [0, 1, 1, 1], [1, 0, 1, 0]]'); +done_testing(); + +exit 0; -- cgit From 9d9859b70f3244382224e9b2e6f97f90ccee223f Mon Sep 17 00:00:00 2001 From: Mohammad S Anwar Date: Thu, 9 Nov 2023 20:02:04 +0000 Subject: - Added solutions by Laurent Rosenfeld. - Added solutions by Humberto Massa. - Added solutions by Paulo Custodio. - Added solutions by Peter Meszaros. --- challenge-242/laurent-rosenfeld/blog1.txt | 1 + challenge-242/laurent-rosenfeld/perl/ch-2.pl | 26 + challenge-242/laurent-rosenfeld/raku/ch-2.raku | 15 + stats/pwc-current.json | 376 +++--- stats/pwc-language-breakdown-summary.json | 62 +- stats/pwc-language-breakdown.json | 1684 ++++++++++++------------ stats/pwc-leaders.json | 742 +++++------ stats/pwc-summary-1-30.json | 112 +- stats/pwc-summary-121-150.json | 106 +- stats/pwc-summary-151-180.json | 88 +- stats/pwc-summary-181-210.json | 98 +- stats/pwc-summary-211-240.json | 106 +- stats/pwc-summary-241-270.json | 40 +- stats/pwc-summary-271-300.json | 108 +- stats/pwc-summary-301-330.json | 42 +- stats/pwc-summary-31-60.json | 56 +- stats/pwc-summary-61-90.json | 114 +- stats/pwc-summary-91-120.json | 42 +- stats/pwc-summary.json | 38 +- 19 files changed, 1964 insertions(+), 1892 deletions(-) create mode 100644 challenge-242/laurent-rosenfeld/blog1.txt create mode 100644 challenge-242/laurent-rosenfeld/perl/ch-2.pl create mode 100644 challenge-242/laurent-rosenfeld/raku/ch-2.raku diff --git a/challenge-242/laurent-rosenfeld/blog1.txt b/challenge-242/laurent-rosenfeld/blog1.txt new file mode 100644 index 0000000000..cb6c67357a --- /dev/null +++ b/challenge-242/laurent-rosenfeld/blog1.txt @@ -0,0 +1 @@ +https://blogs.perl.org/users/laurent_r/2023/11/perl-weekly-challenge-242-flip-matrix.html diff --git a/challenge-242/laurent-rosenfeld/perl/ch-2.pl b/challenge-242/laurent-rosenfeld/perl/ch-2.pl new file mode 100644 index 0000000000..7f646c78dc --- /dev/null +++ b/challenge-242/laurent-rosenfeld/perl