4

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.

Miguel
  • 1,852
  • 4
  • 25
  • 48

2 Answers2

1

Here is a quick n dirty solution with "hard-coded" fact, that you choose groups of six. For a generic solution, you need recursion and generating all combinations (you can start with Algorithm to return all combinations of k elements from n )

var numbersList = new[] { 1, 2, 3, 4, 5, 6 ,7,8,9,10};

        var groupsBySix = from i1 in numbersList
                        from i2 in numbersList.Where( i => i>i1)
                        from i3 in numbersList.Where(i => i > i2)
                        from i4 in numbersList.Where(i => i > i3)
                        from i5 in numbersList.Where(i => i > i4)
                        from i6 in numbersList.Where(i => i > i5)
                        select new []{ i1, i2, i3, i4, i5, i6 };


        var cachedGroups = groupsBySix.ToList();  // 210 groups of int arrays. Starts with [1..6] and ends with [5..10]
        var sums = groupsBySix.Select(list => list.Sum());
Community
  • 1
  • 1
Tomas Grosup
  • 5,776
  • 3
  • 24
  • 42
  • This solution will fail to find the group `[1, 1, 1, 1, 1, 1]` in an input set with 6 `1`s. – Timwi Dec 02 '12 at 09:40
0

Personally I’d write it like this:

var values = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var groupsOfSix = values.Subsequences().Where(s => s.Count() == 6);

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 Subsequences function:

/// <summary>
/// Returns all subsequences of the input <see cref="IEnumerable&lt;T&gt;"/>.
/// </summary>
/// <param name="source">The sequence of items to generate subsequences of.</param>
/// <returns>A collection containing all subsequences of the input <see cref="IEnumerable&lt;T&gt;"/>.</returns>
public static IEnumerable<IEnumerable<T>> Subsequences<T>(this IEnumerable<T> source)
{
    if (source == null)
        throw new ArgumentNullException("source");
    // Ensure that the source IEnumerable is evaluated only once
    return subsequences(source.ToArray());
}

private static IEnumerable<IEnumerable<T>> subsequences<T>(IEnumerable<T> source)
{
    if (source.Any())
    {
        foreach (var comb in subsequences(source.Skip(1)))
        {
            yield return comb;
            yield return source.Take(1).Concat(comb);
        }
    }
    else
    {
        yield return Enumerable.Empty<T>();
    }
}
Timwi
  • 61,190
  • 29
  • 155
  • 224
  • forgive my idiot questions. but im not familiar with this syntax "values.Subsequences().Where(s => s.Count() == 6);" whats actually happening here? – Miguel Dec 02 '12 at 09:35
  • @Miguel: It’s alright. You’ll learn to love this syntax. :) `values.Subsequences()` just calls the `Subsequences` method, which generates all the subsequences. The part `s => s.Count() == 6` is called a [lambda expression](http://msdn.microsoft.com/en-us/library/bb397687.aspx). `Where` code goes through all the subsequences and returns just the ones for which the lambda expression returns `true`, i.e. whose `Count` (i.e. number of elements) is `6`. Thus, you end up with all the groups of 6. – Timwi Dec 02 '12 at 09:38
  • Thank you Timwi. Your solution is quite elegant. compared to mine. :-D. thought is going to take me some time to quite understand exactly how this is all being exectuded it seems to be giving me the results im looking for. Thanks mate. – Miguel Dec 02 '12 at 09:46
  • Timwi i hope you check this again otherwise i guess im out of luck. im finally starting to understand what you do here but i dont see how to implement the .Sum I tried and tried and just cant figuered it out can you throw me a bone? "groupsOfSix.Sum()" this does not work any ideas? – Miguel Dec 02 '12 at 16:30
  • sums = groupsOfSix.Select(subseq => subseq.Sum()); // list of 210 sums of the subsequences. – Tomas Grosup Dec 02 '12 at 20:58
  • thanks tomas but i get this error Error 1 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'int' any ideas? ive been trying for hours on trying to get this to work. i cant seem to be able to iterate through it either. this concept is all new to me. – Miguel Dec 02 '12 at 21:30
  • i did this IEnumerable sums; sums = groupsOfSix.Select(subseq => subseq.Sum()); Console.WriteLine(sums.Sum()); and endup with the total of the whole thing i would love to get the total of each line... – Miguel Dec 02 '12 at 21:36
  • @Miguel: `Console.WriteLine(string.Join(", ", sums))`? – Timwi Dec 03 '12 at 06:44