Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
1.7 kB
0
Indexable
Never
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract BusTicketBooking {
    uint8 constant maxSeats = 20;
    uint8 constant maxSeatsPerAddress = 4;

    mapping(address => uint8[]) private bookedSeats;
    mapping(uint8 => bool) private seatAvailability;

    constructor() {
        // Initialize all seats as available
        for (uint8 i = 1; i <= maxSeats; i++) {
            seatAvailability[i] = true;
        }
    }

    function bookSeats(uint8[] memory seatNumbers) public {
        require(seatNumbers.length > 0 && seatNumbers.length <= maxSeatsPerAddress, "Invalid number of seats");

        for (uint8 i = 0; i < seatNumbers.length; i++) {
            uint8 seatNumber = seatNumbers[i];
            require(seatAvailability[seatNumber], "Seat is not available");
            seatAvailability[seatNumber] = false;
            bookedSeats[msg.sender].push(seatNumber);
        }
    }

    function showAvailableSeats() public view returns (uint8[] memory) {
        uint8[] memory available = new uint8[](maxSeats);
        uint8 availableCount = 0;

        for (uint8 i = 1; i <= maxSeats; i++) {
            if (seatAvailability[i]) {
                available[availableCount] = i;
                availableCount++;
            }
        }

        // Resize the array to remove unused elements
        assembly {
            mstore(available, availableCount)
        }

        return available;
    }

    function checkAvailability(uint8 seatNumber) public view returns (bool) {
        return seatAvailability[seatNumber];
    }

    function myTickets() public view returns (uint8[] memory) {
        return bookedSeats[msg.sender];
    }
}