From 23bb8feea150a2177b5381e9280bfc4a69112217 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Sat, 24 Oct 2020 15:22:44 +0300 Subject: Moved the solution of the range of elements exercise from a gist to a C# file and added a Perl solution --- C#/RangeOfElements.cs | 41 +++++++++++++++++++++++++++++++++++++++++ Perl/range-of-elements.pl | 29 +++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 C#/RangeOfElements.cs create mode 100644 Perl/range-of-elements.pl diff --git a/C#/RangeOfElements.cs b/C#/RangeOfElements.cs new file mode 100644 index 0000000..a81bbdb --- /dev/null +++ b/C#/RangeOfElements.cs @@ -0,0 +1,41 @@ +/* Impliment a method that will determine if there exists a range of non-negative elements in an array that sum up to a specific non-negative number + + Example 1 - targetSum = 3, numbers = [1, 7, 1, 1 ,1, 5, 6, 1] - output true (the sum of the elemtns in range 2 to 4 is 3) + Example 2 - targetSum = 7, numbers = [0, 4, 5, 1, 8, 9, 12, 3, 1] - output false (no range sums to 7) +*/ + +using System; + +namespace Solution { + class MainClass { + public static void Main(string[] args) { + /* Note: this implementation also accounts for these edge cases: + * target = 10, arr = { 1, 1, 1, 1 } + * target = 4, arr = { 10, 9, 8, 6, 5, 4 } + */ + + int[] arr = { 1, 7, 1, 1 ,1, 5, 6, 1 }; + int target = 3; + Console.WriteLine(ContainsSubArray(arr, target)); + } + + private static bool ContainsSubArray(int[] arr, int target) { + int startIndex = 0, endIndex = 0; + int tmpSum = arr[0]; + + while (endIndex < arr.Length) { + if (tmpSum == target) { + return true; + } + else if (tmpSum > target) { + tmpSum -= arr[startIndex++]; + } + else if (++endIndex < arr.Length) { + tmpSum += arr[endIndex]; + } + } + + return false; + } + } +} diff --git a/Perl/range-of-elements.pl b/Perl/range-of-elements.pl new file mode 100644 index 0000000..59d82f5 --- /dev/null +++ b/Perl/range-of-elements.pl @@ -0,0 +1,29 @@ +#!/usr/bin/perl + +# Impliment a method that will determinate if exists a range of +# non-negative elements in an array that sum up to a specific non-negative number +# +# Example 1 - targetSum 3, numbers = [1, 7, 1, 1 ,1, 5, 6, 1] - output true (the sum of the elemtns in range 2 to 4 is 3) +# Example 2 = targetSum 7, numbers = [0, 4, 5, 1, 8, 9, 12, 3, 1] - output false (no range sums to 7) + +$target_sum = shift // 4; +@numbers = (@ARGV > 0) ? @ARGV : (10, 9, 8, 6, 5, 4) ; +$range_exists = False; + +$start = 0; +$end = 1; +$sum = $numbers[0] + $numbers[1]; + +while ($end < int(@numbers)) { + if ($sum == $target_sum) { + $range_exists = True; + last; + } + elsif ($sum > $target_sum) { + $sum -= $numbers[$start++]; + } + else { + $sum += $numbers[++$end]; + } +} +print $range_exists . "\n"; -- cgit v1.2.3