Sha256: 0d75461de7f08321ceb38b38ae60c1937e0f404262df62d9b7cef4af63917dc0

Contents?: true

Size: 1.12 KB

Versions: 36

Compression:

Stored size: 1.12 KB

Contents

package bookstore

import (
	"math"
)

const bookPrice = 8

var discountTiers = [...]float64{0, 0.05, 0.1, 0.2, 0.25}

// Cost implements the book store exercise.
func Cost(books []int) float64 {
	return cost(books, 0)
}

func cost(books []int, priceSoFar float64) float64 {
	if len(books) == 0 {
		return priceSoFar
	}

	distinctBooks, remainingBooks := getDistinctBooks(books)
	minPrice := math.MaxFloat32

	for i := 1; i <= len(distinctBooks); i++ {
		newRemainingBooks := make([]int, len(remainingBooks))
		copy(newRemainingBooks, remainingBooks)
		newRemainingBooks = append(newRemainingBooks, distinctBooks[i:]...)

		price := cost(newRemainingBooks, priceSoFar+groupCost(i))
		minPrice = math.Min(minPrice, price)
	}

	return minPrice
}

func getDistinctBooks(books []int) (distinct []int, remaining []int) {
	exists := make(map[int]bool)
	for _, book := range books {
		if exists[book] {
			remaining = append(remaining, book)
		} else {
			distinct = append(distinct, book)
			exists[book] = true
		}
	}

	return
}

func groupCost(groupSize int) float64 {
	return float64(bookPrice*groupSize) * (1.00 - discountTiers[groupSize-1])
}

Version data entries

36 entries across 36 versions & 1 rubygems

Version Path
trackler-2.2.1.72 tracks/go/exercises/book-store/example.go
trackler-2.2.1.71 tracks/go/exercises/book-store/example.go
trackler-2.2.1.70 tracks/go/exercises/book-store/example.go
trackler-2.2.1.69 tracks/go/exercises/book-store/example.go
trackler-2.2.1.68 tracks/go/exercises/book-store/example.go
trackler-2.2.1.67 tracks/go/exercises/book-store/example.go
trackler-2.2.1.66 tracks/go/exercises/book-store/example.go
trackler-2.2.1.65 tracks/go/exercises/book-store/example.go
trackler-2.2.1.64 tracks/go/exercises/book-store/example.go
trackler-2.2.1.63 tracks/go/exercises/book-store/example.go
trackler-2.2.1.62 tracks/go/exercises/book-store/example.go
trackler-2.2.1.61 tracks/go/exercises/book-store/example.go
trackler-2.2.1.60 tracks/go/exercises/book-store/example.go
trackler-2.2.1.59 tracks/go/exercises/book-store/example.go
trackler-2.2.1.58 tracks/go/exercises/book-store/example.go
trackler-2.2.1.57 tracks/go/exercises/book-store/example.go