Решение на упр.07 задача 1 от Калоян Маринов

Обратно към всички решения

Към профила на Калоян Маринов

Резултати

  • 4 точки от тестове
  • 0 бонус точки
  • 4 точки общо
  • 0 успешни тест(а)
  • 0 неуспешни тест(а)

Код

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BookingError {
InvalidSeat,
AlreadyReserved,
NotReserved,
EmptyGroup,
}
/// A cinema hall with seats indexed from 0 to total_seats - 1.
/// `true` means that the seat is reserved.
#[derive(Debug)]
pub struct Cinema {
seats: Vec<bool>,
}
impl Cinema {
pub fn new(total_seats: usize) -> Self {
Self {
seats: vec![false; total_seats],
}
}
pub fn total_seats(&self) -> usize {
self.seats.len()
}
pub fn available_seats(&self) -> usize {
self.seats.iter().filter(|&&reserved| !reserved).count()
}
pub fn is_available(&self, seat: usize) -> Result<bool, BookingError> {
if seat > self.seats.len() {
return Err(BookingError::InvalidSeat);
}
Ok(!self.seats[seat])
}
pub fn reserve(&mut self, seat: usize) -> Result<(), BookingError> {
if seat >= self.seats.len() {
return Err(BookingError::InvalidSeat);
}
if self.seats[seat] {
return Err(BookingError::AlreadyReserved);
}
self.seats[seat] = true;
Ok(())
}
pub fn cancel(&mut self, seat: usize) -> Result<(), BookingError> {
if seat >= self.seats.len() {
return Err(BookingError::InvalidSeat);
}
if self.seats[seat] {
self.seats[seat] = false;
}
Ok(())
}
/// Reserves `count` consecutive seats starting from `start`.
/// The operation must be atomic: on error no seat is changed.
pub fn reserve_group(
&mut self,
start: usize,
count: usize,
) -> Result<(), BookingError> {
if count == 0 {
return Err(BookingError::EmptyGroup);
}
if start >= self.seats.len() || count > self.seats.len() - start {
return Err(BookingError::InvalidSeat);
}
for seat in start..(start + count) {
self.reserve(seat)?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Helper: returns the state of every seat as a list.
/// `true` means the seat is free, `false` means it is taken.
/// We use it to compare the whole hall before and after an operation.
fn snapshot(cinema: &Cinema) -> Vec<bool> {
(0..cinema.total_seats())
.map(|seat| cinema.is_available(seat).unwrap())
.collect()
}
// A new hall should have every seat free.
#[test]
fn new_cinema_has_all_seats_available() {
let cinema = Cinema::new(5);
assert_eq!(cinema.total_seats(), 5);
assert_eq!(cinema.available_seats(), 5);
for seat in 0..5 {
assert_eq!(cinema.is_available(seat), Ok(true));
}
}
// A hall with 0 seats is allowed, but no seat number is valid in it.
// Every call should return an error instead of crashing.
#[test]
fn empty_cinema_rejects_every_seat() {
let mut cinema = Cinema::new(0);
assert_eq!(cinema.total_seats(), 0);
assert_eq!(cinema.available_seats(), 0);
assert_eq!(cinema.reserve(0), Err(BookingError::InvalidSeat));
assert_eq!(cinema.cancel(0), Err(BookingError::InvalidSeat));
assert_eq!(cinema.reserve_group(0, 1), Err(BookingError::InvalidSeat));
assert_eq!(cinema.reserve_group(0, 0), Err(BookingError::EmptyGroup));
assert_eq!(cinema.is_available(0), Err(BookingError::InvalidSeat));
assert_eq!(cinema.available_seats(), 0);
}
// With 3 seats, the last valid seat is 2. Seat 3 and any bigger
// number should return an error, not crash the program.
#[test]
fn is_available_handles_boundary_indices_without_panic() {
let cinema = Cinema::new(3);
assert_eq!(cinema.is_available(2), Ok(true));
assert_eq!(cinema.is_available(3), Err(BookingError::InvalidSeat));
assert_eq!(cinema.is_available(usize::MAX), Err(BookingError::InvalidSeat));
}
// Booking a free seat works. Booking the same seat again fails,
// and so does booking a seat that does not exist. Failed calls
// should leave the hall unchanged.
#[test]
fn reserve_then_reserve_again_fails_without_side_effects() {
let mut cinema = Cinema::new(3);
assert_eq!(cinema.reserve(2), Ok(()));
assert_eq!(cinema.is_available(2), Ok(false));
assert_eq!(cinema.available_seats(), 2);
assert_eq!(cinema.reserve(2), Err(BookingError::AlreadyReserved));
assert_eq!(cinema.available_seats(), 2);
assert_eq!(cinema.reserve(3), Err(BookingError::InvalidSeat));
assert_eq!(cinema.available_seats(), 2);
assert_eq!(snapshot(&cinema), vec![true, true, false]);
}
// Cancelling a booking makes the seat free again, so it can be booked again.
// Other bookings should not be affected.
#[test]
fn cancel_frees_seat_and_allows_new_reservation() {
let mut cinema = Cinema::new(4);
assert_eq!(cinema.reserve(1), Ok(()));
assert_eq!(cinema.reserve(3), Ok(()));
assert_eq!(cinema.available_seats(), 2);
assert_eq!(cinema.cancel(1), Ok(()));
assert_eq!(cinema.is_available(1), Ok(true));
assert_eq!(cinema.is_available(3), Ok(false));
assert_eq!(cinema.available_seats(), 3);
assert_eq!(cinema.reserve(1), Ok(()));
assert_eq!(cinema.available_seats(), 2);
}
// You cannot cancel a seat that is not booked.
#[test]
fn cancel_free_seat_returns_not_reserved() {
let mut cinema = Cinema::new(3);
assert_eq!(cinema.cancel(0), Err(BookingError::NotReserved));
assert_eq!(cinema.available_seats(), 3);
// Cancelling twice: the first cancel works, the second one should fail.
cinema.reserve(1).unwrap();
assert_eq!(cinema.cancel(1), Ok(()));
assert_eq!(cinema.cancel(1), Err(BookingError::NotReserved));
assert_eq!(cinema.available_seats(), 3);
}
// Cancelling a seat that does not exist fails and changes nothing.
#[test]
fn cancel_invalid_seat_returns_invalid_seat() {
let mut cinema = Cinema::new(2);
cinema.reserve(0).unwrap();
assert_eq!(cinema.cancel(2), Err(BookingError::InvalidSeat));
assert_eq!(cinema.cancel(usize::MAX), Err(BookingError::InvalidSeat));
assert_eq!(snapshot(&cinema), vec![false, true]);
}
// A group can take the whole hall. After that, nothing else can be booked.
#[test]
fn reserve_group_whole_hall() {
let mut cinema = Cinema::new(4);
assert_eq!(cinema.reserve_group(0, 4), Ok(()));
assert_eq!(cinema.available_seats(), 0);
assert_eq!(snapshot(&cinema), vec![false; 4]);
assert_eq!(cinema.reserve(0), Err(BookingError::AlreadyReserved));
assert_eq!(cinema.reserve_group(3, 1), Err(BookingError::AlreadyReserved));
}
// A group must fit inside the hall. Ending exactly on the last seat is fine,
// but going even one seat past the end is an error.
#[test]
fn reserve_group_boundaries_and_overflow() {
let mut cinema = Cinema::new(5);
assert_eq!(cinema.reserve_group(3, 3), Err(BookingError::InvalidSeat));
assert_eq!(cinema.reserve_group(5, 1), Err(BookingError::InvalidSeat));
// A huge count must not cause a math overflow.
assert_eq!(cinema.reserve_group(2, usize::MAX), Err(BookingError::InvalidSeat));
assert_eq!(cinema.available_seats(), 5);
assert_eq!(cinema.reserve_group(3, 2), Ok(()));
assert_eq!(snapshot(&cinema), vec![true, true, true, false, false]);
}
// A group of 0 seats makes no sense, so it is an error.
#[test]
fn reserve_group_with_zero_count_is_empty_group() {
let mut cinema = Cinema::new(3);
assert_eq!(cinema.reserve_group(1, 0), Err(BookingError::EmptyGroup));
assert_eq!(cinema.available_seats(), 3);
}
// Group booking should fail if even one seat is unavailable.
Seat 3 is already taken, so booking
// seats 1 to 4 must fail, and seats 1 and 2 must stay free.
#[test]
fn reserve_group_is_atomic_when_seat_in_middle_is_taken() {
let mut cinema = Cinema::new(6);
cinema.reserve(3).unwrap();
let before = snapshot(&cinema);
assert_eq!(cinema.reserve_group(1, 4), Err(BookingError::AlreadyReserved));
assert_eq!(snapshot(&cinema), before);
assert_eq!(cinema.available_seats(), 5);
// Seats 1 and 2 are still free, so booking them as a group should work.
assert_eq!(cinema.reserve_group(1, 2), Ok(()));
assert_eq!(cinema.available_seats(), 3);
}
}

Лог от изпълнението

Compiling solution v0.1.0 (/tmp/d20261126-2321049-9qk2xg/solution)
error: expected one of `!` or `::`, found `3`
   --> src/lib.rs:240:6
    |
240 | Seat 3 is already taken, so booking
    |      ^ expected one of `!` or `::`

error: could not compile `solution` (lib test) due to 1 previous error

История (1 версия и 1 коментар)