DEV Community

Discussion on: Daily Challenge #45 - Change Machine

Collapse
 
dak425 profile image
Donald Feury

Go - with tests:

change.go:

// Package change contains methods for interacting with US currency
package change

var coins = []int{25, 10, 5, 1}

// Change returns the fewest amount of each US coin to equal the amount of change indicated
func Change(amount int) map[int]int {
    usedCoins := map[int]int{25: 0, 10: 0, 5: 0, 1: 0}

    if amount == 0 {
        return usedCoins
    }

    remain := amount

    for _, coin := range coins {
        if remain == 0 {
            return usedCoins
        }

        mod := remain % coin
        if mod != remain {
            usedCoins[coin] = int(remain / coin)
            remain = mod
        }
    }

    return usedCoins
}

change_test.go

package change

import "testing"

func equal(actual map[int]int, expected map[int]int) bool {
    if len(actual) != len(expected) {
        return false
    }

    for k, v := range actual {
        expectedVal, present := expected[k]

        if !present || v != expectedVal {
            return false
        }
    }

    return true
}

func TestChange(t *testing.T) {
    for _, test := range changeTests {
        if actual := Change(test.input); !equal(actual, test.expected) {
            t.Fatalf(
                "FAIL: %s - Change(%d): %v, expected: %v \n",
                test.description,
                test.input,
                actual,
                test.expected,
            )
        }
        t.Logf("PASS: %s \n", test.description)
    }
}

change_test_cases.go

package change

var changeTests = []struct {
    description string
    input       int
    expected    map[int]int
}{
    {
        "no change",
        0,
        map[int]int{25: 0, 10: 0, 5: 0, 1: 0},
    },
    {
        "uses one coin",
        5,
        map[int]int{25: 0, 10: 0, 5: 1, 1: 0},
    },
    {
        "uses two coins",
        27,
        map[int]int{25: 1, 10: 0, 5: 0, 1: 2},
    },
    {
        "uses many coin",
        39,
        map[int]int{25: 1, 10: 1, 5: 0, 1: 4},
    },
}