Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,936 questions

51,873 answers

573 users

How to multiply every N consecutive items in a list with C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

class Program
{
    static List<int> ProductsNConsecutiveItems(List<int> lst, int nConsecutiveItems)
    {
        var products = new List<int>();

        if (nConsecutiveItems <= 0 || lst.Count < nConsecutiveItems)
            return products; // empty

        int outSize = lst.Count - nConsecutiveItems + 1;

        for (int i = 0; i < outSize; i++) {
            int prod = 1;

            // Multiply lst[i] * lst[i+1] * ... * lst[i+nConsecutiveItems-1]
            for (int j = 0; j < nConsecutiveItems; j++) {
                prod *= lst[i + j];
            }

            products.Add(prod);

            /*
             * Example for nConsecutiveItems = 3:
             * 2 * 3 * 4  = 24
             * 3 * 4 * 5  = 60
             * 4 * 5 * 6  = 120
             * 5 * 6 * 7  = 210
             * 6 * 7 * 8  = 336
             * 7 * 8 * 9  = 504
             * 8 * 9 * 10 = 720
             */
        }

        return products;
    }

    static void Main()
    {
        List<int> lst = new List<int> { 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        int n = 3;

        List<int> products = ProductsNConsecutiveItems(lst, n);

        Console.Write("[");
        for (int i = 0; i < products.Count; i++) {
            Console.Write(products[i]);
            if (i < products.Count - 1)
                Console.Write(", ");
        }
        Console.WriteLine("]");
    }
}



/*
run:

[24, 60, 120, 210, 336, 504, 720]

*/

 



answered Feb 1 by avibootz

Related questions

...