Skip to content

Instantly share code, notes, and snippets.

@jozsefs
Created April 21, 2017 10:51
Show Gist options
  • Select an option

  • Save jozsefs/a120336823e8d6cf3d70b577ee24a853 to your computer and use it in GitHub Desktop.

Select an option

Save jozsefs/a120336823e8d6cf3d70b577ee24a853 to your computer and use it in GitHub Desktop.
kata-harrypotter.go
package main
import (
"fmt"
"sort"
)
var BOOK_PRICE = 8
var priceMultiplier = map[int]float32{
1: 1,
2: .95,
3: .9,
4: .8,
5: .75,
}
func main() {
testBasics()
testSimpleDiscounts()
testSeveralDiscounts()
testEdgeCases()
}
func testBasics() {
assert_equal(0, price([]int{}...))
assert_equal(8, price([]int{0}...))
assert_equal(8, price([]int{1}...))
assert_equal(8, price([]int{2}...))
assert_equal(8, price([]int{3}...))
assert_equal(8, price([]int{4}...))
assert_equal(8*2, price([]int{0, 0}...))
assert_equal(8*3, price([]int{1, 1, 1}...))
}
func testSimpleDiscounts() {
assert_equal(8*2*0.95, price([]int{0, 1}...))
assert_equal(8*3*0.9, price([]int{0, 2, 4}...))
assert_equal(8*4*0.8, price([]int{0, 1, 2, 4}...))
assert_equal(8*5*0.75, price([]int{0, 1, 2, 3, 4}...))
}
func testSeveralDiscounts() {
assert_equal(8+(8*2*0.95), price([]int{0, 0, 1}...))
assert_equal(2*(8*2*0.95), price([]int{0, 0, 1, 1}...))
assert_equal((8*4*0.8)+(8*2*0.95), price([]int{0, 0, 1, 2, 2, 3}...))
assert_equal(8+(8*5*0.75), price([]int{0, 1, 1, 2, 3, 4}...))
}
func testEdgeCases() {
assert_equal(2*(8*4*0.8), price([]int{0, 0, 1, 1, 2, 2, 3, 4}...))
assert_equal(3*(8*5*0.75)+2*(8*4*0.8),
price([]int{0, 0, 0, 0, 0,
1, 1, 1, 1, 1,
2, 2, 2, 2,
3, 3, 3, 3, 3,
4, 4, 4, 4}...))
}
func assert_equal(a float32, b float32) {
if a != b {
fmt.Printf("%f is not equal to %f\n", a, b)
return
}
fmt.Printf("Test passed for %f\n", a)
}
func price(ints ...int) float32 {
var sum float32 = 0
books := []int{0, 0, 0, 0, 0}
for _, item := range ints {
books[item]++
}
sort.Ints(books)
differentBooksCount := len(books)
for i := 0; i < differentBooksCount; i++ {
amount := books[i]
multiplier := differentBooksCount - i
sum += float32(multiplier) * float32(amount) * float32(BOOK_PRICE) * priceMultiplier[multiplier]
//fmt.Println(float32(multiplier), float32(amount), float32(BOOK_PRICE), priceMultiplier[multiplier])
for j := i; j < differentBooksCount; j++ {
books[j] -= amount
}
}
return sum
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment