Greedy algorithm-Find change (C # Implementation)

Source: Internet
Author: User

The question of finding change is very clear, nothing more than always take the maximum face value to find, and finally make the number of the smallest, the implementation is to assume a variety of face value enough.

First drag out an interface, the bottom is a ListBox control

Corresponding code: The problem is relatively simple, there are comments

Using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Linq;
Using System.Text;
Using System.Windows.Forms;

Namespace test
{
public partial class Form1:form
{
Public Form1 ()
{
InitializeComponent ();
}

private void Buttonok_click (object sender, EventArgs e)
{
if (ListMoney.Items.Count! = 0)//The second calculation is emptied for easy re-calculation
ListMoney.Items.Clear ();

var money = Exchange (Convert.todecimal (Txtmoney.text));


foreach (Var)
{
if (single. Value! = 0)
{
string s = String. Format ("{0} meta---->{1}", single. Key, single. Value);
LISTMONEY.ITEMS.ADD (s);
}
}

}
Dictionary<decimal, int> getinit ()//initialization dictionary
{
Dictionary<decimal, int> money = new Dictionary<decimal, int> ();

Key means money, value represents the number of money
Money. ADD (100.00M, 0);
Money. ADD (50.00M, 0);
Money. ADD (20.00M, 0);
Money. ADD (10.00M, 0);
Money. ADD (5.00M, 0);
Money. ADD (2.00M, 0);
Money. ADD (1.00M, 0);
Money. ADD (0.50M, 0);
Money. ADD (0.20M, 0);
Money. ADD (0.10M, 0);

return money;
}

Dictionary<decimal, int> Exchange (decimal num)
{
var money = Getinit ();

int i = 0;

while (true)
{
if (num < 0.1M)
{
if (num > 0.05M)
{
money[0.10m]++; More than 0.05 of the time to give customers 0.1.
return money;
}
Else
return money; Otherwise, forget it.
}

var max = money.  Keys.elementat (i); Get face value

if (num >= max)
{
num = Num-max;
Money[max] + +; Number of money self-increment
}
Else
i++; I'm going to take a face.
}
}
}
}

Greedy algorithm-Find change (C # Implementation)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.