hello guys I’m doing a little self learning and i have come across of problem that seems to have stumped me for the time being i figuere someone here im sure has already encountered something similar to this in the past. i have an array list of 1-10
public List<int> ValueArrays = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
im trying to get the sum of every number groups of 6 but i’m just stuck.
for example i want
[1,2,3,4,5,6]
[1,3,4,5,6,7]
[1,4,5,6,7,8] etc...
i have written some code but im just stumbling on my feet here.
private void runbtn_Click(object sender, EventArgs e)
{
int thisTotal;
//Object ListOfNumbersToCompareTo = new Object[];
List<int> fiveEl = new List<int> { }; //= ValueArrays.GetRange(1, 5);//target a group of 5
List<int> test2 = new List<int> { };
//test2.AddRange(fiveEl);
//thisTotal = SumRange(fiveEl);
int groupSize = 5;
for (int i = 0; i < ValueArrays.Count; i++)
{
fiveEl=ValueArrays.GetRange(i+1, 5);
currentNum = ValueArrays[i];
fiveEl.Add(currentNum);
for (int x = 0; x < 1; x++)
{
thisTotal = SumRange(fiveEl);
//fiveEl = ValueArrays.GetRange(x, groupSize);
//fiveEl.Add(currentNum);
//fiveEl.RemoveRange(x, groupSize); ;
}
}
}
can someone give me a code snippet or point me in the right direction?
Thanks in advance.
Personally I’d write it like this:
And then of course you can use
.Sum()on each of the subsequences thus generated.This uses an extension method I wrote some time ago, which generates all subsequences of an
IEnumerable<T>. This solution is not the most speedy possible, but by golly does it make the code easy to read and obviously correct, and on an input list of just 10 elements it’s way fast enough.Here’s the
Subsequencesfunction: