Untitled

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

contract TicketBooking {

    uint256 constant totalSeats = 20;

    uint256[20] public seats;
    mapping(address => uint256[]) private userTickets;

    // To book seats
    function bookSeats(uint[] memory seatNumbers) public {
        uint256 seatsLength = seatNumbers.length; 
        require(userTickets[msg.sender].length < 4, "Can't book more than 4 tickets");
        require(seatsLength > 0 && seatsLength <= 4, "Invalid number of seats selected");
        require(seatsLength == _unique(seatNumbers), "Duplicate seats");
        require(_areAllAvailable(seatNumbers), "Seats not available");

        for (uint i = 0; i < seatsLength; i++) {
            uint seatNumber = seatNumbers[i];
            require(seatNumber >= 1 && seatNumber <= totalSeats, "Invalid seat number");
            seats[seatNumber - 1] = 1;
            userTickets[msg.sender].push(seatNumber);
        }
    }
    
    // To get available seats
    function showAvailableSeats() public view returns (uint[] memory) {
        uint[] memory availableSeats = new uint[](totalSeats);
        uint count = 0;
        for (uint i = 0; i < totalSeats; i++) {
            if (seats[i] == 0) {
                availableSeats[count] = i + 1;
                count++;
            }
        }
        
        uint[] memory slice = new uint[](count);
        for (uint i = 0; i < count; i++) {
            slice[i] = availableSeats[i];
        }

        return slice;
    }
    
    function checkAvailability(uint seatNumber) public view returns (bool) {
        require(seatNumber >= 1 && seatNumber <= totalSeats, "Invalid seat number");
        return seats[seatNumber - 1] == 0;
    }
    
    function myTickets() public view returns (uint[] memory) {
        return userTickets[msg.sender];
    }

    function _areAllAvailable(uint[] memory seatNumbers) internal view returns (bool) {
        uint256 seatsLength = seatNumbers.length;
        for (uint i = 0; i < seatsLength; i++) {
            uint seatNumber = seatNumbers[i];
            if (seatNumber < 1 || seatNumber > totalSeats || seats[seatNumber - 1] != 0) {
                return false;
            }
        }
        return true;
    }

    function _unique(uint[] memory seatNumbers) internal pure returns (uint) {
        uint256 seatsLength = seatNumbers.length;
        uint[] memory seen = new uint[](totalSeats);
        uint j = 0;

        for (uint i = 0; i < seatsLength; i++) {
            uint seatNumber = seatNumbers[i];
            if (seatNumber >= 1 && seatNumber <= totalSeats && seen[seatNumber - 1] == 0) {
                seen[seatNumber - 1 ] = 1;
                j++;
            }
        }
        return j;
    }
}