This Go snippet calculates the minimum number of bills or coins needed for a given amount of money (change) requested. The program also gives the denomination and number. US curency is used in this example, but can be changed to another currency.

112 Views
``````// minimum_change.go
//
// for a given amount of change (in cents)
// calculate the minimum number of bills or coins needed
// using a csv string converted to a structure
//
// for imported package info see ...
// http://golang.org/pkg/fmt/
// http://golang.org/pkg/strconv/
// http://golang.org/pkg/strings/
//
// online play at:
// http://play.golang.org/p/-bW65AQw-Q
//
// tested with Go version 1.4.2   by vegaseat (dns) 9may2015

package main

import (
"fmt"
"strconv"
"strings"
)

type USmoney struct {
cents int
name  string
}

func main() {
fmt.Println("Minimum number of bills and coins:\n")

// change requested in cents
change := 888
fmt.Printf("Change requested = %d cents\n", change)
fmt.Println("----------------------------")

// half dollar is rare and not used
// cents,name on each line
csv_us_money := `10000,Hundred Dollars
5000,Fifty Dollars
2000,Twenty Dollars
1000,Ten Dollars
500,Five Dollars
100,Dollars
25,Quarters
10,Dimes
5,Nickels
1,Pennies`

// split at the newline char to create a slice of lines
slice_lines := strings.Split(csv_us_money, "\n")
// create pointer to an instance of structure USmoney
pstu := new(USmoney)
// now create a slice of structures	using the pointer
slice_struct := make([]USmoney, len(slice_lines))
for ix, line := range slice_lines {
// split at the comma
cents_name := strings.Split(line, ",")
pstu.cents, _ = strconv.Atoi(cents_name)
pstu.name = cents_name
slice_struct[ix] = *pstu
}

bills_coins := 0
for _, money := range slice_struct {
whole := change / money.cents
remain := change % money.cents
change = remain
fmt.Printf("%-15s = %d\n", money.name, whole)
bills_coins += whole
}
fmt.Println("----------------------------")
fmt.Printf("A total of %d bills or coins\n", bills_coins)

}

/* result ...
Minimum number of bills and coins:

Change requested = 888 cents
----------------------------
Hundred Dollars = 0
Fifty Dollars   = 0
Twenty Dollars  = 0
Ten Dollars     = 0
Five Dollars    = 1
Dollars         = 3
Quarters        = 3
Dimes           = 1
Nickels         = 0
Pennies         = 3
----------------------------
A total of 11 bills or coins
*/``````