Re: [問題] 面試遇到的題目
※ 引述《sunneo (艾斯寇德)》之銘言:
: 我提供一下我會嘗試的做法,首先我先產生31個大小的陣列,裡面有數字0~30
: 以及一個back,為陣列最後一個元素的索引位置。
: 如果back為0 則回傳0
: n = 產生亂數[ 1 , back ];
: 回傳值 = 陣列[ n ];
: 對調(陣列[ n ] 跟陣列[ back ]);
: --back;
: 如果back為0,則清空陣列。
: 回傳回傳值;
: 外面檢查回傳值是否為0,0表示座位已滿。
: 這是在座位沒有0號的情形。
: 有0號的話則以丟出exception的方式。
java我很久沒寫了 倒是用python寫了一下
在class initialize的時候產生亂數陣列
每次Reserve只需回傳亂數陣列裡面index指到的元素
並且index--就好了
越到0就終止
--
#!/usr/bin/python
import os
import sys
import random
NUM_SEATS = 30
class Reservation:
_num_seats = 0
_seat = []
_current_seat = 0
def __init__(self, num_seats):
self._num_seats = num_seats
def Init(self):
for i in range(self._num_seats+1):
self._seat.append(i)
self.__RandomizeSeats(self._seat, self._num_seats)
self._current_seat = self._num_seats
def __RandomizeSeats(self, seats, num_seats):
for i in range(num_seats, 0, -1):
rand = random.randrange(1, i+1)
seats[i],seats[rand] = seats[rand],seats[i]
def Reserve(self):
if self._current_seat:
ret = self._seat[self._current_seat]
self._current_seat -= 1
return ret
else:
return 0
def main():
r = Reservation(NUM_SEATS)
r.Init()
while 1:
in_txt = raw_input("Reserve seat? [y/n] ")
if in_txt=="y" or in_txt=="Y":
seat_num = r.Reserve()
if seat_num:
print "Your seat number is %d" % seat_num
else:
print "Sorry, no more seats"
return 0
else:
print "Thanks for using reserve system"
print "You reserved %d/%d seats" % \
(r._num_seats-r._current_seat, r._num_seats)
return 0
if __name__ == "__main__":
sys.exit(main())
--
http://nigel.twbbs.org
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 76.95.86.77
推
08/13 10:10, , 1F
08/13 10:10, 1F
→
08/13 10:10, , 2F
08/13 10:10, 2F
討論串 (同標題文章)