Is it possible to keep eliminating elements of an array (i.e. shrinking it as you deal with the first, second, etc...) and passing it as a new parameter to the same function (i.e. recursively)?
I am trying to come up with a simple method of calculating the number of each coin required for a customer's change (e.g. in a vending machine) but since I am confused by all the Google search results that use nested loops, etc... (I mean I find them difficult to understand) I decided to see if I could translate my thinking into a simple recursive call for solving this problem.
What I have so far is as follows. Let's say the machine should return 80 cents in change, given a denomination list of 10, 20, 50, 100 and 200 coins. A human would think: The first coin that is "less" than 80 is 50 cents, so I need one 50 cents, and now the remaining is 30 cents.
The first coin that is less than 30 is 20 cents, so I need one 20 cents, and now the remaining is only 10 cents. The first coin that is less than (or in this case equal to) the remaining is 10 cents which completes the process.
So, at each step, after taking care of the biggest coin denomination that helps me, I am "disregarding" the other big coins that were too much; i.e. I am removing the useless coin denominations that are of no help to me.
Now, having coded my simplistic way of thinking, I have come up with the following, and now I am wondering how I can map this "coin denomination array shrinking" to code? This is highlighted where I have put my temp
array...
What I mean is that when I started off, I checked the 2 euro coin (200) which was coins[1]
and it was too big. So was coins[2]
which was 1 euro. And then the 50 cent coin helped (coins[3]
) so that is sorted, but now I would like to run the same method Calculate
on the coins[4]
and coins[5]
which could be thought of as a new axed array that now contains only index 4 and 5 which could continue to solve the problem.
Is this even possible?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CoinsConsole
{
class Program
{
static void Main(string[] args)
{
int[] coins = new int[5] { 200, 100, 50, 20, 10 };
Calculate(coins, 80); // 50 + 20 + 10
Console.ReadLine();
}
static []int Calculate(int[] coins, int change)
{
int[] counts = new int[5] { 0, 0, 0, 0, 0 };
int remaining;
for (int i = 1; i <= coins.Length; i++)
{
if (coins[i] <= change)
{
remaining = change - coins[i];
++counts[i];
[]int temp = coins.Skip(i);
Calculate(temp, remaining);
}
}
return counts;
}
}
}
EDIT 1: This is not just a duplicate of array.Skip(n).Take(n)
. I am trying to understand how to pass the modified array for recursion; e.g. whether I should use array.Copy
or the same axed array, etc...
EDIT 2: I have incorporated the way I think I should pass on the new shortened array, but coins.Skip(i)
and Calculate(temp, remaining)
are all underlined red. What am I doing wrong?