Skip to content

Instantly share code, notes, and snippets.

@syntaqx
Last active January 14, 2019 04:07
Show Gist options
  • Save syntaqx/6df476aa01d159d811e435bc1710e2d0 to your computer and use it in GitHub Desktop.
Save syntaqx/6df476aa01d159d811e435bc1710e2d0 to your computer and use it in GitHub Desktop.
Tailor Swift Ticket Sales Counter
package swifty
// CountTicketSales will return how many tickets will be sold by the time the
// line pos has obtained all of their tickets. Tickets must be sold one at a
// time, and people have to return to the back of the line in order to buy their
// ticket.
func CountTicketSales(line []int, pos int) int {
if len(line) == 0 {
return 0
}
var sales int
var newLine []int
for idx, tickets := range line {
if tickets > 0 {
sales++
}
tickets--
if tickets <= 0 {
if pos == idx {
return sales
}
}
newLine = append(newLine, tickets)
}
return CountTicketSales(newLine, pos) + sales
}
// CountTicketSalesOptimized is a optimized version of the CountTicketSales
// initial implementation that deals with longer lines in a more efficient, and
// less time consuming way.
func CountTicketSalesOptimized(line []int, pos int) int {
if len(line) == 0 {
return 0
}
var newLine []int
var sales int
for idx, tickets := range line {
if tickets > 0 {
sales++
}
tickets--
if tickets <= 0 {
if pos == idx {
return sales
} else if idx > pos {
pos--
}
}
if tickets > 0 {
newLine = append(newLine, tickets)
}
}
return CountTicketSalesOptimized(newLine, pos) + sales
}
package swifty
import (
"testing"
)
var ticketSalesTests = []struct {
in []int
pos int
out int
}{
{in: []int{}, pos: 2, out: 0},
{in: []int{3, 2, 5}, pos: 1, out: 5},
{in: []int{3, 1}, pos: 1, out: 2},
{in: []int{1, 3, 1}, pos: 1, out: 5},
}
func TestCountTicketSales(t *testing.T) {
for _, tt := range ticketSalesTests {
c := CountTicketSales(tt.in, tt.pos)
if c != tt.out {
t.Errorf("%v got %d, want %d", tt.in, c, tt.out)
}
}
}
func TestCountTicketSalesOptimized(t *testing.T) {
for _, tt := range ticketSalesTests {
c := CountTicketSalesOptimized(tt.in, tt.pos)
if c != tt.out {
t.Errorf("%v got %d, want %d", tt.in, c, tt.out)
}
}
}
func BenchmarkCountTicketSales(b *testing.B) {
for n := 0; n < b.N; n++ {
vals := ticketSalesTests[len(ticketSalesTests)-1]
CountTicketSales(vals.in, vals.pos)
}
}
func BenchmarkCountTicketSalesOptimized(b *testing.B) {
for n := 0; n < b.N; n++ {
vals := ticketSalesTests[len(ticketSalesTests)-1]
CountTicketSalesOptimized(vals.in, vals.pos)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment