Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- class FindSequenceOfSumSInArray
- {
- static void Main()
- {
- //Write a program that finds in given array of integers a sequence of given sum S (if present).
- //Example: {4, 3, 1, 4, 2, 5, 8 }, S=11 -> {4, 2, 5}
- int[] myArray = { 5, 3, 3, 4, 2, 5, 8 };
- int sumS = 11;
- List<int> sumSStartIndex = new List<int>();//A list array for the start index of each sequence that equals the desired sumS
- List<int> sumSEndIndex = new List<int>();////A list array for the end index of each sequence that equals the desired sumS
- int currentSum = 0, //Used to store the sum of the elements while searching for our sumS in the cycle
- currentCounter = 0;//Counts how many sumS we have found in the array
- for (int i = 0; i < myArray.Length; i++) //Cycle through the elements: this gives us the start element
- {
- for (int j = i; j < myArray.Length; j++) //Cycle through the elements: this gives us the end element
- {
- currentSum += myArray[j]; //Sum each element
- if (currentSum == sumS) //Check if the sum is equal to the desired SumS
- {
- sumSStartIndex.Add(i); //We have a winner so the start and end inex wil be saved in the lists
- sumSEndIndex.Add(j);
- currentCounter++; //The counter for how many sumS are found is increased
- break;//We have a winner so there is no need to proceed with that j sequence and we break the inner loop
- }
- }
- currentSum = 0; //Get ready to proceed with the next sequence to sum
- }
- //Print the results on the console
- if (currentCounter > 0)//If we have found the desired sum print that there is/are currentCounter sum/s SumS in the array
- {
- Console.WriteLine("There {0} {1} {2} {3} in the array:", currentCounter == 1 ? "is" : "are", currentCounter, currentCounter == 1 ? "sum" : "sums", sumS);
- for (int k = 0; k < currentCounter; k++)//A cycle to print the actual elemnts from myArray that sum up to our SumS
- {
- Console.Write("{");
- for (int result = sumSStartIndex[k]; result <= sumSEndIndex[k]; result++)
- {
- if (result != sumSEndIndex[k])
- {
- Console.Write("{0}, ", myArray[result]);
- }
- else
- {
- Console.Write("{0}", myArray[result]);
- }
- }
- Console.WriteLine("}");
- }
- }
- else
- {
- Console.WriteLine("There isn't a sequence that has a sum {0} in the array", sumS);//No SumS is possible in the array
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement