ellapt

GreedyCoins

Jun 23rd, 2013
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.76 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace T1.Coins
  6. {
  7.     class CoinsProgram
  8.     {
  9.         static void Main()
  10.         {
  11.             Console.WriteLine("Given infinite number of coins (1, 2 and 5) and end value N, write a program");
  12.             Console.WriteLine("to give the number of coins needed so that their sum equals N");
  13.  
  14.                 int realAmount=33;            
  15.                 int[] denominations = { 1, 2, 5 };
  16.                 int[] coins = new int[denominations.Length];
  17.                 Console.WriteLine("\nGreedy changing values for sum={0}: \n", realAmount);
  18.                 greedyChanges(realAmount, coins, denominations);
  19.                 showgreedyResult(denominations, coins);
  20.         }
  21.  
  22.         //Calculate the minimum number of units for given amount (Greedy Strategy)
  23.         private static void greedyChanges(int amount, int[] coin, int[] denomination)
  24.         {
  25.             int counter;
  26.             Array.Sort(denomination, 1, denomination.Length - 1);
  27.             for (int i = 0; i < coin.Length; i++)
  28.             {
  29.                 coin[i] = 0;
  30.             }
  31.             for (counter = coin.Length - 1; counter >= 0 & amount > 0; counter--)
  32.             {
  33.                 coin[counter] = amount / denomination[counter];
  34.                 amount -= coin[counter] * denomination[counter];
  35.             }
  36.         }
  37.  
  38.         //Display the final output on the Console (Greedy Results)
  39.         private static void showgreedyResult(int[] denominations, int[] coins)
  40.         {
  41.             for (int i = 0; i < coins.Length; i++)
  42.             {
  43.                 if (coins[i] > 0)
  44.                     Console.WriteLine("Number of " + denominations[i] + "s : " + coins[i]);
  45.             }
  46.         }
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment