package main
import (
"fmt"
"github.com/deckarep/golang-set"
)
var cities = []string{
"兰州",
"西安",
"郑州",
"武汉",
"广州",
"深圳",
}
var cityIndexMap =map[string]int{
"兰州" :0,
"西安":1,
"郑州":2,
"武汉":3,
"广州":4,
"深圳":5,
}
func main() {
var train *Train =new(Train)
initiate(train,50)
for i:=0;i<50;i++{
train.buyTicket("兰州","武汉")
}
fmt.Println(train.remainTickets("兰州","武汉") )//0
canBuyTicket :=train.canBuyTicket("郑州","深圳")
fmt.Println(canBuyTicket)//false
}
func initiate(train *Train,size int){
train.size =size
train.seats =make(map[string]map[int]bool)
for i:=0;i
startCity,endCity :=cities[i],cities[i+1]
sectionName :=startCity +"-" +endCity
train.seats[sectionName] =make(map[int]bool)
for j:=0;j
train.seats[sectionName][j] =false
}
}
}
type Train struct{
/*
key: 区间名 value: map表示火车座位占用情况 key: 座位号,int
value: 是否占用,ture或false
*/
seats map[string]map[int]bool
//座位数
size int
}
//买票
func (train *Train)buyTicket(start,end string){
if !train.canBuyTicket(start,end){
return
}
seats :=possibleSeats(start,end,train)
choose :=seats.ToSlice()[0]//买到的座位号
value,ok :=choose.(int)
if !ok{
panic(fmt.Errorf("错误!"))
}
mark(train,start,end,value)
}
//是否有票
func (train *Train)canBuyTicket(start,end string)bool{
seats :=possibleSeats(start,end,train)
return len(seats.ToSlice()) >0
}
func (train *Train)remainTickets(start,end string)int{
seats :=possibleSeats(start,end,train)
return len(seats.ToSlice())
}
//退票(TODO: 这里没有做参数校验)
func (train *Train)abortTicket(start,end string,choose int){
unmark(train,start,end,choose)
}
func mark(train *Train,start,end string,choose int){
startIndex,endIndex :=cityIndexMap[start],cityIndexMap[end]
for i:=startIndex;i
startCity,endCity :=cities[i],cities[i+1]
sectionName :=startCity +"-" +endCity
train.seats[sectionName][choose] =true
}
}
func unmark(train *Train,start,end string,choose int){
startIndex,endIndex :=cityIndexMap[start],cityIndexMap[end]
for i:=startIndex;i
startCity,endCity :=cities[i],cities[i+1]
sectionName :=startCity +"-" +endCity
train.seats[sectionName][choose] =false
}
}
func possibleSeats(start,end string,train *Train)mapset.Set{
startIndex,endIndex :=cityIndexMap[start],cityIndexMap[end]
allUnTakenSeats := [][]int{}
for i:=startIndex;i
unTakenSeats := []int{}
startCity,endCity :=cities[i],cities[i+1]
sectionName :=startCity +"-" +endCity
for j:=0;j
//座位没有被占用
if !train.seats[sectionName][j]{
unTakenSeats =append(unTakenSeats,j)
}
}
allUnTakenSeats =append(allUnTakenSeats,unTakenSeats)
}
intersection :=intersect(allUnTakenSeats,train.size)
return intersection
}
//求集合的交集
func intersect(seats [][]int,size int)mapset.Set {
prev :=mapset.NewSet()
for i:=0;i
prev.Add(i)
}
for _,s :=range seats{
set :=mapset.NewSet()
for _,item :=range s {
set.Add(item)
}
prev =set.Intersect(prev)
}
return prev
}
网友评论