aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--challenge-346/sgreen/README.md4
-rw-r--r--challenge-346/sgreen/blog.txt1
-rwxr-xr-xchallenge-346/sgreen/perl/ch-1.pl42
-rwxr-xr-xchallenge-346/sgreen/perl/ch-2.pl45
-rwxr-xr-xchallenge-346/sgreen/python/ch-1.py53
-rwxr-xr-xchallenge-346/sgreen/python/ch-2.py51
-rwxr-xr-xchallenge-346/sgreen/python/test.py28
7 files changed, 222 insertions, 2 deletions
diff --git a/challenge-346/sgreen/README.md b/challenge-346/sgreen/README.md
index 38d33ba9fb..4cc0150d80 100644
--- a/challenge-346/sgreen/README.md
+++ b/challenge-346/sgreen/README.md
@@ -1,3 +1,3 @@
-# The Weekly Challenge 345
+# The Weekly Challenge 346
-Blog: [Peak Visitors](https://dev.to/simongreennet/weekly-challenge-peak-visitors-3lei)
+Blog: [Longest Expression](https://dev.to/simongreennet/weekly-challenge-longest-expression-b8b)
diff --git a/challenge-346/sgreen/blog.txt b/challenge-346/sgreen/blog.txt
new file mode 100644
index 0000000000..cc51888601
--- /dev/null
+++ b/challenge-346/sgreen/blog.txt
@@ -0,0 +1 @@
+https://dev.to/simongreennet/weekly-challenge-longest-expression-b8b \ No newline at end of file
diff --git a/challenge-346/sgreen/perl/ch-1.pl b/challenge-346/sgreen/perl/ch-1.pl
new file mode 100755
index 0000000000..b1d0506fcc
--- /dev/null
+++ b/challenge-346/sgreen/perl/ch-1.pl
@@ -0,0 +1,42 @@
+#!/usr/bin/env perl
+
+use strict;
+use warnings;
+use feature 'say';
+use experimental 'signatures';
+
+sub is_balanced ($s) {
+ my $count = 0;
+ foreach my $char ( split //, $s ) {
+ if ( $char eq '(' ) {
+ $count++;
+ }
+ elsif ( $char eq ')' ) {
+ $count--;
+ return 0 if $count < 0;
+ }
+ }
+ return $count == 0;
+}
+
+sub main ($input_string) {
+ # Check the input string is only parentheses
+ if ( $input_string !~ /^[()]+$/ ) {
+ die "Input string must contain only parentheses '()'\n";
+ }
+
+ for ( my $len = length($input_string) ; $len > 1 ; $len-- ) {
+ foreach my $start ( 0 .. length($input_string) - $len ) {
+ my $substring = substr( $input_string, $start, $len );
+ if ( is_balanced($substring) ) {
+ say $len;
+ return;
+ }
+ }
+ }
+
+ say 0;
+
+}
+
+main( $ARGV[0] );
diff --git a/challenge-346/sgreen/perl/ch-2.pl b/challenge-346/sgreen/perl/ch-2.pl
new file mode 100755
index 0000000000..df849369a5
--- /dev/null
+++ b/challenge-346/sgreen/perl/ch-2.pl
@@ -0,0 +1,45 @@
+#!/usr/bin/env perl
+
+use strict;
+use warnings;
+use feature 'say';
+use experimental 'signatures';
+
+use Algorithm::Combinatorics 'variations_with_repetition';
+use List::Util 'mesh';
+
+sub main ( $input_string, $target ) {
+ # Check the input string is only parentheses
+ if ( $input_string !~ /^[0-9]+$/ ) {
+ die "Input string must contain only digits\n";
+ }
+ my @input_digits = split //, $input_string;
+
+ # Possible operators to insert between digits
+ my @operators = ( '', '+', '-', '*' );
+
+ my @magic_expressions = ();
+
+ my $iter =
+ variations_with_repetition( \@operators, length($input_string) - 1 );
+ while ( my $ops = $iter->next ) {
+ my $expression = join( "", mesh( \@input_digits, [@$ops, ''] ) );
+
+ if ( $expression =~ /[\+\-\*]0\d/ ) {
+ # Skip expressions with leading zeros
+ next;
+ }
+ if ( eval($expression) == $target ) {
+ push @magic_expressions, $expression;
+ }
+ }
+
+ if ( $#magic_expressions == -1 ) {
+ say "No expressions found";
+ }
+ else {
+ say '("' . join( '", "', @magic_expressions ) . '")';
+ }
+}
+
+main( $ARGV[0], $ARGV[1] );
diff --git a/challenge-346/sgreen/python/ch-1.py b/challenge-346/sgreen/python/ch-1.py
new file mode 100755
index 0000000000..c755993dbf
--- /dev/null
+++ b/challenge-346/sgreen/python/ch-1.py
@@ -0,0 +1,53 @@
+#!/usr/bin/env python3
+
+import re
+import sys
+
+
+def is_balanced(s: str) -> bool:
+ """Check if a string of parentheses is balanced.
+
+ Args:
+ s (str): A string consisting of '(' and ')'.
+
+ Returns:
+ bool: True if the string is balanced, False otherwise.
+ """
+ count = 0
+ for char in s:
+ if char == '(':
+ count += 1
+ elif char == ')':
+ if count == 0:
+ return False
+ count -= 1
+ return count == 0
+
+def longest_parenthesis(input_string: str) -> int:
+ """Return the length of the longest balanced parentheses substring.
+
+ Args:
+ input_string (str): A string consisting of '(' and ')'.
+
+ Returns:
+ int: Length of the longest balanced parentheses substring.
+ """
+ # Check the input string is only parentheses
+ if not re.search(r'^[()]+$', input_string):
+ raise ValueError("Input string must contain only parentheses")
+
+ for length in range(len(input_string), 1, -1):
+ for start in range(len(input_string) - length + 1):
+ substring = input_string[start:start + length]
+ if is_balanced(substring):
+ return length
+
+ return 0
+
+def main():
+ result = longest_parenthesis(sys.argv[1])
+ print(result)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/challenge-346/sgreen/python/ch-2.py b/challenge-346/sgreen/python/ch-2.py
new file mode 100755
index 0000000000..802e538910
--- /dev/null
+++ b/challenge-346/sgreen/python/ch-2.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python3
+
+from itertools import product, zip_longest
+import re
+import sys
+
+
+def magic_expression(input_string: str | int, target: int) -> list[str]:
+ """Return all expressions formed by inserting +, -, * between digits
+ of input_string that evaluate to target.
+
+ Args:
+ input_string (str | int): A string or integer consisting of digits.
+ target (int): The target integer value.
+
+ Returns:
+ list[str]: A list of expressions that evaluate to target.
+ """
+ # Turn input into a string if it isn't already
+ input_string = str(input_string)
+ if not re.search(r'^[0-9]+$', input_string):
+ raise ValueError("Input string must contain only digits")
+
+ # Possible operators to insert between digits
+ operators = ['', '+', '-', '*']
+
+ magic_expressions = []
+
+ for ops in product(operators, repeat=len(input_string)-1):
+ expression = ''.join(
+ digit + op for digit, op in zip_longest(input_string, ops, fillvalue='')
+ )
+ if re.search(r'[\+\-\*]0\d', expression):
+ # Skip expressions with leading zeros
+ continue
+ if eval(expression) == target:
+ magic_expressions.append(expression)
+
+ return magic_expressions
+
+
+def main():
+ result = magic_expression(sys.argv[1], int(sys.argv[2]))
+ if not result:
+ print("No expressions found")
+ else:
+ print('("' + '", "'.join(result) + '")')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/challenge-346/sgreen/python/test.py b/challenge-346/sgreen/python/test.py
new file mode 100755
index 0000000000..7651f10d7f
--- /dev/null
+++ b/challenge-346/sgreen/python/test.py
@@ -0,0 +1,28 @@
+#!/usr/bin/env python3
+
+import unittest
+ch_1 = __import__('ch-1')
+ch_2 = __import__('ch-2')
+
+
+class TestClass(unittest.TestCase):
+ def test_ch_1(self):
+ self.assertEqual(ch_1.longest_parenthesis('(()())'), 6)
+ self.assertEqual(ch_1.longest_parenthesis(')()())'), 4)
+ self.assertEqual(ch_1.longest_parenthesis('((()))()(((()'), 8)
+ self.assertEqual(ch_1.longest_parenthesis('))))((()('), 2)
+ self.assertEqual(ch_1.longest_parenthesis('()(()'), 2)
+
+ def test_ch_2(self):
+ self.assertEqual(ch_2.magic_expression(123, 6), ["1+2+3", "1*2*3"])
+ self.assertEqual(ch_2.magic_expression(105, 5), ["10-5", "1*0+5"])
+ self.assertEqual(ch_2.magic_expression(232, 8), ["2+3*2", "2*3+2"])
+ self.assertEqual(ch_2.magic_expression(1234, 10), ["1+2+3+4", "1*2*3+4"])
+ self.assertEqual(
+ ch_2.magic_expression(1001, 2),
+ ['1+0+0+1', '1+0-0+1', '1+0*0+1', '1-0+0+1', '1-0-0+1', '1-0*0+1']
+ )
+
+
+if __name__ == '__main__':
+ unittest.main()