Using a map for minimum bills or coins (golang)

Updated vegaseat 0 Tallied Votes 407 Views Share

Again, calculate the minimum number of bills or coins required for a given amount of money (change). This time we will use a Go map instead of a csv string converted to a structure.

// minimum_change2.go
//
// for a given amount of change (in cents)
// calculate the minimum number of bills or coins needed
// using a map
//
// for imported package info see ...
// http://golang.org/pkg/fmt/
// http://golang.org/pkg/sort/
//
// online play at:
// http://play.golang.org/p/S38FOamvL5
//
// tested with Go version 1.4.2   by vegaseat (dns) 9may2015

package main

import (
	"fmt"
	"sort"
)

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("----------------------------")

	// a map of cents:name pairs
	// note that a map will go to 'hash' order
	us_money := map[int]string{
		10000: "Hundred Dollars",
		5000:  "Fifty Dollars",
		2000:  "Twenty Dollars",
		1000:  "Ten Dollars",
		500:   "Five Dollars",
		100:   "Dollars",
		25:    "Quarters",
		10:    "Dimes",
		5:     "Nickels",
		1:     "Cents",
	}

	// create a slice of keys
	cents := []int{}
	for key, _ := range us_money {
		cents = append(cents, key)
	}
	// sort slice, highest value first
	sort.Sort(sort.Reverse(sort.IntSlice(cents)))

	bills_coins := 0
	for _, cent := range cents {
		whole := change / cent
		remain := change % cent
		change = remain
		fmt.Printf("%-15s = %d\n", us_money[cent], 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
*/