Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- namespace Euler_P31
- {
- class Program
- {
- static void Main()
- {
- Console.BufferHeight = 200;
- // Count the number of ways to make change for targetSum using the denominations in coinSet
- int[] coinSet = { 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000 }; //, 10, 20, 50, 100 };
- int targetSum = 200;
- Console.WriteLine(CountSubsetSums(ref coinSet, targetSum));
- }
- public static ulong CountSubsetSums(ref int[] set, int targetSum)
- {
- Stack<int> myStack = new Stack<int>();
- int stackTotal = 0;
- int i = 0;
- ulong count = 0;
- int[] mySet = set.Where(g => g <= targetSum).ToArray();
- mySet = mySet.OrderByDescending(g => g).ToArray();
- bool modeAscending = true;
- while (true)
- {
- if (stackTotal >= targetSum)
- {
- if (stackTotal == targetSum)
- {
- count++;
- /*
- foreach (int item in myStack)
- {
- Console.Write(item + ", ");
- }
- Console.WriteLine();
- */
- }
- if (modeAscending || i != mySet.Length - 1)
- i = Array.IndexOf(mySet, myStack.Peek()) + 1;
- if (i == mySet.Length)
- break;
- while (myStack.Count != 0 && myStack.Peek() <= mySet[i]) // Depends on the order of the conditions
- {
- stackTotal -= myStack.Pop();
- }
- if (!modeAscending)
- i = Array.IndexOf(mySet, myStack.Peek()) + 1;
- stackTotal -= myStack.Pop();
- if (i == mySet.Length - 1 && modeAscending)
- modeAscending = false;
- }
- else
- {
- if (stackTotal == 0)
- modeAscending = true;
- myStack.Push(mySet[i]);
- stackTotal += mySet[i];
- }
- }
- return count;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement