aboutsummaryrefslogtreecommitdiff
path: root/challenge-074
diff options
context:
space:
mode:
Diffstat (limited to 'challenge-074')
-rw-r--r--challenge-074/brtastic/perl/ch-1.pl31
-rw-r--r--challenge-074/brtastic/perl/ch-2.pl43
2 files changed, 74 insertions, 0 deletions
diff --git a/challenge-074/brtastic/perl/ch-1.pl b/challenge-074/brtastic/perl/ch-1.pl
new file mode 100644
index 0000000000..015c803bc6
--- /dev/null
+++ b/challenge-074/brtastic/perl/ch-1.pl
@@ -0,0 +1,31 @@
+use v5.30;
+use warnings;
+
+# the solution is based on my own module Quantum::Superpositions::Lazy from CPAN
+use Quantum::Superpositions::Lazy;
+
+sub get_majority
+{
+ # a superposition will automate all the counting for us
+ my $list = superpos(@_);
+
+ # superpositions have a built in statistics module
+ my $majority = $list->stats->most_probable;
+
+ # majority is actually a new superposition, it can have multiple states
+ return -1 if $majority->states->@* != 1;
+
+ # we now know that this element is certainly a majority, but does it have a proper weight?
+ my $state = $majority->states->[0];
+ return $state->weight > 0.5 ? $state->value : -1;
+}
+
+use Test::More;
+
+is get_majority(1, 1, 1, 2), 1;
+is get_majority(1, 1, 2, 2), -1;
+is get_majority(1, 1, 2, 2, 2), 2;
+is get_majority(1, 2, 3, 4), -1;
+is get_majority(6), 6;
+
+done_testing;
diff --git a/challenge-074/brtastic/perl/ch-2.pl b/challenge-074/brtastic/perl/ch-2.pl
new file mode 100644
index 0000000000..9464f0b80e
--- /dev/null
+++ b/challenge-074/brtastic/perl/ch-2.pl
@@ -0,0 +1,43 @@
+use v5.30;
+use warnings;
+use List::Util qw(first);
+
+# the solution is based on my own module Quantum::Superpositions::Lazy from CPAN
+use Quantum::Superpositions::Lazy;
+
+sub first_non_repeating
+{
+ my sub find_fnt
+ {
+ my @split = split "", shift;
+
+ # a superposition will automate some of the counting for us
+ my $split_pos = superpos(@split);
+
+ # the default weight for an element is 1, and weights are merged by values
+ my @non_repeating = grep { $_->weight == 1 } $split_pos->states->@*;
+
+ return "#" if @non_repeating == 0;
+ return (shift @non_repeating)->value if @non_repeating == 1;
+
+ # since we have a couple of non-repeating characters, we get the first one
+ # (the superposition here helps so that we solve this by a simple eq)
+ my $alternatives = superpos(map { $_->value } @non_repeating);
+ return first { $_ eq $alternatives } @split;
+ }
+
+ my ($string) = @_;
+ my $result = "";
+ for (1 .. length $string) {
+ $result .= find_fnt(substr $string, 0, $_);
+ }
+ return $result;
+}
+
+use Test::More;
+
+is first_non_repeating("ababc"), "aab#c";
+is first_non_repeating("xyzzyx"), "xxxxx#";
+is first_non_repeating("geeksforgeeksandgeeksquizfor"), "ggggggggkkksfffffffffffffora";
+
+done_testing;