Sha256: 4237084418399af39dbe4568c5f3f705529f221b3f45b9d15e47368f2940e4d1

Contents?: true

Size: 1.17 KB

Versions: 86

Compression:

Stored size: 1.17 KB

Contents

package bookstore

import "math"

const bookPrice = 800 // 800 cents = $8.00

var discountTiers = [...]int{0, 5, 10, 20, 25}

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

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

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

	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))
		if price < minPrice {
			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) int {
	normalPrice := bookPrice * groupSize
	discount := (normalPrice * discountTiers[groupSize-1]) / 100
	return normalPrice - discount
}

Version data entries

86 entries across 86 versions & 1 rubygems

Version Path
trackler-2.2.1.180 tracks/go/exercises/book-store/example.go
trackler-2.2.1.179 tracks/go/exercises/book-store/example.go
trackler-2.2.1.178 tracks/go/exercises/book-store/example.go
trackler-2.2.1.177 tracks/go/exercises/book-store/example.go
trackler-2.2.1.176 tracks/go/exercises/book-store/example.go
trackler-2.2.1.175 tracks/go/exercises/book-store/example.go
trackler-2.2.1.174 tracks/go/exercises/book-store/example.go
trackler-2.2.1.173 tracks/go/exercises/book-store/example.go
trackler-2.2.1.172 tracks/go/exercises/book-store/example.go
trackler-2.2.1.171 tracks/go/exercises/book-store/example.go
trackler-2.2.1.170 tracks/go/exercises/book-store/example.go
trackler-2.2.1.169 tracks/go/exercises/book-store/example.go
trackler-2.2.1.167 tracks/go/exercises/book-store/example.go
trackler-2.2.1.166 tracks/go/exercises/book-store/example.go
trackler-2.2.1.165 tracks/go/exercises/book-store/example.go
trackler-2.2.1.164 tracks/go/exercises/book-store/example.go
trackler-2.2.1.163 tracks/go/exercises/book-store/example.go
trackler-2.2.1.162 tracks/go/exercises/book-store/example.go
trackler-2.2.1.161 tracks/go/exercises/book-store/example.go
trackler-2.2.1.160 tracks/go/exercises/book-store/example.go