aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--challenge-248/barroff/perl/ch-1.pl40
-rw-r--r--challenge-248/barroff/raku/ch-1.p634
2 files changed, 74 insertions, 0 deletions
diff --git a/challenge-248/barroff/perl/ch-1.pl b/challenge-248/barroff/perl/ch-1.pl
new file mode 100644
index 0000000000..b9868b1df6
--- /dev/null
+++ b/challenge-248/barroff/perl/ch-1.pl
@@ -0,0 +1,40 @@
+#!/usr/bin/env perl
+
+use v5.38;
+
+sub minimal_distance ( $start, @positions ) {
+ use List::Util qw / min /;
+ min( map( { abs( $start - $_ ) } @positions ) );
+}
+
+sub shortest_distance ( $str, $char ) {
+ my @split_str = split( //, $str );
+ my %indices;
+ $indices{$_}++ for grep( { $split_str[$_] eq $char } 0 .. $#split_str );
+ return () unless %indices;
+ my @result =
+ map( { exists $indices{$_} ? 0 : minimal_distance( $_, keys %indices ) }
+ 0 .. $#split_str );
+ return \@result;
+}
+
+sub MAIN() {
+ if (@ARGV) {
+
+ #| Run on command line argument
+ say shortest_distance( $ARGV[0], @ARGV[ 1 .. -1 ] );
+ }
+ else {
+ #| Run test cases
+ use Test2::V0 qw( is plan );
+ plan 2;
+
+ is shortest_distance( 'loveleetcode', 'e' ),
+ [ 3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0 ],
+ "works for ('loveleetcode', 'e')";
+ is shortest_distance( 'aaab', 'b' ), [ 3, 2, 1, 0 ],
+ "works for ('aaab', 'b')";
+ }
+}
+
+MAIN();
diff --git a/challenge-248/barroff/raku/ch-1.p6 b/challenge-248/barroff/raku/ch-1.p6
new file mode 100644
index 0000000000..2d741d95dd
--- /dev/null
+++ b/challenge-248/barroff/raku/ch-1.p6
@@ -0,0 +1,34 @@
+#!/usr/bin/env raku
+
+use v6.d;
+
+sub minimal-distance(Int:D $start, @positions --> Int:D) {
+ min(map({ abs($start - $_) }, @positions));
+}
+
+sub sd(Str:D $str, Str:D $char where $char.chars == 1 --> List) {
+ my @indices = $str.indices($char);
+ # return empty list if string does not contain searched character
+ return () unless @indices;
+ map({ $_ (elem) @indices
+ ?? 0 # index is character
+ !! minimal-distance($_, @indices) # find closest index
+ }, 0..$str.chars - 1
+ ).list;
+}
+
+#| Run test cases
+multi sub MAIN('test') {
+ use Test;
+ plan 2;
+
+ is sd('loveleetcode', 'e'), [3,2,1,0,1,0,0,1,2,2,1,0],
+ 'works for "e" in "loveleetcode"';
+ is sd('aaab', 'b'), [3, 2, 1, 0],
+ 'works for "b" in "aaab"';
+}
+
+#| Take user provided list like aba aabb abcd bac aabc
+multi sub MAIN(Str:D $str, Str:D $char) {
+ say sd($str, $char);
+}