Transform an array by repeatedly adding N consecutive elements until possible

Consider an array = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
If N = 4, add first four elements and next four elements
Result : array = {4, 4, 2}

If n=3, add first three elements, then next three elements and then the repeat process until size of array <= N
Result1: array = {3, 3, 3, 1}
Result2 : array = {9, 1}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Diagnostics;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] array = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
            int N = 3;
            ArrayList list = new ArrayList(array);
            ArrayList tempList = new ArrayList();
            Console.WriteLine("Initial Array:");
            for (int i = 0; i < list.Count; i++)
            {
                Console.Write(list[i] + " ");
            }
            Console.WriteLine();
            while (list.Count >= N)
            {
                int sum = 0, flag = 0;
                for (int i = 1; i <= list.Count; i++)
                {
                    sum = sum + (int)list[i-1];
                    flag = 1;
                    if(i % N == 0)
                    {
                        tempList.Add(sum);
                        sum = 0;
                        flag = 0;
                    }
                }
                if(flag == 1)
                {
                    tempList.Add(sum);
                }
                list.Clear();
                list.AddRange(tempList);
                tempList.Clear();
            }
            Console.WriteLine("Processed Array:");
            for (int i = 0; i < list.Count; i++)
            {
                Console.Write(list[i] + " ");
            }
            Console.WriteLine();
        }
    }
}

Output
=======
Initial Array:
1 1 1 1 1 1 1 1 1 1
Processed Array:
9 1
Press any key to continue . . .
Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s