From b757f502a9d57f5ddced1f5c1a9a93fa1ece27b1 Mon Sep 17 00:00:00 2001 From: Mariano Spadaccini Date: Thu, 6 Apr 2023 11:18:19 +0200 Subject: Add ch-1.pl --- challenge-211/spadacciniweb/perl/ch-1.pl | 53 ++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 challenge-211/spadacciniweb/perl/ch-1.pl (limited to 'challenge-211') diff --git a/challenge-211/spadacciniweb/perl/ch-1.pl b/challenge-211/spadacciniweb/perl/ch-1.pl new file mode 100644 index 0000000000..4d69deaa17 --- /dev/null +++ b/challenge-211/spadacciniweb/perl/ch-1.pl @@ -0,0 +1,53 @@ +#!/usr/bin/env perl + +# Task 1: Toeplitz Matrix +# Submitted by: Mohammad S Anwar +# +# You are given a matrix m x n. +# Write a script to find out if the given matrix is Toeplitz Matrix. +# A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements. +# +# +# Example 1 +# Input: @matrix = [ [4, 3, 2, 1], +# [5, 4, 3, 2], +# [6, 5, 4, 3], +# ] +# Output: true +# +# Example 2 +# Input: @matrix = [ [1, 2, 3], +# [3, 2, 1], +# ] +# Output: false + +use strict; +use warnings; +use feature qw/say/; + +sub check_toeplitz {; + my $matrix = shift; + my $rows = @$matrix; + my $cols = scalar @{$matrix->[0]}; + my $min = ($rows < $cols) + ? $rows + : $cols; + my $value = $matrix->[0]->[0]; + foreach my $i (0..$min-1) { + return 'false' + unless $matrix->[$i]->[$i] == $value; + } + return 'true'; +} + +my $matrix = [ [4, 3, 2, 1], + [5, 4, 3, 2], + [6, 5, 4, 3], + ]; +say check_toeplitz($matrix); + +$matrix = [ [1, 2, 3], + [3, 2, 1], + ]; +say check_toeplitz($matrix); + -- cgit From 7e35f81f3255f235fc751cfaf30074b83a8b39a0 Mon Sep 17 00:00:00 2001 From: Mariano Spadaccini Date: Thu, 6 Apr 2023 11:33:16 +0200 Subject: Add ch-1.py --- challenge-211/spadacciniweb/python/ch-1.py | 43 ++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 challenge-211/spadacciniweb/python/ch-1.py (limited to 'challenge-211') diff --git a/challenge-211/spadacciniweb/python/ch-1.py b/challenge-211/spadacciniweb/python/ch-1.py new file mode 100644 index 0000000000..00f663b9f1 --- /dev/null +++ b/challenge-211/spadacciniweb/python/ch-1.py @@ -0,0 +1,43 @@ +# Task 1: Toeplitz Matrix +# Submitted by: Mohammad S Anwar +# +# You are given a matrix m x n. +# Write a script to find out if the given matrix is Toeplitz Matrix. +# A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements. +# +# +# Example 1 +# Input: @matrix = [ [4, 3, 2, 1], +# [5, 4, 3, 2], +# [6, 5, 4, 3], +# ] +# Output: true +# +# Example 2 +# Input: @matrix = [ [1, 2, 3], +# [3, 2, 1], +# ] +# Output: false + +import numpy + +def check_toeplitz(matrix): + m = numpy.array(matrix) + dim = min(m.shape) + value = m[0][0] + for i in range(dim): + if m[i][i] != value: + return 'false' + return 'true' + +if __name__ == "__main__": + matrix = [ [4, 3, 2, 1], + [5, 4, 3, 2], + [6, 5, 4, 3], + ] + print(check_toeplitz(matrix)) + + matrix = [ [1, 2, 3], + [3, 2, 1], + ] + print(check_toeplitz(matrix)) -- cgit From 3457c7a15b48e32fa9eb55630657287942ca0d98 Mon Sep 17 00:00:00 2001 From: Mariano Spadaccini Date: Thu, 6 Apr 2023 11:57:00 +0200 Subject: Add ch-1.rb --- challenge-211/spadacciniweb/perl/ch-1.pl | 2 +- challenge-211/spadacciniweb/ruby/ch-1.rb | 40 ++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 challenge-211/spadacciniweb/ruby/ch-1.rb (limited to 'challenge-211') diff --git a/challenge-211/spadacciniweb/perl/ch-1.pl b/challenge-211/spadacciniweb/perl/ch-1.pl index 4d69deaa17..78e264778b 100644 --- a/challenge-211/spadacciniweb/perl/ch-1.pl +++ b/challenge-211/spadacciniweb/perl/ch-1.pl @@ -25,7 +25,7 @@ use strict; use warnings; use feature qw/say/; -sub check_toeplitz {; +sub check_toeplitz { my $matrix = shift; my $rows = @$matrix; my $cols = scalar @{$matrix->[0]}; diff --git a/challenge-211/spadacciniweb/ruby/ch-1.rb b/challenge-211/spadacciniweb/ruby/ch-1.rb new file mode 100644 index 0000000000..03b84d9ff3 --- /dev/null +++ b/challenge-211/spadacciniweb/ruby/ch-1.rb @@ -0,0 +1,40 @@ +# Task 1: Toeplitz Matrix +# Submitted by: Mohammad S Anwar +# +# You are given a matrix m x n. +# Write a script to find out if the given matrix is Toeplitz Matrix. +# A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements. +# +# +# Example 1 +# Input: @matrix = [ [4, 3, 2, 1], +# [5, 4, 3, 2], +# [6, 5, 4, 3], +# ] +# Output: true +# +# Example 2 +# Input: @matrix = [ [1, 2, 3], +# [3, 2, 1], +# ] +# Output: false + +def check_toeplitz(m) + rc = [m.length, m[0].length].min - 1 + val = m[0][0] + (0..rc).each {|e| + return 'false' if m[e][e] != val + } + return 'true' +end + +matrix = [ [4, 3, 2, 1], + [5, 4, 3, 2], + [6, 5, 4, 3], + ] +puts check_toeplitz matrix + +matrix = [ [1, 2, 3], + [3, 2, 1], + ] +puts check_toeplitz matrix -- cgit From d4bacf05e9f6837997f06554a1c6a971d42ae6ad Mon Sep 17 00:00:00 2001 From: Mariano Spadaccini Date: Thu, 6 Apr 2023 14:39:52 +0200 Subject: Add ch-1.go --- challenge-211/spadacciniweb/go/ch-1.go | 59 ++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 challenge-211/spadacciniweb/go/ch-1.go (limited to 'challenge-211') diff --git a/challenge-211/spadacciniweb/go/ch-1.go b/challenge-211/spadacciniweb/go/ch-1.go new file mode 100644 index 0000000000..97d6d47354 --- /dev/null +++ b/challenge-211/spadacciniweb/go/ch-1.go @@ -0,0 +1,59 @@ +/* +Task 1: Toeplitz Matrix +Submitted by: Mohammad S Anwar + +You are given a matrix m x n. +Write a script to find out if the given matrix is Toeplitz Matrix. +A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements. + + +Example 1 +Input: @matrix = [ [4, 3, 2, 1], + [5, 4, 3, 2], + [6, 5, 4, 3], + ] +Output: true + +Example 2 +Input: @matrix = [ [1, 2, 3], + [3, 2, 1], + ] +Output: false +*/ + +package main + +import ( + "fmt" +) + +func check_toeplitz(m [][]int) bool { + rows := len(m) + cols := len(m[0]) + var dimens int = rows + if (cols < rows) { + dimens = cols + } + val := m[0][0] + for i := 0; i < dimens; i++ { + if m[i][i] != val { + return false + } + } + return true +} + +func main() { + matrix1 := [][]int{ + {4, 3, 2, 1}, + {5, 4, 3, 2}, + {6, 5, 4, 3}, + } + fmt.Println(check_toeplitz(matrix1)) + + matrix2 := [][]int{ + {1, 2, 3}, + {3, 2, 1}, + } + fmt.Println(check_toeplitz(matrix2)) +} -- cgit From 8662fc692022781222416ddbb447ed59ff559b28 Mon Sep 17 00:00:00 2001 From: rir Date: Thu, 6 Apr 2023 23:35:48 -0400 Subject: 211 --- challenge-211/0rir/raku/ch-1.raku | 196 ++++++++++++++++++++++++++++++++++++++ challenge-211/0rir/raku/ch-2.raku | 91 ++++++++++++++++++ 2 files changed, 287 insertions(+) create mode 100644 challenge-211/0rir/raku/ch-1.raku create mode 100644 challenge-211/0rir/raku/ch-2.raku (limited to 'challenge-211') diff --git a/challenge-211/0rir/raku/ch-1.raku b/challenge-211/0rir/raku/ch-1.raku new file mode 100644 index 0000000000..ef8770fe98 --- /dev/null +++ b/challenge-211/0rir/raku/ch-1.raku @@ -0,0 +1,196 @@ +#!/usr/bin/env raku +# :vim ft=raku sw=4 expandtab # 🦋 ∅∪∩∋∈∉ ≡ ≢ «␤ » ∴ +use v6.d; +use Test; + +=begin comment +211-1: Toeplitz Matrix Submitted by: Mohammad S Anwar +Given a matrix m x n, find out if the given matrix is Toeplitz Matrix. + +A matrix is Toeplitz if every diagonal from top-left to bottom-right has +the same elements. + +Example 1 +Input: @matrix = [ [4, 3, 2, 1], + [5, 4, 3, 2], + [6, 5, 4, 3], + ] +Output: true +Example 2 +Input: @matrix = [ [1, 2, 3], + [3, 2, 1], + ] +Output: false +=end comment + +my @Test = + # shorted + [ [1,],], True, + [ [1,2,3,4,5,],], True, + [ [1,],[2,],[3,],[4,],[5],], True, + + # examples + [ [4,3,2,1], [5,4,3,2], [6,5,4,3],], True, + [ [1,2,3], [3,2,1],], False, + + # more + [ [1,1,1,1,], [1,1,1,1,], [1,1,1,1,], [1,1,1,1,],], True, + [ [1,2],[2,1],], True, + [ [1,2,3,], [4,1,2,], [5,4,1,],], True, + [ [0,1,2],[1,0,1],[2,1,0],[3,2,1],[4,3,2],], True, + + [ [9,9,], + [9,0,],], False, + + [ [0,9,], + [9,9,],], False, + + [ [0,1,9], + [1,0,1], + [9,1,0],], True, + + [ [9,1,9], + [1,0,1], + [9,1,0],], False, + + [ [0,9,9], + [1,0,1], + [9,1,0],], False, + + [ [0,1,9], + [9,0,1], + [9,1,0],], False, + + [ [0,1,9], + [1,9,1], + [9,1,0],], False, + + [ [0,1,9], + [1,0,9], + [9,1,0],], False, + + [ [0,1,9], + [1,0,1], + [9,9,0],], False, + + [ [0,1,9], + [1,0,1], + [9,1,9],], False, + + [ [0,2,], + [1,0,], + [2,1,], + [0,2,],], True, + + [ [0,1,5,6,], + [1,0,1,5,], + [2,1,0,1,], + [6,2,1,0,],], True, + + [ [0,1,2,6,], + [1,0,1,2,], + [2,1,0,1,], + [6,2,1,0,],], True, + + [ [0,1,5,6,7,], + [1,0,1,5,6,], + [2,1,0,1,5,], + [0,2,1,0,1,],], True, + + [ [0,1,5,6,7,], + [1,0,1,5,6,], + [2,1,0,1,5,], + [0,2,1,0,1,],], True, +; + +my @Dead = + [ ], + [ [],], + [ [1,],[],], + [ [1,],[1,2],], + [ [4,3,2,1], [5,4,3,2], [5,4,3],], +; + +plan @Test + @Dead; + + +sub is-toeplitz( @a -->Bool){ + + invalid( @a); + + my ($cols, $rows) = @a[0].end, @a.end; + + return True if $cols == 0 or $rows == 0; # very short diagonals + + my $o = [ $rows-1, 0]; + + loop { + return False unless $o.&diag; + $o.&next-diag; + last if $o.&last-diag; + } + return True; + + # --- not reached ---- + + constant R = 0; + constant C = 1; + + sub val( $d -->Any){ @a[ $d[R]][ $d[C]] } + + sub next-diag( $d is rw -->Array){ # alter dyad to index next diag origin + when $d[R] > 0 { --$d[R]; $d } + when $d[R] == 0 { ++$d[C]; $d } + die 'not reached ( stupid programmer either way)'; + } + + sub last-diag( $d -->Bool){ $d[R] == 0 and $d[C] == $cols} + + sub diag( $d -->Bool){ + my $ref = $d.&val; + my ($R, $C) = 1 + $d[R], 1 + $d[C]; + while $R ≤ $rows and $C ≤ $cols { + return False if $ref ≠ @a[$R++][$C++]; + } + return True; + } + sub invalid( @a -->Nil){ + when @a ~~ Empty { die "Empty" } + when @a.any ~~ Empty { die "Empty elem" } + with @a[1..^@a].first( {.end !~~ @a[0].end} ) { + die "Misshapened"; } + return; + } +} + +for @Dead -> @in { + dies-ok { is-toeplitz( @in )}, + "Died-ok: Empty, Empty elem, or misshapened"; +} +for @Test -> @in, $exp { + lives-ok { is-toeplitz( @in )}, + "Lives-ok: Empty, Empty elem, or misshapened"; + is is-toeplitz(@in), $exp, "$exp <- @in.raku()"; +} +done-testing; + + +my @matrix = [ [0,1,5,6,7,], + [1,0,1,5,6,], + [2,1,0,1,5,], + [0,2,1,0,1,],]; + +sub matrix-say( @m is copy ) { + for @matrix -> $row is rw { + $row = $row.join( ","); + } + print "\nInput @matrix = [ ["; + print @matrix.join: "],\n ["; + print "],\n ]\n"; +} + +matrix-say( @matrix); +say "Output: ", is-toeplitz( @matrix); + +exit; + diff --git a/challenge-211/0rir/raku/ch-2.raku b/challenge-211/0rir/raku/ch-2.raku new file mode 100644 index 0000000000..3828fa95c6 --- /dev/null +++ b/challenge-211/0rir/raku/ch-2.raku @@ -0,0 +1,91 @@ +#!/usr/bin/env raku +# :vim ft=raku sw=4 expandtab # 🦋 ∅∪∩∋∈∉ ≡ ≢ «␤ » ∴ +use v6.d; +use Test; + +=begin comment +211-2: Split Same Average Submitted by: Mohammad S Anwar +Given an array of integers, find out if the array can be split into two +separate arrays whose averages are the same. + +Example 1: +Input: @nums = (1, 2, 3, 4, 5, 6, 7, 8) +Output: true +We can split the given array into (1, 4, 5, 8) and (2, 3, 6, 7). +The average of the two arrays are the same i.e. 4.5. + +Example 2: +Input: @list = (1, 3) +Output: false +=end comment + +my @Test = + # shorts -- atomic + [ ], False, + [ 1], False, + # given examples + [ 1,3], False, + [ 2,3,6,7, 1,4,5,8], True, + # more + [ 11 xx 111], True, + [ 0,0,0,0,0], True, + [ 1,1], True, + [ 1,2], False, + [ 1,2,4], False, + [ 2,2,3], False, + [ 1,-1], False, + [ 1,14,15], False, + [ 1,14, 0,15], True, + [ 0,0,1,14,15], False, + [ 0,1,14, 0,0,15], True, + [ 1,2,3,12,13,14,15], False, + [ 0,7, 1,2,3,4,5,6], True, + [ 0,1,1,2,3,4,5,6,7], False, + [ 1,4, 2,3], True, + [ 2, 0,1,3,4], True, + [ 1,4,5,7, 0,2,3,6,8], True, + [ -2, -1,-1,0], True, + [ -3,-2,-1,1], False, + [ -3…0], True, + [ -3…1], True, + [ -1,0,2,6,7, 1,1,3,4,5], True, + [ -1,-1,2,6,7, 0,1,3,4,5], True, + [ -1,1,2,3,4,5,6,7], False, + [ -10…10], True, + [ -9…10], True, + [ 1…12], True, + [ 0…12], True, + [ -2…1], True, + [ -4…4], True, +; + +# return True if so 'subset.elems × other.sum == subset.sum × other.elems' +# is found, else False. +multi same-average-parts2( @in where *.elems ≤ 1 -->Bool ){ False } +multi same-average-parts2( @in -->Bool){ + + my Int $total = [+] @in; + + my $prev; + for 1..(@in.elems div 2) -> $a-elems { + for @in.combinations( $a-elems).sort -> $a { + my $b-val = $a-elems × ($total - [+] $a); + + if $b-val == ([+] $a) × ( @in.elems - $a-elems) { + return True; + } } } + return False; +} + +plan @Test/2; + +for @Test -> @t, $exp { + is same-average-parts2( @t), $exp, "$exp <- @t[]"; +} +done-testing; + +my $ints = @Test[*-2]; +say "\nInput: \$ints = $ints[]" + ,"\nOutput: &same-average-parts2($ints)"; + +exit; -- cgit From b69c6dab84dbceb45cdb28c6f09370ec6bbf1498 Mon Sep 17 00:00:00 2001 From: Mark <53903062+andemark@users.noreply.github.com> Date: Fri, 7 Apr 2023 04:40:45 +0000 Subject: ch-2.raku do-over --- challenge-211/mark-anderson/raku/ch-2.raku | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) (limited to 'challenge-211') diff --git a/challenge-211/mark-anderson/raku/ch-2.raku b/challenge-211/mark-anderson/raku/ch-2.raku index 255ada41f4..8af4568b57 100644 --- a/challenge-211/mark-anderson/raku/ch-2.raku +++ b/challenge-211/mark-anderson/raku/ch-2.raku @@ -1,6 +1,11 @@ #!/usr/bin/env raku use Test; +# This is a do-over after reading other's solutions. +# Jorg Sommrey and W. Luis Mochan explained that if one subset's average +# equals the average of the whole list then the other subset will have +# the same average. + ok split-same-avg(1,2,3,4,5,6,7,8); # [1 8] [2 3 4 5 6 7] nok split-same-avg(1,3); ok split-same-avg(3,3,5,5,5,2,2,1); # [2 3 3 5] [1 2 5 5] @@ -8,14 +13,11 @@ nok split-same-avg(5,5,5,2,2,1); sub split-same-avg(*@nums) { - for (^@nums).combinations(1..@nums.elems div 2) -> @a is copy - { - my @b = (^@nums (-) @a).keys; + my $avg = @nums.sum / @nums.elems; - @a = @nums[@a]; - @b = @nums[@b]; - - return True if @a.sum / @a.elems == @b.sum / @b.elems + for (^@nums).combinations(1..@nums.elems div 2) -> @a + { + return True if @nums[@a].sum / @nums[@a].elems == $avg } return False -- cgit From e58956be5e5b9788b02214561b208b6828b33d60 Mon Sep 17 00:00:00 2001 From: Mark <53903062+andemark@users.noreply.github.com> Date: Fri, 7 Apr 2023 04:50:38 +0000 Subject: ch-2.raku do-over --- challenge-211/mark-anderson/raku/ch-2.raku | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) (limited to 'challenge-211') diff --git a/challenge-211/mark-anderson/raku/ch-2.raku b/challenge-211/mark-anderson/raku/ch-2.raku index 8af4568b57..42711963d7 100644 --- a/challenge-211/mark-anderson/raku/ch-2.raku +++ b/challenge-211/mark-anderson/raku/ch-2.raku @@ -13,11 +13,9 @@ nok split-same-avg(5,5,5,2,2,1); sub split-same-avg(*@nums) { - my $avg = @nums.sum / @nums.elems; - for (^@nums).combinations(1..@nums.elems div 2) -> @a { - return True if @nums[@a].sum / @nums[@a].elems == $avg + return True if @nums[@a].sum / @nums[@a].elems == @nums.sum / @nums.elems } return False -- cgit From a8b89b2dae3fb6f3740950dbe5f7a3c076f87997 Mon Sep 17 00:00:00 2001 From: Mark <53903062+andemark@users.noreply.github.com> Date: Fri, 7 Apr 2023 05:38:05 +0000 Subject: ch-2.raku do-over --- challenge-211/mark-anderson/raku/ch-2.raku | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'challenge-211') diff --git a/challenge-211/mark-anderson/raku/ch-2.raku b/challenge-211/mark-anderson/raku/ch-2.raku index 42711963d7..8af4568b57 100644 --- a/challenge-211/mark-anderson/raku/ch-2.raku +++ b/challenge-211/mark-anderson/raku/ch-2.raku @@ -13,9 +13,11 @@ nok split-same-avg(5,5,5,2,2,1); sub split-same-avg(*@nums) { + my $avg = @nums.sum / @nums.elems; + for (^@nums).combinations(1..@nums.elems div 2) -> @a { - return True if @nums[@a].sum / @nums[@a].elems == @nums.sum / @nums.elems + return True if @nums[@a].sum / @nums[@a].elems == $avg } return False -- cgit From 1d1f8699952d5136282ee4f18a0f898e71e8c7a8 Mon Sep 17 00:00:00 2001 From: Thomas Köhler Date: Fri, 7 Apr 2023 10:01:10 +0200 Subject: Add solution for week 211. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Thomas Köhler --- challenge-211/jeanluc2020/blog-1.txt | 1 + challenge-211/jeanluc2020/blog-2.txt | 1 + challenge-211/jeanluc2020/perl/ch-1.pl | 79 +++++++++++++++++++++++++++ challenge-211/jeanluc2020/perl/ch-2.pl | 97 ++++++++++++++++++++++++++++++++++ 4 files changed, 178 insertions(+) create mode 100644 challenge-211/jeanluc2020/blog-1.txt create mode 100644 challenge-211/jeanluc2020/blog-2.txt create mode 100755 challenge-211/jeanluc2020/perl/ch-1.pl create mode 100755 challenge-211/jeanluc2020/perl/ch-2.pl (limited to 'challenge-211') diff --git a/challenge-211/jeanluc2020/blog-1.txt b/challenge-211/jeanluc2020/blog-1.txt new file mode 100644 index 0000000000..0f0f93f599 --- /dev/null +++ b/challenge-211/jeanluc2020/blog-1.txt @@ -0,0 +1 @@ +http://gott-gehabt.de/800_wer_wir_sind/thomas/Homepage/Computer/perl/theweeklychallenge-211-1.html diff --git a/challenge-211/jeanluc2020/blog-2.txt b/challenge-211/jeanluc2020/blog-2.txt new file mode 100644 index 0000000000..bd76722861 --- /dev/null +++ b/challenge-211/jeanluc2020/blog-2.txt @@ -0,0 +1 @@ +http://gott-gehabt.de/800_wer_wir_sind/thomas/Homepage/Computer/perl/theweeklychallenge-211-2.html diff --git a/challenge-211/jeanluc2020/perl/ch-1.pl b/challenge-211/jeanluc2020/perl/ch-1.pl new file mode 100755 index 0000000000..c68d360ce9 --- /dev/null +++ b/challenge-211/jeanluc2020/perl/ch-1.pl @@ -0,0 +1,79 @@ +#!/usr/bin/perl +# https://theweeklychallenge.org/blog/perl-weekly-challenge-211/#TASK1 +# +# Task 1: Toeplitz Matrix +# ======================= +# +# You are given a matrix m x n. +# +# Write a script to find out if the given matrix is Toeplitz Matrix. +# +## A matrix is Toeplitz if every diagonal from top-left to bottom-right has the +## same elements. +# +## Example 1 +## +## Input: @matrix = [ [4, 3, 2, 1], +## [5, 4, 3, 2], +## [6, 5, 4, 3], +## ] +## Output: true +# +## Example 2 +## +## Input: @matrix = [ [1, 2, 3], +## [3, 2, 1], +## ] +## Output: false +# +############################################################ +## +## discussion +## +############################################################ +# +# We just need to walk all diagonals and check if all numbers are +# the same. But actually it's easier to walk the matrix and check +# whether the element to the right bottom of the current one differs +# from the current one. When we do that everywhere we can know +# whether all diagonals have the same number everywhere as well, +# so let's do that. + +toeplitz([ [4, 3, 2, 1], + [5, 4, 3, 2], + [6, 5, 4, 3] ]); +toeplitz([ [1, 2, 3], + [3, 2, 1] ]); + +sub toeplitz { + my $matrix = shift; + die "Not a matrix" unless is_matrix($matrix); + # get the dimensions of the matrix + my $lines = scalar(@$matrix); + my $columns = scalar(@{$matrix->[0]}); + # for each line and column except the last one, compare the element + # at that position and the one on the right bottom of it + foreach my $i (0..$lines-2) { + foreach my $j (0..$columns-2) { + my $this_element = $matrix->[$i]->[$j]; + my $next_diagonal_element = $matrix->[$i+1]->[$j+1]; + if ($this_element != $next_diagonal_element) { + print "Output: false\n"; + return; + } + } + } + print "Output: true\n"; +} + +# helper function to check if we actually have a matrix +sub is_matrix { + my $matrix = shift; + return 0 unless ref($matrix) eq "ARRAY"; + my $columns = scalar(@{$matrix->[0]}); + foreach my $line (@$matrix) { + return 0 unless scalar(@$line) == $columns; + } + return 1; +} + diff --git a/challenge-211/jeanluc2020/perl/ch-2.pl b/challenge-211/jeanluc2020/perl/ch-2.pl new file mode 100755 index 0000000000..10407b7a85 --- /dev/null +++ b/challenge-211/jeanluc2020/perl/ch-2.pl @@ -0,0 +1,97 @@ +#!/usr/bin/perl +# https://theweeklychallenge.org/blog/perl-weekly-challenge-211/#TASK2 +# +# Task 2: Split Same Average +# ========================== +# +# You are given an array of integers. +# +# Write a script to find out if the given can be split into two separate arrays whose average are the same. +# +## Example 1: +## +## Input: @nums = (1, 2, 3, 4, 5, 6, 7, 8) +## Output: true +## +## We can split the given array into (1, 4, 5, 8) and (2, 3, 6, 7). +## The average of the two arrays are the same i.e. 4.5. +# +## Example 2: +## +## Input: @list = (1, 3) +## Output: false +# +############################################################ +## +## discussion +## +############################################################ +# +# This is basically a problem on how to create all possible +# combinations and checking if any of these allows for the +# same average + +use strict; +use warnings; +use List::Util qw(sum); + +split_same_average(1, 2, 3, 4, 5, 6, 7, 8); +split_same_average(1, 3); + +sub split_same_average { + my @list = @_; + print "Input: (" . join(", ", @list) . ")\n"; + if(has_matching_split([@list], [], [])) { + print "Output: true\n"; + } else { + print "Output: false\n"; + } +} + +# check if the rest of the current list, with two partially +# filled lists from the previous elements, can still be turned +# into two lists that have the same average +# so we create all possible combinations step by step, if we have +# found one we check if it has lead us to two lists of the same +# average, and otherwise return a non-true value (which will lead +# to the next recursive call) +sub has_matching_split { + my ($rest, $list1, $list2) = @_; + if(@$rest) { + # we still have some elements to distribute among the two + # lists, so we get the first element of this remainder + my $first = shift @$rest; + # if by adding this to the first partial list we can achieve + # a combination where both lists have the same average, we can + # finish searching and return 1 + if(has_matching_split([@$rest], [@$list1, $first], [@$list2])) { + return 1; + } + # same is true if we can achieve a good combination by adding the + # element to the second partial list + if(has_matching_split([@$rest], [@$list1], [@$list2, $first])) { + return 1; + } + # if we didn't succeed either way, we can't find any matching combination + # that leads to two arrays with the same average, so we return 0 + return 0; + } else { + # we have distributed all elements to the two lists, so if both + # lists are non-empty and share the same average we have found a + # solution + if(@$list1 && @$list2 && average(@$list1) == average(@$list2)) { + return 1; + } + } + return 0; +} + +# of course we need a helper function to calculate the average of all +# elements of a list +sub average { + my @list = @_; + my $count = @list; + return undef unless $count; + my $sum = sum @list; + return $sum / $count; +} -- cgit From 65e8fdebe3c9dcbcb173fc4db79bfb0d6a615abb Mon Sep 17 00:00:00 2001 From: Flavio Poletti Date: Fri, 7 Apr 2023 12:31:52 +0200 Subject: Add polettix's solution to challenge-211 --- challenge-211/polettix/blog.txt | 1 + challenge-211/polettix/blog1.txt | 1 + challenge-211/polettix/perl/ch-1.pl | 28 +++++++++++++++++++ challenge-211/polettix/perl/ch-2.pl | 52 +++++++++++++++++++++++++++++++++++ challenge-211/polettix/raku/ch-1.raku | 22 +++++++++++++++ challenge-211/polettix/raku/ch-2.raku | 48 ++++++++++++++++++++++++++++++++ 6 files changed, 152 insertions(+) create mode 100644 challenge-211/polettix/blog.txt create mode 100644 challenge-211/polettix/blog1.txt create mode 100644 challenge-211/polettix/perl/ch-1.pl create mode 100644 challenge-211/polettix/perl/ch-2.pl create mode 100644 challenge-211/polettix/raku/ch-1.raku create mode 100644 challenge-211/polettix/raku/ch-2.raku (limited to 'challenge-211') diff --git a/challenge-211/polettix/blog.txt b/challenge-211/polettix/blog.txt new file mode 100644 index 0000000000..cc264f1cba --- /dev/null +++ b/challenge-211/polettix/blog.txt @@ -0,0 +1 @@ +https://etoobusy.polettix.it/2023/04/06/pwc211-toepliz-matrix/ diff --git a/challenge-211/polettix/blog1.txt b/challenge-211/polettix/blog1.txt new file mode 100644 index 0000000000..180b88d60d --- /dev/null +++ b/challenge-211/polettix/blog1.txt @@ -0,0 +1 @@ +https://etoobusy.polettix.it/2023/04/07/pwc211-split-same-average/ diff --git a/challenge-211/polettix/perl/ch-1.pl b/challenge-211/polettix/perl/ch-1.pl new file mode 100644 index 0000000000..43c94fde0e --- /dev/null +++ b/challenge-211/polettix/perl/ch-1.pl @@ -0,0 +1,28 @@ +#!/usr/bin/env perl +use v5.24; +use warnings; +use experimental 'signatures'; + +my $m1 = [ [4, 3, 2, 1], + [5, 4, 3, 2], + [6, 5, 4, 3], + ]; +say 'm1: ', is_toepliz_matrix($m1) ? 'true' : 'false'; + +my $m2 = [ [1, 2, 3], + [3, 2, 1], + ]; +say 'm2: ', is_toepliz_matrix($m2) ? 'true' : 'false'; + + +sub is_toepliz_matrix ($m) { + for my $i (1 .. $m->$#*) { + my ($r0, $r1) = $m->@[$i - 1, $i]; + my $end = $r1->$#*; + return 0 if $end != $r0->$#*; + for my $j (1 .. $end) { + return 0 if $r0->[$j - 1] != $r1->[$j]; + } + } + return 1; +} diff --git a/challenge-211/polettix/perl/ch-2.pl b/challenge-211/polettix/perl/ch-2.pl new file mode 100644 index 0000000000..fcea34b5a7 --- /dev/null +++ b/challenge-211/polettix/perl/ch-2.pl @@ -0,0 +1,52 @@ +#!/usr/bin/env perl +use v5.24; +use warnings; +use experimental 'signatures'; + +my @args = @ARGV ? @ARGV : 1 .. 8; +say split_same_average(@args) ? 'true' : 'false'; + +sub split_same_average (@list) { + + # pre-massage the list to only cope with non-negative integers + (my $min, @list) = sort { $a <=> $b } @list; + my @partial_sums = (0); + push @partial_sums, $partial_sums[-1] + ($list[$_] -= $min) + for 0 .. $#list; + unshift @list, 0; # put "min" back + + my %cache; + my $has_subset = sub ($sum, $k, $i = $#list) { + return 1 if ($sum == 0) && ($k == 0); # found! + return 0 + if ($sum < 0) # removed more than needed + || ($i < 0) # nothing more to look at + || ($sum > $partial_sums[$i]) # cannot remove as much as needed + ; + + # caching on subset size $k and end cursor position $i only, the $sum + # is a consequence of $k + return $cache{$k}{$i} //= + __SUB__->($sum - $list[$i], $k - 1, $i - 1) # try greedy first + || __SUB__->($sum, $k, $i - 1); # fallback + }; + + # calculate p and q (average for modified list is p/q) + my $n = @list; + my $sum = $partial_sums[-1]; + my $gcd = gcd($sum, $n); + my ($p, $q) = ($sum / $gcd, $n / $gcd); + + # iterate finding subsets of multiples of q, starting at q itself + my $k = $q; + while ($k <= $n / 2) { + my $S = $p * $k / $q; # target sum + return 1 if $has_subset->($S, $k); + $k += $q; + } + + # nothing found, fail + return 0; +} + +sub gcd ($A, $B) { ($A, $B) = ($B % $A, $A) while $A; return $B } diff --git a/challenge-211/polettix/raku/ch-1.raku b/challenge-211/polettix/raku/ch-1.raku new file mode 100644 index 0000000000..c8b551d15c --- /dev/null +++ b/challenge-211/polettix/raku/ch-1.raku @@ -0,0 +1,22 @@ +#!/usr/bin/env raku +use v6; +sub MAIN { + my $m1 = [ [4, 3, 2, 1], + [5, 4, 3, 2], + [6, 5, 4, 3], + ]; + put 'm1: ', is-toepliz-matrix($m1); + + my $m2 = [ [1, 2, 3], + [3, 2, 1], + ]; + put 'm2: ', is-toepliz-matrix($m2); +} + +sub is-toepliz-matrix ($m) { + for 1 .. $m.end -> $i { + my ($r0, $r1) = $m[$i - 1, $i]; + return False unless all($r0[0 .. *-2] «==» $r1[1 .. *-1]); + } + return True; +} diff --git a/challenge-211/polettix/raku/ch-2.raku b/challenge-211/polettix/raku/ch-2.raku new file mode 100644 index 0000000000..c7dfd3861d --- /dev/null +++ b/challenge-211/polettix/raku/ch-2.raku @@ -0,0 +1,48 @@ +#!/usr/bin/env raku +use v6; +sub MAIN (*@args) { + @args = 1 .. 8 unless @args; + put split-same-average(@args); +} + +sub split-same-average (@list) { + (my $min, @list) = @list.sort.Slip; + my @partial-sums = 0; + @partial-sums.push: @partial-sums[*-1] + (@list[$_] -= $min) for ^@list; + @list.unshift: 0; # put "min" back + + my %cache; + sub has_subset ($sum, $k, $i = @list.end) { + return True if ($sum == 0) && ($k == 0); + return False + if ($sum < 0) # removed more than needed + || ($i < 0) # nothing more to look at + || ($sum > @partial-sums[$i]) # cannot remove as much as needed + ; + + # caching on subset size $k and end cursor position $i only, the $sum + # is a consequence of $k + return %cache{$k}{$i} //= + samewith($sum - @list[$i], $k - 1, $i - 1) + || samewith($sum, $k, $i - 1); + } + + # calculate p and q (average for modified list is p/q) + my $n = @list.elems; + my $sum = @partial-sums[*-1]; + my $gcd = gcd($sum, $n); + my ($p, $q) = $sum div $gcd, $n div $gcd; + + # iterate finding subsets of multiples of q, starting at q itself + my $k = $q; + while $k <= $n div 2 { + my $S = $p * $k / $q; # target sum + return True if has_subset($S, $k); + $k += $q; + } + + # nothing found, fail + return False; +} + +sub gcd ($A is copy, $B is copy) { ($A, $B) = ($B % $A, $A) while $A; $B } -- cgit From a09dd507ef7a08b356adc5d0be0e71a84852eace Mon Sep 17 00:00:00 2001 From: Mark <53903062+andemark@users.noreply.github.com> Date: Fri, 7 Apr 2023 15:47:09 +0000 Subject: ch-2.raku do-over --- challenge-211/mark-anderson/raku/ch-2.raku | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'challenge-211') diff --git a/challenge-211/mark-anderson/raku/ch-2.raku b/challenge-211/mark-anderson/raku/ch-2.raku index 8af4568b57..9b88288ee3 100644 --- a/challenge-211/mark-anderson/raku/ch-2.raku +++ b/challenge-211/mark-anderson/raku/ch-2.raku @@ -1,7 +1,7 @@ #!/usr/bin/env raku use Test; -# This is a do-over after reading other's solutions. +# This is a do-over after reading other solutions. # Jorg Sommrey and W. Luis Mochan explained that if one subset's average # equals the average of the whole list then the other subset will have # the same average. -- cgit From bd398079f449e13bbd2cd4c4790418dcb5ffbed1 Mon Sep 17 00:00:00 2001 From: Peter Campbell Smith Date: Fri, 7 Apr 2023 20:05:28 +0100 Subject: Week 211 --- challenge-211/peter-campbell-smith/blog.txt | 1 + challenge-211/peter-campbell-smith/perl/ch-1.pl | 79 ++++++++++++++++++++++++ challenge-211/peter-campbell-smith/perl/ch-2.pl | 81 +++++++++++++++++++++++++ 3 files changed, 161 insertions(+) create mode 100644 challenge-211/peter-campbell-smith/blog.txt create mode 100755 challenge-211/peter-campbell-smith/perl/ch-1.pl create mode 100755 challenge-211/peter-campbell-smith/perl/ch-2.pl (limited to 'challenge-211') diff --git a/challenge-211/peter-campbell-smith/blog.txt b/challenge-211/peter-campbell-smith/blog.txt new file mode 100644 index 0000000000..8ca8f03329 --- /dev/null +++ b/challenge-211/peter-campbell-smith/blog.txt @@ -0,0 +1 @@ +http://ccgi.campbellsmiths.force9.co.uk/challenge/211 diff --git a/challenge-211/peter-campbell-smith/perl/ch-1.pl b/challenge-211/peter-campbell-smith/perl/ch-1.pl new file mode 100755 index 0000000000..bd20e4b8ce --- /dev/null +++ b/challenge-211/peter-campbell-smith/perl/ch-1.pl @@ -0,0 +1,79 @@ +#!/usr/bin/perl + +use v5.16; # The Weekly Challenge - 2023-04-03 +use utf8; # Week 211 task 1 - Toeplitz matrix +use strict; # Peter Campbell Smith +use warnings; # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge + +toeplitz_matrix( [[4, 3, 2, 1], + [5, 4, 3, 2], + [6, 5, 4, 3]] ); + +toeplitz_matrix( [[4, 3, 2, 1], + [5, 4, 3, 2], + [6, 5, 4, 7]] ); + +toeplitz_matrix( [[37.1, 114, 0, -23.65, 5, 3], + [-40, 37.1, 114, 0, -23.65, 5], + [-19, -40, 37.1, 114, 0, -23.65], + [3, -19, -40, 37.1, 114, 0], + [55, 3, -19, -40, 37.1, 114], + [0, 55, 3, -19, -40, 37.1], + [999, 0, 55, 3, -19, -40]] ); + +toeplitz_matrix( [[6, 0, 0, 0, 6], + [0, 0, 6, 0, 0], + [6, 0, 0, 0, 6]] ); + +sub toeplitz_matrix { + + my($m, $r, $c, $x, $good); + + $m = $_[0]; + + # loop over rows and then columns + ROW: for $r (1 .. scalar @$m - 1) { + for $c (1. .. scalar @{$m->[0]} - 1) { + + # check each element against the appropriate edge element + $x = $m->[$r]->[$c]; + if ($r >= $c) { + $good = $x == $m->[$r - $c]->[0] ? 1 : 0; + last ROW unless $good; + } else { + $good = $x == $m->[0]->[$c - $r] ? 1 : 0; + last ROW unless $good; + } + } + } + + # format the output + my ($w, $width, $rubric, $prefix, $spaces); + + # find maximum width of element (as printed by Perl) + $w = 0; + for $r (0 .. scalar @$m - 1) { + for $c (0. .. scalar @{$m->[0]} - 1) { + $width = length($m->[$r]->[$c]); + $w = $width if $width > $w; + } + } + + # construct and output each row of matrix + $rubric = ''; + $prefix = qq{\nInput: \@matrix = [ [ }; + for $r (0 .. scalar @$m - 1) { + $rubric .= $prefix; + for $c (0. .. scalar @{$m->[0]} - 1) { + $spaces = $w + 1 - length($m->[$r]->[$c]); + $rubric .= (' ' x $spaces) . $m->[$r]->[$c] . ','; + } + $rubric =~ s|.$| ]|s; + $rubric .= ' ]' if $r == scalar @$m - 1; + say $rubric; + $rubric = ''; + $prefix = ' [ '; + } + say qq[Output: ] . ($good ? 'true' : 'false'); +} + diff --git a/challenge-211/peter-campbell-smith/perl/ch-2.pl b/challenge-211/peter-campbell-smith/perl/ch-2.pl new file mode 100755 index 0000000000..ad289c91af --- /dev/null +++ b/challenge-211/peter-campbell-smith/perl/ch-2.pl @@ -0,0 +1,81 @@ +#!/usr/bin/perl + +use v5.16; # The Weekly Challenge - 2023-04-03 +use utf8; # Week 211 task 2 - Split same average +use strict; # Peter Campbell Smith +use warnings; # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge + +use Algorithm::Combinatorics ('combinations'); + +my ($j, @data); + +equal_means(1, 2, 3, 4, 5, 6, 7, 8); +equal_means(1, 3); +equal_means(10, 1, 7, 5, 3, 11, 8, 4, 2, 9); +equal_means(6, 3, 1, 9, 12, 25, 18, 20); +equal_means(8, 6, 3, 5, 1, 4, 2, 7); + +for $j (0 .. 20) { + $data[$j] = int(rand(15)); +} +equal_means(@data); + +sub equal_means { + + my (@array, $count, $mean, $sum, $count1, @array1, $mean1, $sum1, + $count2, $sum2, $mean2, $comb, $iter, $d, $array2p, $combs); + + # initialise + @array = @_; + ($count, $sum, $mean) = stats(@array); + + # loop over sizes of @array1 to consider + OUTER: for $count1 (1 .. int($count / 2)) { + + # loop over combinations from @array of that size + $iter = combinations(\@array, $count1); + while ($comb = $iter->next) { + + # calculate @array1 data + $combs ++; + @array1 = @$comb; + ($count1, $sum1, $mean1) = stats(@array1); + + # deduce @array2 data + $count2 = $count - $count1; + $sum2 = $sum - $sum1; + $mean2 = $sum2 / $count2; + + # means match - result! + if ($mean1 == $mean2) { + + # format and print + $array2p = ', ' . join(', ', @array) . ', '; + for $d (@array1) { + $array2p =~ s|, $d,|,|; + } + say qq[\nInput: (] . join(', ', @array) . q[)]; + say qq[Output: true]; + say qq[ array1: (] . join(', ', @array1) . q[)]; + say qq[ array2: (] . substr($array2p, 2, -2) . q[)]; + say qq[ mean = $mean1 (after $combs combinations tested)]; + return; + } + } + } + say qq[\nInput: (] . join(', ', @array) . q[)]; + say qq[Output: false (after $combs combinations tested)]; +} + +sub stats { + + my ($sum, $count, $d); + + $sum = $count = 0; + for $d (@_) { + $sum += $d; + $count ++; + } + return ($count, $sum, $sum / $count); +} + \ No newline at end of file -- cgit From 179e4b69b5060f752454bf14008c4a859345b0fe Mon Sep 17 00:00:00 2001 From: Simon Green Date: Sat, 8 Apr 2023 20:09:13 +1000 Subject: Simon's solution to challenge 211 --- challenge-211/sgreen/README.md | 4 ++-- challenge-211/sgreen/blog.txt | 1 + challenge-211/sgreen/perl/ch-1.pl | 47 +++++++++++++++++++++++++++++++++++++ challenge-211/sgreen/perl/ch-2.pl | 38 ++++++++++++++++++++++++++++++ challenge-211/sgreen/python/ch-1.py | 40 +++++++++++++++++++++++++++++++ challenge-211/sgreen/python/ch-2.py | 31 ++++++++++++++++++++++++ 6 files changed, 159 insertions(+), 2 deletions(-) create mode 100644 challenge-211/sgreen/blog.txt create mode 100755 challenge-211/sgreen/perl/ch-1.pl create mode 100755 challenge-211/sgreen/perl/ch-2.pl create mode 100755 challenge-211/sgreen/python/ch-1.py create mode 100755 challenge-211/sgreen/python/ch-2.py (limited to 'challenge-211') diff --git a/challenge-211/sgreen/README.md b/challenge-211/sgreen/README.md index 0f4559dc5a..1c9faf1810 100644 --- a/challenge-211/sgreen/README.md +++ b/challenge-211/sgreen/README.md @@ -1,3 +1,3 @@ -# The Weekly Challenge 210 +# The Weekly Challenge 211 -Blog: [Numbers Challenges](https://dev.to/simongreennet/numbers-challenges-32k1) +Blog: [Weekly Challenge 211](https://dev.to/simongreennet/weekly-challenge-211-1np1) diff --git a/challenge-211/sgreen/blog.txt b/challenge-211/sgreen/blog.txt new file mode 100644 index 0000000000..12a949a17b --- /dev/null +++ b/challenge-211/sgreen/blog.txt @@ -0,0 +1 @@ +https://dev.to/simongreennet/weekly-challenge-211-1np1 \ No newline at end of file diff --git a/challenge-211/sgreen/perl/ch-1.pl b/challenge-211/sgreen/perl/ch-1.pl new file mode 100755 index 0000000000..efee5c8349 --- /dev/null +++ b/challenge-211/sgreen/perl/ch-1.pl @@ -0,0 +1,47 @@ +#!/usr/bin/env perl + +use strict; +use warnings; +use feature 'say'; +use experimental 'signatures'; + +use List::Util 'min'; +use JSON; + +sub main ($matrix) { + # Let's define some variables + my $rows = scalar(@$matrix); + my $cols = scalar( @{ $matrix->[0] } ); + + # We always check from the top left + my @offsets = ( [ 0, 0 ] ); + + # If the matrix isn't square, we also use an offset to hit the bottom right + if ( $rows > $cols ) { + push @offsets, [ $rows - $cols, 0 ]; + } + elsif ( $rows < $cols ) { + push @offsets, [ 0, $cols - $rows ]; + } + + # The number of checks we need to make + my $counts = min( $rows, $cols ); + + foreach my $o (@offsets) { + # Define the offsets, and the first value + my ( $row_offset, $col_offset ) = @$o; + my $value = $matrix->[$row_offset][$col_offset]; + + foreach my $i ( 1 .. $counts - 1 ) { + # Compare the value until we find one that doesn't match + if ( $value != $matrix->[ $row_offset + $i ][ $col_offset + $i ] ) { + say 'false'; + return; + } + } + } + + say 'true'; +} + +main( decode_json( $ARGV[0] ) ); \ No newline at end of file diff --git a/challenge-211/sgreen/perl/ch-2.pl b/challenge-211/sgreen/perl/ch-2.pl new file mode 100755 index 0000000000..42e2533746 --- /dev/null +++ b/challenge-211/sgreen/perl/ch-2.pl @@ -0,0 +1,38 @@ +#!/usr/bin/env perl + +use strict; +use warnings; +use feature 'say'; +use experimental 'signatures'; + +use List::Util 'sum'; +use Algorithm::Combinatorics 'combinations'; + +sub main(@n) { + # Calculate average + my $avg = sum(@n) / scalar(@n); + + # A single element is always true + if ($#n == 0) { + say 'true'; + return; + } + + + # Consider combination of size 1 to half the length + foreach my $i (1 .. scalar(@n)/2) { + # Work through each combination + my $iter = combinations(\@n, $i); + while ( my $c = $iter->next ) { + # If combination average is same, the remaining items also will be + if (sum(@$c) / $i == $avg) { + say 'true'; + return; + } + } + } + + say 'false'; +} + +main(@ARGV); \ No newline at end of file diff --git a/challenge-211/sgreen/python/ch-1.py b/challenge-211/sgreen/python/ch-1.py new file mode 100755 index 0000000000..334aeeb4bf --- /dev/null +++ b/challenge-211/sgreen/python/ch-1.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 + +import json +import sys + + +def main(matrix): + # Let's define some variables + rows = len(matrix) + cols = len(matrix[0]) + + # We always check from the top left + offsets = [[0, 0]] + + # If the matrix isn't square, we also use an offset to hit the bottom right + if rows > cols: + offsets.append([rows-cols, 0]) + elif rows < cols: + offsets.append([0, cols-rows]) + + # The number of checks we need to make + counts = min(rows, cols) + + for o in offsets: + # Define the offsets, and the first value + row_offset, col_offset = o + value = matrix[row_offset][col_offset] + + for i in range(1, counts): + # Compare the value until we find one that doesn't match + if value != matrix[row_offset+i][col_offset+i]: + print('false') + return + + # Print results + print('true') + + +if __name__ == '__main__': + main(json.loads(sys.argv[1])) diff --git a/challenge-211/sgreen/python/ch-2.py b/challenge-211/sgreen/python/ch-2.py new file mode 100755 index 0000000000..57226ad4bf --- /dev/null +++ b/challenge-211/sgreen/python/ch-2.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 + +from itertools import combinations +import sys + + +def main(n): + # Calculate average + avg = sum(n) / len(n) + + # A single element is always true + if len(n) == 1: + print('true') + return + + # Consider combination of size 1 to half the length + for i in range(1, len(n)//2+1): + # Work through each combination + for c in combinations(n, i): + # If combination average is same, the remaining items also will be + if sum(c) / i == avg: + print('true') + return + + print('false') + + +if __name__ == '__main__': + # Turn the strings into integers + n = [int(i) for i in sys.argv[1:]] + main(n) -- cgit From 17a514fbf0fb17f3391929681c9f7a073618ad8d Mon Sep 17 00:00:00 2001 From: Pip Date: Sat, 8 Apr 2023 10:56:06 -0500 Subject: Pip Stuart's submission for challenge-211. --- challenge-211/pip/perl/ch-1.pl | 38 ++++++++++++++++++++++++++++++++++++++ challenge-211/pip/perl/ch-2.pl | 32 ++++++++++++++++++++++++++++++++ challenge-211/pip/raku/ch-1.raku | 39 +++++++++++++++++++++++++++++++++++++++ challenge-211/pip/raku/ch-2.raku | 33 +++++++++++++++++++++++++++++++++ 4 files changed, 142 insertions(+) create mode 100644 challenge-211/pip/perl/ch-1.pl create mode 100644 challenge-211/pip/perl/ch-2.pl create mode 100644 challenge-211/pip/raku/ch-1.raku create mode 100644 challenge-211/pip/raku/ch-2.raku (limited to 'challenge-211') diff --git a/challenge-211/pip/perl/ch-1.pl b/challenge-211/pip/perl/ch-1.pl new file mode 100644 index 0000000000..d703cb093a --- /dev/null +++ b/challenge-211/pip/perl/ch-1.pl @@ -0,0 +1,38 @@ +#!/usr/bin/perl +# HTTPS://TheWeeklyChallenge.Org - Perl/Raku Weekly Challenge #211 - Pip Stuart +# Task1: Toeplitz Matrix: Submitted by: Mohammad S Anwar; You are given a matrix m x n. Write a script to find out if the given matrix is Toeplitz Matrix. +# A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements. +# Example1: +# In-put: @matrix = [ [4, 3, 2, 1], +# [5, 4, 3, 2], +# [6, 5, 4, 3], ] +# Output: true +# Example2: +# In-put: @matrix = [ [1, 2, 3], +# [3, 2, 1], ] +# Output: false +use strict;use warnings;use utf8;use v5.12;my $d8VS='N48M8DlW'; +sub TpzM {my $mtrx = shift(@_);my $tplz = 1; # below eval string that looks like it's exclusively a 2D matrix array-ref of just comma-separated integerz + if (ref($mtrx) ne 'ARRAY' && $mtrx =~ /^\s*\[\s*(\[\s*(\d+\s*,?\s*)+\]\s*,?\s*)+\]\s*$/ ) { $mtrx = eval($mtrx); } + my $enen = @{$mtrx}; my $emem = @{$mtrx->[0]} ; + for (1 .. $enen - 2) { my $edge = $mtrx->[$_][0];my $roww = $_;my $colm = 0; if ($tplz) { # loop left-side diagonals but not bottom corner + while ($roww < $enen && $colm < $emem ) {#say "edge:$edge $mtrx->[$roww][$colm]:mtrx->roww,colm;"; + if ($edge != $mtrx->[ $roww++][ $colm++]) { $tplz = 0;last; } } } } + for (0 .. $emem - 2) { my $edge = $mtrx->[0][$_];my $roww = 0;my $colm = $_; if ($tplz) { # loop top-side diagonals but not right corner + while ($roww < $enen && $colm < $emem ) {#say "edge:$edge $mtrx->[$roww][$colm]:mtrx->roww,colm;"; + if ($edge != $mtrx->[ $roww++][ $colm++]) { $tplz = 0;last; } } } } + print '[ ';my $fnif = 1; # set FirstNoIndentFlag; + for (@{$mtrx}) { if ($fnif) { $fnif = 0; } else { print "\n "; } + printf("[%-10s],", join(', ',@{$_}) ); } + say " ] => $tplz;"; + return( $tplz ); +} +if (@ARGV) { + TpzM(@ARGV); +} else { + TpzM([ [4, 3, 2, 1], + [5, 4, 3, 2], + [6, 5, 4, 3], ]); # => 1; + TpzM([ [1, 2, 3 ], + [3, 2, 1 ], ]); # => 0; +} diff --git a/challenge-211/pip/perl/ch-2.pl b/challenge-211/pip/perl/ch-2.pl new file mode 100644 index 0000000000..b757eff298 --- /dev/null +++ b/challenge-211/pip/perl/ch-2.pl @@ -0,0 +1,32 @@ +#!/usr/bin/perl +# HTTPS://TheWeeklyChallenge.Org - Perl/Raku Weekly Challenge #211 - Pip Stuart +# Task2: Split Same Average: Submitted by: Mohammad S Anwar; You are given an array of integers. +# Write a script to find out if the given can be split into two separate arrays whose average are the same. +# Example1: +# In-put: @nums = (1, 2, 3, 4, 5, 6, 7, 8) +# Output: true We can split the given array into (1, 4, 5, 8) and (2, 3, 6, 7). The average of the two arrays are the same i.e. 4.5. +# Example2: +# In-put: @nums = (1, 3) +# Output: false +# Last date to submit the solution 23:59 (UK Time) Sunday 9th April 2023. +use strict;use warnings;use utf8;use v5.12;my $d8VS='N48M8KR8'; +sub SSAv { my @numz = @_;my $smav = 0;my $nsiz = @numz; + my $spld = 2 ** $nsiz; + while (--$spld) { + my $splb = sprintf("%0${nsiz}b", $spld);my @bdgz = split(//, $splb);my @left = ();my @rite = ();my $lsum = 0;my $rsum = 0; + for (0 .. @bdgz - 1) { + if ($bdgz[$_]) { + push(@rite, $numz[$_]);$rsum += $numz[$_]; } + else { + push(@left, $numz[$_]);$lsum += $numz[$_]; } } + if (@left && @rite && ($lsum / @left) == ($rsum / @rite)) {#say "splb:$splb avrg:" . ($lsum / @left) . " left:@left rite:@rite;"; + $smav = 1;last; } } # removing last here && uncommenting say above will show all 16 ways it works for average 4.5 for Example1 of 1..8 + printf("(%-22s) => $smav;\n", join(', ', @numz)); + return( $smav); +} +if (@ARGV) { + SSAv(@ARGV); +} else { + SSAv(1, 2, 3, 4, 5, 6, 7, 8); # => 1; + SSAv(1, 3 ); # => 0; +} diff --git a/challenge-211/pip/raku/ch-1.raku b/challenge-211/pip/raku/ch-1.raku new file mode 100644 index 0000000000..c6a729f026 --- /dev/null +++ b/challenge-211/pip/raku/ch-1.raku @@ -0,0 +1,39 @@ +#!/usr/bin/env raku +# HTTPS://TheWeeklyChallenge.Org - Perl/Raku Weekly Challenge #211 - Pip Stuart +# Task1: Toeplitz Matrix: Submitted by: Mohammad S Anwar; You are given a matrix m x n. Write a script to find out if the given matrix is Toeplitz Matrix. +# A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements. +# Example1: +# In-put: @matrix = [ [4, 3, 2, 1], +# [5, 4, 3, 2], +# [6, 5, 4, 3], ] +# Output: true +# Example2: +# In-put: @matrix = [ [1, 2, 3], +# [3, 2, 1], ] +# Output: false +use v6;use MONKEY-SEE-NO-EVAL;my $d8VS='N48MAntE'; +sub TpzM {my $mtrx = [];my $tplz = 1; + push(@($mtrx), shift(@_)) while (@_); # below EVAL Str (ing) that looks like it's exclusively characters of a 2D array-ref matrix, commas, && integerz + if ($mtrx[0].WHAT.^name eq 'Str' && $mtrx ~~ /^ <[\[\d\,\]\s]>+ $/) { $mtrx = EVAL("$mtrx"); } + my $enen = @($mtrx).elems;my $emem = @($mtrx[0]).elems; + for (1 .. $enen - 2) { my $edge = $mtrx[$_][0]; my $roww = $_;my $colm = 0; if ($tplz) { # loop left-side diagonals but not bottom corner + while ($roww < $enen && $colm < $emem ) { #say "edge:$edge $mtrx[$roww][$colm]:mtrx[roww][colm];"; + if ($edge != $mtrx[ $roww++][ $colm++]) { $tplz = 0;last; } } } } + for (0 .. $emem - 2) { my $edge = $mtrx[0][$_]; my $roww = 0;my $colm = $_; if ($tplz) { # loop top-side diagonals but not right corner + while ($roww < $enen && $colm < $emem ) { #say "edge:$edge $mtrx[$roww][$colm]:mtrx[roww][colm];"; + if ($edge != $mtrx[ $roww++][ $colm++]) { $tplz = 0;last; } } } } + print '[ ';my $fnif = 1; # set FirstNoIndentFlag; + for (@($mtrx)) { if ($fnif) { $fnif = 0; } else { print "\n "; } + printf("[%-10s],", join(', ',@($_)) ); } + say " ] => $tplz;"; + return( $tplz ); +} +if (@*ARGS) { + TpzM(@*ARGS); +} else { + TpzM([ [4, 3, 2, 1], + [5, 4, 3, 2], + [6, 5, 4, 3], ]); # => 1; + TpzM([ [1, 2, 3 ], + [3, 2, 1 ], ]); # => 0; +} diff --git a/challenge-211/pip/raku/ch-2.raku b/challenge-211/pip/raku/ch-2.raku new file mode 100644 index 0000000000..4ec5f8cd95 --- /dev/null +++ b/challenge-211/pip/raku/ch-2.raku @@ -0,0 +1,33 @@ +#!/usr/bin/env raku +# HTTPS://TheWeeklyChallenge.Org - Perl/Raku Weekly Challenge #211 - Pip Stuart +# Task2: Split Same Average: Submitted by: Mohammad S Anwar; You are given an array of integers. +# Write a script to find out if the given can be split into two separate arrays whose average are the same. +# Example1: +# In-put: @nums = (1, 2, 3, 4, 5, 6, 7, 8) +# Output: true We can split the given array into (1, 4, 5, 8) and (2, 3, 6, 7). The average of the two arrays are the same i.e. 4.5. +# Example2: +# In-put: @nums = (1, 3) +# Output: false +# Last date to submit the solution 23:59 (UK Time) Sunday 9th April 2023. +use v6;my $d8VS='N48MAnEt'; +sub SSAv { my @numz = @_;my $smav = 0;my $nsiz = @numz.elems; + my $spld = 2 ** $nsiz; + while (--$spld) { + my $splb = sprintf("%0" ~ $nsiz ~ "b", $spld);my @bdgz = split('', $splb, :skip-empty);my @left = ();my @rite = ();my $lsum = 0;my $rsum = 0; + for (0 .. @bdgz - 1 ) { + if (@bdgz[$_] eq '1') { + push(@rite, @numz[$_]);$rsum += @numz[$_]; } + else { + push(@left, @numz[$_]);$lsum += @numz[$_]; } } + if (@left.elems && @rite.elems && ($lsum / @left.elems) == ($rsum / @rite.elems)) { +# say "splb:$splb avrg:" ~ ($lsum / @left.elems) ~ " left:@left[] rite:@rite[];"; + $smav = 1;last; } } # removing last here && uncommenting say above will show all 16 ways it works for average 4.5 for Example1 of 1..8 + printf("(%-22s) => $smav;\n", join(', ', @numz)); + return( $smav); +} +if (@*ARGS) { + SSAv(@*ARGS); +} else { + SSAv(1, 2, 3, 4, 5, 6, 7, 8); # => 1; + SSAv(1, 3 ); # => 0; +} -- cgit From 400fc6ccba6517131b0a90b5fe34c2912c66ff43 Mon Sep 17 00:00:00 2001 From: Solathian Date: Sat, 8 Apr 2023 19:49:40 +0200 Subject: Adding files for challenge --- challenge-211/solathian/perl/ch-1.pl | 52 +++++++++++++++++++ challenge-211/solathian/perl/ch-2.pl | 97 ++++++++++++++++++++++++++++++++++++ 2 files changed, 149 insertions(+) create mode 100644 challenge-211/solathian/perl/ch-1.pl create mode 100644 challenge-211/solathian/perl/ch-2.pl (limited to 'challenge-211') diff --git a/challenge-211/solathian/perl/ch-1.pl b/challenge-211/solathian/perl/ch-1.pl new file mode 100644 index 0000000000..987c547731 --- /dev/null +++ b/challenge-211/solathian/perl/ch-1.pl @@ -0,0 +1,52 @@ +#!usr/bin/perl +use v5.36; + +use builtin qw(indexed true false); +no warnings 'experimental'; + +# Challenge 211- 1 - Toeplitz Matrix +# You are given a matrix m x n. + +# Write a script to find out if the given matrix is Toeplitz Matrix. + + +my @matrix = ( [4, 3, 2, 1], + [5, 4, 3, 2], + [6, 5, 4, 3]); + +Toeplitz(\@matrix); # Output: true + +my @matrix2 = ( [1, 2, 3], + [3, 2, 1]); + +Toeplitz(\@matrix2); # Output: true + + + +sub Toeplitz($matrixRef) +{ + my $retVal = true; + + OUTER: + foreach my ($i, $row) (indexed @$matrixRef) + { + foreach my ($j, $jVal) (indexed @$row) + { + # skip the elements in the last column and the row, since we cannot check diagonally + next if($i == $#$matrixRef); + next if($j == $#$row); + + if($matrixRef->[$i][$j] != $matrixRef->[$i + 1][$j + 1] ) + { + $retVal = false; + last OUTER; + } + + } + } + + if($retVal){ say "true" } + else{ say "false" } + + +} \ No newline at end of file diff --git a/challenge-211/solathian/perl/ch-2.pl b/challenge-211/solathian/perl/ch-2.pl new file mode 100644 index 0000000000..27f2c07669 --- /dev/null +++ b/challenge-211/solathian/perl/ch-2.pl @@ -0,0 +1,97 @@ +#!usr/bin/perl +use v5.36; + +use Algorithm::Combinatorics qw(combinations); +use List::Util qw(sum); +use builtin qw( true false); +no warnings 'experimental'; + +# Challenge 211 - 2 - Split Same Average +# You are given an array of integers. +# Write a script to find out if the given can be split into two separate arrays whose average are the same. +# (1, 2, 3, 4, 5, 6, 7, 8) + + + +ssa(1, 2, 3, 4, 5, 6, 7, 8); +# ssa(1, 2, 3, 4, 4, 6, 7, 8); +# We can split the given array into (1, 4, 5, 8) and (2, 3, 6, 7). +# The average of the two arrays are the same i.e. 4.5. +# Output: true + +ssa(1, 3); + +# Output: false + +sub getLeftOut($originalArray, $firstArray) +{ + my @secondArray; + + foreach my $elem (@$originalArray) + { + next if($elem ~~ @$firstArray); + + push(@secondArray, $elem); + + # yes, currently it goes haywire if the array is not unique + } + + return \@secondArray; +} + +sub splitArray($arrayRef, $firstSize) +{ + my @resultArray; + + foreach my $firstPart ( combinations($arrayRef, $firstSize)) + { + my $secondArray = getLeftOut($arrayRef, $firstPart); + + push(@resultArray, [$firstPart, $secondArray]) + } + + return \@resultArray; +} + +sub avg($list) +{ + return sum(@$list) / @$list; +} + + + +sub ssa(@list) +{ + + say "Array: @list"; + + my $currentSize = 1; + my $returnFlag = false; + + OUTER: + while($currentSize < (@list - 1)) + { + my $splitArrays = splitArray(\@list, $currentSize); + + foreach my $splitArray (@$splitArrays) + { + my $first = $splitArray->[0]; + my $second = $splitArray->[1]; + + if(avg($first) == avg($second)) + { + + say "Found an array:"; + say "Average is:" . avg($first); + say '(' . join(',', @$first) . '),('. join(',', @$second) . ')'; + say ""; + $returnFlag = true; + last OUTER; + } + } + + $currentSize++; + } + + if(!$returnFlag){say "Did not found such array"} +} \ No newline at end of file -- cgit From 596200ed10c9bd772b4e10112addb43b2b916427 Mon Sep 17 00:00:00 2001 From: "E. Choroba" Date: Sun, 9 Apr 2023 01:27:26 +0200 Subject: Solve 211: Toeplitz Matrix & Split Same Average by E. Choroba --- challenge-211/e-choroba/perl/ch-1.pl | 47 +++++++++++++++++++++++ challenge-211/e-choroba/perl/ch-2.pl | 72 ++++++++++++++++++++++++++++++++++++ 2 files changed, 119 insertions(+) create mode 100755 challenge-211/e-choroba/perl/ch-1.pl create mode 100755 challenge-211/e-choroba/perl/ch-2.pl (limited to 'challenge-211') diff --git a/challenge-211/e-choroba/perl/ch-1.pl b/challenge-211/e-choroba/perl/ch-1.pl new file mode 100755 index 0000000000..90ae514e7b --- /dev/null +++ b/challenge-211/e-choroba/perl/ch-1.pl @@ -0,0 +1,47 @@ +#! /usr/bin/perl +use warnings; +use strict; +use experimental qw( signatures ); + +sub toeplitz_matrix($m) { + my $x = 0; + my $y = $#$m; + while ($x <= $#{ $m->[0] }) { + my ($u, $v) = ($x, $y); + while (++$u <= $#{ $m->[0] } && ++$v <= $#$m) { + return if $m->[$v][$u] != $m->[$y][$x]; + } + } continue { + if ($y) { + --$y; + } else { + ++$x; + } + } + return 1 +} + +use Test::More tests => 4; + +ok toeplitz_matrix([ [4, 3, 2, 1], + [5, 4, 3, 2], + [6, 5, 4, 3], + ]), 'Example 1'; + +ok ! toeplitz_matrix([ [1, 2, 3], + [3, 2, 1], + ]), 'Example 2'; + +ok toeplitz_matrix([[1]]), '1x1'; +ok toeplitz_matrix([[1,2,3,4,5,6,7], + [8,1,2,3,4,5,6], + [9,8,1,2,3,4,5], + [10,9,8,1,2,3,4], + [11,10,9,8,1,2,3], + [12,11,10,9,8,1,2], + [13,12,11,10,9,8,1], + [14,13,12,11,10,9,8], + [15,14,13,12,11,10,9], + [16,15,14,13,12,11,10], + [17,16,15,14,13,12,11], + ]), 'Larger'; diff --git a/challenge-211/e-choroba/perl/ch-2.pl b/challenge-211/e-choroba/perl/ch-2.pl new file mode 100755 index 0000000000..02942855f9 --- /dev/null +++ b/challenge-211/e-choroba/perl/ch-2.pl @@ -0,0 +1,72 @@ +#! /usr/bin/perl +use warnings; +use strict; +use experimental qw( signatures ); + +use List::Util qw{ sum }; + +sub split_same_average_brute_force(@list) { + my $avg = sum(@list) / @list; + my @mask = (0) x @list; + $mask[-1] = 1; + while (1) { + my $s = sum(@list[grep $mask[$_], 0 .. $#mask]); + return 1 if abs($s / (grep $_, @mask) - $avg) < 1e-9; + + my $pos = $#mask; + while ($mask[$pos]) { + $mask[$pos] = 0; + return if --$pos < 1; + } + $mask[$pos] = 1; + } + +} + +sub split_same_average(@list) { + my $sum = sum(@list); + my $avg = $sum / @list; + my $max_length = (@list + 1) / 2; + --$max_length if $max_length >= @list - 1; + + my %possible; # {sum}{length} + $possible{0}{0} = 1; + for my $e (@list) { + # Sort is needed so we don't process the added sum again in + # the same step. + for my $s (sort { $b <=> $a } keys %possible) { + for my $length (keys %{ $possible{$s} }) { + next if $length == @list - 1; + + $possible{ $s + $e }{ $length + 1 } = 1; + return 1 if abs(($s + $e) / ($length+1) - $avg) < 1e-9; + } + } + } + return +} + +use Test::More; + +ok split_same_average(1, 2, 3, 4, 5, 6, 7, 8), 'Example 1'; +ok ! split_same_average(1, 3), 'Example 2'; + +ok split_same_average(-2, 0, 2), 'Avg 0'; +ok split_same_average(1, 5, 5, 1), 'Duplicates'; + +for (1 .. 200) { + my @list = map int rand 20, 1 .. 2 + rand 10; + is split_same_average(@list), split_same_average_brute_force(@list), + "same @list"; +} + +my @l = map int rand 50, 1 .. 12; +is split_same_average(@l), split_same_average_brute_force(@l), + "same @l"; +done_testing(); + +use Benchmark qw{ cmpthese }; +cmpthese(-3, { + brute_force => sub { split_same_average_brute_force(@l) }, + fast => sub { split_same_average(@l) }, +}); -- cgit From 63c6ac5026b1bc34d80101b150d297dd00ab4884 Mon Sep 17 00:00:00 2001 From: Carlos Eduardo de Oliveira Date: Sat, 8 Apr 2023 20:56:59 -0300 Subject: solution to challenge 211 --- challenge-211/carlos-oliveira/perl/ch-1.pl | 27 +++++++++++++++++++++++++++ challenge-211/carlos-oliveira/perl/ch-2.pl | 19 +++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 challenge-211/carlos-oliveira/perl/ch-1.pl create mode 100644 challenge-211/carlos-oliveira/perl/ch-2.pl (limited to 'challenge-211') diff --git a/challenge-211/carlos-oliveira/perl/ch-1.pl b/challenge-211/carlos-oliveira/perl/ch-1.pl new file mode 100644 index 0000000000..bfd6351111 --- /dev/null +++ b/challenge-211/carlos-oliveira/perl/ch-1.pl @@ -0,0 +1,27 @@ +use strict; +use warnings; +use v5.36; + +use Test::More; +use List::Util qw(uniq); + +sub is_toeplitz_matrix (@matrix) { + my $cols = $matrix[0]->@*; + for my $i (0..$#matrix) { + my @diagonal = uniq map { $i < $cols ? $_->[$i++] : () } @matrix; + return 0 unless @diagonal == 1; + } + return 1; +} + +is is_toeplitz_matrix( + [4, 3, 2, 1], + [5, 4, 3, 2], + [6, 5, 4, 3] +), 1; +is is_toeplitz_matrix( + [1, 2, 3], + [3, 2, 1] +), 0; + +done_testing; diff --git a/challenge-211/carlos-oliveira/perl/ch-2.pl b/challenge-211/carlos-oliveira/perl/ch-2.pl new file mode 100644 index 0000000000..421b8e94d7 --- /dev/null +++ b/challenge-211/carlos-oliveira/perl/ch-2.pl @@ -0,0 +1,19 @@ +use strict; +use warnings; +use v5.36; + +use Test::More; +use Algorithm::Combinatorics qw(partitions); +use List::Util qw(any sum uniqnum); +use builtin qw(true false); + +sub can_be_split_with_same_average (@array) { + re