Converting nested for loops into recursion

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        public static int counter = 0;
        public static ArrayList distict = new ArrayList();
        static void Main(string[] args)
        {
            int[] currencyList = { 10, 20 };
            int sum = 50;
            int[] frequencyList = new int[currencyList.Length];
            ArrayList cl = new ArrayList(currencyList);
            ArrayList fl = new ArrayList(frequencyList);
            getCombinations(cl, fl, sum, currencyList.Length - 1);
            Console.WriteLine("Total number of combinations = " + counter);
        }

        public static void getCombinations(ArrayList cl, ArrayList fl, int sum, int index)
        {
            for (fl[index] = 0; (int)fl[index] <= sum / (int)cl[index]; fl[index] = (int)fl[index] + 1)
            {
                if (index != 0)
                {
                    getCombinations(cl, fl, sum, index - 1);
                }
                else
                {
                    int currSum = 0;
                    for (int i = 0; i < cl.Count; i++)
                    {
                        currSum = currSum + ((int)cl[i] * (int)fl[i]);
                    }
                    if (currSum == sum)
                    {
                        for (int i = 0; i < cl.Count; i++)
                        {
                            Console.WriteLine(cl[i] + " --> " + fl[i]);
                        }
                        Console.WriteLine("===========================");
                        counter++;
                    }
                }
            }
        }
    }
}

Output
=======
10 --> 5
20 --> 0
===========================
10 --> 3
20 --> 1
===========================
10 --> 1
20 --> 2
===========================
Total number of combinations = 3
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