From 6adf699efe9bd4cfdd2a622de23cc932c2e8f398 Mon Sep 17 00:00:00 2001 From: Conor Hoekstra Date: Sat, 25 Oct 2025 12:48:04 -0400 Subject: :sparkles: additional 307 solutions --- challenge-307/conor-hoekstra/apl/ch-1.apl | 1 + challenge-307/conor-hoekstra/cuda/ch-1.cu | 5 + challenge-307/conor-hoekstra/python/ch-1.py | 143 ++++++++++++++++++++++++++++ 3 files changed, 149 insertions(+) create mode 100644 challenge-307/conor-hoekstra/apl/ch-1.apl create mode 100644 challenge-307/conor-hoekstra/cuda/ch-1.cu create mode 100644 challenge-307/conor-hoekstra/python/ch-1.py diff --git a/challenge-307/conor-hoekstra/apl/ch-1.apl b/challenge-307/conor-hoekstra/apl/ch-1.apl new file mode 100644 index 0000000000..53a183db51 --- /dev/null +++ b/challenge-307/conor-hoekstra/apl/ch-1.apl @@ -0,0 +1 @@ +CheckOrder ← 1-⍨⍸(⊂⍤⍋⍛⌷)⍛≠ \ No newline at end of file diff --git a/challenge-307/conor-hoekstra/cuda/ch-1.cu b/challenge-307/conor-hoekstra/cuda/ch-1.cu new file mode 100644 index 0000000000..ecab913a08 --- /dev/null +++ b/challenge-307/conor-hoekstra/cuda/ch-1.cu @@ -0,0 +1,5 @@ +#import "parrot.h" + +auto check_order(auto ints) { // + return ints.sort().neq(ints).where() - 1; +} \ No newline at end of file diff --git a/challenge-307/conor-hoekstra/python/ch-1.py b/challenge-307/conor-hoekstra/python/ch-1.py new file mode 100644 index 0000000000..de99d0885e --- /dev/null +++ b/challenge-307/conor-hoekstra/python/ch-1.py @@ -0,0 +1,143 @@ +import numpy as np +import jax +import jax.numpy as jnp +import tensorflow as tf +import torch + + +def check_order(lst): + return [c for c, (a, b) in enumerate(zip(lst, sorted(lst))) if a != b] + + +# NumPy Solution +def check_order_np(lst): + l = np.array(lst) + return np.where(l != sorted(l))[0] + + +def check_order_jax(lst): + l = jnp.array(lst) + return jnp.where(l != jnp.sort(l))[0] + + +# @jax.jit +# def check_order_jax_jit(lst): +# l = jnp.array(lst) +# return jnp.where(l != jnp.sort(l))[0] + +# jax.errors.ConcretizationTypeError: Abstract tracer value encountered +# where concrete value is expected: traced array with shape int32[] +# The size argument of jnp.nonzero must be statically specified to use +# jnp.nonzero within JAX transformations. + + +# TensorFlow Solution (CPU) +def check_order_tf(lst): + l = tf.constant(lst) + return tf.where(l != tf.sort(l))[:, 0].numpy() + + +# TensorFlow Solution (CUDA/GPU) +def check_order_tf_cuda(lst): + with tf.device("/GPU:0"): + l = tf.constant(lst) + return tf.where(l != tf.sort(l))[:, 0].numpy() + + +# TensorFlow Function Solution (CPU) +@tf.function +def check_order_tf_fn(l): + return tf.where(l != tf.sort(l))[:, 0] + + +# TensorFlow Function Solution (CUDA/GPU) +@tf.function +def check_order_tf_fn_cuda_impl(l): + return tf.where(l != tf.sort(l))[:, 0] + + +def check_order_tf_fn_cuda(lst): + with tf.device("/GPU:0"): + l = tf.constant(lst) + return check_order_tf_fn_cuda_impl(l).numpy() + + +# PyTorch Solution (CPU) +def check_order_torch(lst): + l = torch.tensor(lst) + return torch.where(l != torch.sort(l)[0])[0].numpy() + + +# PyTorch Solution (CUDA/GPU) +def check_order_torch_cuda(lst): + l = torch.tensor(lst).cuda() + return torch.where(l != torch.sort(l)[0])[0].cpu().numpy() + + +# PyTorch JIT Compile Solution (CPU) +@torch.jit.script +def check_order_torch_jit_impl(l): + return torch.where(l != torch.sort(l)[0])[0] + + +def check_order_torch_jit(lst): + l = torch.tensor(lst) + return check_order_torch_jit_impl(l).numpy() + + +# PyTorch JIT Compile Solution (CUDA/GPU) +@torch.jit.script +def check_order_torch_jit_cuda_impl(l): + return torch.where(l != torch.sort(l)[0])[0] + + +def check_order_torch_jit_cuda(lst): + l = torch.tensor(lst).cuda() + return check_order_torch_jit_cuda_impl(l).cpu().numpy() + + +# Tests +print(check_order([5, 2, 4, 3, 1])) # [0, 2, 3, 4] +print(check_order([1, 2, 1, 1, 3])) # [1, 3] +print(check_order([3, 1, 3, 2, 3])) # [0, 1, 3] +print(check_order_np([5, 2, 4, 3, 1])) # [0, 2, 3, 4] +print(check_order_np([1, 2, 1, 1, 3])) # [1, 3] +print(check_order_np([3, 1, 3, 2, 3])) # [0, 1, 3] +print(check_order_jax([5, 2, 4, 3, 1])) # [0, 2, 3, 4] +print(check_order_jax([1, 2, 1, 1, 3])) # [1, 3] +print(check_order_jax([3, 1, 3, 2, 3])) # [0, 1, 3] +print(check_order_tf([5, 2, 4, 3, 1])) # [0, 2, 3, 4] +print(check_order_tf([1, 2, 1, 1, 3])) # [1, 3] +print(check_order_tf([3, 1, 3, 2, 3])) # [0, 1, 3] +print(check_order_tf_fn(tf.constant([5, 2, 4, 3, 1])).numpy()) # [0, 2, 3, 4] +print(check_order_tf_fn(tf.constant([1, 2, 1, 1, 3])).numpy()) # [1, 3] +print(check_order_tf_fn(tf.constant([3, 1, 3, 2, 3])).numpy()) # [0, 1, 3] +print(check_order_torch([5, 2, 4, 3, 1])) # [0, 2, 3, 4] +print(check_order_torch([1, 2, 1, 1, 3])) # [1, 3] +print(check_order_torch([3, 1, 3, 2, 3])) # [0, 1, 3] +print(check_order_torch_jit([5, 2, 4, 3, 1])) # [0, 2, 3, 4] +print(check_order_torch_jit([1, 2, 1, 1, 3])) # [1, 3] +print(check_order_torch_jit([3, 1, 3, 2, 3])) # [0, 1, 3] + +# CUDA/GPU Tests (requires CUDA-capable GPU) +if tf.config.list_physical_devices("GPU"): + print("TensorFlow GPU available") + print(check_order_tf_cuda([5, 2, 4, 3, 1])) # [0, 2, 3, 4] + print(check_order_tf_cuda([1, 2, 1, 1, 3])) # [1, 3] + print(check_order_tf_cuda([3, 1, 3, 2, 3])) # [0, 1, 3] + print(check_order_tf_fn_cuda([5, 2, 4, 3, 1])) # [0, 2, 3, 4] + print(check_order_tf_fn_cuda([1, 2, 1, 1, 3])) # [1, 3] + print(check_order_tf_fn_cuda([3, 1, 3, 2, 3])) # [0, 1, 3] +else: + print("TensorFlow GPU not available") + +if torch.cuda.is_available(): + print("PyTorch CUDA available") + print(check_order_torch_cuda([5, 2, 4, 3, 1])) # [0, 2, 3, 4] + print(check_order_torch_cuda([1, 2, 1, 1, 3])) # [1, 3] + print(check_order_torch_cuda([3, 1, 3, 2, 3])) # [0, 1, 3] + print(check_order_torch_jit_cuda([5, 2, 4, 3, 1])) # [0, 2, 3, 4] + print(check_order_torch_jit_cuda([1, 2, 1, 1, 3])) # [1, 3] + print(check_order_torch_jit_cuda([3, 1, 3, 2, 3])) # [0, 1, 3] +else: + print("PyTorch CUDA not available") -- cgit From 6706a7a33b611995783292a1e5f677fa7a02aba7 Mon Sep 17 00:00:00 2001 From: Mark Anderson Date: Mon, 27 Oct 2025 05:22:39 +0000 Subject: Challenge 345 Solutions (Raku) --- challenge-345/mark-anderson/raku/ch-1.raku | 47 +++++++++++++++++++++++++ challenge-345/mark-anderson/raku/ch-2.raku | 55 ++++++++++++++++++++++++++++++ 2 files changed, 102 insertions(+) create mode 100644 challenge-345/mark-anderson/raku/ch-1.raku create mode 100644 challenge-345/mark-anderson/raku/ch-2.raku diff --git a/challenge-345/mark-anderson/raku/ch-1.raku b/challenge-345/mark-anderson/raku/ch-1.raku new file mode 100644 index 0000000000..8fba9f428c --- /dev/null +++ b/challenge-345/mark-anderson/raku/ch-1.raku @@ -0,0 +1,47 @@ +#!/usr/bin/env raku +use Test; + +is-deeply peak-positions([<1 3 2>]), (1,); +is-deeply peak-positions([<2 4 6 5 3>]), (2,); +is-deeply peak-positions([<1 2 3 2 4 1>]), (2,4); +is-deeply peak-positions([<5 3 1>]), (0,); +is-deeply peak-positions([<1 5 1 5 1 5 1>]), (1,3,5); + +my @arr = (^100).roll(1000); +is-deeply peak-positions(@arr), peak-positions-alternate(@arr); + +sub peak-positions(@ints) +{ + @ints.unshift(0); + @ints.push(0); + + @ints.pairs + .rotor(3 => -2) + .grep({ .[0].value < .[1].value > .[2].value }) + .map( { .[0].key }) +} + +sub peak-positions-alternate(@ints) +{ + my @histogram; + + @ints.kv.map(-> $k,$v { @histogram[$k] = flat 'x' xx $v, + ' ' xx @ints.max - $v }); + + @histogram = [Z] @histogram; + @histogram .= map(*.Array); + + .sort given gather for @histogram -> @row + { + last if @row.none eq 'x'; + + if @row.join ~~ m:g/<< x >>/ -> @m + { + for @m + { + take .from - 1; + @histogram[*;.from] = ' ' xx * + } + } + } +} diff --git a/challenge-345/mark-anderson/raku/ch-2.raku b/challenge-345/mark-anderson/raku/ch-2.raku new file mode 100644 index 0000000000..100e34e242 --- /dev/null +++ b/challenge-345/mark-anderson/raku/ch-2.raku @@ -0,0 +1,55 @@ +#!/usr/bin/env raku +use v6.e.PREVIEW; +use Test; + +is-deeply last-visitor(<5 -1 -1>), [<5 -1>]; +is-deeply last-visitor(<3 7 -1 -1 -1>), [<7 3 -1>]; +is-deeply last-visitor(<2 -1 4 -1 -1>), [<2 4 2>]; +is-deeply last-visitor(<10 20 -1 30 -1 -1>), [<20 30 20>]; +is-deeply last-visitor(<-1 -1 5 -1>), [<-1 -1 5>]; + +my @arr = (-1 xx 1000, 1..1000).flat.roll(10_000); +is last-visitor(@arr), last-visitor-alternate(@arr); + +sub last-visitor(@ints) +{ + my @ans; + my @seen; + my $seq = flat (@ints.head > 0 ?? (* > 0, * == -1) !! (* == -1, * > 0)) xx *; + my @snip = @ints.snip: $seq; + + @ans.append: @snip.shift.flat if @snip.head.head == -1; + @snip.pop if @snip.tail.tail > 0; + + for @snip -> @pos, @neg-ones + { + @seen.append: @pos; + @ans.append: flat (reverse @seen.tail: @neg-ones), @neg-ones.tail: @neg-ones - @seen + } + + return @ans +} + +sub last-visitor-alternate(@ints) +{ + my $x = 0; + my @seen; + my @ans; + + for @ints -> $i + { + if $i.sign == 1 + { + $x = 0; + @seen.unshift: $i + } + + else + { + @ans.push: @seen[$x] // -1; + $x++ + } + } + + return @ans +} -- cgit From 13256a8339f0e90a9d7ede9fe35c441bbfebde78 Mon Sep 17 00:00:00 2001 From: Mark Anderson Date: Mon, 27 Oct 2025 05:42:25 +0000 Subject: Challenge 345 Solutions (Raku) --- challenge-345/mark-anderson/raku/ch-2.raku | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/challenge-345/mark-anderson/raku/ch-2.raku b/challenge-345/mark-anderson/raku/ch-2.raku index 100e34e242..ad1adfdec5 100644 --- a/challenge-345/mark-anderson/raku/ch-2.raku +++ b/challenge-345/mark-anderson/raku/ch-2.raku @@ -13,12 +13,10 @@ is last-visitor(@arr), last-visitor-alternate(@arr); sub last-visitor(@ints) { - my @ans; my @seen; - my $seq = flat (@ints.head > 0 ?? (* > 0, * == -1) !! (* == -1, * > 0)) xx *; - my @snip = @ints.snip: $seq; + my @snip = @ints.snip: flat (@ints.head > 0 ?? (* > 0, * == -1) !! (* == -1, * > 0)) xx *; - @ans.append: @snip.shift.flat if @snip.head.head == -1; + my @ans.append: @snip.shift.flat if @snip.head.head == -1; @snip.pop if @snip.tail.tail > 0; for @snip -> @pos, @neg-ones -- cgit From b6540fee7037ce9c30bc283e7a2a639e363ee5d4 Mon Sep 17 00:00:00 2001 From: Mark Anderson Date: Mon, 27 Oct 2025 05:46:15 +0000 Subject: Challenge 345 Solutions (Raku) --- challenge-345/mark-anderson/raku/ch-2.raku | 1 - 1 file changed, 1 deletion(-) diff --git a/challenge-345/mark-anderson/raku/ch-2.raku b/challenge-345/mark-anderson/raku/ch-2.raku index ad1adfdec5..0fe34524aa 100644 --- a/challenge-345/mark-anderson/raku/ch-2.raku +++ b/challenge-345/mark-anderson/raku/ch-2.raku @@ -15,7 +15,6 @@ sub last-visitor(@ints) { my @seen; my @snip = @ints.snip: flat (@ints.head > 0 ?? (* > 0, * == -1) !! (* == -1, * > 0)) xx *; - my @ans.append: @snip.shift.flat if @snip.head.head == -1; @snip.pop if @snip.tail.tail > 0; -- cgit From 3f58236c298fe8864fca80aa24481746feeae7aa Mon Sep 17 00:00:00 2001 From: Mark Anderson Date: Mon, 27 Oct 2025 06:01:15 +0000 Subject: Challenge 345 Solutions (Raku) --- challenge-345/mark-anderson/raku/ch-1.raku | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/challenge-345/mark-anderson/raku/ch-1.raku b/challenge-345/mark-anderson/raku/ch-1.raku index 8fba9f428c..cd553461a8 100644 --- a/challenge-345/mark-anderson/raku/ch-1.raku +++ b/challenge-345/mark-anderson/raku/ch-1.raku @@ -25,8 +25,7 @@ sub peak-positions-alternate(@ints) { my @histogram; - @ints.kv.map(-> $k,$v { @histogram[$k] = flat 'x' xx $v, - ' ' xx @ints.max - $v }); + @ints.kv.map(-> $k,$v { @histogram[$k] = flat 'x' xx $v, ' ' xx @ints.max - $v }); @histogram = [Z] @histogram; @histogram .= map(*.Array); -- cgit From 7bb99254c936a0c4b43ecfc95c620b5eb452b305 Mon Sep 17 00:00:00 2001 From: Mark Anderson Date: Mon, 27 Oct 2025 06:25:05 +0000 Subject: Challenge 345 Solutions (Raku) --- challenge-345/mark-anderson/raku/ch-2.raku | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/challenge-345/mark-anderson/raku/ch-2.raku b/challenge-345/mark-anderson/raku/ch-2.raku index 0fe34524aa..21c28efa1b 100644 --- a/challenge-345/mark-anderson/raku/ch-2.raku +++ b/challenge-345/mark-anderson/raku/ch-2.raku @@ -9,7 +9,7 @@ is-deeply last-visitor(<10 20 -1 30 -1 -1>), [<20 30 20>]; is-deeply last-visitor(<-1 -1 5 -1>), [<-1 -1 5>]; my @arr = (-1 xx 1000, 1..1000).flat.roll(10_000); -is last-visitor(@arr), last-visitor-alternate(@arr); +is-deeply last-visitor(@arr), last-visitor-alternate(@arr); sub last-visitor(@ints) { -- cgit From 01be821ef5ccd02011cad0d9927b873300bd6800 Mon Sep 17 00:00:00 2001 From: Andrew Shitov Date: Mon, 27 Oct 2025 09:32:53 +0100 Subject: Task 1 Week 345 in Raku by @ash --- challenge-345/ash/raku/ch-1.raku | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 challenge-345/ash/raku/ch-1.raku diff --git a/challenge-345/ash/raku/ch-1.raku b/challenge-345/ash/raku/ch-1.raku new file mode 100644 index 0000000000..bc53c65653 --- /dev/null +++ b/challenge-345/ash/raku/ch-1.raku @@ -0,0 +1,13 @@ +# Task 1 of the Weekly Challenge 345 +# https://theweeklychallenge.org/blog/perl-weekly-challenge-345/#TASK1 + +say peaks 1, 3, 2; # 1 +say peaks 2, 4, 6, 5, 3; # 2 +say peaks 1, 2, 3, 2, 4, 1; # 2 4 +say peaks 5, 3, 1; # 0 +say peaks 1, 5, 1, 5, 1, 5, 1; # 1 3 5 + +sub peaks(*@data) { + my @indices = 1 .. (@data.elems - 2); + return (@indices.grep: {@data[$_ - 1] < @data[$_] > @data[$_ + 1]}) || (0,); +} -- cgit From 88f043a11896e9eb2f6fa999e7253de0a1d6ca3b Mon Sep 17 00:00:00 2001 From: Andrew Shitov Date: Mon, 27 Oct 2025 09:34:55 +0100 Subject: task 2 --- challenge-345/ash/raku/ch-2.raku | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 challenge-345/ash/raku/ch-2.raku diff --git a/challenge-345/ash/raku/ch-2.raku b/challenge-345/ash/raku/ch-2.raku new file mode 100644 index 0000000000..86db3a5ded --- /dev/null +++ b/challenge-345/ash/raku/ch-2.raku @@ -0,0 +1,34 @@ +# Task 2 of the Weekly Challenge 345 +# https://theweeklychallenge.org/blog/perl-weekly-challenge-345/#TASK2 + +say process 5, -1, -1; # 5 -1 +say process 3, 7, -1, -1, -1; # 7 3 -1 +say process 2, -1, 4, -1, -1; # 2 4 2 +say process 10, 20, -1, 30, -1, -1; # 20 30 20 +say process -1, -1, 5, -1; # -1 -1 5 + +sub process(*@data) { + my @seen; + my @ans; + + my $x = 0; + + for @data -> $val { + if $val > 0 { + @seen.unshift($val); + $x = 0; # this was not clear from the task + } + elsif $val == -1 { + if $x < @seen.elems { + @ans.push(@seen[$x]); + } + else { + @ans.push(-1); + } + + $x++; + } + } + + return @ans; +} -- cgit From 3a0dbfc3827aab88997c27f909f319ec6527fa61 Mon Sep 17 00:00:00 2001 From: Lubos Kolouch Date: Mon, 27 Oct 2025 09:49:55 +0100 Subject: Add lubos-kolouch solutions for challenge 345 --- challenge-345/lubos-kolouch/README | 53 ++++++++++------------ challenge-345/lubos-kolouch/perl/ch-1.pl | 54 ++++++++++++++++++++++ challenge-345/lubos-kolouch/perl/ch-2.pl | 73 ++++++++++++++++++++++++++++++ challenge-345/lubos-kolouch/python/ch-1.py | 62 +++++++++++++++++++++++++ challenge-345/lubos-kolouch/python/ch-2.py | 58 ++++++++++++++++++++++++ 5 files changed, 271 insertions(+), 29 deletions(-) create mode 100644 challenge-345/lubos-kolouch/perl/ch-1.pl create mode 100644 challenge-345/lubos-kolouch/perl/ch-2.pl create mode 100644 challenge-345/lubos-kolouch/python/ch-1.py create mode 100644 challenge-345/lubos-kolouch/python/ch-2.py diff --git a/challenge-345/lubos-kolouch/README b/challenge-345/lubos-kolouch/README index 972fc9e0d2..5b34a3ed40 100644 --- a/challenge-345/lubos-kolouch/README +++ b/challenge-345/lubos-kolouch/README @@ -1,38 +1,33 @@ -# Perl Weekly Challenge Solutions +# Perl Weekly Challenge 345 Solutions -Solutions for Perl Weekly Challenge 344 presented in both Perl and Python. +Perl and Python implementations for both tasks of Weekly Challenge 345. -## Task 1: Array Form Compute +## Task 1: Peak Positions -### Description -Given an integer represented as an array of digits (`@ints`) and another integer (`$x`), add them and return the resulting integer in array form. +Identify every index whose value is strictly greater than its immediate +neighbour(s). Endpoints are considered peaks when they exceed their sole +neighbour. -### Solution -- **Perl (`perl/ch-1.pl`)**: Processes digits from least significant to most significant, maintaining a carry and constructing the resulting digit list. -- **Python (`python/ch-1.py`)**: Mirrors the Perl approach using an iterative carry-based loop to build the new digit array. -- **Examples Covered**: - - `(1, 2, 3, 4) + 12` → `(1, 2, 4, 6)` - - `(2, 7, 4) + 181` → `(4, 5, 5)` - - `(9, 9, 9) + 1` → `(1, 0, 0, 0)` - - `(1, 0, 0, 0, 0) + 9999` → `(1, 9, 9, 9, 9)` - - `(0) + 1000` → `(1, 0, 0, 0)` +- **Perl (`perl/ch-1.pl`)**: Validates the integer list with `Type::Params`, + then performs a single pass comparing each value against the surrounding + entries to collect the peak indices. +- **Python (`python/ch-1.py`)**: Mirrors the linear scan with explicit type + hints and a set of `unittest` cases for the provided examples. -## Task 2: Array Formation +## Task 2: Last Visitor -### Description -Determine if the target array (`@target`) can be formed by concatenating subarrays from `@source` without altering the order inside each subarray, though subarrays themselves may be reordered. +Process a mixed list of positive integers and `-1` markers. Each integer is +stored at the front of a queue, while every `-1` requests the value `x` steps +back in that queue, where `x` counts consecutive `-1` entries. -### Solution -- **Perl (`perl/ch-2.pl`)**: Iterates through the target, greedily matching unused source subarrays based on their leading element and length, marking each subarray as consumed once used. -- **Python (`python/ch-2.py`)**: Utilises the same greedy matching strategy, leveraging Python's iteration constructs for clarity. -- **Examples Covered**: - - `([2,3], [1], [4])` → `(1, 2, 3, 4)` → `true` - - `([1,3], [2,4])` → `(1, 2, 3, 4)` → `false` - - `([9,1], [5,8], [2])` → `(5, 8, 2, 9, 1)` → `true` - - `([1], [3])` → `(1, 2, 3)` → `false` - - `([7,4,6])` → `(7, 4, 6)` → `true` +- **Perl (`perl/ch-2.pl`)**: Maintains the visitor queue with input validation + and tracks the current `-1` run to select the right lookup or `-1` when the + queue is too short. +- **Python (`python/ch-2.py`)**: Provides the same behaviour with typed + functions and unit tests aligned with the specification examples. ## Running the Solutions -- **Perl**: Execute `perl perl/ch-1.pl` or `perl perl/ch-2.pl`. -- **Python**: Execute `python3 python/ch-1.py` or `python3 python/ch-2.py`. -- Each script includes embedded unit tests covering all examples from the task specification. + +- **Perl**: `perl perl/ch-1.pl` or `perl perl/ch-2.pl` +- **Python**: `python3 python/ch-1.py` or `python3 python/ch-2.py` +- Each script runs only the official example cases as unit tests. diff --git a/challenge-345/lubos-kolouch/perl/ch-1.pl b/challenge-345/lubos-kolouch/perl/ch-1.pl new file mode 100644 index 0000000000..0ba4d952a0 --- /dev/null +++ b/challenge-345/lubos-kolouch/perl/ch-1.pl @@ -0,0 +1,54 @@ +#!/usr/bin/env perl +use strict; +use warnings; +use feature qw(signatures state); +no warnings qw(experimental::signatures); +use Type::Params qw(compile); +use Types::Standard qw(ArrayRef Int); +use Test::More; + +=pod + +=head1 PURPOSE + +Identify every peak in the supplied integer array. A peak is any element +that is strictly greater than its immediate neighbours. The first and last +elements are peaks if they are strictly greater than their single neighbour. + +=head1 ALGORITHM + +We validate the input with L to ensure an array reference of +integers. Iterating once over the array, we compare each element with its +left and right neighbours where they exist. Indices meeting the peak +predicate are collected and returned as an array reference. + +=cut + +## no critic (Subroutines::ProhibitSubroutinePrototypes) +sub peak_positions ($ints_ref) { + state $check = compile( ArrayRef [Int] ); + my ($ints) = $check->($ints_ref); + + my @peaks; + for my $idx ( 0 .. $#$ints ) { + my $current = $ints->[$idx]; + my $left = $idx > 0 ? $ints->[ $idx - 1 ] : undef; + my $right = $idx < $#$ints ? $ints->[ $idx + 1 ] : undef; + + next if defined($left) && $current <= $left; + next if defined($right) && $current <= $right; + + push @peaks, $idx; + } + + return \@peaks; +} + +# Example tests provided by the specification. +is_deeply( peak_positions( [ 1, 3, 2 ] ), [1], 'Example 1' ); +is_deeply( peak_positions( [ 2, 4, 6, 5, 3 ] ), [2], 'Example 2' ); +is_deeply( peak_positions( [ 1, 2, 3, 2, 4, 1 ] ), [ 2, 4 ], 'Example 3' ); +is_deeply( peak_positions( [ 5, 3, 1 ] ), [0], 'Example 4' ); +is_deeply( peak_positions( [ 1, 5, 1, 5, 1, 5, 1 ] ), [ 1, 3, 5 ], 'Example 5' ); + +done_testing(); diff --git a/challenge-345/lubos-kolouch/perl/ch-2.pl b/challenge-345/lubos-kolouch/perl/ch-2.pl new file mode 100644 index 0000000000..f1d90f714c --- /dev/null +++ b/challenge-345/lubos-kolouch/perl/ch-2.pl @@ -0,0 +1,73 @@ +#!/usr/bin/env perl +use strict; +use warnings; +use feature qw(signatures state); +no warnings qw(experimental::signatures); +use Type::Params qw(compile); +use Types::Standard qw(ArrayRef Int); +use Test::More; + +=pod + +=head1 PURPOSE + +Simulate the “last visitor” queue defined in the challenge. Positive +integers arriving from left to right are stored with the newest at the front, +and each C<-1> requests the visitor seen C places earlier in that queue, +where C counts consecutive C<-1> values encountered so far. + +=head1 ALGORITHM + +The input array is validated as an array reference of integers. We iterate +through the values maintaining two arrays: + +=over 4 + +=item * +C<@seen> keeps previously encountered positive integers with the newest at +the front. + +=item * +C<@ans> collects the values to return for each C<-1>. + +=back + +Whenever we see a C<-1>, we look up the C-th element in C<@seen> counting +from zero (if present) and append that value to C<@ans>; otherwise we append +C<-1>. Runs of C<-1> values are tracked so the lookup offset increments +within the run, and resets when a positive integer appears. + +=cut + +## no critic (Subroutines::ProhibitSubroutinePrototypes) +sub last_visitor ($ints_ref) { + state $check = compile( ArrayRef [Int] ); + my ($ints) = $check->($ints_ref); + + my @seen; + my @answer; + my $neg_run = 0; + + for my $value (@$ints) { + if ( $value == -1 ) { + my $lookup = $neg_run < @seen ? $seen[$neg_run] : -1; + push @answer, $lookup; + $neg_run++; + next; + } + + unshift @seen, $value; + $neg_run = 0; + } + + return \@answer; +} + +# Example tests provided by the specification. +is_deeply( last_visitor( [ 5, -1, -1 ] ), [ 5, -1 ], 'Example 1' ); +is_deeply( last_visitor( [ 3, 7, -1, -1, -1 ] ), [ 7, 3, -1 ], 'Example 2' ); +is_deeply( last_visitor( [ 2, -1, 4, -1, -1 ] ), [ 2, 4, 2 ], 'Example 3' ); +is_deeply( last_visitor( [ 10, 20, -1, 30, -1, -1 ] ), [ 20, 30, 20 ], 'Example 4' ); +is_deeply( last_visitor( [ -1, -1, 5, -1 ] ), [ -1, -1, 5 ], 'Example 5' ); + +done_testing(); diff --git a/challenge-345/lubos-kolouch/python/ch-1.py b/challenge-345/lubos-kolouch/python/ch-1.py new file mode 100644 index 0000000000..352b18406c --- /dev/null +++ b/challenge-345/lubos-kolouch/python/ch-1.py @@ -0,0 +1,62 @@ +"""Peak Positions Challenge Solution. + +This module implements the Weekly Challenge task that asks for all peak +indices in a sequence of integers. Peaks are elements strictly greater than +neighbours, with the endpoints compared against their single neighbour. +""" + +from collections.abc import Iterable, Sequence +import unittest + + +def peak_positions(ints: Sequence[int]) -> list[int]: + """Return the zero-based indices of every peak in ``ints``. + + Args: + ints: Sequence of integers to analyse. + + Returns: + A list of indices at which the element is strictly greater than its + immediate neighbour(s). + """ + peaks: list[int] = [] + last_index = len(ints) - 1 + + for idx, value in enumerate(ints): + left = ints[idx - 1] if idx > 0 else None + right = ints[idx + 1] if idx < last_index else None + + if left is not None and value <= left: + continue + if right is not None and value <= right: + continue + peaks.append(idx) + + return peaks + + +class PeakPositionsTests(unittest.TestCase): + """Unit tests restricted to the specification examples.""" + + def _assert_example(self, data: Iterable[int], + expected: list[int]) -> None: + self.assertEqual(peak_positions(list(data)), expected) + + def test_example_1(self) -> None: + self._assert_example((1, 3, 2), [1]) + + def test_example_2(self) -> None: + self._assert_example((2, 4, 6, 5, 3), [2]) + + def test_example_3(self) -> None: + self._assert_example((1, 2, 3, 2, 4, 1), [2, 4]) + + def test_example_4(self) -> None: + self._assert_example((5, 3, 1), [0]) + + def test_example_5(self) -> None: + self._assert_example((1, 5, 1, 5, 1, 5, 1), [1, 3, 5]) + + +if __name__ == "__main__": + unittest.main() diff --git a/challenge-345/lubos-kolouch/python/ch-2.py b/challenge-345/lubos-kolouch/python/ch-2.py new file mode 100644 index 0000000000..50877e33a6 --- /dev/null +++ b/challenge-345/lubos-kolouch/python/ch-2.py @@ -0,0 +1,58 @@ +"""Last Visitor Challenge Solution. + +Process a mixed sequence of positive integers and ``-1`` sentinel values to +report, for each ``-1``, which previously seen visitor should be returned. +""" + +from collections.abc import Iterable, Sequence +import unittest + + +def last_visitor(ints: Sequence[int]) -> list[int]: + """Return the lookups requested by ``-1`` entries in ``ints``. + + Positive integers are stored with the newest at index 0. For a run of + ``-1`` values, the ``x``-th ``-1`` retrieves the ``x``-th element of the + stored list (if present) or ``-1`` otherwise. + """ + seen: list[int] = [] + answers: list[int] = [] + neg_run = 0 + + for value in ints: + if value == -1: + answers.append(seen[neg_run] if neg_run < len(seen) else -1) + neg_run += 1 + continue + + seen.insert(0, value) + neg_run = 0 + + return answers + + +class LastVisitorTests(unittest.TestCase): + """Unit tests restricted to the specification examples.""" + + def _assert_example(self, data: Iterable[int], + expected: list[int]) -> None: + self.assertEqual(last_visitor(list(data)), expected) + + def test_example_1(self) -> None: + self._assert_example((5, -1, -1), [5, -1]) + + def test_example_2(self) -> None: + self._assert_example((3, 7, -1, -1, -1), [7, 3, -1]) + + def test_example_3(self) -> None: + self._assert_example((2, -1, 4, -1, -1), [2, 4, 2]) + + def test_example_4(self) -> None: + self._assert_example((10, 20, -1, 30, -1, -1), [20, 30, 20]) + + def test_example_5(self) -> None: + self._assert_example((-1, -1, 5, -1), [-1, -1, 5]) + + +if __name__ == "__main__": + unittest.main() -- cgit From a09ecf8eee4013cad8b8bb1edb43b6db0a87d3e1 Mon Sep 17 00:00:00 2001 From: Ali Date: Mon, 27 Oct 2025 13:52:19 +0330 Subject: TWC345 --- challenge-345/deadmarshal/blog.txt | 1 + challenge-345/deadmarshal/go/ch1.go | 23 ++++++++++ challenge-345/deadmarshal/go/ch2.go | 30 +++++++++++++ challenge-345/deadmarshal/java/Ch1.java | 21 ++++++++++ challenge-345/deadmarshal/java/Ch2.java | 28 +++++++++++++ challenge-345/deadmarshal/modula-3/Ch1/src/Ch1.m3 | 43 +++++++++++++++++++ .../deadmarshal/modula-3/Ch1/src/m3makefile | 4 ++ challenge-345/deadmarshal/modula-3/Ch2/src/Ch2.m3 | 49 ++++++++++++++++++++++ .../deadmarshal/modula-3/Ch2/src/m3makefile | 4 ++ challenge-345/deadmarshal/perl/ch-1.pl | 22 ++++++++++ challenge-345/deadmarshal/perl/ch-2.pl | 28 +++++++++++++ 11 files changed, 253 insertions(+) create mode 100644 challenge-345/deadmarshal/blog.txt create mode 100644 challenge-345/deadmarshal/go/ch1.go create mode 100644 challenge-345/deadmarshal/go/ch2.go create mode 100644 challenge-345/deadmarshal/java/Ch1.java create mode 100644 challenge-345/deadmarshal/java/Ch2.java create mode 100644 challenge-345/deadmarshal/modula-3/Ch1/src/Ch1.m3 create mode 100644 challenge-345/deadmarshal/modula-3/Ch1/src/m3makefile create mode 100644 challenge-345/deadmarshal/modula-3/Ch2/src/Ch2.m3 create mode 100644 challenge-345/deadmarshal/modula-3/Ch2/src/m3makefile create mode 100644 challenge-345/deadmarshal/perl/ch-1.pl create mode 100644 challenge-345/deadmarshal/perl/ch-2.pl diff --git a/challenge-345/deadmarshal/blog.txt b/challenge-345/deadmarshal/blog.txt new file mode 100644 index 0000000000..eeaa7e644f --- /dev/null +++ b/challenge-345/deadmarshal/blog.txt @@ -0,0 +1 @@ +https://deadmarshal.blogspot.com/2025/10/twc345.html diff --git a/challenge-345/deadmarshal/go/ch1.go b/challenge-345/deadmarshal/go/ch1.go new file mode 100644 index 0000000000..8d055ab731 --- /dev/null +++ b/challenge-345/deadmarshal/go/ch1.go @@ -0,0 +1,23 @@ +package main + +import ( + "fmt" +) + +func peakPositions(arr []int) []int { + res := []int{} + for i := 1; i < len(arr)-1; i++ { + if arr[i-1] < arr[i] && arr[i+1] < arr[i] { + res = append(res, i) + } + } + return res +} + +func main() { + fmt.Println(peakPositions([]int{1, 3, 2})) + fmt.Println(peakPositions([]int{2, 4, 6, 5, 3})) + fmt.Println(peakPositions([]int{1, 2, 3, 2, 4, 1})) + fmt.Println(peakPositions([]int{5, 3, 1})) + fmt.Println(peakPositions([]int{1, 5, 1, 5, 1, 5, 1})) +} diff --git a/challenge-345/deadmarshal/go/ch2.go b/challenge-345/deadmarshal/go/ch2.go new file mode 100644 index 0000000000..dae2c9a781 --- /dev/null +++ b/challenge-345/deadmarshal/go/ch2.go @@ -0,0 +1,30 @@ +package main + +import ( + "fmt" +) + +func lastVisitor(arr []int) []int { + res, seen := []int{}, []int{} + k := 0 + for _, e := range arr { + if e != -1 { + seen = append(seen, e) + k = len(seen) + } else if k == 0 { + res = append(res, -1) + } else { + k-- + res = append(res, seen[k]) + } + } + return res +} + +func main() { + fmt.Println(lastVisitor([]int{5, -1, -1})) + fmt.Println(lastVisitor([]int{3, 7, -1, -1, -1})) + fmt.Println(lastVisitor([]int{2, -1, 4, -1, -1})) + fmt.Println(lastVisitor([]int{10, 20, -1, 30, -1, -1})) + fmt.Println(lastVisitor([]int{-1, -1, 5, -1})) +} diff --git a/challenge-345/deadmarshal/java/Ch1.java b/challenge-345/deadmarshal/java/Ch1.java new file mode 100644 index 0000000000..d3012c5f90 --- /dev/null +++ b/challenge-345/deadmarshal/java/Ch1.java @@ -0,0 +1,21 @@ +import java.util.List; +import java.util.ArrayList; + +public class Ch1 { + public static void main(String[] args) { + System.out.println(peak_positions(new int[]{1,3,2})); + System.out.println(peak_positions(new int[]{2,4,6,5,3})); + System.out.println(peak_positions(new int[]{1,2,3,2,4,1})); + System.out.println(peak_positions(new int[]{5,3,1})); + System.out.println(peak_positions(new int[]{1,5,1,5,1,5,1})); + } + + private static List peak_positions(int[] arr) { + List res = new ArrayList<>(); + for(int i = 1; i < arr.length-1; ++i) { + if(arr[i-1] < arr[i] && arr[i+1] < arr[i]) res.add(i); + } + return res; + } +} + diff --git a/challenge-345/deadmarshal/java/Ch2.java b/challenge-345/deadmarshal/java/Ch2.java new file mode 100644 index 0000000000..25c25ff98a --- /dev/null +++ b/challenge-345/deadmarshal/java/Ch2.java @@ -0,0 +1,28 @@ +import java.util.List; +import java.util.LinkedList; +import java.util.ArrayList; + +public class Ch2 { + public static void main(String[] args) { + System.out.println(last_visitor(new int[]{5,-1,-1})); + System.out.println(last_visitor(new int[]{3,7,-1,-1,-1})); + System.out.println(last_visitor(new int[]{2,-1,4,-1,-1})); + System.out.println(last_visitor(new int[]{10,20,-1,30,-1,-1})); + System.out.println(last_visitor(new int[]{-1,-1,5,-1})); + } + + private static List last_visitor(int[] arr) { + List res = new LinkedList(); + List seen = new ArrayList(); + int k = 0; + for(int i =0; i < arr.length; ++i) { + if(arr[i] != -1) { + seen.add(arr[i]); + k = seen.size(); + } + else if(k == 0) res.add(-1); + else res.add(seen.get(--k)); + } + return res; + } +} diff --git a/challenge-345/deadmarshal/modula-3/Ch1/src/Ch1.m3 b/challenge-345/deadmarshal/modula-3/Ch1/src/Ch1.m3 new file mode 100644 index 0000000000..473ff745be --- /dev/null +++ b/challenge-345/deadmarshal/modula-3/Ch1/src/Ch1.m3 @@ -0,0 +1,43 @@ +MODULE Ch1 EXPORTS Main; + +IMPORT SIO,IntSeq; + +VAR + A1 := ARRAY[0..2] OF INTEGER{1,3,2}; + A2 := ARRAY[0..4] OF INTEGER{2,4,6,5,3}; + A3 := ARRAY[0..5] OF INTEGER{1,2,3,2,4,1}; + A4 := ARRAY[0..2] OF INTEGER{5,3,1}; + A5 := ARRAY[0..6] OF INTEGER{1,5,1,5,1,5,1}; + +PROCEDURE PeakPositions(VAR A:ARRAY OF INTEGER):IntSeq.T = + VAR + S := NEW(IntSeq.T).init(NUMBER(A)); + I:INTEGER := 1; + BEGIN + IF NUMBER(A) < 3 THEN RETURN NIL END; + WHILE I < NUMBER(A)-1 DO + IF A[I-1] < A[I] AND A[I+1] < A[I] THEN S.addhi(I) END; + INC(I); + END; + IF S.size() = 0 THEN S.addhi(0) END; + RETURN S + END PeakPositions; + +PROCEDURE PrintSeq(READONLY S:IntSeq.T) = + BEGIN + IF S = NIL OR S.size() = 0 THEN SIO.PutText("[]\n"); RETURN END; + FOR I := 0 TO S.size()-1 DO + SIO.PutInt(S.get(I)); + SIO.PutChar(' ') + END; + SIO.Nl() + END PrintSeq; + +BEGIN + PrintSeq(PeakPositions(A1)); + PrintSeq(PeakPositions(A2)); + PrintSeq(PeakPositions(A3)); + PrintSeq(PeakPositions(A4)); + PrintSeq(PeakPositions(A5)) +END Ch1. + diff --git a/challenge-345/deadmarshal/modula-3/Ch1/src/m3makefile b/challenge-345/deadmarshal/modula-3/Ch1/src/m3makefile new file mode 100644 index 0000000000..643b33d043 --- /dev/null +++ b/challenge-345/deadmarshal/modula-3/Ch1/src/m3makefile @@ -0,0 +1,4 @@ +import("libm3") +import("libsio") +implementation("Ch1") +program("Ch1") diff --git a/challenge-345/deadmarshal/modula-3/Ch2/src/Ch2.m3 b/challenge-345/deadmarshal/modula-3/Ch2/src/Ch2.m3 new file mode 100644 index 0000000000..2cd2cb5560 --- /dev/null +++ b/challenge-345/deadmarshal/modula-3/Ch2/src/Ch2.m3 @@ -0,0 +1,49 @@ +MODULE Ch2 EXPORTS Main; + +IMPORT SIO,IntSeq; + +VAR + A1 := ARRAY[0..2] OF INTEGER{5,-1,-1}; + A2 := ARRAY[0..4] OF INTEGER{3,7,-1,-1,-1}; + A3 := ARRAY[0..4] OF INTEGER{2,-1,4,-1,-1}; + A4 := ARRAY[0..5] OF INTEGER{10,20,-1,30,-1,-1}; + A5 := ARRAY[0..3] OF INTEGER{-1,-1,5,-1}; + +PROCEDURE LastVisitor(VAR A:ARRAY OF INTEGER):IntSeq.T = + VAR + Res := NEW(IntSeq.T).init(NUMBER(A)); + Seen := NEW(IntSeq.T).init(NUMBER(A)); + K := 0; + BEGIN + FOR I := FIRST(A) TO LAST(A) DO + IF A[I] # -1 THEN + Seen.addhi(A[I]); + K := Seen.size() + ELSIF K = 0 THEN + Res.addhi(-1) + ELSE + DEC(K); + Res.addhi(Seen.get(K)) + END + END; + RETURN Res + END LastVisitor; + +PROCEDURE PrintSeq(READONLY S:IntSeq.T) = + BEGIN + IF S = NIL OR S.size() = 0 THEN SIO.PutText("[]\n"); RETURN END; + FOR I := 0 TO S.size()-1 DO + SIO.PutInt(S.get(I)); + SIO.PutChar(' ') + END; + SIO.Nl() + END PrintSeq; + +BEGIN + PrintSeq(LastVisitor(A1)); + PrintSeq(LastVisitor(A2)); + PrintSeq(LastVisitor(A3)); + PrintSeq(LastVisitor(A4)); + PrintSeq(LastVisitor(A5)) +END Ch2. + diff --git a/challenge-345/deadmarshal/modula-3/Ch2/src/m3makefile b/challenge-345/deadmarshal/modula-3/Ch2/src/m3makefile new file mode 100644 index 0000000000..78802242fe --- /dev/null +++ b/challenge-345/deadmarshal/modula-3/Ch2/src/m3makefile @@ -0,0 +1,4 @@ +import("libm3") +import("libsio") +implementation("Ch2") +program("Ch2") diff --git a/challenge-345/deadmarshal/perl/ch-1.pl b/challenge-345/deadmarshal/perl/ch-1.pl new file mode 100644 index 0000000000..a6c90d204a --- /dev/null +++ b/challenge-345/deadmarshal/perl/ch-1.pl @@ -0,0 +1,22 @@ +#!/usr/bin/env perl +use strict; +use warnings; +use Data::Show; + +sub peak_positions{ + my ($arr) = @_; + my @res; + foreach my $i(1..$#$arr) { + if($arr->[$i-1] < $arr->[$i] && $arr->[$i+1] < $arr->[$i]) { + push @res,$i + } + } + @res +} + +show peak_positions([1,3,2]); +show peak_positions([2,4,6,5,3]); +show peak_positions([1,2,3,2,4,1]); +show peak_positions([5,3,1]); +show peak_positions([1,5,1,5,1,5,1]); + diff --git a/challenge-345/deadmarshal/perl/ch-2.pl b/challenge-345/deadmarshal/perl/ch-2.pl new file mode 100644 index 0000000000..18aeb76c47 --- /dev/null +++ b/challenge-345/deadmarshal/perl/ch-2.pl @@ -0,0 +1,28 @@ +#!/usr/bin/env perl +use strict; +use warnings; +use Data::Show; + +sub last_visitor{ + my ($arr) = @_; + my (@res,@seen); + my $k = 0; + foreach my $i(0..$#$arr) { + if($arr->[$i] != -1) { + push @seen,$arr->[$i]; + $k = @seen + } elsif ($k == 0) { + push @res,-1 + } else { + push @res,$seen[--$k] + } + } + @res +} + +show last_visitor([5,-1,-1]); +show last_visitor([3,7,-1,-1,-1]); +show last_visitor([2,-1,4,-1,-1]); +show last_visitor([10,20,-1,30,-1,-1]); +show last_visitor([-1,-1,5,-1]) + -- cgit From 50ce40a6f64d4590fcc54705502fc48d800d1baa Mon Sep 17 00:00:00 2001 From: Mark Anderson Date: Mon, 27 Oct 2025 11:34:18 +0000 Subject: Challenge 345 Solutions (Raku) --- challenge-345/mark-anderson/raku/ch-1.raku | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/challenge-345/mark-anderson/raku/ch-1.raku b/challenge-345/mark-anderson/raku/ch-1.raku index cd553461a8..513e881298 100644 --- a/challenge-345/mark-anderson/raku/ch-1.raku +++ b/challenge-345/mark-anderson/raku/ch-1.raku @@ -12,13 +12,10 @@ is-deeply peak-positions(@arr), peak-positions-alternate(@arr); sub peak-positions(@ints) { - @ints.unshift(0); - @ints.push(0); - - @ints.pairs - .rotor(3 => -2) - .grep({ .[0].value < .[1].value > .[2].value }) - .map( { .[0].key }) + given flat 0, @ints, 0 + { + (^@ints).grep(-> $i { .[$i] < .[$i+1] > .[$i+2] }) + } } sub peak-positions-alternate(@ints) @@ -38,7 +35,7 @@ sub peak-positions-alternate(@ints) { for @m { - take .from - 1; + take .from; @histogram[*;.from] = ' ' xx * } } -- cgit From 3c0e3dade6c5abf197691f46c4315b6426104a65 Mon Sep 17 00:00:00 2001 From: Pok Date: Mon, 27 Oct 2025 20:11:26 +0700 Subject: pwc345 solution in python --- challenge-345/pokgopun/python/ch-1.py | 85 ++++++++++++++++++++++++++++ challenge-345/pokgopun/python/ch-2.py | 101 ++++++++++++++++++++++++++++++++++ 2 files changed, 186 insertions(+) create mode 100644 challenge-345/pokgopun/python/ch-1.py create mode 100644 challenge-345/pokgopun/python/ch-2.py diff --git a/challenge-345/pokgopun/python/ch-1.py b/challenge-345/pokgopun/python/ch-1.py new file mode 100644 index 0000000000..af603b166f --- /dev/null +++ b/challenge-345/pokgopun/python/ch-1.py @@ -0,0 +1,85 @@ +### https://theweeklychallenge.org/blog/perl-weekly-challenge-345/ +""" + +Task 1: Peak Positions + +Submitted by: [43]Mohammad Sajid Anwar + __________________________________________________________________ + + You are given an array of integers, @ints. + + Find all the peaks in the array, a peak is an element that is strictly + greater than its left and right neighbours. Return the indices of all + such peak positions. + +Example 1 + +Input: @ints = (1, 3, 2) +Output: (1) + +Example 2 + +Input: @ints = (2, 4, 6, 5, 3) +Output: (2) + +Example 3 + +Input: @ints = (1, 2, 3, 2, 4, 1) +Output: (2, 4) + +Example 4 + +Input: @ints = (5, 3, 1) +Output: (0) + +Example 5 + +Input: @ints = (1, 5, 1, 5, 1, 5, 1) +Output: (1, 3, 5) + +Task 2: Last Visitor +""" +### solution by pokgopun@gmail.com + +def pp(ints: tuple[int]) -> tuple[int]: + l = len(ints) + if l < 2: + return tuple(range(l)) + i = 0 + p = [] + while i < l: + if i == l - 1: + p.append(i) + break + if ints[i] < ints[i+1]: + i += 1 + continue + if ints[i] > ints[i+1]: + p.append(i) + i += 2 + if i == l - 1 and ints[i] <= ints[i-1]: + break + return tuple(p) + +import unittest + +class TestPp(unittest.TestCase): + def test(self): + for inpt, otpt in { + (1, 3, 2): (1,), + (2, 4, 6, 5, 3): (2,), + (1, 2, 3, 2, 4, 1): (2, 4), + (5, 3, 1): (0,), + (1, 5, 1, 5, 1, 5, 1): (1, 3, 5), + (2, 3, 4): (2,), + (2, 2, 2): (), + (3, 3): (), + (5, 3): (0,), + (5, 7): (1,), + (7,): (0,), + (): (), + }.items(): + #print(inpt,otpt) + self.assertEqual(pp(inpt),otpt) + +unittest.main() diff --git a/challenge-345/pokgopun/python/ch-2.py b/challenge-345/pokgopun/python/ch-2.py new file mode 100644 index 0000000000..dea0ecfc09 --- /dev/null +++ b/challenge-345/pokgopun/python/ch-2.py @@ -0,0 +1,101 @@ +### https://theweeklychallenge.org/blog/perl-weekly-challenge-345/ +""" + +Task 2: Last Visitor + +Submitted by: [44]Mohammad Sajid Anwar + __________________________________________________________________ + + You are given an integer array @ints where each element is either a + positive integer or -1. + + We process the array from left to right while maintaining two lists: +@seen: stores previously seen positive integers (newest at the front) +@ans: stores the answers for each -1 + + Rules: +If $ints[i] is a positive number -> insert it at the front of @seen +If $ints[i] is -1: + + Let $x be how many -1s in a row we’ve seen before this one. + + If $x < len(@seen) -> append seen[x] to @ans + + Else -> append -1 to @ans + + At the end, return @ans. + +Example 1 + +Input: @ints = (5, -1, -1) +Output: (5, -1) + +@seen = (5) +First -1: @ans = (5) +Second -1: @ans = (5, -1) + +Example 2 + +Input: @ints = (3, 7, -1, -1, -1) +Output: (7, 3, -1) + +@seen = (3, 7) +First -1: @ans = (7) +Second -1: @ans = (7, 3) +Third -1: @ans = (7, 3, -1) + +Example 3 + +Input: @ints = (2, -1, 4, -1, -1) +Output: (2, 4, 2) + +Example 4 + +Input: @ints = (10, 20, -1, 30, -1, -1) +Output: (20, 30, 20) + +Example 5 + +Input: @ints = (-1, -1, 5, -1) +Output: (-1, -1, 5) + __________________________________________________________________ + + Last date to submit the solution 23:59 (UK Time) Sunday 2nd November + 2025. + __________________________________________________________________ + +SO WHAT DO YOU THINK ? +""" +### solution by pokgopun@gmail.com + +def lv(ints: tuple[int]) -> tuple[int]: + seen = list() + ans = list() + x = 0 + for v in ints: + if v == -1: + if x < len(seen): + ans.append(seen[x]) + else: + ans.append(-1) + x += 1 + else: + x = 0 + seen.insert(0, v) + #print(f'v => {v}, seen => {seen}, ans => {ans}, x = {x}') + return tuple(ans) + +import unittest + +class TestLv(unittest.TestCase): + def test(self): + for inpt, otpt in { + (5, -1, -1): (5, -1), + (3, 7, -1, -1, -1): (7, 3, -1), + (2, -1, 4, -1, -1): (2, 4, 2), + (10, 20, -1, 30, -1, -1): (20, 30, 20), + (-1, -1, 5, -1): (-1, -1, 5), + }.items(): + self.assertEqual(lv(inpt), otpt) + +unittest.main() -- cgit From f6b775ceb35655572866795941576db2040d12b9 Mon Sep 17 00:00:00 2001 From: Andreas Mahnke Date: Mon, 27 Oct 2025 15:00:04 +0100 Subject: Challenge 345 --- challenge-345/mahnkong/perl/ch-1.pl | 20 ++++++++++++++++++++ challenge-345/mahnkong/perl/ch-2.pl | 28 ++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 challenge-345/mahnkong/perl/ch-1.pl create mode 100644 challenge-345/mahnkong/perl/ch-2.pl diff --git a/challenge-345/mahnkong/perl/ch-1.pl b/challenge-345/mahnkong/perl/ch-1.pl new file mode 100644 index 0000000000..6f43d7438d --- /dev/null +++ b/challenge-345/mahnkong/perl/ch-1.pl @@ -0,0 +1,20 @@ +use strict; +use warnings; +use feature 'signatures'; +use Test::More 'no_plan'; + +sub run(@ints) { + my @peaks; + for (my $i = 0; $i < scalar(@ints); $i++) { + if ((! exists $ints[$i-1] || $ints[$i] > $ints[$i-1]) && (! exists $ints[$i+1] || $ints[$i] > $ints[$i+1])) { + push @peaks, $i; + } + } + return [ @peaks ]; +} + +is_deeply(run(1,3,2), [1], "Example 1"); +is_deeply(run(2,4,6,5,3), [2], "Example 2"); +is_deeply(run(1,2,3,2,4,1), [2,4], "Example 3"); +is_deeply(run(5,3,1), [0], "Example 4"); +is_deeply(run(1,5,1,5,1,5,1), [1,3,5], "Example 5"); diff --git a/challenge-345/mahnkong/perl/ch-2.pl b/challenge-345/mahnkong/perl/ch-2.pl new file mode 100644 index 0000000000..c3bd2ae793 --- /dev/null +++ b/challenge-345/mahnkong/perl/ch-2.pl @@ -0,0 +1,28 @@ +use strict; +use warnings; +use feature 'signatures'; +use Test::More 'no_plan'; + +sub run(@ints) { + my @seen; + my @ans; + my $streak = 0; + + foreach my $int (@ints) { + if ($int == -1) { + push @ans, $streak < scalar(@seen) ? $seen[$streak] : -1; + $streak += 1; + } else { + unshift @seen, $int if $int > 0; + $streak = 0; + } + } + + return [ @ans ]; +} + +is_deeply(run(5, -1, -1), [5, -1], "Example 1"); +is_deeply(run(3, 7, -1, -1, -1), [7, 3, -1], "Example 2"); +is_deeply(run(2, -1, 4, -1, -1), [2, 4, 2], "Example 3"); +is_deeply(run(10, 20, -1, 30, -1, -1), [20, 30, 20], "Example 4"); +is_deeply(run(-1, -1, 5, -1), [-1, -1, 5], "Example 5"); -- cgit From 7c0bca87cde4d66f357f42a9388d82166d8f9568 Mon Sep 17 00:00:00 2001 From: Peter Campbell Smith Date: Mon, 27 Oct 2025 14:19:15 +0000 Subject: Week 345 - Peak at the answers --- challenge-345/peter-campbell-smith/blog.txt | 1 + challenge-345/peter-campbell-smith/perl/ch-1.pl | 36 +++++++++++++++++ challenge-345/peter-campbell-smith/perl/ch-2.pl | 52 +++++++++++++++++++++++++ 3 files changed, 89 insertions(+) create mode 100644 challenge-345/peter-campbell-smith/blog.txt create mode 100755 challenge-345/peter-campbell-smith/perl/ch-1.pl create mode 100755 challenge-345/peter-campbell-smith/perl/ch-2.pl diff --git a/challenge-345/peter-campbell-smith/blog.txt b/challenge-345/peter-campbell-smith/blog.txt new file mode 100644 index 0000000000..1800695822 --- /dev/null +++ b/challenge-345/peter-campbell-smith/blog.txt @@ -0,0 +1 @@ +http://ccgi.campbellsmiths.force9.co.uk/challenge/345 diff --git a/challenge-345/peter-campbell-smith/perl/ch-1.pl b/challenge-345/peter-campbell-smith/perl/ch-1.pl new file mode 100755 index 0000000000..01f705f5cb --- /dev/null +++ b/challenge-345/peter-campbell-smith/perl/ch-1.pl @@ -0,0 +1,36 @@ +#!/usr/bin/perl + +# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge + +use v5.26; # The Weekly Challenge - 2025-10-27 +use utf8; # Week 345 - task 1 - Peak positions +use warnings; # Peter Campbell Smith +binmode STDOUT, ':utf8'; +use Encode; + +peak_positions(1, 2, 3, 2, 1); +peak_positions(1, 2, 3, 4, 5); +peak_positions(3, 3, 3, 3, 3); +peak_positions(3, 2, 1, 2, 3); +peak_positions(1, 2, 1, 3, 1, 4, 1, 6, 1); +peak_positions(1, 2); +peak_positions(-3, -2, -4, 0, 9, -100); + +sub peak_positions { + + my (@ints, @peaks, $j); + + # initialise + @ints = @_; + + # do as instructed + if ($#ints > 2) { + for $j (1 .. $#ints - 1) { + push @peaks, $j if ($ints[$j] > $ints[$j - 1] + and $ints[$j] > $ints[$j + 1]); + } + } + + say qq[\nInput: (] . join(', ', @ints) . ')'; + say qq[Output: (] . join(', ', @peaks) . ')'; +} diff --git a/challenge-345/peter-campbell-smith/perl/ch-2.pl b/challenge-345/peter-campbell-smith/perl/ch-2.pl new file mode 100755 index 0000000000..2f822e28b7 --- /dev/null +++ b/challenge-345/peter-campbell-smith/perl/ch-2.pl @@ -0,0 +1,52 @@ +#!/usr/bin/perl + +# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge + +use v5.26; # The Weekly Challenge - 2025-10-27 +use utf8; # Week 345 - task 2 - Last visitor +use warnings; # Peter Campbell Smith +binmode STDOUT, ':utf8'; +use Encode; + +last_visitor(5, -1, -1); +last_visitor(3, 7, -1, -1, -1); +last_visitor(2, -1, 4, -1, -1); +last_visitor(10, 20, -1, 30, -1, -1); +last_visitor(-1, -1, 5, -1); + +sub last_visitor { + + my (@ints, @ans, @seen, $i, $x); + + # initialise + @ints = @_; + $x = 0; + + for $i (0 .. $#ints) { + + # if $ints[i] is +ve push it onto @seen + if ($ints[$i] > 0) { + push @seen, $ints[$i]; + $x = 0; + + # if $ints[$i] is -1 ... + } elsif ($ints[$i] == -1) { + + # ... and $x <= length of @seen + if ($x <= $#seen) { + + # push $x'th from last element of @seen onto @ans + push @ans, $seen[$#seen - $x]; + } else { + + # else push -1 onto @ans + push @ans, -1; + } + + # increment no of consecutive -1s + $x ++; + } + } + say qq[\nInput: (] . join(', ', @ints) . ')'; + say qq[Output: (] . join(', ', @ans) . ')'; +} -- cgit From abe996e9ac2cb8caef4b993c2135a7f0d14bf455 Mon Sep 17 00:00:00 2001 From: Mohammad Sajid Anwar Date: Mon, 27 Oct 2025 14:35:15 +0000 Subject: - Added solutions by Eric Cheung. - Added solutions by Mark Anderson. - Added solutions by Lubos Kolouch. - Added solutions by Ali Moradi. - Added solutions by Feng Chang. - Added solutions by Andreas Mahnke. - Added solutions by Peter Campbell Smith. --- challenge-345/eric-cheung/python/ch-1.py | 23 ++ challenge-345/eric-cheung/python/ch-2.py | 25 ++ stats/pwc-challenge-344.json | 623 ++++++++++++++++++++++++++++++ stats/pwc-current.json | 493 +---------------------- stats/pwc-language-breakdown-2019.json | 2 +- stats/pwc-language-breakdown-2020.json | 2 +- stats/pwc-language-breakdown-2021.json | 2 +- stats/pwc-language-breakdown-2022.json | 2 +- stats/pwc-language-breakdown-2023.json | 2 +- stats/pwc-language-breakdown-2024.json | 2 +- stats/pwc-language-breakdown-2025.json | 25 +- stats/pwc-language-breakdown-summary.json | 8 +- stats/pwc-leaders.json | 26 +- stats/pwc-summary-1-30.json | 8 +- stats/pwc-summary-121-150.json | 2 +- stats/pwc-summary-151-180.json | 6 +- stats/pwc-summary-181-210.json | 2 +- stats/pwc-summary-211-240.json | 6 +- stats/pwc-summary-241-270.json | 2 +- stats/pwc-summary-271-300.json | 2 +- stats/pwc-summary-301-330.json | 2 +- stats/pwc-summary-31-60.json | 4 +- stats/pwc-summary-61-90.json | 4 +- stats/pwc-summary-91-120.json | 2 +- stats/pwc-summary.json | 20 +- stats/pwc-yearly-language-summary.json | 10 +- 26 files changed, 761 insertions(+), 544 deletions(-) create mode 100755 challenge-345/eric-cheung/python/ch-1.py create mode 100755 challenge-345/eric-cheung/python/ch-2.py create mode 100644 stats/pwc-challenge-344.json diff --git a/challenge-345/eric-cheung/python/ch-1.py b/challenge-345/eric-cheung/python/ch-1.py new file mode 100755 index 0000000000..fffcde2be1 --- /dev/null +++ b/challenge-345/eric-cheung/python/ch-1.py @@ -0,0 +1,23 @@ + +## arrInts = [1, 3, 2] ## Example 1 +## arrInts = [2, 4, 6, 5, 3] ## Example 2 +## arrInts = [1, 2, 3, 2, 4, 1] ## Example 3 +## arrInts = [5, 3, 1] ## Example 4 +arrInts = [1, 5, 1, 5, 1, 5, 1] ## Example 5 + +arrOutput = [] + +for nIndx, nElem in enumerate(arrInts): + bIsPeak = False + + if nIndx == 0 and nElem > arrInts[nIndx + 1]: + bIsPeak = True + elif nIndx == len(arrInts) - 1 and nElem > arrInts[nIndx - 1]: + bIsPeak = True + elif nElem > arrInts[nIndx - 1] and nElem > arrInts[nIndx + 1]: + bIsPeak = True + + if bIsPeak: + arrOutput.append(nIndx) + +print (arrOutput) diff --git a/challenge-345/eric-cheung/python/ch-2.py b/challenge-345/eric-cheung/python/ch-2.py new file mode 100755 index 0000000000..5a4b728ca3 --- /dev/null +++ b/challenge-345/eric-cheung/python/ch-2.py @@ -0,0 +1,25 @@ + +## Ref.: +## https://leetcode.com/problems/last-visited-integers/description/ + +## arrInts = [5, -1, -1] ## Example 1 +## arrInts = [3, 7, -1, -1, -1] ## Example 2 +## arrInts = [2, -1, 4, -1, -1] ## Example 3 +## arrInts = [10, 20, -1, 30, -1, -1] ## Example 4 +## arrInts = [-1, -1, 5, -1] ## Example 5 + +## arrInts = [1, 2, -1, -1, -1] ## Example 6 +arrInts = [1, -1, 2, -1, -1] ## Example 7 + +arrSeen = [] +arrAns = [] +arrMinusOne = [] + +for nElem in arrInts: + if nElem > 0: + arrSeen.insert(0, nElem) + else: + arrAns.append(arrSeen[len(arrMinusOne)] if len(arrMinusOne) < len(arrSeen) else nElem) + arrMinusOne.append(nElem) + +print (arrAns) diff --git a/stats/pwc-challenge-344.json b/stats/pwc-challenge-344.json new file mode 100644 index 0000000000..d0d6fdccb6 --- /dev/null +++ b/stats/pwc-challenge-344.json @@ -0,0 +1,623 @@ +{ + "chart" : { + "type" : "column" + }, + "drilldown" : { + "series" : [ + { + "data" : [ + [ + "Blog", + 1 + ] + ], + "id" : "Ali Moradi", + "name" : "Ali Moradi" + }, + { + "data" : [ + [ + "Perl", + 2 + ] + ], + "id" : "Andreas Mahnke", + "name" : "Andreas Mahnke" + }, + { + "data" : [ + [ + "Raku", + 2 + ] + ], + "id" : "Andrew Shitov", + "name" : "Andrew Shitov" + }, + { + "data" : [ + [ + "Raku", + 2 + ], + [ + "Blog", + 1 + ] + ], + "id" : "Arne Sommer", + "name" : "Arne Sommer" + }, + { + "data" : [ + [ + "Raku", + 1 + ] + ], + "id" : "Asher Harvey-Smith", + "name" : "Asher Harvey-Smith" + }, + { + "data" : [ + [ + "Perl", + 2 + ], + [ + "Raku", + 2 + ] + ], + "id" : "Athanasius", + "name" : "Athanasius" + }, + { + "data" : [ + [ + "Raku", + 1 + ] + ], + "id" : "BarrOff", + "name" : "BarrOff" + }, + { + "data" : [ + [ + "Perl", + 2 + ], + [ + "Blog", + 1 + ] + ], + "id" : "Bob Lied", + "name" : "Bob Lied" + }, + { + "data" : [ + [ + "Perl", + 2 + ] + ], + "id" : "David Ferrone", + "name" : "David Ferrone" + }, + { + "data" : [ + [ + "Perl", + 2 + ] + ], + "id" : "E. Choroba", + "name" : "E. Choroba" + }, + { + "data" : [ + [ + "Raku", + 2 + ] + ], + "id" : "Feng Chang", + "name" : "Feng Chang" + }, + { + "data" : [ + [ + "Perl", + 2 + ], + [ + "Raku", + 2 + ], + [ + "Blog", + 1 + ] + ], + "id" : "Jaldhar H. Vyas", + "name" : "Jaldhar H. Vyas" + }, + { + "data" : [ + [ + "Raku", + 1 + ] + ], + "id" : "Jan Krnavek", + "name" : "Jan Krnavek" + }, + { + "data" : [ + [ + "Perl", + 2 + ], + [ + "Blog", + 1 + ] + ], + "id" : "Jorg Sommrey", + "name" : "Jorg Sommrey" + }, + { + "data" : [ + [ + "Perl", + 2 + ] + ], + "id" : "Lubos Kolouch", + "name" : "Lubos Kolouch" + }, + { + "data" : [ + [ + "Raku", + 2 + ], + [ + "Blog", + 2 + ] + ], + "id" : "Luca Ferrari", + "name" : "Luca Ferrari" + }, + { + "data" : [ + [ + "Raku", + 2 + ] + ], + "id" : "Mark Anderson", + "name" : "Mark Anderson" + }, + { + "data" : [ + [ + "Perl", + 2 + ] + ], + "id" : "Matthew Neleigh", + "name" : "Matthew Neleigh" + }, + { + "data" : [ + [ + "Perl", + 2 + ], + [ + "Blog", + 1 + ] + ], + "id" : "Matthias Muth", + "name" : "Matthias Muth" + }, + { + "data" : [ + [ + "Perl", + 1 + ], + [ + "Raku", + 1 + ] + ], + "id" : "Mohammad Sajid Anwar", + "name" : "Mohammad Sajid Anwar" + }, + { + "data" : [ + [ + "Perl", + 2 + ] + ], + "id" : "Niels van Dijke", + "name" : "Niels van Dijke" + }, + { + "data" : [ + [ + "Perl", + 2 + ], + [ + "Raku", + 2 + ], + [ + "Blog", + 1 + ] + ], + "id" : "Packy Anderson", + "name" : "Packy Anderson" + }, + { + "data" : [ + [ + "Perl", + 2 + ], + [ + "Blog", + 1 + ] + ], + "id" : "Peter Campbell Smith", + "name" : "Peter Campbell Smith" + }, + { + "data" : [ + [ + "Perl", + 2 + ] + ], + "id" : "Peter Meszaros", + "name" : "Peter Meszaros" + }, + { + "data" : [ + [ + "Perl", + 2 + ], + [ + "Blog", + 1 + ] + ], + "id" : "Robbie Hatley", + "name" : "Robbie Hatley" + }, + { + "data" : [ + [ + "Raku", + 2 + ] + ], + "id" : "Robert Ransbottom", + "name" : "Robert Ransbottom" + }, + { + "data" : [ + [ + "Perl", + 2 + ], + [ + "Blog", + 1 + ] + ], + "id" : "Roger Bell_West", + "name" : "Roger Bell_West" + }, + { + "data" : [ + [ + "Perl", + 2 + ], + [ + "Blog", + 1 + ] + ], + "id" : "Simon Green", + "name" : "Simon Green" + }, + { + "data" : [ + [ + "Perl", + 2 + ], + [ + "Blog", + 2 + ] + ], + "id" : "Thomas Kohler", + "name" : "Thomas Kohler" + }, + { + "data" : [ + [ + "Perl", + 2 + ], + [ + "Raku", + 2 + ] + ], + "id" : "Ulrich Rieke", + "name" : "Ulrich Rieke" + }, + { + "data" : [ + [ + "Perl", + 2 + ], + [ + "Raku", + 1 + ], + [ + "Blog", + 1 + ] + ], + "id" : "Vinod Kumar K", + "name" : "Vinod Kumar K" + }, + { + "data" : [ + [ + "Perl", + 2 + ], + [ + "Blog", + 1 + ] + ], + "id" : "W. Luis Mochan", + "name" : "W. Luis Mochan" + }, + { + "data" : [ + [ + "Perl", + 2 + ] + ], + "id" : "Wanderdoc", + "name" : "Wanderdoc" + } + ] + }, + "legend" : { + "enabled" : 0 + }, + "plotOptions" : { + "series" : { + "borderWidth" : 0, + "dataLabels" : { + "enabled" : 1, + "format" : "{point.y}" + } + } + }, + "series" : [ + { + "colorByPoint" : 1, + "data" : [ + { + "drilldown" : "Ali Moradi", + "name" : "Ali Moradi", + "y" : 1 + }, + { + "drilldown" : "Andreas Mahnke", + "name" : "Andreas Mahnke", + "y" : 2 + }, + { + "drilldown" : "Andrew Shitov", + "name" : "Andrew Shitov", +