diff options
| author | Syndamia <kamen.d.mladenov@protonmail.com> | 2020-10-24 15:22:44 +0300 |
|---|---|---|
| committer | Syndamia <kamen.d.mladenov@protonmail.com> | 2020-10-24 15:22:44 +0300 |
| commit | 23bb8feea150a2177b5381e9280bfc4a69112217 (patch) | |
| tree | 0e41ece10461b3c914a115a17b1ab3081a7976f1 /C# | |
| parent | c6c8585834d1c43e536ca460b1c32e25b63a4ec4 (diff) | |
| download | algorithms-23bb8feea150a2177b5381e9280bfc4a69112217.tar algorithms-23bb8feea150a2177b5381e9280bfc4a69112217.tar.gz algorithms-23bb8feea150a2177b5381e9280bfc4a69112217.zip | |
Moved the solution of the range of elements exercise from a gist to a C# file and added a Perl solution
Diffstat (limited to 'C#')
| -rw-r--r-- | C#/RangeOfElements.cs | 41 |
1 files changed, 41 insertions, 0 deletions
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; + } + } +} |
