diff --git a/DeckOfCards/Card.java b/DeckOfCards/Card.java new file mode 100644 index 00000000..7dddac8c --- /dev/null +++ b/DeckOfCards/Card.java @@ -0,0 +1,17 @@ +package DeckOfCards; + + +public class Card { + private Suit suit; + private Rank rank; + + public Card(Suit suit, Rank rank) { + this.suit = suit; + this.rank = rank; + } + + @Override + public String toString() { + return rank + " of " + suit; + } +} diff --git a/DeckOfCards/Deck.java b/DeckOfCards/Deck.java new file mode 100644 index 00000000..ccc82772 --- /dev/null +++ b/DeckOfCards/Deck.java @@ -0,0 +1,75 @@ +package DeckOfCards; + +import java.util.*; + +public class Deck { + private Stack cards; + + public Deck(int numberOfDecks) { + cards = new Stack<>(); + createDeck(numberOfDecks); + } + + private void createDeck(int numberOfDecks) { + for (int i = 0; i < numberOfDecks; i++) { + for (Suit suit : Suit.values()) { + for (Rank rank : Rank.values()) { + cards.push(new Card(suit, rank)); + } + } + } + } + + public void shuffleDeck(int numberOfShuffles) { + Random random = new Random(); + Card[] tempArray = cards.toArray(new Card[0]); + + for (int m = 0; m < numberOfShuffles; m++) { // Shuffle M times + for (int i = tempArray.length - 1; i > 0; i--) { + int j = random.nextInt(i + 1); + Card temp = tempArray[i]; + tempArray[i] = tempArray[j]; + tempArray[j] = temp; + } + } + + // Rebuild the stack + cards.clear(); + for (Card card : tempArray) { + cards.push(card); + } + } + + // Distribute cards to players + public Map> dealCards(int numberOfPlayers, int cardsPerPlayer) { + int totalAvailable = cards.size(); + int required = numberOfPlayers * cardsPerPlayer; + + // Edge case check + if (required > totalAvailable) { + throw new IllegalArgumentException("Not enough cards! Required: " + required + ", Available: " + totalAvailable); + } + + Map> playerHands = new HashMap<>(); + for (int player = 1; player <= numberOfPlayers; player++) { + List hand = new ArrayList<>(); + for (int c = 0; c < cardsPerPlayer; c++) { + hand.add(cards.pop()); + } + playerHands.put(player, hand); + } + return playerHands; + } + + + public Card drawCard() { + if (cards.isEmpty()) { + throw new IllegalStateException("No cards left in the deck!"); + } + return cards.pop(); // Draw from top + } + + public int remainingCards() { + return cards.size(); + } +} diff --git a/DeckOfCards/Main.java b/DeckOfCards/Main.java new file mode 100644 index 00000000..f63fee6c --- /dev/null +++ b/DeckOfCards/Main.java @@ -0,0 +1,33 @@ +package DeckOfCards; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Scanner; + +public class Main { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + System.out.print("Enter number of decks (N): "); + int N = sc.nextInt(); + + System.out.print("Enter number of shuffles (M): "); + int M = sc.nextInt(); + + Deck deck = new Deck(N); + deck.shuffleDeck(M); + + Map> dealCards = deck.dealCards(11, 11); + + for (Map.Entry> entry : dealCards.entrySet()) { + Integer playerId = entry.getKey(); + List cards = entry.getValue(); + + System.out.println("Player " + playerId + ": " + cards); + } + + + System.out.println("Remaining cards: " + deck.remainingCards()); + } +} diff --git a/DeckOfCards/Rank.java b/DeckOfCards/Rank.java new file mode 100644 index 00000000..a7840c86 --- /dev/null +++ b/DeckOfCards/Rank.java @@ -0,0 +1,6 @@ +package DeckOfCards; + +enum Rank { + TWO, THREE, FOUR, FIVE, SIX, SEVEN, + EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE +} \ No newline at end of file diff --git a/DeckOfCards/Suit.java b/DeckOfCards/Suit.java new file mode 100644 index 00000000..75f1a3aa --- /dev/null +++ b/DeckOfCards/Suit.java @@ -0,0 +1,17 @@ +package DeckOfCards; + +public enum Suit { + SPADE(0), + HEART(1), + CLUB(2), + DIAMOND(3); + private final int value; + + private Suit(int value) { + this.value = value; + } + + public int getValue() { + return value; + } +} diff --git a/atm/ATM.java b/atm/ATM.java new file mode 100644 index 00000000..faad2738 --- /dev/null +++ b/atm/ATM.java @@ -0,0 +1,79 @@ +package atm; + + + +public class ATM { + + private static ATM atmObject = new ATM(); //Singleton: eager initialization + + ATMState currentATMState; + + private int atmBalance; + int noOfTwoThousandNotes; + int noOfFiveHundredNotes; + int noOfOneHundredNotes; + + + private ATM() { + } + + public void setCurrentATMState(ATMState currentATMState) { + this.currentATMState = currentATMState; + } + + public ATMState getCurrentATMState() { + return currentATMState; + } + + public static ATM getATMObject() { + atmObject.setCurrentATMState(new IdleState()); + return atmObject; + } + + public int getAtmBalance() { + return atmBalance; + } + + public void setAtmBalance(int atmBalance, int noOfTwoThousandNotes, int noOfFiveHundredNotes, int noOfOneHundredNotes) { + this.atmBalance = atmBalance; + this.noOfTwoThousandNotes = noOfTwoThousandNotes; + this.noOfFiveHundredNotes = noOfFiveHundredNotes; + this.noOfOneHundredNotes = noOfOneHundredNotes; + } + + public int getNoOfTwoThousandNotes() { + return noOfTwoThousandNotes; + } + + public int getNoOfFiveHundredNotes() { + return noOfFiveHundredNotes; + } + + public int getNoOfOneHundredNotes() { + return noOfOneHundredNotes; + } + + public void deductATMBalance(int amount) { + atmBalance = atmBalance - amount; + } + + public void deductTwoThousandNotes(int number) { + noOfTwoThousandNotes = noOfTwoThousandNotes - number; + } + + public void deductFiveHundredNotes(int number) { + noOfFiveHundredNotes = noOfFiveHundredNotes - number; + } + + public void deductOneHundredNotes(int number) { + noOfOneHundredNotes = noOfOneHundredNotes - number; + } + + public void printCurrentATMStatus(){ + System.out.println("Balance: " + atmBalance); + System.out.println("2kNotes: " + noOfTwoThousandNotes); + System.out.println("500Notes: " + noOfFiveHundredNotes); + System.out.println("100Notes: " + noOfOneHundredNotes); + + } +} diff --git a/atm/ATMRoom.java b/atm/ATMRoom.java new file mode 100644 index 00000000..893ba729 --- /dev/null +++ b/atm/ATMRoom.java @@ -0,0 +1,55 @@ +package atm; + +public class ATMRoom { + ATM atm; + User user; + + public static void main(String args[]) { + + ATMRoom atmRoom = new ATMRoom(); + atmRoom.initialize(); + + atmRoom.atm.printCurrentATMStatus(); + atmRoom.atm.getCurrentATMState().insertCard(atmRoom.atm, atmRoom.user.card); + atmRoom.atm.getCurrentATMState().authenticatePin(atmRoom.atm, atmRoom.user.card, 112211); + atmRoom.atm.getCurrentATMState().selectOperation(atmRoom.atm, atmRoom.user.card, TransactionType.CASH_WITHDRAWAL); + atmRoom.atm.getCurrentATMState().cashWithdrawal(atmRoom.atm, atmRoom.user.card, 2700); + atmRoom.atm.printCurrentATMStatus(); + + + } + + private void initialize() { + + //create ATM + atm = ATM.getATMObject(); + atm.setAtmBalance(3500, 1,2,5); + + //create User + this.user = createUser(); + } + + private User createUser(){ + + User user = new User(); + user.setCard(createCard()); + return user; + } + + private Card createCard(){ + + Card card = new Card(); + card.setBankAccount(createBankAccount()); + return card; + } + + private UserBankAccount createBankAccount() { + + UserBankAccount bankAccount = new UserBankAccount(); + bankAccount.balance = 3000; + + return bankAccount; + + } + +} diff --git a/atm/ATMState.java b/atm/ATMState.java new file mode 100644 index 00000000..c5022207 --- /dev/null +++ b/atm/ATMState.java @@ -0,0 +1,32 @@ +package atm; + +public abstract class ATMState { + + public void insertCard(ATM atm, Card card) { + System.out.println("OOPS!! Something went wrong"); + } + + public void authenticatePin(ATM atm, Card card, int pin){ + System.out.println("OOPS!! Something went wrong"); + } + + public void selectOperation(ATM atm, Card card, TransactionType txnType){ + System.out.println("OOPS!! Something went wrong"); + } + + public void cashWithdrawal(ATM atm, Card card, int withdrawAmount){ + System.out.println("OOPS!! Something went wrong"); + } + + public void displayBalance(ATM atm, Card card){ + System.out.println("OOPS!! Something went wrong"); + } + + public void returnCard(){ + System.out.println("OOPS!! Something went wrong"); + } + + public void exit(ATM atm){ + System.out.println("OOPS!! Something went wrong"); + } +} \ No newline at end of file diff --git a/atm/Card.java b/atm/Card.java new file mode 100644 index 00000000..45446478 --- /dev/null +++ b/atm/Card.java @@ -0,0 +1,31 @@ +package atm; + +public class Card { + + private int cardNumber; + private int cvv; + private int expiryDate; + private int holderName; + static int PIN_NUMBER = 112211; + private UserBankAccount bankAccount; + + public boolean isCorrectPINEntered(int pin) { + + if (pin == PIN_NUMBER) { + return true; + } + return false; + } + + public int getBankBalance(){ + return bankAccount.balance; + } + + public void deductBankBalance(int amount){ + bankAccount.withdrawalBalance(amount); + } + + public void setBankAccount(UserBankAccount bankAccount) { + this.bankAccount = bankAccount; + } +} \ No newline at end of file diff --git a/atm/CashWithdrawProcessor.java b/atm/CashWithdrawProcessor.java new file mode 100644 index 00000000..39903014 --- /dev/null +++ b/atm/CashWithdrawProcessor.java @@ -0,0 +1,19 @@ +package atm; + +public abstract class CashWithdrawProcessor { + + CashWithdrawProcessor nextCashWithdrawalProcessor; + + CashWithdrawProcessor(CashWithdrawProcessor cashWithdrawalProcessor) { + + this.nextCashWithdrawalProcessor = cashWithdrawalProcessor; + + } + + public void withdraw(ATM atm, int remainingAmount) { + + if (nextCashWithdrawalProcessor != null) { + nextCashWithdrawalProcessor.withdraw(atm, remainingAmount); + } + } +} \ No newline at end of file diff --git a/atm/CashWithdrawalState.java b/atm/CashWithdrawalState.java new file mode 100644 index 00000000..b462dfe6 --- /dev/null +++ b/atm/CashWithdrawalState.java @@ -0,0 +1,43 @@ +package atm; + + +public class CashWithdrawalState extends ATMState { + + public CashWithdrawalState() { + System.out.println("Please enter the Withdrawal Amount"); + } + + public void cashWithdrawal(ATM atmObject, Card card, int withdrawalAmountRequest) { + + if (atmObject.getAtmBalance() < withdrawalAmountRequest) { + System.out.println("Insufficient fund in the ATM Machine"); + exit(atmObject); + } else if (card.getBankBalance() < withdrawalAmountRequest) { + System.out.println("Insufficient fund in the your Bank Account"); + exit(atmObject); + } else { + + card.deductBankBalance(withdrawalAmountRequest); + atmObject.deductATMBalance(withdrawalAmountRequest); + + //using chain of responsibility for this logic, how many 2k Rs notes, how many 500 Rs notes etc, has to be withdrawal + CashWithdrawProcessor withdrawProcessor = + new TwoThousandWithdrawProcessor(new FiveHundredWithdrawProcessor(new OneHundredWithdrawProcessor(null))); + + withdrawProcessor.withdraw(atmObject, withdrawalAmountRequest); + exit(atmObject); + } + } + + @Override + public void exit(ATM atmObject) { + returnCard(); + atmObject.setCurrentATMState(new IdleState()); + System.out.println("Exit happens"); + } + + @Override + public void returnCard() { + System.out.println("Please collect your card"); + } +} \ No newline at end of file diff --git a/atm/CheckBalanceState.java b/atm/CheckBalanceState.java new file mode 100644 index 00000000..4125540f --- /dev/null +++ b/atm/CheckBalanceState.java @@ -0,0 +1,25 @@ +package atm; + +public class CheckBalanceState extends ATMState { + + public CheckBalanceState() { + } + + @Override + public void displayBalance(ATM atm, Card card){ + System.out.println("Your Balance is: " + card.getBankBalance()); + exit(atm); + } + + @Override + public void exit(ATM atmObject){ + returnCard(); + atmObject.setCurrentATMState(new IdleState()); + System.out.println("Exit happens"); + } + + @Override + public void returnCard(){ + System.out.println("Please collect your card"); + } +} \ No newline at end of file diff --git a/atm/FiveHundredWithdrawProcessor.java b/atm/FiveHundredWithdrawProcessor.java new file mode 100644 index 00000000..5ffa777f --- /dev/null +++ b/atm/FiveHundredWithdrawProcessor.java @@ -0,0 +1,26 @@ +package atm; + +public class FiveHundredWithdrawProcessor extends CashWithdrawProcessor { + + public FiveHundredWithdrawProcessor(CashWithdrawProcessor nextCashWithdrawProcessor){ + super(nextCashWithdrawProcessor); + } + + public void withdraw(ATM atm, int remainingAmount){ + + int required = remainingAmount/500; + int balance = remainingAmount%500; + + if(required <= atm.getNoOfFiveHundredNotes()) { + atm.deductFiveHundredNotes(required); + } + else if(required > atm.getNoOfFiveHundredNotes()) { + atm.deductFiveHundredNotes(atm.getNoOfFiveHundredNotes()); + balance = balance + (required-atm.getNoOfFiveHundredNotes()) * 500; + } + + if(balance != 0){ + super.withdraw(atm, balance); + } + } +} diff --git a/atm/HasCardState.java b/atm/HasCardState.java new file mode 100644 index 00000000..438f9bd2 --- /dev/null +++ b/atm/HasCardState.java @@ -0,0 +1,32 @@ +package atm; + +public class HasCardState extends ATMState { + + public HasCardState(){ + System.out.println("enter your card pin number"); + } + + @Override + public void authenticatePin(ATM atm, Card card, int pin){ + boolean isCorrectPinEntered = card.isCorrectPINEntered(pin); + + if(isCorrectPinEntered) { + atm.setCurrentATMState(new SelectOperationState()); + } else { + System.out.println("Invalid PIN Number"); + exit(atm); + } + } + + @Override + public void exit(ATM atm){ + returnCard(); + atm.setCurrentATMState(new IdleState()); + System.out.println("Exit happens"); + } + + @Override + public void returnCard(){ + System.out.println("Please collect your card"); + } +} \ No newline at end of file diff --git a/atm/IdleState.java b/atm/IdleState.java new file mode 100644 index 00000000..1049a468 --- /dev/null +++ b/atm/IdleState.java @@ -0,0 +1,10 @@ +package atm; + +public class IdleState extends ATMState { + + @Override + public void insertCard(ATM atm, Card card) { + System.out.println("Card is inserted"); + atm.setCurrentATMState(new HasCardState()); + } +} diff --git a/atm/OneHundredWithdrawProcessor.java b/atm/OneHundredWithdrawProcessor.java new file mode 100644 index 00000000..5784dc33 --- /dev/null +++ b/atm/OneHundredWithdrawProcessor.java @@ -0,0 +1,26 @@ +package atm; + +public class OneHundredWithdrawProcessor extends CashWithdrawProcessor { + + public OneHundredWithdrawProcessor(CashWithdrawProcessor nextCashWithdrawProcessor){ + super(nextCashWithdrawProcessor); + } + + public void withdraw(ATM atm, int remainingAmount){ + + int required = remainingAmount/100; + int balance = remainingAmount%100; + + if(required <= atm.getNoOfOneHundredNotes()) { + atm.deductOneHundredNotes(required); + } + else if(required > atm.getNoOfOneHundredNotes()) { + atm.deductOneHundredNotes(atm.getNoOfOneHundredNotes()); + balance = balance + (required-atm.getNoOfOneHundredNotes()) * 100; + } + + if(balance != 0){ + System.out.println("Something went wrong"); + } + } +} \ No newline at end of file diff --git a/atm/SelectOperationState.java b/atm/SelectOperationState.java new file mode 100644 index 00000000..02a8ab15 --- /dev/null +++ b/atm/SelectOperationState.java @@ -0,0 +1,44 @@ +package atm; + +public class SelectOperationState extends ATMState { + + public SelectOperationState(){ + showOperations(); + } + + @Override + public void selectOperation(ATM atmObject, Card card, TransactionType txnType){ + + switch (txnType) { + + case CASH_WITHDRAWAL: + atmObject.setCurrentATMState(new CashWithdrawalState()); + break; + case BALANCE_CHECK: + atmObject.setCurrentATMState(new CheckBalanceState()); + break; + default: { + System.out.println("Invalid Option"); + exit(atmObject); + } + + } + } + + @Override + public void exit(ATM atmObject){ + returnCard(); + atmObject.setCurrentATMState(new IdleState()); + System.out.println("Exit happens"); + } + + @Override + public void returnCard(){ + System.out.println("Please collect your card"); + } + + private void showOperations(){ + System.out.println("Please select the Operation"); + TransactionType.showAllTransactionTypes(); + } +} \ No newline at end of file diff --git a/atm/TransactionType.java b/atm/TransactionType.java new file mode 100644 index 00000000..c53b559e --- /dev/null +++ b/atm/TransactionType.java @@ -0,0 +1,14 @@ +package atm; + +public enum TransactionType { + + CASH_WITHDRAWAL, + BALANCE_CHECK; + + public static void showAllTransactionTypes(){ + + for(TransactionType type: TransactionType.values()){ + System.out.println(type.name()); + } + } +} \ No newline at end of file diff --git a/atm/TwoThousandWithdrawProcessor.java b/atm/TwoThousandWithdrawProcessor.java new file mode 100644 index 00000000..0f76d6ff --- /dev/null +++ b/atm/TwoThousandWithdrawProcessor.java @@ -0,0 +1,26 @@ +package atm; + +public class TwoThousandWithdrawProcessor extends CashWithdrawProcessor { + + public TwoThousandWithdrawProcessor(CashWithdrawProcessor nextCashWithdrawProcessor) { + super(nextCashWithdrawProcessor); + } + + public void withdraw(ATM atm, int remainingAmount) { + + int required = remainingAmount/2000; + int balance = remainingAmount%2000; + + if(required <= atm.getNoOfTwoThousandNotes()) { + atm.deductTwoThousandNotes(required); + } + else if(required > atm.getNoOfTwoThousandNotes()) { + atm.deductTwoThousandNotes(atm.getNoOfTwoThousandNotes()); + balance = balance + (required-atm.getNoOfTwoThousandNotes()) * 2000; + } + + if(balance != 0){ + super.withdraw(atm, balance); + } + } +} \ No newline at end of file diff --git a/atm/User.java b/atm/User.java new file mode 100644 index 00000000..46f9e042 --- /dev/null +++ b/atm/User.java @@ -0,0 +1,16 @@ +package atm; + + +public class User { + + public Card card; + public UserBankAccount bankAccount; + + public Card getCard() { + return card; + } + + public void setCard(Card card) { + this.card = card; + } +} \ No newline at end of file diff --git a/atm/UserBankAccount.java b/atm/UserBankAccount.java new file mode 100644 index 00000000..23d56fe4 --- /dev/null +++ b/atm/UserBankAccount.java @@ -0,0 +1,10 @@ +package atm; + +public class UserBankAccount { + + int balance; + + public void withdrawalBalance(int amount) { + balance = balance - amount; + } +} \ No newline at end of file diff --git a/bookmyshow/BookMyShow.java b/bookmyshow/BookMyShow.java new file mode 100644 index 00000000..c62004fc --- /dev/null +++ b/bookmyshow/BookMyShow.java @@ -0,0 +1,120 @@ +package bookmyshow; + +import java.util.*; + +public class BookMyShow { + private final Map> cityVsTheater; + private final List allTheaters; + private final BookingController bookingController; + + public BookMyShow() { + this.cityVsTheater = new HashMap<>(); + this.allTheaters = new ArrayList<>(); + this.bookingController = new BookingController(); + } + + public void addTheater(Theater theater, City city) { + allTheaters.add(theater); + cityVsTheater.computeIfAbsent(city, k -> new ArrayList<>()).add(theater); + } + + public String bookTicket(Movie movie, Show show, List seats, UserDetails user, Date bookingDate, Payment payment) { + return bookingController.bookTicket(movie, show, seats, user, bookingDate, payment); + } + + public Booking getBookingDetails(UserDetails user, Integer bookingId) { + return bookingController.getTicketDetails(user, bookingId); + } + + public void showAvailableTheaters(City city) { + List theaters = cityVsTheater.getOrDefault(city, new ArrayList<>()); + if (theaters.isEmpty()) { + System.out.println("No theaters available in " + city); + } else { + theaters.forEach(theater -> System.out.println(theater.getName())); + } + } + + public static void main(String[] args) { + BookMyShow bookMyShow = new BookMyShow(); + + // Creating Screens + Screen screen1 = new Screen(); + Screen screen2 = new Screen(); + + // Creating Movies + Movie movie1 = new Movie.MovieBuilder("RRR", 1,"Patriortic",new Date(),"Inception").setDuration(90).build(); + Movie movie2 = new Movie.MovieBuilder("RRR", 1,"Patriortic",new Date(),"Inception").setDuration(120).build(); + + // Creating Seats + Seat seatA1 = new Seat(); + seatA1.setSeatId(1); + seatA1.setSeatNumber("A1"); + seatA1.setSeatType(SeatType.REGULAR); + seatA1.setSeatStatus(SeatStatus.AVAILABLE); + + Seat seatA2 = new Seat(); + seatA2.setSeatId(2); + seatA2.setSeatNumber("A2"); + seatA2.setSeatType(SeatType.REGULAR); + seatA2.setSeatStatus(SeatStatus.AVAILABLE); + + // Creating Shows with seats + List show1Seats = Collections.synchronizedList(new ArrayList<>(List.of(1, 2))); + Show show1 = new Show(show1Seats, movie1, screen1, 1, 1900); + + List show2Seats = Collections.synchronizedList(new ArrayList<>(List.of(1, 2))); + Show show2 = new Show(show2Seats, movie2, screen2, 2, 2100); + + // Creating Theater + List screens = Arrays.asList(screen1, screen2); + List shows = Arrays.asList(show1, show2); + Theater theater = new Theater(City.Delhi, "PVR Cinemas", screens, shows, 1); + + // Adding Theater to BookMyShow + bookMyShow.addTheater(theater, City.Delhi); + + // Display available theaters in the city + bookMyShow.showAvailableTheaters(City.Delhi); + + // Create Users + UserDetails user1 = new UserDetails(); + user1.setUserId("U1001"); + user1.setName("Alice"); + user1.setEmail("alice@example.com"); + + UserDetails user2 = new UserDetails(); + user2.setUserId("U1002"); + user2.setName("Bob"); + user2.setEmail("bob@example.com"); + + // Create Payments + Payment payment1 = new Payment(); + payment1.setPaymentId("P1001"); + payment1.setAmount(250.0); + payment1.setType(PaymentType.CREDIT_CARD); + payment1.setStatus(PaymentStatus.SUCCESS); + payment1.setPaymentDate(new Date()); + + Payment payment2 = new Payment(); + payment2.setPaymentId("P1002"); + payment2.setAmount(250.0); + payment2.setType(PaymentType.DEBIT_CARD); + payment2.setStatus(PaymentStatus.SUCCESS); + payment2.setPaymentDate(new Date()); + + // Simulate Concurrent Booking + Thread user1Thread = new Thread(() -> { + String result = bookMyShow.bookTicket(movie1, show1, List.of(seatA1), user1, new Date(), payment1); + System.out.println("User 1: " + result); + }); + + Thread user2Thread = new Thread(() -> { + String result = bookMyShow.bookTicket(movie1, show1, List.of(seatA1), user2, new Date(), payment2); + System.out.println("User 2: " + result); + }); + + user1Thread.start(); + user2Thread.start(); + } +} diff --git a/bookmyshow/Booking.java b/bookmyshow/Booking.java new file mode 100644 index 00000000..da331fc3 --- /dev/null +++ b/bookmyshow/Booking.java @@ -0,0 +1,100 @@ +package bookmyshow; + + + +import java.util.Date; +import java.util.List; + + +class Booking { + private String bookingId; + private UserDetails user; + private Show show; + private List seats; + private Payment payment; + private BookingStatus status; + private Date bookingDate; + private ListbookedSeats; + + + // Constructors, getters, and setters + + + public Booking() { + } + + public Booking(List bookedSeats, Date bookingDate, String bookingId, Payment payment, List seats, Show show, BookingStatus status, UserDetails user) { + this.bookedSeats = bookedSeats; + this.bookingDate = bookingDate; + this.bookingId = bookingId; + this.payment = payment; + this.seats = seats; + this.show = show; + this.status = status; + this.user = user; + } + + public List getBookedSeats() { + return bookedSeats; + } + + public Date getBookingDate() { + return bookingDate; + } + + public String getBookingId() { + return bookingId; + } + + public Payment getPayment() { + return payment; + } + + public List getSeats() { + return seats; + } + + public Show getShow() { + return show; + } + + public BookingStatus getStatus() { + return status; + } + + public UserDetails getUser() { + return user; + } + + public void setBookedSeats(List bookedSeats) { + this.bookedSeats = bookedSeats; + } + + public void setBookingDate(Date bookingDate) { + this.bookingDate = bookingDate; + } + + public void setBookingId(String bookingId) { + this.bookingId = bookingId; + } + + public void setPayment(Payment payment) { + this.payment = payment; + } + + public void setSeats(List seats) { + this.seats = seats; + } + + public void setShow(Show show) { + this.show = show; + } + + public void setStatus(BookingStatus status) { + this.status = status; + } + + public void setUser(UserDetails user) { + this.user = user; + } +} diff --git a/bookmyshow/BookingController.java b/bookmyshow/BookingController.java new file mode 100644 index 00000000..c56c19fb --- /dev/null +++ b/bookmyshow/BookingController.java @@ -0,0 +1,52 @@ +package bookmyshow; + +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +import static bookmyshow.SeatStatus.BOOKED; + +public class BookingController { + + private final Map bookingRecords = new ConcurrentHashMap<>(); + private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); + private int bookingCounter = 1; + + // Book a ticket (Write Lock ensures one thread can write at a time) + public String bookTicket(Movie movie, Show show, List seats, UserDetails user, Date bookingDate, Payment payment) { + lock.writeLock().lock(); + try { + // Check if any seat is already booked + for (Seat seat : seats) { + if (seat.getSeatStatus().equals(BOOKED)) { + return "Seat " + seat.getSeatNumber() + " is already booked!"; + } + } + + // Mark seats as booked + for (Seat seat : seats) { + seat.setSeatStatus(BOOKED); + } + + int bookingId = bookingCounter++; + Booking bookingDetail = new Booking(seats, bookingDate, String.valueOf(bookingId), payment,seats, show, BookingStatus.CONFIRMED, user); + bookingRecords.put(bookingId, bookingDetail); + + return "Booking Successful! Booking ID: " + bookingId; + } finally { + lock.writeLock().unlock(); + } + } + + // Retrieve ticket details (Read Lock allows multiple reads) + public Booking getTicketDetails(UserDetails user, Integer bookingId) { + lock.readLock().lock(); + try { + return bookingRecords.get(bookingId); + } finally { + lock.readLock().unlock(); + } + } +} diff --git a/bookmyshow/BookingStatus.java b/bookmyshow/BookingStatus.java new file mode 100644 index 00000000..aca7ab98 --- /dev/null +++ b/bookmyshow/BookingStatus.java @@ -0,0 +1,5 @@ +package bookmyshow; + +enum BookingStatus { + CONFIRMED, CANCELLED, PENDING +} diff --git a/bookmyshow/City.java b/bookmyshow/City.java new file mode 100644 index 00000000..b63147ce --- /dev/null +++ b/bookmyshow/City.java @@ -0,0 +1,7 @@ +package bookmyshow; + +public enum City { + Bangalore, + Delhi; +} + diff --git a/bookmyshow/Location.java b/bookmyshow/Location.java new file mode 100644 index 00000000..0ceb8b42 --- /dev/null +++ b/bookmyshow/Location.java @@ -0,0 +1,48 @@ +package bookmyshow; + + + +import java.util.List; + + +class Location { + private String cityId; + private String cityName; + private List theaters; + + // Constructors, getters, and setters + + public Location() { + } + + public Location(String cityId, String cityName, List theaters) { + this.cityId = cityId; + this.cityName = cityName; + this.theaters = theaters; + } + + public String getCityId() { + return cityId; + } + + public String getCityName() { + return cityName; + } + + public List getTheaters() { + return theaters; + } + + public void setCityId(String cityId) { + this.cityId = cityId; + } + + public void setCityName(String cityName) { + this.cityName = cityName; + } + + public void setTheaters(List theaters) { + this.theaters = theaters; + } +} + diff --git a/bookmyshow/Movie.java b/bookmyshow/Movie.java new file mode 100644 index 00000000..041171bc --- /dev/null +++ b/bookmyshow/Movie.java @@ -0,0 +1,107 @@ +package bookmyshow; + + +import java.util.Date; + + +class Movie { + private Integer movieId; + private String movieName; + private String title; + private String genre; + private int duration; // Duration in minutes + private Date releaseDate; + + + // Constructors, getters, and setters + + + public Movie() { + } + + public Movie(MovieBuilder builder) { + this.duration = builder.duration; + this.genre = builder.genre; + this.movieId = builder.movieId; + this.movieName = builder.movieName; + this.releaseDate = builder.releaseDate; + this.title = builder.title; + } + + public int getDuration() { + return duration; + } + + public String getGenre() { + return genre; + } + + public Integer getMovieId() { + return movieId; + } + + public String getMovieName() { + return movieName; + } + + public Date getReleaseDate() { + return releaseDate; + } + + public String getTitle() { + return title; + } + + public void setDuration(int duration) { + this.duration = duration; + } + + public void setGenre(String genre) { + this.genre = genre; + } + + public void setMovieId(Integer movieId) { + this.movieId = movieId; + } + + public void setMovieName(String movieName) { + this.movieName = movieName; + } + + public void setReleaseDate(Date releaseDate) { + this.releaseDate = releaseDate; + } + + public void setTitle(String title) { + this.title = title; + } + + public static class MovieBuilder { + + private Integer movieId; + private String movieName; + private String title; + private String genre; + private int duration; // Duration in minutes // optional + private Date releaseDate; + + public MovieBuilder(String movieName, Integer movieId, String genre, Date releaseDate, String title) { + this.movieName = movieName; + this.movieId = movieId; + this.genre = genre; + this.releaseDate = releaseDate; + this.title = title; + } + + public MovieBuilder setDuration(int duration) { + this.duration = duration; + return this; + } + + public Movie build(){ + return new Movie(this); + } + + + } +} diff --git a/bookmyshow/MovieController.java b/bookmyshow/MovieController.java new file mode 100644 index 00000000..de442781 --- /dev/null +++ b/bookmyshow/MovieController.java @@ -0,0 +1,50 @@ +package bookmyshow; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class MovieController { + + Map> cityVsMovies; + List allMovies; + + MovieController(){ + cityVsMovies = new HashMap<>(); + allMovies = new ArrayList<>(); + } + + + //ADD movie to a particular city, make use of cityVsMovies map + void addMovie(Movie movie, City city) { + + allMovies.add(movie); + + List movies = cityVsMovies.getOrDefault(city, new ArrayList<>()); + movies.add(movie); + cityVsMovies.put(city, movies); + } + + + Movie getMovieByName(String name) { + + for(Movie movie : allMovies) { + if((movie.getMovieName()).equals(name)) { + return movie; + } + } + return null; + } + + + List getMoviesByCity(City city) { + return cityVsMovies.get(city); + } + //REMOVE movie from a particular city, make use of cityVsMovies map + + //UPDATE movie of a particular city, make use of cityVsMovies map + + //CRUD operation based on Movie ID, make use of allMovies list + +} diff --git a/bookmyshow/Payment.java b/bookmyshow/Payment.java new file mode 100644 index 00000000..324f3554 --- /dev/null +++ b/bookmyshow/Payment.java @@ -0,0 +1,55 @@ +package bookmyshow; + + +import java.util.Date; + + +class Payment { + private String paymentId; + private PaymentType type; + private double amount; + private PaymentStatus status; + private Date paymentDate; + + // Constructors, getters, and setters + + public double getAmount() { + return amount; + } + + public Date getPaymentDate() { + return paymentDate; + } + + public String getPaymentId() { + return paymentId; + } + + public PaymentStatus getStatus() { + return status; + } + + public PaymentType getType() { + return type; + } + + public void setAmount(double amount) { + this.amount = amount; + } + + public void setPaymentDate(Date paymentDate) { + this.paymentDate = paymentDate; + } + + public void setPaymentId(String paymentId) { + this.paymentId = paymentId; + } + + public void setStatus(PaymentStatus status) { + this.status = status; + } + + public void setType(PaymentType type) { + this.type = type; + } +} diff --git a/bookmyshow/PaymentStatus.java b/bookmyshow/PaymentStatus.java new file mode 100644 index 00000000..45e3ce0c --- /dev/null +++ b/bookmyshow/PaymentStatus.java @@ -0,0 +1,5 @@ +package bookmyshow; + +enum PaymentStatus { + SUCCESS, FAILURE, PENDING +} diff --git a/bookmyshow/PaymentType.java b/bookmyshow/PaymentType.java new file mode 100644 index 00000000..93eacd80 --- /dev/null +++ b/bookmyshow/PaymentType.java @@ -0,0 +1,5 @@ +package bookmyshow; + +enum PaymentType { + CREDIT_CARD, DEBIT_CARD, NET_BANKING, UPI, WALLET +} diff --git a/bookmyshow/Screen.java b/bookmyshow/Screen.java new file mode 100644 index 00000000..11ded4cb --- /dev/null +++ b/bookmyshow/Screen.java @@ -0,0 +1,55 @@ +package bookmyshow; + + +import java.util.List; + +class Screen { + private Integer screenId; + private String name; + + private List seats; + private List shows; + + // Constructors, getters, and setters + + public Screen() { + } + + public String getName() { + return name; + } + + public Integer getScreenId() { + return screenId; + } + + public List getSeats() { + return seats; + } + + public List getShows() { + return shows; + } + + + + public void setName(String name) { + this.name = name; + } + + public void setScreenId(Integer screenId) { + this.screenId = screenId; + } + + public void setSeats(List seats) { + this.seats = seats; + } + + public void setShows(List shows) { + this.shows = shows; + } + + +} + + diff --git a/bookmyshow/Seat.java b/bookmyshow/Seat.java new file mode 100644 index 00000000..ed130ca4 --- /dev/null +++ b/bookmyshow/Seat.java @@ -0,0 +1,71 @@ +package bookmyshow; + + +public class Seat { + private Integer seatId; + private String seatNumber; + private SeatType seatType; + private SeatStatus seatStatus; + private boolean isLocked = false; + + public synchronized boolean lockSeat() { + if (seatStatus == SeatStatus.AVAILABLE && !isLocked) { + isLocked = true; + return true; + } + return false; + } + + public synchronized void unlockSeat() { + isLocked = false; + } + + public synchronized boolean bookSeat() { + if (isLocked) { + seatStatus = SeatStatus.BOOKED; + isLocked = false; + return true; + } + return false; + } + + public boolean isLocked() { + return isLocked; + } + + public Integer getSeatId() { + return seatId; + } + + public String getSeatNumber() { + return seatNumber; + } + + public SeatStatus getSeatStatus() { + return seatStatus; + } + + public SeatType getSeatType() { + return seatType; + } + + public void setLocked(boolean locked) { + isLocked = locked; + } + + public void setSeatId(Integer seatId) { + this.seatId = seatId; + } + + public void setSeatNumber(String seatNumber) { + this.seatNumber = seatNumber; + } + + public void setSeatStatus(SeatStatus seatStatus) { + this.seatStatus = seatStatus; + } + + public void setSeatType(SeatType seatType) { + this.seatType = seatType; + } +} diff --git a/bookmyshow/SeatStatus.java b/bookmyshow/SeatStatus.java new file mode 100644 index 00000000..3f3c2a01 --- /dev/null +++ b/bookmyshow/SeatStatus.java @@ -0,0 +1,5 @@ +package bookmyshow; + +enum SeatStatus { + AVAILABLE, BOOKED, RESERVED +} diff --git a/bookmyshow/SeatType.java b/bookmyshow/SeatType.java new file mode 100644 index 00000000..cdd6bed5 --- /dev/null +++ b/bookmyshow/SeatType.java @@ -0,0 +1,5 @@ +package bookmyshow; + +enum SeatType { + REGULAR, PREMIUM, VIP +} diff --git a/bookmyshow/Show.java b/bookmyshow/Show.java new file mode 100644 index 00000000..6ed0ec2f --- /dev/null +++ b/bookmyshow/Show.java @@ -0,0 +1,67 @@ +package bookmyshow; + + + +import java.util.List; + + +class Show { + private Integer showId; + private Movie movie; + private Screen screen; + private Integer showTime; + private List bookedSeats; + + // Constructors, getters, and setters + + public Show() { + } + + public Show(List bookedSeats, Movie movie, Screen screen, Integer showId, Integer showTime) { + this.bookedSeats = bookedSeats; + this.movie = movie; + this.screen = screen; + this.showId = showId; + this.showTime = showTime; + } + + public List getBookedSeats() { + return bookedSeats; + } + + public Movie getMovie() { + return movie; + } + + public Screen getScreen() { + return screen; + } + + public Integer getShowId() { + return showId; + } + + public Integer getShowTime() { + return showTime; + } + + public void setBookedSeats(List bookedSeats) { + this.bookedSeats = bookedSeats; + } + + public void setMovie(Movie movie) { + this.movie = movie; + } + + public void setScreen(Screen screen) { + this.screen = screen; + } + + public void setShowId(Integer showId) { + this.showId = showId; + } + + public void setShowTime(Integer showTime) { + this.showTime = showTime; + } +} diff --git a/bookmyshow/Theater.java b/bookmyshow/Theater.java new file mode 100644 index 00000000..7b3ccee0 --- /dev/null +++ b/bookmyshow/Theater.java @@ -0,0 +1,67 @@ +package bookmyshow; + + +import java.util.List; + + +class Theater { + private Integer theaterId; + private String name; + private City city; + private List screens; + private List shows; + + // Constructors, getters, and setters + + public Theater() { + } + + public Theater(City city, String name, List screens, List shows, Integer theaterId) { + this.city = city; + this.name = name; + this.screens = screens; + this.shows = shows; + this.theaterId = theaterId; + } + + public City getCity() { + return city; + } + + public String getName() { + return name; + } + + public List getScreens() { + return screens; + } + + public List getShows() { + return shows; + } + + public Integer getTheaterId() { + return theaterId; + } + + public void setCity(City city) { + this.city = city; + } + + public void setName(String name) { + this.name = name; + } + + public void setScreens(List screens) { + this.screens = screens; + } + + public void setShows(List shows) { + this.shows = shows; + } + + public void setTheaterId(Integer theaterId) { + this.theaterId = theaterId; + } +} + diff --git a/bookmyshow/TheaterController.java b/bookmyshow/TheaterController.java new file mode 100644 index 00000000..e66e37a7 --- /dev/null +++ b/bookmyshow/TheaterController.java @@ -0,0 +1,56 @@ +package bookmyshow; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class TheaterController { + + Map> cityVsTheater; + List allTheater; + + TheaterController() { + cityVsTheater = new HashMap<>(); + allTheater = new ArrayList<>(); + } + + void addTheater(Theater Theater, City city) { + + allTheater.add(Theater); + + List Theaters = cityVsTheater.getOrDefault(city, new ArrayList<>()); + Theaters.add(Theater); + cityVsTheater.put(city, Theaters); + } + + + Map> getAllShow(Movie movie, City city) { + + //get all the theater of this city + + Map> TheaterVsShows = new HashMap<>(); + + List Theaters = cityVsTheater.get(city); + + //filter the Theaters which run this movie + + for(Theater Theater : Theaters) { + + List givenMovieShows = new ArrayList<>(); + List shows = Theater.getShows(); + + for(Show show : shows) { + if(show.getMovie().getMovieId() == movie.getMovieId()) { + givenMovieShows.add(show); + } + } + if(!givenMovieShows.isEmpty()) { + TheaterVsShows.put(Theater, givenMovieShows); + } + } + + return TheaterVsShows; + } +} + diff --git a/bookmyshow/UserDetails.java b/bookmyshow/UserDetails.java new file mode 100644 index 00000000..14bed601 --- /dev/null +++ b/bookmyshow/UserDetails.java @@ -0,0 +1,53 @@ +package bookmyshow; + + +class UserDetails { + private String userId; + private String name; + private String email; + private String phoneNumber; + private UserProfile profile; + + // Constructors, getters, and setters + + public String getEmail() { + return email; + } + + public String getName() { + return name; + } + + public String getPhoneNumber() { + return phoneNumber; + } + + public UserProfile getProfile() { + return profile; + } + + public String getUserId() { + return userId; + } + + public void setEmail(String email) { + this.email = email; + } + + public void setName(String name) { + this.name = name; + } + + public void setPhoneNumber(String phoneNumber) { + this.phoneNumber = phoneNumber; + } + + public void setProfile(UserProfile profile) { + this.profile = profile; + } + + public void setUserId(String userId) { + this.userId = userId; + } +} + diff --git a/bookmyshow/UserProfile.java b/bookmyshow/UserProfile.java new file mode 100644 index 00000000..9b445684 --- /dev/null +++ b/bookmyshow/UserProfile.java @@ -0,0 +1,26 @@ +package bookmyshow; + + +import java.util.List; +class UserProfile { + private String address; + private List bookings; + + // Constructors, getters, and setters + + public String getAddress() { + return address; + } + + public List getBookings() { + return bookings; + } + + public void setAddress(String address) { + this.address = address; + } + + public void setBookings(List bookings) { + this.bookings = bookings; + } +} diff --git a/cache/pom.xml b/cache/pom.xml new file mode 100644 index 00000000..c18b9983 --- /dev/null +++ b/cache/pom.xml @@ -0,0 +1,25 @@ + + + 4.0.0 + + org.example + cache + 1.0-SNAPSHOT + + + 21 + 21 + UTF-8 + + + + org.projectlombok + lombok + 1.18.30 + provided + + + + \ No newline at end of file diff --git a/cache/src/main/java/org/example/Cache.java b/cache/src/main/java/org/example/Cache.java new file mode 100644 index 00000000..8b5dbf30 --- /dev/null +++ b/cache/src/main/java/org/example/Cache.java @@ -0,0 +1,79 @@ +package org.example; + +import org.example.cache.policies.LRUEvictionPolicy; +import org.example.cache.storage.HashMapStorage; +import org.example.cache.storage.Storage; +import org.example.cache.policies.EvictionPolicy; + +import java.util.concurrent.CompletableFuture; + +public class Cache { + private final Storage storage; + private final EvictionPolicy evictionPolicy; + private final KeyBasedExecutor executor; + + public Cache(EvictionPolicy evictionPolicy, Storage storage, int threadCount) { + this.evictionPolicy = evictionPolicy; + this.storage = storage; + this.executor = new KeyBasedExecutor(threadCount); + } + + public CompletableFuture putAsync(Key k, Value v) { + CompletableFuture future = new CompletableFuture<>(); + executor.submit(k, () -> { + try { + storage.add(k, v); + evictionPolicy.keyAccessed(k); + future.complete(null); + } catch (Exception e) { + Key keyToRemove = evictionPolicy.evictKey(); + if (keyToRemove == null) { + future.completeExceptionally(new RuntimeException("Eviction failed")); + return; + } + storage.remove(keyToRemove); + // Retry after eviction + putAsync(k, v).thenAccept(future::complete) + .exceptionally(ex -> { future.completeExceptionally(ex); return null; }); + } + }); + return future; + } + + public CompletableFuture getAsync(Key k) { + CompletableFuture future = new CompletableFuture<>(); + executor.submit(k, () -> { + try { + Value value = storage.get(k); + evictionPolicy.keyAccessed(k); + future.complete(value); + } catch (RuntimeException e) { + future.complete(null); // key not present + } + }); + return future; + } + + public void shutdown() { + executor.shutdown(); + } + + + public static void main(String[] args) { + EvictionPolicy evictionPolicy = new LRUEvictionPolicy<>(); + Storage storage = new HashMapStorage<>(2); + + Cache cache = new Cache<>(evictionPolicy, storage, 4); // 4 threads + + cache.putAsync("1", "one").join(); + cache.putAsync("2", "two").join(); + + cache.getAsync("1").thenAccept(v -> System.out.println("Get 1: " + v)).join(); + cache.putAsync("3", "three").join(); // Should evict key "2" + + cache.getAsync("2").thenAccept(v -> System.out.println("Get 2 (should be null): " + v)).join(); + cache.getAsync("3").thenAccept(v -> System.out.println("Get 3: " + v)).join(); + + cache.shutdown(); + } +} \ No newline at end of file diff --git a/cache/src/main/java/org/example/KeyBasedExecutor.java b/cache/src/main/java/org/example/KeyBasedExecutor.java new file mode 100644 index 00000000..30666735 --- /dev/null +++ b/cache/src/main/java/org/example/KeyBasedExecutor.java @@ -0,0 +1,37 @@ +package org.example; + + +import java.util.concurrent.*; + +public class KeyBasedExecutor { + private final int numThreads; + private final ExecutorService[] executors; + + public KeyBasedExecutor(int numThreads) { + this.numThreads = numThreads; + this.executors = new ExecutorService[numThreads]; + for (int i = 0; i < numThreads; i++) { + executors[i] = Executors.newSingleThreadExecutor(); + } + } + + private int getExecutorIndex(Object key) { + return Math.abs(key.hashCode() % numThreads); + } + + public void submit(Object key, Runnable task) { + int index = getExecutorIndex(key); + executors[index].submit(task); + } + + public Future submit(Object key, Callable task) { + int index = getExecutorIndex(key); + return executors[index].submit(task); + } + + public void shutdown() { + for (ExecutorService executor : executors) { + executor.shutdown(); + } + } +} diff --git a/cache/src/main/java/org/example/cache/policies/DoublyLinkedList.java b/cache/src/main/java/org/example/cache/policies/DoublyLinkedList.java new file mode 100644 index 00000000..f1e205a1 --- /dev/null +++ b/cache/src/main/java/org/example/cache/policies/DoublyLinkedList.java @@ -0,0 +1,82 @@ +package org.example.cache.policies; + +import java.util.NoSuchElementException; + +public class DoublyLinkedList { + + DoublyLinkedListNode dummyHead; + DoublyLinkedListNode dummyTail; + + public DoublyLinkedList() { + // We can instantiate these by null, since we are never gonna use val for these dummyNodes + dummyHead = new DoublyLinkedListNode<>(null); + dummyTail = new DoublyLinkedListNode<>(null); + + // Also Initially there are no items + // so just join dummyHead and Tail, we can add items in between them easily. + dummyHead.next = dummyTail; + dummyTail.prev = dummyHead; + } + + /** + * Method to detach a random node from the doubly linked list. The node itself will not be removed from the memory. + * Just that it will be removed from the list and becomes orphaned. + * + * @param node Node to be detached. + */ + public void detachNode(DoublyLinkedListNode node) { + // Just Simply modifying the pointers. + if (node != null) { + node.prev.next = node.next; + node.next.prev = node.prev; + } + } + + /** + * Helper method to add a node at the end of the list. + * + * @param node Node to be added. + */ + public void addNodeAtLast(DoublyLinkedListNode node) { + DoublyLinkedListNode tailPrev = dummyTail.prev; + tailPrev.next = node; + node.next = dummyTail; + dummyTail.prev = node; + node.prev = tailPrev; + } + + /** + * Helper method to add an element at the end. + * + * @param element Element to be added. + * @return Reference to new node created for the element. + */ + public DoublyLinkedListNode addElementAtLast(E element) { + if (element == null) { + throw new RuntimeException(); + } + DoublyLinkedListNode newNode = new DoublyLinkedListNode<>(element); + addNodeAtLast(newNode); + return newNode; + } + + public boolean isItemPresent() { + return dummyHead.next != dummyTail; + } + + public DoublyLinkedListNode getFirstNode() throws NoSuchElementException { + DoublyLinkedListNode item = null; + if (!isItemPresent()) { + return null; + } + return dummyHead.next; + } + + public DoublyLinkedListNode getLastNode() throws NoSuchElementException { + DoublyLinkedListNode item = null; + if (!isItemPresent()) { + return null; + } + return dummyTail.prev; + } +} \ No newline at end of file diff --git a/cache/src/main/java/org/example/cache/policies/DoublyLinkedListNode.java b/cache/src/main/java/org/example/cache/policies/DoublyLinkedListNode.java new file mode 100644 index 00000000..40440653 --- /dev/null +++ b/cache/src/main/java/org/example/cache/policies/DoublyLinkedListNode.java @@ -0,0 +1,16 @@ +package org.example.cache.policies; + +import lombok.Getter; + +@Getter +public class DoublyLinkedListNode { + DoublyLinkedListNode next; + DoublyLinkedListNode prev; + E element; + + public DoublyLinkedListNode(E element) { + this.element = element; + this.next = null; + this.prev = null; + } +} \ No newline at end of file diff --git a/cache/src/main/java/org/example/cache/policies/EvictionPolicy.java b/cache/src/main/java/org/example/cache/policies/EvictionPolicy.java new file mode 100644 index 00000000..1bbb4a4b --- /dev/null +++ b/cache/src/main/java/org/example/cache/policies/EvictionPolicy.java @@ -0,0 +1,8 @@ +package org.example.cache.policies; + +public interface EvictionPolicy { + + void keyAccessed(Key key); + + Key evictKey(); +} diff --git a/cache/src/main/java/org/example/cache/policies/LRUEvictionPolicy.java b/cache/src/main/java/org/example/cache/policies/LRUEvictionPolicy.java new file mode 100644 index 00000000..816ff9bb --- /dev/null +++ b/cache/src/main/java/org/example/cache/policies/LRUEvictionPolicy.java @@ -0,0 +1,35 @@ +package org.example.cache.policies; + +import java.util.HashMap; +import java.util.Map; + +public class LRUEvictionPolicy implements EvictionPolicy{ + private DoublyLinkedList dll; + private Map> mapper; + + public LRUEvictionPolicy() { + this.dll = new DoublyLinkedList<>(); + this.mapper = new HashMap<>(); + } + + @Override + public void keyAccessed(Key key) { + if (mapper.containsKey(key)) { + dll.detachNode(mapper.get(key)); + dll.addNodeAtLast(mapper.get(key)); + } else { + DoublyLinkedListNode newNode = dll.addElementAtLast(key); + mapper.put(key, newNode); + } + } + + @Override + public Key evictKey() { + DoublyLinkedListNode first = dll.getFirstNode(); + if(first == null) { + return null; + } + dll.detachNode(first); + return first.getElement(); + } +} diff --git a/cache/src/main/java/org/example/cache/storage/HashMapStorage.java b/cache/src/main/java/org/example/cache/storage/HashMapStorage.java new file mode 100644 index 00000000..e67721f8 --- /dev/null +++ b/cache/src/main/java/org/example/cache/storage/HashMapStorage.java @@ -0,0 +1,38 @@ +package org.example.cache.storage; + + +import java.util.HashMap; +import java.util.Map; + +public class HashMapStorage implements Storage { + Map storage; + private final Integer capacity; + + public HashMapStorage(Integer capacity) { + this.capacity = capacity; + storage = new HashMap<>(); + } + + @Override + public void add(Key k, Value v) { + if(storage.size()==capacity) + throw new RuntimeException("Cache is Full"); + else + storage.put(k,v); + } + + @Override + public Value get(Key k) { + if(!storage.containsKey(k)) + { + throw new RuntimeException("Key is not available"); + } + return storage.get(k); + + } + + @Override + public void remove(Object k) { + storage.remove(k); + } +} diff --git a/cache/src/main/java/org/example/cache/storage/Storage.java b/cache/src/main/java/org/example/cache/storage/Storage.java new file mode 100644 index 00000000..cc53172f --- /dev/null +++ b/cache/src/main/java/org/example/cache/storage/Storage.java @@ -0,0 +1,7 @@ +package org.example.cache.storage; + +public interface Storage { + void add(Key k , Value v); + Value get(Key k); + void remove(Key k); +} diff --git a/coffeeMachine/BrewingState.java b/coffeeMachine/BrewingState.java new file mode 100644 index 00000000..a87f19f7 --- /dev/null +++ b/coffeeMachine/BrewingState.java @@ -0,0 +1,8 @@ +package coffeeMachine; + +class BrewingState implements MachineState { + @Override + public void handleRequest(CoffeeMachine machine) { + System.out.println("Machine is brewing coffee."); + } +} diff --git a/coffeeMachine/Coffee.java b/coffeeMachine/Coffee.java new file mode 100644 index 00000000..7c948236 --- /dev/null +++ b/coffeeMachine/Coffee.java @@ -0,0 +1,50 @@ +package coffeeMachine; + +class Coffee { + private int waterRequired; + private int milkRequired; + private int coffeeBeansRequired; + + private Coffee(CoffeeBuilder builder) { + this.waterRequired = builder.waterRequired; + this.milkRequired = builder.milkRequired; + this.coffeeBeansRequired = builder.coffeeBeansRequired; + } + + public int getWaterRequired() { + return waterRequired; + } + + public int getMilkRequired() { + return milkRequired; + } + + public int getCoffeeBeansRequired() { + return coffeeBeansRequired; + } + + public static class CoffeeBuilder { + private int waterRequired; + private int milkRequired; + private int coffeeBeansRequired; + + public CoffeeBuilder setWaterRequired(int waterRequired) { + this.waterRequired = waterRequired; + return this; + } + + public CoffeeBuilder setMilkRequired(int milkRequired) { + this.milkRequired = milkRequired; + return this; + } + + public CoffeeBuilder setCoffeeBeansRequired(int coffeeBeansRequired) { + this.coffeeBeansRequired = coffeeBeansRequired; + return this; + } + + public Coffee build() { + return new Coffee(this); + } + } +} diff --git a/coffeeMachine/CoffeeCommand.java b/coffeeMachine/CoffeeCommand.java new file mode 100644 index 00000000..ae763b0c --- /dev/null +++ b/coffeeMachine/CoffeeCommand.java @@ -0,0 +1,5 @@ +package coffeeMachine; + +interface CoffeeCommand { + void execute(); +} \ No newline at end of file diff --git a/coffeeMachine/CoffeeFactory.java b/coffeeMachine/CoffeeFactory.java new file mode 100644 index 00000000..70c7555f --- /dev/null +++ b/coffeeMachine/CoffeeFactory.java @@ -0,0 +1,11 @@ +package coffeeMachine; + +class CoffeeFactory { + public static Coffee createCoffee(CoffeeType coffeeType) { + return new Coffee.CoffeeBuilder() + .setWaterRequired(coffeeType.waterRequired) + .setMilkRequired(coffeeType.milkRequired) + .setCoffeeBeansRequired(coffeeType.coffeeBeansRequired) + .build(); + } +} diff --git a/coffeeMachine/CoffeeMachine.java b/coffeeMachine/CoffeeMachine.java new file mode 100644 index 00000000..7bc9cba2 --- /dev/null +++ b/coffeeMachine/CoffeeMachine.java @@ -0,0 +1,52 @@ +package coffeeMachine; + +class CoffeeMachine { + private static CoffeeMachine instance; + + private int water = 1000; + private int milk = 500; + private int coffeeBeans = 200; + + private MachineState currentState; + + private CoffeeMachine() { + this.currentState = new ReadyState(); + } + + public static CoffeeMachine getInstance() { + if (instance == null) { + instance = new CoffeeMachine(); + } + return instance; + } + + public void setState(MachineState state) { + this.currentState = state; + } + + public void processState() { + currentState.handleRequest(this); + } + + public boolean hasEnoughIngredients(Coffee coffee) { + return water >= coffee.getWaterRequired() && + milk >= coffee.getMilkRequired() && + coffeeBeans >= coffee.getCoffeeBeansRequired(); + } + + public void makeCoffee(CoffeeType coffeeType) { + Coffee coffee = CoffeeFactory.createCoffee(coffeeType); + if (hasEnoughIngredients(coffee)) { + setState(new BrewingState()); + processState(); + water -= coffee.getWaterRequired(); + milk -= coffee.getMilkRequired(); + coffeeBeans -= coffee.getCoffeeBeansRequired(); + System.out.println("Your " + coffeeType.name() + " is ready!"); + setState(new ReadyState()); + } else { + setState(new OutOfStockState()); + processState(); + } + } +} diff --git a/coffeeMachine/CoffeeMachineInvoker.java b/coffeeMachine/CoffeeMachineInvoker.java new file mode 100644 index 00000000..00cd8d0a --- /dev/null +++ b/coffeeMachine/CoffeeMachineInvoker.java @@ -0,0 +1,15 @@ +package coffeeMachine; + +class CoffeeMachineInvoker { + private CoffeeCommand command; + + public void setCommand(CoffeeCommand command) { + this.command = command; + } + + public void processCommand() { + if (command != null) { + command.execute(); + } + } +} diff --git a/coffeeMachine/CoffeeType.java b/coffeeMachine/CoffeeType.java new file mode 100644 index 00000000..c7bfed94 --- /dev/null +++ b/coffeeMachine/CoffeeType.java @@ -0,0 +1,17 @@ +package coffeeMachine; + +enum CoffeeType { + ESPRESSO(50, 0, 15), + LATTE(50, 150, 20), + CAPPUCCINO(50, 100, 20); + + int waterRequired; + int milkRequired; + int coffeeBeansRequired; + + CoffeeType(int waterRequired, int milkRequired, int coffeeBeansRequired) { + this.waterRequired = waterRequired; + this.milkRequired = milkRequired; + this.coffeeBeansRequired = coffeeBeansRequired; + } +} diff --git a/coffeeMachine/MachineState.java b/coffeeMachine/MachineState.java new file mode 100644 index 00000000..fc833a0c --- /dev/null +++ b/coffeeMachine/MachineState.java @@ -0,0 +1,5 @@ +package coffeeMachine; + +interface MachineState { + void handleRequest(CoffeeMachine machine); +} diff --git a/coffeeMachine/Main.java b/coffeeMachine/Main.java new file mode 100644 index 00000000..dbbf790a --- /dev/null +++ b/coffeeMachine/Main.java @@ -0,0 +1,21 @@ +package coffeeMachine; + +public class Main { + public static void main(String[] args) { + CoffeeMachine machine = CoffeeMachine.getInstance(); + + CoffeeMachineInvoker invoker = new CoffeeMachineInvoker(); + + // User selects Espresso + invoker.setCommand(new MakeCoffeeCommand(machine, CoffeeType.ESPRESSO)); + invoker.processCommand(); + + // User selects Latte + invoker.setCommand(new MakeCoffeeCommand(machine, CoffeeType.LATTE)); + invoker.processCommand(); + + // User selects Cappuccino + invoker.setCommand(new MakeCoffeeCommand(machine, CoffeeType.CAPPUCCINO)); + invoker.processCommand(); + } +} diff --git a/coffeeMachine/MakeCoffeeCommand.java b/coffeeMachine/MakeCoffeeCommand.java new file mode 100644 index 00000000..3d2ed31e --- /dev/null +++ b/coffeeMachine/MakeCoffeeCommand.java @@ -0,0 +1,16 @@ +package coffeeMachine; + +class MakeCoffeeCommand implements CoffeeCommand { + private CoffeeMachine machine; + private CoffeeType coffeeType; + + public MakeCoffeeCommand(CoffeeMachine machine, CoffeeType coffeeType) { + this.machine = machine; + this.coffeeType = coffeeType; + } + + @Override + public void execute() { + machine.makeCoffee(coffeeType); + } +} \ No newline at end of file diff --git a/coffeeMachine/OutOfStockState.java b/coffeeMachine/OutOfStockState.java new file mode 100644 index 00000000..d81d86ac --- /dev/null +++ b/coffeeMachine/OutOfStockState.java @@ -0,0 +1,8 @@ +package coffeeMachine; + +class OutOfStockState implements MachineState { + @Override + public void handleRequest(CoffeeMachine machine) { + System.out.println("Machine is out of stock. Please refill ingredients."); + } +} \ No newline at end of file diff --git a/coffeeMachine/ReadyState.java b/coffeeMachine/ReadyState.java new file mode 100644 index 00000000..4023479a --- /dev/null +++ b/coffeeMachine/ReadyState.java @@ -0,0 +1,8 @@ +package coffeeMachine; + +class ReadyState implements MachineState { + @Override + public void handleRequest(CoffeeMachine machine) { + System.out.println("Machine is ready. Choose your coffee."); + } +} diff --git a/cricbuzz/BallType.java b/cricbuzz/BallType.java new file mode 100644 index 00000000..94641da5 --- /dev/null +++ b/cricbuzz/BallType.java @@ -0,0 +1,8 @@ +package cricbuzz; + +public enum BallType { + NORMAL, + NO_BALL, + WIDE_BALL +} + diff --git a/cricbuzz/Balls.java b/cricbuzz/Balls.java new file mode 100644 index 00000000..2e592231 --- /dev/null +++ b/cricbuzz/Balls.java @@ -0,0 +1,136 @@ +package cricbuzz; + + + +import java.util.ArrayList; +import java.util.List; + + +public class Balls { + + int ballNumber; + BallType type; + RunType runType; + Player playedBy; + Player bowledBy; + public Wicket wicket; + List scoreUpdaterObserverList = new ArrayList<>(); + + public Balls(int ballNumber) { + this.ballNumber = ballNumber; + scoreUpdaterObserverList.add(new BowlingScoreUpdater()); + scoreUpdaterObserverList.add(new BattingScoreUpdater()); + } + + public int getBallNumber() { + return ballNumber; + } + + public Player getBowledBy() { + return bowledBy; + } + + public Player getPlayedBy() { + return playedBy; + } + + public List getScoreUpdaterObserverList() { + return scoreUpdaterObserverList; + } + + public BallType getType() { + return type; + } + + public Wicket getWicket() { + return wicket; + } + + public void setBallNumber(int ballNumber) { + this.ballNumber = ballNumber; + } + + public void setBowledBy(Player bowledBy) { + this.bowledBy = bowledBy; + } + + public void setPlayedBy(Player playedBy) { + this.playedBy = playedBy; + } + + public void setRunType(RunType runType) { + this.runType = runType; + } + + public void setScoreUpdaterObserverList(List scoreUpdaterObserverList) { + this.scoreUpdaterObserverList = scoreUpdaterObserverList; + } + + public void setType(BallType type) { + this.type = type; + } + + public void setWicket(Wicket wicket) { + this.wicket = wicket; + } + + public void startBallDelivery(Team battingTeam, Team bowlingTeam, Overs over) { + + playedBy = battingTeam.getStriker(); + this.bowledBy = over.bowledBy; + //THROW BALL AND GET THE BALL TYPE, assuming here that ball type is always NORMAL + type = BallType.NORMAL; + + //wicket or no wicket + if (isWicketTaken()) { + runType = RunType.ZERO; + //considering only BOLD + wicket = new Wicket(WicketType.BOLD, bowlingTeam.getCurrentBowler(), over,this); + //making only striker out for now + battingTeam.setStriker(null); + } else { + runType = getRunType(); + + if(runType == RunType.ONE || runType == RunType.THREE) { + //swap striket and non striker + Player temp = battingTeam.getStriker(); + battingTeam.setStriker(battingTeam.getNonStriker()); + battingTeam.setNonStriker(temp); + } + } + + //update player scoreboard + notifyUpdaters(this); + } + + private void notifyUpdaters(Balls Balls){ + + for(ScoreUpdaterObserver observer : scoreUpdaterObserverList) { + observer.update(Balls); + } + } + + private RunType getRunType() { + + double val = Math.random(); + if (val <= 0.2) { + return RunType.ONE; + } else if (val >= 0.3 && val <= 0.5) { + return RunType.TWO; + } else if (val >= 0.6 && val <= 0.8) { + return RunType.FOUR; + } else { + return RunType.SIX; + } + } + + private boolean isWicketTaken() { + //random function return value between 0 and 1 + if (Math.random() < 0.2) { + return true; + } else { + return false; + } + } + +} diff --git a/cricbuzz/BattingScoreCard.java b/cricbuzz/BattingScoreCard.java new file mode 100644 index 00000000..3f8ca58c --- /dev/null +++ b/cricbuzz/BattingScoreCard.java @@ -0,0 +1,11 @@ +package cricbuzz; + +public class BattingScoreCard { + int totalRuns; + int totalBallsPlayed; + int totalFours; + int totalSixes; + int strikeRate; + public Wicket wicketDetails; +} + diff --git a/cricbuzz/BattingScoreUpdater.java b/cricbuzz/BattingScoreUpdater.java new file mode 100644 index 00000000..24ef3513 --- /dev/null +++ b/cricbuzz/BattingScoreUpdater.java @@ -0,0 +1,28 @@ +package cricbuzz; + +public class BattingScoreUpdater implements ScoreUpdaterObserver { + @Override + public void update(Balls ballDetails) { + int run = 0; + + if (RunType.ONE == ballDetails.runType) { + run = 1; + } else if (RunType.TWO == ballDetails.runType) { + run = 2; + } else if (RunType.FOUR == ballDetails.runType) { + run = 4; + ballDetails.playedBy.battingScoreCard.totalFours++; + } else if (RunType.SIX == ballDetails.runType) { + run = 6; + ballDetails.playedBy.battingScoreCard.totalSixes++; + } + ballDetails.playedBy.battingScoreCard.totalRuns += run; + + ballDetails.playedBy.battingScoreCard.totalBallsPlayed++; + + if (ballDetails.wicket != null) { + ballDetails.playedBy.battingScoreCard.wicketDetails = ballDetails.wicket; + } + } +} + diff --git a/cricbuzz/BowlingScoreCard.java b/cricbuzz/BowlingScoreCard.java new file mode 100644 index 00000000..70afb52f --- /dev/null +++ b/cricbuzz/BowlingScoreCard.java @@ -0,0 +1,11 @@ +package cricbuzz; + +public class BowlingScoreCard { + int totalOversDelivered; + int runsGiven; + int wicketsTaken; + int noBallCount; + int wideBalls; + double economyRate; +} + diff --git a/cricbuzz/BowlingScoreUpdater.java b/cricbuzz/BowlingScoreUpdater.java new file mode 100644 index 00000000..7144317b --- /dev/null +++ b/cricbuzz/BowlingScoreUpdater.java @@ -0,0 +1,33 @@ +package cricbuzz; + +public class BowlingScoreUpdater implements ScoreUpdaterObserver { + @Override + public void update(Balls Balls) { + + if (Balls.ballNumber == 6 && Balls.type == BallType.NORMAL) { + Balls.bowledBy.bowlingScoreCard.totalOversDelivered++; + } + + if (RunType.ONE == Balls.runType) { + Balls.bowledBy.bowlingScoreCard.runsGiven += 1; + } else if (RunType.TWO == Balls.runType) { + Balls.bowledBy.bowlingScoreCard.runsGiven += 2; + } else if (RunType.FOUR == Balls.runType) { + Balls.bowledBy.bowlingScoreCard.runsGiven += 4; + } else if (RunType.SIX == Balls.runType) { + Balls.bowledBy.bowlingScoreCard.runsGiven += 6; + } + + if (Balls.wicket != null) { + Balls.bowledBy.bowlingScoreCard.wicketsTaken++; + } + + if (Balls.type == BallType.NO_BALL) { + Balls.bowledBy.bowlingScoreCard.noBallCount++; + } + + if (Balls.type == BallType.WIDE_BALL) { + Balls.bowledBy.bowlingScoreCard.wideBalls++; + } + } +} diff --git a/cricbuzz/Innings.java b/cricbuzz/Innings.java new file mode 100644 index 00000000..b0e262d1 --- /dev/null +++ b/cricbuzz/Innings.java @@ -0,0 +1,55 @@ +package cricbuzz; + +import java.util.ArrayList; +import java.util.List; + +public class Innings { + + Team battingTeam; + Team bowlingTeam; + MatchType matchType; + List Overss; + public Innings(Team battingTeam, Team bowlingTeam, MatchType matchType) { + this.battingTeam = battingTeam; + this.bowlingTeam = bowlingTeam; + this.matchType = matchType; + Overss = new ArrayList<>(); + } + + public void start(int runsToWin){ + + //set batting players + try { + battingTeam.chooseNextBatsMan(); + }catch (Exception e) { + + } + + int noOfOverss = matchType.noOfOvers(); + for (int OversNumber = 1; OversNumber <= noOfOverss; OversNumber++) { + + //chooseBowler + bowlingTeam.chooseNextBowler(matchType.maxOverCountBowlers()); + + Overs Overs = new Overs(OversNumber, bowlingTeam.getCurrentBowler()); + Overss.add(Overs); + try { + boolean won = Overs.startOver(battingTeam, bowlingTeam, runsToWin); + if(won == true) { + break; + } + }catch (Exception e) { + break; + } + + //swap striket and non striker + Player temp = battingTeam.getStriker(); + battingTeam.setStriker(battingTeam.getNonStriker()); + battingTeam.setNonStriker(temp); + } + } + + public int getTotalRuns(){ + return battingTeam.getTotalRuns(); + } +} diff --git a/cricbuzz/Main.java b/cricbuzz/Main.java new file mode 100644 index 00000000..3b163fd9 --- /dev/null +++ b/cricbuzz/Main.java @@ -0,0 +1,69 @@ +package cricbuzz; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; + +public class Main { + + public static void main(String args[]) { + + Main ob = new Main(); + + Team teamA = ob.addTeam("India"); + Team teamB = ob.addTeam("SriLanka"); + + MatchType matchType = new T20MatchType(); + Match match = new Match(teamA, teamB, null, "SMS STADIUM", matchType); + match.startMatch(); + + } + + private Team addTeam(String name) { + + Queue Player = new LinkedList<>(); + + Player p1 = addPlayer(name + "1", PlayerType.ALLROUNDER); + Player p2 = addPlayer(name + "2", PlayerType.ALLROUNDER); + Player p3 = addPlayer(name + "3", PlayerType.ALLROUNDER); + Player p4 = addPlayer(name + "4", PlayerType.ALLROUNDER); + Player p5 = addPlayer(name + "5", PlayerType.ALLROUNDER); + Player p6 = addPlayer(name + "6", PlayerType.ALLROUNDER); + Player p7 = addPlayer(name + "7", PlayerType.ALLROUNDER); + Player p8 = addPlayer(name + "8", PlayerType.ALLROUNDER); + Player p9 = addPlayer(name + "9", PlayerType.ALLROUNDER); + Player p10 = addPlayer(name + "10", PlayerType.ALLROUNDER); + Player p11 = addPlayer(name + "11", PlayerType.ALLROUNDER); + + Player.add(p1); + Player.add(p2); + Player.add(p3); + Player.add(p4); + Player.add(p5); + Player.add(p6); + Player.add(p7); + Player.add(p8); + Player.add(p9); + Player.add(p10); + Player.add(p11); + + List bowlers = new ArrayList<>(); + bowlers.add(p8); + bowlers.add(p9); + bowlers.add(p10); + bowlers.add(p11); + + Team team = new Team(name, Player, new ArrayList<>(), bowlers); + return team; + + } + + private Player addPlayer(String name, PlayerType playerType) { + + Person person = new Person(); + person.name = name; + Player Player = new Player(person, playerType); + return Player; + } +} diff --git a/cricbuzz/Match.java b/cricbuzz/Match.java new file mode 100644 index 00000000..895a790e --- /dev/null +++ b/cricbuzz/Match.java @@ -0,0 +1,89 @@ +package cricbuzz; + +import java.util.Date; + +public class Match { + Team teamA; + Team teamB; + Date date; + String location; + Innings[] innings; + MatchType type; + Team tossWon; + + public Match(Team teamA, Team teamB, Date matchDate, String venue, MatchType matchType) { + + this.teamA = teamA; + this.teamB = teamB; + this.date = matchDate; + this.location = venue; + this.type = matchType; + innings = new Innings[2]; + } + + public void startMatch() { + + //1. Toss + tossWon = toss(teamA, teamB); + + //start The Inning, there are 2 innings in a match + for(int inning=1; inning<=2; inning++){ + + Innings inningDetails; + Team bowlingTeam; + Team battingTeam; + + //assuming here that tossWon batFirst + boolean isChasing = false; + if(inning == 1){ + battingTeam = tossWon; + bowlingTeam = tossWon.getTeamName().equals(teamA.getTeamName()) ? teamB : teamA; + inningDetails = new Innings(battingTeam, bowlingTeam, type); + inningDetails.start( -1); + + }else { + bowlingTeam = tossWon; + battingTeam = tossWon.getTeamName().equals(teamA.getTeamName()) ? teamB : teamA; + inningDetails = new Innings(battingTeam, bowlingTeam, type); + inningDetails.start(innings[0].getTotalRuns()); + if(bowlingTeam.getTotalRuns() > battingTeam.getTotalRuns()) { + bowlingTeam.isWinner = true; + } + } + + + innings[inning-1] = inningDetails; + + //print inning details + System.out.println(); + System.out.println("INNING " + inning + " -- total Run: " + battingTeam.getTotalRuns()); + System.out.println("---Batting ScoreCard : " + battingTeam.name + "---"); + + battingTeam.printBattingScoreCard(); + + System.out.println(); + System.out.println("---Bowling ScoreCard : " + bowlingTeam.name + "---"); + bowlingTeam.printBowlingScoreCard(); + + } + + System.out.println(); + if(teamA.isWinner){ + System.out.println("---WINNER---" + teamA.name); + + }else { + System.out.println("---WINNER---" + teamB.name); + + } + + } + + private Team toss(Team teamA, Team teamB){ + //random function return value between 0 and 1 + if(Math.random() < 0.5) { + return teamA; + } else { + return teamB; + } + } +} diff --git a/cricbuzz/MatchType.java b/cricbuzz/MatchType.java new file mode 100644 index 00000000..62cef2b0 --- /dev/null +++ b/cricbuzz/MatchType.java @@ -0,0 +1,6 @@ +package cricbuzz; + +public interface MatchType { + public int noOfOvers(); + public int maxOverCountBowlers(); +} diff --git a/cricbuzz/OneDayMatchType.java b/cricbuzz/OneDayMatchType.java new file mode 100644 index 00000000..e681d09d --- /dev/null +++ b/cricbuzz/OneDayMatchType.java @@ -0,0 +1,13 @@ +package cricbuzz; + +public class OneDayMatchType implements MatchType { + @Override + public int noOfOvers() { + return 50; + } + + @Override + public int maxOverCountBowlers() { + return 10; + } +} diff --git a/cricbuzz/Overs.java b/cricbuzz/Overs.java new file mode 100644 index 00000000..7888b594 --- /dev/null +++ b/cricbuzz/Overs.java @@ -0,0 +1,81 @@ +package cricbuzz; + + + +import java.util.ArrayList; +import java.util.List; + + +public class Overs { + int overNumber; + List balls; + int extraBallsCount; + Player bowledBy; + + + Overs(int overNumber, Player bowledBy){ + this.overNumber = overNumber; + balls = new ArrayList<>(); + this.bowledBy = bowledBy; + } + + public List getBalls() { + return balls; + } + + public Player getBowledBy() { + return bowledBy; + } + + public int getExtraBallsCount() { + return extraBallsCount; + } + + public int getOverNumber() { + return overNumber; + } + + public void setBalls(List balls) { + this.balls = balls; + } + + public void setBowledBy(Player bowledBy) { + this.bowledBy = bowledBy; + } + + public void setExtraBallsCount(int extraBallsCount) { + this.extraBallsCount = extraBallsCount; + } + + public void setOverNumber(int overNumber) { + this.overNumber = overNumber; + } + + public boolean startOver(Team battingTeam, Team bowlingTeam, int runsToWin) throws Exception{ + + int ballCount = 1; + while(ballCount<=6){ + + Balls ball = new Balls(ballCount); + ball.startBallDelivery(battingTeam, bowlingTeam, this); + if(ball.type == BallType.NORMAL) { + balls.add(ball); + ballCount++; + if(ball.wicket != null) { + battingTeam.chooseNextBatsMan(); + } + + if( runsToWin != -1 && battingTeam.getTotalRuns() >= runsToWin){ + battingTeam.isWinner = true; + return true; + } + } + else { + extraBallsCount++; + } + } + + return false; + } + +} diff --git a/cricbuzz/Person.java b/cricbuzz/Person.java new file mode 100644 index 00000000..4850988f --- /dev/null +++ b/cricbuzz/Person.java @@ -0,0 +1,7 @@ +package cricbuzz; + +public class Person { + String name; + int age; +} + diff --git a/cricbuzz/Player.java b/cricbuzz/Player.java new file mode 100644 index 00000000..b9054dbc --- /dev/null +++ b/cricbuzz/Player.java @@ -0,0 +1,26 @@ +package cricbuzz; + +public class Player { + Person person; + PlayerType type; + BattingScoreCard battingScoreCard; + BowlingScoreCard bowlingScoreCard; + public Player(Person person, PlayerType playerType){ + this.person = person; + this.type = playerType; + battingScoreCard = new BattingScoreCard(); + bowlingScoreCard = new BowlingScoreCard(); + } + + public void printBattingScoreCard(){ + + System.out.println("PlayerName: " + person.name + " -- totalRuns: " + battingScoreCard.totalRuns + + " -- totalBallsPlayed: " + battingScoreCard.totalBallsPlayed + " -- 4s: " + battingScoreCard.totalFours + + " -- 6s: " + battingScoreCard.totalSixes + " -- outby: " + ((battingScoreCard.wicketDetails != null) ? battingScoreCard.wicketDetails.takenBy.person.name : "notout")); + } + + public void printBowlingScoreCard(){ + System.out.println("PlayerName: " + person.name + " -- totalOversThrown: " + bowlingScoreCard.totalOversDelivered + + " -- totalRunsGiven: " + bowlingScoreCard.runsGiven + " -- WicketsTaken: " + bowlingScoreCard.wicketsTaken); + } +} diff --git a/cricbuzz/PlayerBattingController.java b/cricbuzz/PlayerBattingController.java new file mode 100644 index 00000000..db90de8a --- /dev/null +++ b/cricbuzz/PlayerBattingController.java @@ -0,0 +1,46 @@ +package cricbuzz; + +import java.util.LinkedList; +import java.util.Queue; + +public class PlayerBattingController { + Queue yetToPlay; + Player striker; + Player nonStriker; + public PlayerBattingController(Queue playing11) { + this.yetToPlay = new LinkedList<>(); + this.yetToPlay.addAll(playing11); + } + + public void getNextPlayer() throws Exception { + + if (yetToPlay.isEmpty()) { + throw new Exception(); + } + + if (striker == null) { + striker = yetToPlay.poll(); + } + + if (nonStriker == null) { + nonStriker = yetToPlay.poll(); + } + } + + public Player getStriker() { + return striker; + } + + public Player getNonStriker() { + return nonStriker; + } + + public void setStriker(Player Player) { + striker = Player; + } + + public void setNonStriker(Player Player) { + nonStriker = Player; + } + +} diff --git a/cricbuzz/PlayerBowlingController.java b/cricbuzz/PlayerBowlingController.java new file mode 100644 index 00000000..fbf991f6 --- /dev/null +++ b/cricbuzz/PlayerBowlingController.java @@ -0,0 +1,38 @@ +package cricbuzz; + +import java.util.*; + +public class PlayerBowlingController { + Deque bowler; + Map blowerOverCount; + Player currentBowler; + public PlayerBowlingController(List bowlers) { + setBowlersList(bowlers); + } + + private void setBowlersList(List bowlersList) { + this.bowler = new LinkedList<>(); + blowerOverCount = new HashMap<>(); + for (Player bowler : bowlersList) { + this.bowler.addLast(bowler); + blowerOverCount.put(bowler, 0); + } + } + + public void getNextBowler(int maxOverCountPerBowler) { + + Player Player = bowler.poll(); + if(blowerOverCount.get(Player)+1 == maxOverCountPerBowler) { + currentBowler = Player; + } + else { + currentBowler = Player; + bowler.addLast(Player); + blowerOverCount.put(Player, blowerOverCount.get(Player)+1); + } + } + + public Player getCurrentBowler(){ + return currentBowler; + } +} diff --git a/cricbuzz/PlayerType.java b/cricbuzz/PlayerType.java new file mode 100644 index 00000000..0306e2ee --- /dev/null +++ b/cricbuzz/PlayerType.java @@ -0,0 +1,10 @@ +package cricbuzz; + +public enum PlayerType { + BOWLER, + BATSMAN, + WICKET_KEEPER, + ALLROUNDER, + CAPTAIN +} + diff --git a/cricbuzz/RunType.java b/cricbuzz/RunType.java new file mode 100644 index 00000000..abf2a162 --- /dev/null +++ b/cricbuzz/RunType.java @@ -0,0 +1,12 @@ +package cricbuzz; + +public enum RunType { + ZERO, + ONE, + TWO, + THREE, + FOUR, + SIX, + WIDE_RUN +} + diff --git a/cricbuzz/ScoreUpdaterObserver.java b/cricbuzz/ScoreUpdaterObserver.java new file mode 100644 index 00000000..5ad46a27 --- /dev/null +++ b/cricbuzz/ScoreUpdaterObserver.java @@ -0,0 +1,7 @@ +package cricbuzz; + +public interface ScoreUpdaterObserver { + + public void update(Balls ballDetails); +} + diff --git a/cricbuzz/T20MatchType.java b/cricbuzz/T20MatchType.java new file mode 100644 index 00000000..bc5c8a52 --- /dev/null +++ b/cricbuzz/T20MatchType.java @@ -0,0 +1,15 @@ +package cricbuzz; + +public class T20MatchType implements MatchType{ + @Override + public int noOfOvers() { + return 20; + } + + @Override + public int maxOverCountBowlers() { + return 5; + } + +} + diff --git a/cricbuzz/Team.java b/cricbuzz/Team.java new file mode 100644 index 00000000..057cfee3 --- /dev/null +++ b/cricbuzz/Team.java @@ -0,0 +1,81 @@ +package cricbuzz; + + +import java.util.List; +import java.util.Queue; + + + +public class Team { + + String name; + Queue players; + List extraPlayers; + PlayerBattingController battingController; + PlayerBowlingController bowlingController; + public boolean isWinner; + public Team(String teamName, Queue playing11, List bench, List bowlers){ + this.name = teamName; + this.players = playing11; + this.extraPlayers = bench; + battingController = new PlayerBattingController(playing11); + bowlingController = new PlayerBowlingController(bowlers); + } + + public String getTeamName() { + return name; + } + + public void chooseNextBatsMan() throws Exception{ + battingController.getNextPlayer(); + } + + public void chooseNextBowler(int maxOverCountPerBowler){ + bowlingController.getNextBowler(maxOverCountPerBowler); + } + + public Player getStriker() { + return battingController.getStriker(); + } + + public Player getNonStriker() { + return battingController.getNonStriker(); + } + + public void setStriker(Player player) { + battingController.setStriker(player); + } + + public void setNonStriker(Player player) { + battingController.setNonStriker(player); + } + + public Player getCurrentBowler() { + return bowlingController.getCurrentBowler(); + } + + public void printBattingScoreCard(){ + + for(Player Player : players){ + Player.printBattingScoreCard(); + } + } + + public void printBowlingScoreCard(){ + + for(Player Player : players){ + if(Player.bowlingScoreCard.totalOversDelivered > 0) { + Player.printBowlingScoreCard(); + } + } + } + + public int getTotalRuns(){ + int totalRun=0; + for (Player player : players){ + + totalRun+=player.battingScoreCard.totalRuns; + } + return totalRun; + } +} diff --git a/cricbuzz/Wicket.java b/cricbuzz/Wicket.java new file mode 100644 index 00000000..4768bde7 --- /dev/null +++ b/cricbuzz/Wicket.java @@ -0,0 +1,18 @@ +package cricbuzz; + +public class Wicket { + + public WicketType wicketType; + public Player takenBy; + public Overs overDetail; + public Balls ballDetail; + + public Wicket(WicketType wicketType, Player takenBy, Overs overDetail, Balls ballDetail) { + this.wicketType = wicketType; + this.takenBy = takenBy; + this.overDetail = overDetail; + this.ballDetail = ballDetail; + } +} + + diff --git a/cricbuzz/WicketType.java b/cricbuzz/WicketType.java new file mode 100644 index 00000000..93673775 --- /dev/null +++ b/cricbuzz/WicketType.java @@ -0,0 +1,9 @@ +package cricbuzz; + +public enum WicketType { + + RUNOUT, + BOLD, + CATCH; +} + diff --git a/elevatorSystem/ATM.java b/elevatorSystem/ATM.java new file mode 100644 index 00000000..25949ac6 --- /dev/null +++ b/elevatorSystem/ATM.java @@ -0,0 +1,78 @@ +package elevatorSystem; + + +public class ATM { + + private static ATM atmObject = new ATM(); //Singleton: eager initialization + + ATMState currentATMState; + + private int atmBalance; + int noOfTwoThousandNotes; + int noOfFiveHundredNotes; + int noOfOneHundredNotes; + + + private ATM() { + } + + public void setCurrentATMState(ATMState currentATMState) { + this.currentATMState = currentATMState; + } + + public ATMState getCurrentATMState() { + return currentATMState; + } + + public static ATM getATMObject() { + atmObject.setCurrentATMState(new IdleState()); + return atmObject; + } + + public int getAtmBalance() { + return atmBalance; + } + + public void setAtmBalance(int atmBalance, int noOfTwoThousandNotes, int noOfFiveHundredNotes, int noOfOneHundredNotes) { + this.atmBalance = atmBalance; + this.noOfTwoThousandNotes = noOfTwoThousandNotes; + this.noOfFiveHundredNotes = noOfFiveHundredNotes; + this.noOfOneHundredNotes = noOfOneHundredNotes; + } + + public int getNoOfTwoThousandNotes() { + return noOfTwoThousandNotes; + } + + public int getNoOfFiveHundredNotes() { + return noOfFiveHundredNotes; + } + + public int getNoOfOneHundredNotes() { + return noOfOneHundredNotes; + } + + public void deductATMBalance(int amount) { + atmBalance = atmBalance - amount; + } + + public void deductTwoThousandNotes(int number) { + noOfTwoThousandNotes = noOfTwoThousandNotes - number; + } + + public void deductFiveHundredNotes(int number) { + noOfFiveHundredNotes = noOfFiveHundredNotes - number; + } + + public void deductOneHundredNotes(int number) { + noOfOneHundredNotes = noOfOneHundredNotes - number; + } + + public void printCurrentATMStatus(){ + System.out.println("Balance: " + atmBalance); + System.out.println("2kNotes: " + noOfTwoThousandNotes); + System.out.println("500Notes: " + noOfFiveHundredNotes); + System.out.println("100Notes: " + noOfOneHundredNotes); + + } +} diff --git a/elevatorSystem/ATMRoom.java b/elevatorSystem/ATMRoom.java new file mode 100644 index 00000000..5f9cff73 --- /dev/null +++ b/elevatorSystem/ATMRoom.java @@ -0,0 +1,55 @@ +package elevatorSystem; + +public class ATMRoom { + ATM atm; + User user; + + public static void main(String args[]) { + + ATMRoom atmRoom = new ATMRoom(); + atmRoom.initialize(); + + atmRoom.atm.printCurrentATMStatus(); + atmRoom.atm.getCurrentATMState().insertCard(atmRoom.atm, atmRoom.user.card); + atmRoom.atm.getCurrentATMState().authenticatePin(atmRoom.atm, atmRoom.user.card, 112211); + atmRoom.atm.getCurrentATMState().selectOperation(atmRoom.atm, atmRoom.user.card, TransactionType.CASH_WITHDRAWAL); + atmRoom.atm.getCurrentATMState().cashWithdrawal(atmRoom.atm, atmRoom.user.card, 2700); + atmRoom.atm.printCurrentATMStatus(); + + + } + + private void initialize() { + + //create ATM + atm = ATM.getATMObject(); + atm.setAtmBalance(3500, 1,2,5); + + //create User + this.user = createUser(); + } + + private User createUser(){ + + User user = new User(); + user.setCard(createCard()); + return user; + } + + private Card createCard(){ + + Card card = new Card(); + card.setBankAccount(createBankAccount()); + return card; + } + + private UserBankAccount createBankAccount() { + + UserBankAccount bankAccount = new UserBankAccount(); + bankAccount.balance = 3000; + + return bankAccount; + + } + +} diff --git a/elevatorSystem/ATMState.java b/elevatorSystem/ATMState.java new file mode 100644 index 00000000..8c7d4f9e --- /dev/null +++ b/elevatorSystem/ATMState.java @@ -0,0 +1,32 @@ +package elevatorSystem; + +public abstract class ATMState { + + public void insertCard(ATM atm, Card card) { + System.out.println("OOPS!! Something went wrong"); + } + + public void authenticatePin(ATM atm, Card card, int pin){ + System.out.println("OOPS!! Something went wrong"); + } + + public void selectOperation(ATM atm, Card card, TransactionType txnType){ + System.out.println("OOPS!! Something went wrong"); + } + + public void cashWithdrawal(ATM atm, Card card, int withdrawAmount){ + System.out.println("OOPS!! Something went wrong"); + } + + public void displayBalance(ATM atm, Card card){ + System.out.println("OOPS!! Something went wrong"); + } + + public void returnCard(){ + System.out.println("OOPS!! Something went wrong"); + } + + public void exit(ATM atm){ + System.out.println("OOPS!! Something went wrong"); + } +} \ No newline at end of file diff --git a/elevatorSystem/Card.java b/elevatorSystem/Card.java new file mode 100644 index 00000000..9936aaf5 --- /dev/null +++ b/elevatorSystem/Card.java @@ -0,0 +1,31 @@ +package elevatorSystem; + +public class Card { + + private int cardNumber; + private int cvv; + private int expiryDate; + private int holderName; + static int PIN_NUMBER = 112211; + private UserBankAccount bankAccount; + + public boolean isCorrectPINEntered(int pin) { + + if (pin == PIN_NUMBER) { + return true; + } + return false; + } + + public int getBankBalance(){ + return bankAccount.balance; + } + + public void deductBankBalance(int amount){ + bankAccount.withdrawalBalance(amount); + } + + public void setBankAccount(UserBankAccount bankAccount) { + this.bankAccount = bankAccount; + } +} \ No newline at end of file diff --git a/elevatorSystem/CashWithdrawProcessor.java b/elevatorSystem/CashWithdrawProcessor.java new file mode 100644 index 00000000..b6d1225e --- /dev/null +++ b/elevatorSystem/CashWithdrawProcessor.java @@ -0,0 +1,19 @@ +package elevatorSystem; + +public abstract class CashWithdrawProcessor { + + CashWithdrawProcessor nextCashWithdrawalProcessor; + + CashWithdrawProcessor(CashWithdrawProcessor cashWithdrawalProcessor) { + + this.nextCashWithdrawalProcessor = cashWithdrawalProcessor; + + } + + public void withdraw(ATM atm, int remainingAmount) { + + if (nextCashWithdrawalProcessor != null) { + nextCashWithdrawalProcessor.withdraw(atm, remainingAmount); + } + } +} \ No newline at end of file diff --git a/elevatorSystem/CashWithdrawalState.java b/elevatorSystem/CashWithdrawalState.java new file mode 100644 index 00000000..540b5a24 --- /dev/null +++ b/elevatorSystem/CashWithdrawalState.java @@ -0,0 +1,43 @@ +package elevatorSystem; + + +public class CashWithdrawalState extends ATMState { + + public CashWithdrawalState() { + System.out.println("Please enter the Withdrawal Amount"); + } + + public void cashWithdrawal(ATM atmObject, Card card, int withdrawalAmountRequest) { + + if (atmObject.getAtmBalance() < withdrawalAmountRequest) { + System.out.println("Insufficient fund in the ATM Machine"); + exit(atmObject); + } else if (card.getBankBalance() < withdrawalAmountRequest) { + System.out.println("Insufficient fund in the your Bank Account"); + exit(atmObject); + } else { + + card.deductBankBalance(withdrawalAmountRequest); + atmObject.deductATMBalance(withdrawalAmountRequest); + + //using chain of responsibility for this logic, how many 2k Rs notes, how many 500 Rs notes etc, has to be withdrawal + CashWithdrawProcessor withdrawProcessor = + new TwoThousandWithdrawProcessor(new FiveHundredWithdrawProcessor(new OneHundredWithdrawProcessor(null))); + + withdrawProcessor.withdraw(atmObject, withdrawalAmountRequest); + exit(atmObject); + } + } + + @Override + public void exit(ATM atmObject) { + returnCard(); + atmObject.setCurrentATMState(new IdleState()); + System.out.println("Exit happens"); + } + + @Override + public void returnCard() { + System.out.println("Please collect your card"); + } +} \ No newline at end of file diff --git a/elevatorSystem/CheckBalanceState.java b/elevatorSystem/CheckBalanceState.java new file mode 100644 index 00000000..d3c86414 --- /dev/null +++ b/elevatorSystem/CheckBalanceState.java @@ -0,0 +1,25 @@ +package elevatorSystem; + +public class CheckBalanceState extends ATMState { + + public CheckBalanceState() { + } + + @Override + public void displayBalance(ATM atm, Card card){ + System.out.println("Your Balance is: " + card.getBankBalance()); + exit(atm); + } + + @Override + public void exit(ATM atmObject){ + returnCard(); + atmObject.setCurrentATMState(new IdleState()); + System.out.println("Exit happens"); + } + + @Override + public void returnCard(){ + System.out.println("Please collect your card"); + } +} \ No newline at end of file diff --git a/elevatorSystem/FiveHundredWithdrawProcessor.java b/elevatorSystem/FiveHundredWithdrawProcessor.java new file mode 100644 index 00000000..b1944001 --- /dev/null +++ b/elevatorSystem/FiveHundredWithdrawProcessor.java @@ -0,0 +1,26 @@ +package elevatorSystem; + +public class FiveHundredWithdrawProcessor extends CashWithdrawProcessor { + + public FiveHundredWithdrawProcessor(CashWithdrawProcessor nextCashWithdrawProcessor){ + super(nextCashWithdrawProcessor); + } + + public void withdraw(ATM atm, int remainingAmount){ + + int required = remainingAmount/500; + int balance = remainingAmount%500; + + if(required <= atm.getNoOfFiveHundredNotes()) { + atm.deductFiveHundredNotes(required); + } + else if(required > atm.getNoOfFiveHundredNotes()) { + atm.deductFiveHundredNotes(atm.getNoOfFiveHundredNotes()); + balance = balance + (required-atm.getNoOfFiveHundredNotes()) * 500; + } + + if(balance != 0){ + super.withdraw(atm, balance); + } + } +} diff --git a/elevatorSystem/HasCardState.java b/elevatorSystem/HasCardState.java new file mode 100644 index 00000000..b0dc5f5e --- /dev/null +++ b/elevatorSystem/HasCardState.java @@ -0,0 +1,32 @@ +package elevatorSystem; + +public class HasCardState extends ATMState { + + public HasCardState(){ + System.out.println("enter your card pin number"); + } + + @Override + public void authenticatePin(ATM atm, Card card, int pin){ + boolean isCorrectPinEntered = card.isCorrectPINEntered(pin); + + if(isCorrectPinEntered) { + atm.setCurrentATMState(new SelectOperationState()); + } else { + System.out.println("Invalid PIN Number"); + exit(atm); + } + } + + @Override + public void exit(ATM atm){ + returnCard(); + atm.setCurrentATMState(new IdleState()); + System.out.println("Exit happens"); + } + + @Override + public void returnCard(){ + System.out.println("Please collect your card"); + } +} \ No newline at end of file diff --git a/elevatorSystem/IdleState.java b/elevatorSystem/IdleState.java new file mode 100644 index 00000000..5607353d --- /dev/null +++ b/elevatorSystem/IdleState.java @@ -0,0 +1,10 @@ +package elevatorSystem; + +public class IdleState extends ATMState { + + @Override + public void insertCard(ATM atm, Card card) { + System.out.println("Card is inserted"); + atm.setCurrentATMState(new HasCardState()); + } +} diff --git a/elevatorSystem/OneHundredWithdrawProcessor.java b/elevatorSystem/OneHundredWithdrawProcessor.java new file mode 100644 index 00000000..1e90bfbb --- /dev/null +++ b/elevatorSystem/OneHundredWithdrawProcessor.java @@ -0,0 +1,26 @@ +package elevatorSystem; + +public class OneHundredWithdrawProcessor extends CashWithdrawProcessor { + + public OneHundredWithdrawProcessor(CashWithdrawProcessor nextCashWithdrawProcessor){ + super(nextCashWithdrawProcessor); + } + + public void withdraw(ATM atm, int remainingAmount){ + + int required = remainingAmount/100; + int balance = remainingAmount%100; + + if(required <= atm.getNoOfOneHundredNotes()) { + atm.deductOneHundredNotes(required); + } + else if(required > atm.getNoOfOneHundredNotes()) { + atm.deductOneHundredNotes(atm.getNoOfOneHundredNotes()); + balance = balance + (required-atm.getNoOfOneHundredNotes()) * 100; + } + + if(balance != 0){ + System.out.println("Something went wrong"); + } + } +} \ No newline at end of file diff --git a/elevatorSystem/SelectOperationState.java b/elevatorSystem/SelectOperationState.java new file mode 100644 index 00000000..fd242876 --- /dev/null +++ b/elevatorSystem/SelectOperationState.java @@ -0,0 +1,44 @@ +package elevatorSystem; + +public class SelectOperationState extends ATMState { + + public SelectOperationState(){ + showOperations(); + } + + @Override + public void selectOperation(ATM atmObject, Card card, TransactionType txnType){ + + switch (txnType) { + + case CASH_WITHDRAWAL: + atmObject.setCurrentATMState(new CashWithdrawalState()); + break; + case BALANCE_CHECK: + atmObject.setCurrentATMState(new CheckBalanceState()); + break; + default: { + System.out.println("Invalid Option"); + exit(atmObject); + } + + } + } + + @Override + public void exit(ATM atmObject){ + returnCard(); + atmObject.setCurrentATMState(new IdleState()); + System.out.println("Exit happens"); + } + + @Override + public void returnCard(){ + System.out.println("Please collect your card"); + } + + private void showOperations(){ + System.out.println("Please select the Operation"); + TransactionType.showAllTransactionTypes(); + } +} \ No newline at end of file diff --git a/elevatorSystem/TransactionType.java b/elevatorSystem/TransactionType.java new file mode 100644 index 00000000..cafbf964 --- /dev/null +++ b/elevatorSystem/TransactionType.java @@ -0,0 +1,14 @@ +package elevatorSystem; + +public enum TransactionType { + + CASH_WITHDRAWAL, + BALANCE_CHECK; + + public static void showAllTransactionTypes(){ + + for(TransactionType type: TransactionType.values()){ + System.out.println(type.name()); + } + } +} \ No newline at end of file diff --git a/elevatorSystem/TwoThousandWithdrawProcessor.java b/elevatorSystem/TwoThousandWithdrawProcessor.java new file mode 100644 index 00000000..a17523fb --- /dev/null +++ b/elevatorSystem/TwoThousandWithdrawProcessor.java @@ -0,0 +1,26 @@ +package elevatorSystem; + +public class TwoThousandWithdrawProcessor extends CashWithdrawProcessor { + + public TwoThousandWithdrawProcessor(CashWithdrawProcessor nextCashWithdrawProcessor) { + super(nextCashWithdrawProcessor); + } + + public void withdraw(ATM atm, int remainingAmount) { + + int required = remainingAmount/2000; + int balance = remainingAmount%2000; + + if(required <= atm.getNoOfTwoThousandNotes()) { + atm.deductTwoThousandNotes(required); + } + else if(required > atm.getNoOfTwoThousandNotes()) { + atm.deductTwoThousandNotes(atm.getNoOfTwoThousandNotes()); + balance = balance + (required-atm.getNoOfTwoThousandNotes()) * 2000; + } + + if(balance != 0){ + super.withdraw(atm, balance); + } + } +} \ No newline at end of file diff --git a/elevatorSystem/User.java b/elevatorSystem/User.java new file mode 100644 index 00000000..5216d725 --- /dev/null +++ b/elevatorSystem/User.java @@ -0,0 +1,16 @@ +package elevatorSystem; + + +public class User { + + public Card card; + public UserBankAccount bankAccount; + + public Card getCard() { + return card; + } + + public void setCard(Card card) { + this.card = card; + } +} \ No newline at end of file diff --git a/elevatorSystem/UserBankAccount.java b/elevatorSystem/UserBankAccount.java new file mode 100644 index 00000000..13ce6ff0 --- /dev/null +++ b/elevatorSystem/UserBankAccount.java @@ -0,0 +1,10 @@ +package elevatorSystem; + +public class UserBankAccount { + + int balance; + + public void withdrawalBalance(int amount) { + balance = balance - amount; + } +} \ No newline at end of file diff --git a/flighbookingsystem/Airline.java b/flighbookingsystem/Airline.java new file mode 100644 index 00000000..7571b02b --- /dev/null +++ b/flighbookingsystem/Airline.java @@ -0,0 +1,31 @@ +package flighbookingsystem; + +import java.util.ArrayList; +import java.util.List; + +public class Airline { + String name; + List flightList; + + public Airline(String name, List flightList) { + this.name = name; + this.flightList = new ArrayList<>(); + } + + public String getName() { + return name; + } + + public List getFlightList() { + return flightList; + } + + public void setName(String name) { + this.name = name; + } + + public void setFlightList(List flightList) { + this.flightList = flightList; + } +} + diff --git a/flighbookingsystem/Airport.java b/flighbookingsystem/Airport.java new file mode 100644 index 00000000..554ed74b --- /dev/null +++ b/flighbookingsystem/Airport.java @@ -0,0 +1,16 @@ +package flighbookingsystem; + +import java.util.List; + +public class Airport { + String name; + String loc; + List flightList; + + public Airport(String name, String loc, List flightList) { + this.name = name; + this.loc = loc; + this.flightList = flightList; + } +} + diff --git a/flighbookingsystem/BookingDetail.java b/flighbookingsystem/BookingDetail.java new file mode 100644 index 00000000..331a2fbf --- /dev/null +++ b/flighbookingsystem/BookingDetail.java @@ -0,0 +1,13 @@ +package flighbookingsystem; + +import java.util.Date; + +public class BookingDetail { + String bookingId; + Flight flight; + String start; + String destination; + Date date; + String pnr; +} + diff --git a/flighbookingsystem/BookingSystem.java b/flighbookingsystem/BookingSystem.java new file mode 100644 index 00000000..34ca3317 --- /dev/null +++ b/flighbookingsystem/BookingSystem.java @@ -0,0 +1,95 @@ +package flighbookingsystem; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.List; + +public class BookingSystem { + private List userList; + private List flightList; + private List bookingList; + + public BookingSystem(List userList, List flightList) { + this.userList = userList; + this.flightList = flightList; + } + + public void setUserList(List userList) { + this.userList = userList; + } + + // Add a flight to the system + public void addFlight(Flight flight) { + flightList.add(flight); + } + + // Add a user to the system + public void addUser(User user) { + userList.add(user); + } + + // Get available flights based on criteria + public List getFlightDetails(String start, String end, String date) { + + SimpleDateFormat inputFormat = new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy"); + SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"); + return flightList.stream() + .filter(flight -> flight.getSchedules().stream() + .anyMatch(schedule -> { + try { + // Define the input and output date formats + + + // Convert date from schedule to desired format + String formattedDate = outputFormat.format(inputFormat.parse(schedule.getDateOfJourney().toString())); + + // Compare converted date with the provided date + return schedule.getStart().loc.equals(start) && + schedule.getDestination().loc.equals(end) + && + formattedDate.equals(date); + } catch (ParseException e) { + e.printStackTrace(); + return false; // Skip schedules with invalid dates + } + })) + .toList(); + } + + // Book a flight +// public BookingDetail bookFlight(Flight flight, User user) { +// if (flight.getAvailableSeats() <= 0) { +// System.out.println("No available seats on this flight."); +// return null; +// } +// +// // Generate a booking ID +// String bookingId = "BOOK" + (bookingList.size() + 1); +// +// // Reduce available seats +// flight.setAvailableSeats(flight.getAvailableSeats() - 1); +// +// // Create and store booking +// BookingDetail bookingDetail = new BookingDetail(bookingId, flight, user, new Timestamp(System.currentTimeMillis())); +// bookingList.add(bookingDetail); +// +// System.out.println("Booking confirmed: " + bookingDetail); +// return bookingDetail; +// } +// +// // Confirm booking +// public void confirmBooking(BookingDetail details) { +// if (details == null) { +// System.out.println("Invalid booking details."); +// } else { +// System.out.println("Booking confirmed for user: " + details.getUser().getName() + +// " on flight: " + details.getFlight().getFlightNumber()); +// } +// } + + // View all bookings + public List getAllBookings() { + return bookingList; + } +} + diff --git a/flighbookingsystem/Flight.java b/flighbookingsystem/Flight.java new file mode 100644 index 00000000..b6423fe1 --- /dev/null +++ b/flighbookingsystem/Flight.java @@ -0,0 +1,62 @@ +package flighbookingsystem; + +import java.util.ArrayList; +import java.util.List; + + +public class Flight { + private String id; + private Airline airline; + private int seatCapacity; + List seats; + List schedules; + + public Flight(String id, Airline airline, int seatCapacity, List seats, List schedules) { + this.id = id; + this.airline = airline; + this.seatCapacity = seatCapacity; + this.seats = new ArrayList<>(); + this.schedules = new ArrayList<>(); + } + + public void setId(String id) { + this.id = id; + } + + public void setAirline(Airline airline) { + this.airline = airline; + } + + public void setSeatCapacity(int seatCapacity) { + this.seatCapacity = seatCapacity; + } + + public void setSeats(List seats) { + this.seats = seats; + } + + public void setSchedules(List schedules) { + this.schedules = schedules; + } + + public String getId() { + return id; + } + + public Airline getAirline() { + return airline; + } + + public int getSeatCapacity() { + return seatCapacity; + } + + public List getSeats() { + return seats; + } + + public List getSchedules() { + return schedules; + } +} + diff --git a/flighbookingsystem/FlightSeat.java b/flighbookingsystem/FlightSeat.java new file mode 100644 index 00000000..ff1318c8 --- /dev/null +++ b/flighbookingsystem/FlightSeat.java @@ -0,0 +1,13 @@ +package flighbookingsystem; + +public class FlightSeat extends Seat{ + int price; + Status status; + + public FlightSeat(int price, Status status) { + super(); + this.price = price; + this.status = status; + } +} + diff --git a/flighbookingsystem/Main.java b/flighbookingsystem/Main.java new file mode 100644 index 00000000..0ca1c6ba --- /dev/null +++ b/flighbookingsystem/Main.java @@ -0,0 +1,78 @@ +package flighbookingsystem; + +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +public class Main { + public static void main(String[] args) { + List seats = new ArrayList<>(); + seats.add(new Seat(1, "Economy")); + seats.add(new Seat(2, "Business")); + + // Create FlightSeats + List flightSeats = new ArrayList<>(); + flightSeats.add(new FlightSeat(5000, Status.OPEN)); + flightSeats.add(new FlightSeat(10000, Status.OPEN)); + + // Create Airlines + Airline airline = new Airline("Indigo", new ArrayList<>()); + + // Create Flights + Flight flight1 = new Flight("FL123", airline, 150, seats, new ArrayList<>()); + Flight flight2 = new Flight("FL456", airline, 200, seats, new ArrayList<>()); + + airline.getFlightList().add(flight1); + airline.getFlightList().add(flight2); + + // Create Airports + Airport airport1 = new Airport("Delhi Airport", "Delhi", new ArrayList<>()); + Airport airport2 = new Airport("Mumbai Airport", "Mumbai", new ArrayList<>()); + + // Create Schedules + List schedules = new ArrayList<>(); + Schedule schedule1 = new Schedule( + flight1, + airport1, + airport2, + new Date(), + Timestamp.valueOf("2024-11-10 10:00:00"), + Timestamp.valueOf("2024-11-10 12:00:00"), + Status.ONTIME, + flightSeats + ); + + Schedule schedule2 = new Schedule( + flight2, + airport2, + airport1, + new Date(), + Timestamp.valueOf("2024-11-11 15:00:00"), + Timestamp.valueOf("2024-11-11 17:00:00"), + Status.DELAY, + flightSeats + ); + + flight1.getSchedules().add(schedule1); + flight2.getSchedules().add(schedule2); + + // Booking System + BookingSystem bookingSystem = new BookingSystem(new ArrayList<>(),List.of(flight1, flight2)); + + // Example User + User user = new User("John Doe", "john.doe@example.com"); + bookingSystem.setUserList(List.of(user)); + + // Search Flights + System.out.println("Available Flights:"); + List availableFlights = bookingSystem.getFlightDetails("Delhi", "Mumbai", String.valueOf(Timestamp.valueOf("2024-11-11 13:56:52"))); + for (Flight flight : availableFlights) { + System.out.println("Flight ID: " + flight.getId()); + } + + // Book a Flight + System.out.println("Booking Flight..."); + // bookingSystem.bookingFlight(flight1, user); + } +} diff --git a/flighbookingsystem/Readme b/flighbookingsystem/Readme new file mode 100644 index 00000000..2223d40c --- /dev/null +++ b/flighbookingsystem/Readme @@ -0,0 +1,31 @@ +MakeMyTrip.com/Yatra/Booking.com + +Functional Requirements: +1.User should be able to search flights based on arrival + destination+ date of travel +2.User should be able to login to application. +3.Select the flight based on time/preference. +4.Enter the personal details. +5.Make payment in your application. +6.Notification to the email. + +Non-Functional Requirements +1.Scalable +2.Reliable +3.Modular + +Finding the actors +1.User +2.Airline authority +3.Admin + +Entities: +1.User +2.Flights +3.Booking +4.Payment +5.Notification +6.Airline + + + + diff --git a/flighbookingsystem/Schedule.java b/flighbookingsystem/Schedule.java new file mode 100644 index 00000000..211a5de3 --- /dev/null +++ b/flighbookingsystem/Schedule.java @@ -0,0 +1,93 @@ +package flighbookingsystem; + +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +public class Schedule { + Flight flight; + Airport start; + Airport destination; + Date dateOfJourney; + Timestamp startTime; + Timestamp endTime; + Status status; + List fare; + + public Schedule(Flight flight, Airport start, Airport destination, Date dateOfJourney, Timestamp startTime, Timestamp endTime, Status status, List fare) { + this.flight = flight; + this.start = start; + this.destination = destination; + this.dateOfJourney = dateOfJourney; + this.startTime = startTime; + this.endTime = endTime; + this.status = status; + this.fare = new ArrayList<>(); + } + + public void setFlight(Flight flight) { + this.flight = flight; + } + + public void setStart(Airport start) { + this.start = start; + } + + public void setDestination(Airport destination) { + this.destination = destination; + } + + public void setDateOfJourney(Date dateOfJourney) { + this.dateOfJourney = dateOfJourney; + } + + public void setStartTime(Timestamp startTime) { + this.startTime = startTime; + } + + public void setEndTime(Timestamp endTime) { + this.endTime = endTime; + } + + public void setStatus(Status status) { + this.status = status; + } + + public void setFare(List fare) { + this.fare = fare; + } + + public Flight getFlight() { + return flight; + } + + public Airport getStart() { + return start; + } + + public Airport getDestination() { + return destination; + } + + public Date getDateOfJourney() { + return dateOfJourney; + } + + public Timestamp getStartTime() { + return startTime; + } + + public Timestamp getEndTime() { + return endTime; + } + + public Status getStatus() { + return status; + } + + public List getFare() { + return fare; + } +} + diff --git a/flighbookingsystem/Seat.java b/flighbookingsystem/Seat.java new file mode 100644 index 00000000..5a51481a --- /dev/null +++ b/flighbookingsystem/Seat.java @@ -0,0 +1,16 @@ +package flighbookingsystem; + +public class Seat { + private int seatId; + private String seatType; + + public Seat(int seatId, String seatType) { + this.seatId = seatId; + this.seatType = seatType; + } + + public Seat() { + + } +} + diff --git a/flighbookingsystem/Status.java b/flighbookingsystem/Status.java new file mode 100644 index 00000000..f2da5c75 --- /dev/null +++ b/flighbookingsystem/Status.java @@ -0,0 +1,10 @@ +package flighbookingsystem; + +public enum Status { + DELAY, + ONTIME, + CANCLLED, + BOOKED, + OPEN +} + diff --git a/flighbookingsystem/User.java b/flighbookingsystem/User.java new file mode 100644 index 00000000..1b07da76 --- /dev/null +++ b/flighbookingsystem/User.java @@ -0,0 +1,12 @@ +package flighbookingsystem; + +public class User { + String name; + String email; + + public User(String name, String email) { + this.name = name; + this.email = email; + } +} + diff --git a/librarymanagement/Book.java b/librarymanagement/Book.java new file mode 100644 index 00000000..328a9c20 --- /dev/null +++ b/librarymanagement/Book.java @@ -0,0 +1,37 @@ +package librarymanagement; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +public class Book { + private String bookId; + private String title; + private List authors; + private List publishers; + private List copies; + + public Book(String bookId, String title, List authors, List publishers) { + this.bookId = bookId; + this.title = title; + this.authors = authors; + this.publishers = publishers; + this.copies = new ArrayList<>(); + } + + public Optional getAvailableCopy() { + return copies.stream().filter(copy -> !copy.isBorrowed()).findFirst(); + } + + public void addBookCopy(BookCopy copy) { + copies.add(copy); + } + + public void search(String attribute, String value) { + if ((attribute.equals("book_id") && bookId.equals(value)) || + (attribute.equals("author") && authors.contains(value)) || + (attribute.equals("publisher") && publishers.contains(value))) { + copies.forEach(BookCopy::printDetails); + } + } + } diff --git a/librarymanagement/BookCopy.java b/librarymanagement/BookCopy.java new file mode 100644 index 00000000..10dd6de0 --- /dev/null +++ b/librarymanagement/BookCopy.java @@ -0,0 +1,50 @@ +package librarymanagement; + +public class BookCopy { + private String copyId; + private Book book; + private Rack rack; + private String borrowedBy; + private String dueDate; + + public Book getBook() { + return book; + } + + public void setBook(Book book) { + this.book = book; + } + + public BookCopy(String copyId, Book book, Rack rack) { + this.copyId = copyId; + this.book = book; + this.rack = rack; + } + + public String getCopyId() { + return copyId; + } + + public Rack getRack() { + return rack; + } + + public boolean isBorrowed() { + return borrowedBy != null; + } + + public void borrow(String userId, String dueDate) { + this.borrowedBy = userId; + this.dueDate = dueDate; + } + + public void returnCopy() { + this.borrowedBy = null; + this.dueDate = null; + } + + public void printDetails() { + System.out.println(copyId + " " + rack.getRackNumber()); + } +} + diff --git a/librarymanagement/Library.java b/librarymanagement/Library.java new file mode 100644 index 00000000..717e4daa --- /dev/null +++ b/librarymanagement/Library.java @@ -0,0 +1,116 @@ +package librarymanagement; + + +import java.util.*; + +class Library { + private String libraryId; + private Map books; + private Map racks; + private Map users; + private int totalRacks; + + public Library(String libraryId, int totalRacks) { + this.libraryId = libraryId; + this.totalRacks = totalRacks; + this.books = new HashMap<>(); + this.racks = new HashMap<>(); + this.users = new HashMap<>(); + + for (int i = 1; i <= totalRacks; i++) { + racks.put("R" + i, new Rack(i)); + } + } + + public List addBook(String bookId, String title, List authors, List publishers, List bookCopyIds) { + Book book = books.getOrDefault(bookId, new Book(bookId, title, authors, publishers)); + List addedRackNos = new ArrayList<>(); + + for (String copyId : bookCopyIds) { + Optional availableRack = racks.values().stream().filter(rack -> !rack.isOccupied()).findFirst(); + if (availableRack.isPresent()) { + Rack rack = availableRack.get(); + BookCopy bookCopy = new BookCopy(copyId, book, rack); + rack.placeBookCopy(bookCopy); + book.addBookCopy(bookCopy); + addedRackNos.add(rack.getRackNumber()); + } else { + break; + } + } + + if (!addedRackNos.isEmpty()) books.put(bookId, book); + return addedRackNos; + } + + public int removeBookCopy(String bookCopyId) { + for (Rack rack : racks.values()) { + if (rack.isOccupied() && rack.getBookCopy().getCopyId().equals(bookCopyId)) { + rack.removeBookCopy(); + return rack.getRackNumber(); + } + } + return -1; + } + + public String borrowBook(String bookId, String userId, String dueDate) { + User user = users.computeIfAbsent(userId, id -> new User(userId)); + if (user.getBorrowedBooks().size() >= 5) return "Overlimit"; + + Book book = books.get(bookId); + if (book == null) return "Invalid Book ID"; + + Optional availableCopy = book.getAvailableCopy(); + if (!availableCopy.isPresent()) return "Not available"; + + BookCopy copy = availableCopy.get(); + copy.borrow(userId, dueDate); + user.borrowBook(copy); + return "Borrowed Book from rack: " + copy.getRack().getRackNumber(); + } + + public String borrowBookCopy(String bookCopyId, String userId, String dueDate) { + User user = users.computeIfAbsent(userId, id -> new User(userId)); + if (user.getBorrowedBooks().size() >= 5) return "Overlimit"; + + Optional bookCopyOpt = racks.values().stream() + .filter(rack -> rack.isOccupied() && rack.getBookCopy().getCopyId().equals(bookCopyId)) + .map(Rack::getBookCopy) + .findFirst(); + + if (!bookCopyOpt.isPresent()) return "Invalid Book Copy ID"; + + BookCopy bookCopy = bookCopyOpt.get(); + bookCopy.borrow(userId, dueDate); + user.borrowBook(bookCopy); + return "Borrowed Book Copy from rack: " + bookCopy.getRack().getRackNumber(); + } + + public String returnBookCopy(String bookCopyId) { + for (Rack rack : racks.values()) { + if (!rack.isOccupied()) { + Optional borrowedCopy = racks.values().stream() + .filter(r -> r.getBookCopy() != null && r.getBookCopy().getCopyId().equals(bookCopyId)) + .map(Rack::getBookCopy) + .findFirst(); + + if (borrowedCopy.isPresent()) { + borrowedCopy.get().returnCopy(); + rack.placeBookCopy(borrowedCopy.get()); + return "Returned book copy " + bookCopyId + " and added to rack: " + rack.getRackNumber(); + } + } + } + return "Invalid Book Copy ID"; + } + + public void printBorrowed(String userId) { + User user = users.get(userId); + if (user != null) user.printBorrowedBooks(); + } + + public void search(String attribute, String value) { + books.values().forEach(book -> book.search(attribute, value)); + } +} + diff --git a/librarymanagement/Main.java b/librarymanagement/Main.java new file mode 100644 index 00000000..f79847f4 --- /dev/null +++ b/librarymanagement/Main.java @@ -0,0 +1,89 @@ +package librarymanagement; + +import java.util.Arrays; +import java.util.List; +import java.util.Scanner; + +public class Main { + private static Library library; + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + while (scanner.hasNextLine()) { + String command = scanner.nextLine(); + if (command.equals("exit")) break; + + processCommand(command); + } + } + + private static void processCommand(String command) { + String[] tokens = command.split(" "); + switch (tokens[0]) { + case "create_library": + int numRacks = Integer.parseInt(tokens[1]); + library = new Library(tokens[1], numRacks); + System.out.println("Created library with " + numRacks + " racks"); + break; + + case "add_book": + String bookId = tokens[1]; + String title = tokens[2]; + List authors = Arrays.asList(tokens[3].split(",")); + List publishers = Arrays.asList(tokens[4].split(",")); + List bookCopyIds = Arrays.asList(tokens[5].split(",")); + List rackNos = library.addBook(bookId, title, authors, publishers, bookCopyIds); + if (rackNos.isEmpty()) { + System.out.println("Rack not available"); + } else { + System.out.println("Added Book to racks: " + rackNos.toString().replaceAll("[\\[\\]]", "")); + } + break; + + case "remove_book_copy": + String bookCopyId = tokens[1]; + int removedRack = library.removeBookCopy(bookCopyId); + if (removedRack == -1) { + System.out.println("Invalid Book Copy ID"); + } else { + System.out.println("Removed book copy: " + bookCopyId + " from rack: " + removedRack); + } + break; + + case "borrow_book": + bookId = tokens[1]; + String userId = tokens[2]; + String dueDate = tokens[3]; + String borrowResult = library.borrowBook(bookId, userId, dueDate); + System.out.println(borrowResult); + break; + + case "borrow_book_copy": + bookCopyId = tokens[1]; + userId = tokens[2]; + dueDate = tokens[3]; + borrowResult = library.borrowBookCopy(bookCopyId, userId, dueDate); + System.out.println(borrowResult); + break; + + case "return_book_copy": + bookCopyId = tokens[1]; + String returnResult = library.returnBookCopy(bookCopyId); + System.out.println(returnResult); + break; + + case "print_borrowed": + userId = tokens[1]; + library.printBorrowed(userId); + break; + + case "search": + String attribute = tokens[1]; + String attributeValue = tokens[2]; + library.search(attribute, attributeValue); + break; + } + } +} + diff --git a/librarymanagement/Rack.java b/librarymanagement/Rack.java new file mode 100644 index 00000000..70f5bc3f --- /dev/null +++ b/librarymanagement/Rack.java @@ -0,0 +1,30 @@ +package librarymanagement; + +class Rack { + private int rackNumber; + private BookCopy bookCopy; + + public Rack(int rackNumber) { + this.rackNumber = rackNumber; + } + + public int getRackNumber() { + return rackNumber; + } + + public boolean isOccupied() { + return bookCopy != null; + } + + public void placeBookCopy(BookCopy bookCopy) { + this.bookCopy = bookCopy; + } + + public void removeBookCopy() { + this.bookCopy = null; + } + + public BookCopy getBookCopy() { + return bookCopy; + } +} diff --git a/librarymanagement/User.java b/librarymanagement/User.java new file mode 100644 index 00000000..c6cf7e99 --- /dev/null +++ b/librarymanagement/User.java @@ -0,0 +1,29 @@ +package librarymanagement; + +import java.util.ArrayList; +import java.util.List; + +class User { + private String userId; + private List borrowedBooks; + + public User(String userId) { + this.userId = userId; + this.borrowedBooks = new ArrayList<>(); + } + + public void borrowBook(BookCopy copy) { + borrowedBooks.add(copy); + } + + public void printBorrowedBooks() { + for (BookCopy copy : borrowedBooks) { + System.out.println(copy.getCopyId()); + } + } + + public List getBorrowedBooks() { + return borrowedBooks; + } +} + diff --git a/logger/ErrorProcessor.java b/logger/ErrorProcessor.java new file mode 100644 index 00000000..7b497579 --- /dev/null +++ b/logger/ErrorProcessor.java @@ -0,0 +1,18 @@ +package logger; + + +public class ErrorProcessor extends LogProcessor{ + public ErrorProcessor(LogProcessor logProcessor) { + super(logProcessor); + } + + public void log(int log, String message){ + if(log == ERROR){ + System.out.println("ERROR::"+message); + } + else { + super.log(log,message); + } + + } +} diff --git a/logger/InfoProcessor.java b/logger/InfoProcessor.java new file mode 100644 index 00000000..90df8741 --- /dev/null +++ b/logger/InfoProcessor.java @@ -0,0 +1,16 @@ +package logger; + +public class InfoProcessor extends LogProcessor{ + public InfoProcessor(LogProcessor logProcessor) { + super(logProcessor); + } + + public void log(int log, String message){ + if(log == INFO){ + System.out.println("Info::"+message); + } + else { + super.log(log,message); + } + } +} diff --git a/logger/LogProcessor.java b/logger/LogProcessor.java new file mode 100644 index 00000000..e17dff6f --- /dev/null +++ b/logger/LogProcessor.java @@ -0,0 +1,21 @@ +package logger; + +public abstract class LogProcessor { + + int INFO = 1; + int DEBUG = 2; + int ERROR = 3; + + LogProcessor logProcessor; + + + public LogProcessor(LogProcessor logProcessor) { + this.logProcessor = logProcessor; + } + + public void log(int level , String message ){ + if(logProcessor!=null){ + logProcessor.log(level,message); + } + } +} diff --git a/logger/Main.java b/logger/Main.java new file mode 100644 index 00000000..e180fa27 --- /dev/null +++ b/logger/Main.java @@ -0,0 +1,9 @@ +package logger; + +public class Main { + public static void main(String[] args) { + LogProcessor logProcessor = new InfoProcessor(new ErrorProcessor(null)); + logProcessor.log(logProcessor.ERROR, "error message"); + logProcessor.log(logProcessor.INFO, "info message"); + } +} diff --git a/meetingroom/Calender.java b/meetingroom/Calender.java new file mode 100644 index 00000000..227ca51f --- /dev/null +++ b/meetingroom/Calender.java @@ -0,0 +1,16 @@ +package meetingroom; + +import java.util.List; + +public class Calender { + List intervalList; + + public void setIntervalList(List list) { + this.intervalList = list; + } + + public List getIntervalList() { + return intervalList; + } +} + diff --git a/meetingroom/Interval.java b/meetingroom/Interval.java new file mode 100644 index 00000000..bda645a1 --- /dev/null +++ b/meetingroom/Interval.java @@ -0,0 +1,41 @@ +package meetingroom; + +import java.time.LocalDate; +import java.time.LocalTime; + +public class Interval { + LocalDate date; + LocalTime start; + LocalTime end; + + public Interval(LocalDate date, LocalTime start, LocalTime end) { + this.date = date; + this.start = start; + this.end = end; + } + + public LocalDate getDate() { + return date; + } + + public LocalTime getStart() { + return start; + } + + public LocalTime getEnd() { + return end; + } + + public void setDate(LocalDate date) { + this.date = date; + } + + public void setStart(LocalTime start) { + this.start = start; + } + + public void setEnd(LocalTime end) { + this.end = end; + } + +} diff --git a/meetingroom/Location.java b/meetingroom/Location.java new file mode 100644 index 00000000..ef98313c --- /dev/null +++ b/meetingroom/Location.java @@ -0,0 +1,29 @@ +package meetingroom; + +public class Location { + int floorNo; + + public void setFloorNo(int floorNo) { + this.floorNo = floorNo; + } + + public void setBuildingNo(int buildingNo) { + BuildingNo = buildingNo; + } + + public int getFloorNo() { + return floorNo; + } + + public int getBuildingNo() { + return BuildingNo; + } + + public Location(int floorNo, int buildingNo) { + this.floorNo = floorNo; + BuildingNo = buildingNo; + } + + int BuildingNo; +} + diff --git a/meetingroom/MeetingRoom.java b/meetingroom/MeetingRoom.java new file mode 100644 index 00000000..8d646012 --- /dev/null +++ b/meetingroom/MeetingRoom.java @@ -0,0 +1,95 @@ +package meetingroom; + +import java.time.LocalDate; +import java.time.LocalTime; +import java.util.Map; + +public class MeetingRoom { + int id; + + @Override + public String toString() { + return "MeetingRoom{" + + "id=" + id + + ", location=" + location + + ", isBooked=" + isBooked + + ", capacity=" + capacity + + '}'; + } + + Location location; + boolean isBooked; + + public void setId(int id) { + this.id = id; + } + + public void setLocation(Location location) { + this.location = location; + } + + public void setBooked(boolean booked) { + isBooked = booked; + } + + public void setCapacity(int capacity) { + this.capacity = capacity; + } + + public int getId() { + return id; + } + + public Location getLocation() { + return location; + } + + public boolean isBooked() { + return isBooked; + } + + public int getCapacity() { + return capacity; + } + + public void setCalender(Calender calender) { + this.calender = calender; + } + + public Calender getCalender() { + return calender; + } + + int capacity; + + Calender calender; + + public void bookRoom(int meetingRoomId, LocalTime start, LocalTime end, LocalDate date, Map meetingRoomCalenderMap) { + // Retrieve or create a calendar for the meeting room + Calender calendar = meetingRoomCalenderMap.getOrDefault(this, new Calender()); + + // Check for overlapping intervals + boolean isOverlapping = calendar.getIntervalList().stream().anyMatch(interval -> + interval.getDate().equals(date) && + (start.isBefore(interval.getEnd()) && end.isAfter(interval.getStart())) + ); + + // If there's an overlap, return an error or handle it appropriately + if (isOverlapping) { + System.out.println("Meeting room is already booked for the requested time interval."); + return; + } + + // Add the new interval if no overlap is found + Interval newInterval = new Interval(date,start,end); + calendar.getIntervalList().add(newInterval); + + // Update the calendar in the map if it's new + meetingRoomCalenderMap.put(this, calendar); + + // Mark the room as booked + this.setBooked(true); + System.out.println("Meeting room " + meetingRoomId + " booked successfully from " + start + " to " + end + " on " + date); + } + +} diff --git a/meetingroom/MeetingRoomManager.java b/meetingroom/MeetingRoomManager.java new file mode 100644 index 00000000..3292680f --- /dev/null +++ b/meetingroom/MeetingRoomManager.java @@ -0,0 +1,71 @@ +package meetingroom; + +import java.time.LocalDate; +import java.time.LocalTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class MeetingRoomManager { + public MeetingRoomManager() { + this.meetingRoomList = new ArrayList<>(); + this.meetingRoomCalenderMap = new HashMap<>(); + } + + List meetingRoomList ; + Map meetingRoomCalenderMap; + + List getAvailableMeetingRooms(int capacity, LocalTime startTime, LocalTime endTime, LocalDate date){ + return meetingRoomList.stream() + .filter(room -> !room.isBooked + && room.getCapacity() >= capacity + && room.getCalender().getIntervalList().stream() + .anyMatch(interval -> interval.getDate().equals(date) + && (interval.getStart().isBefore(endTime) && interval.getEnd().isAfter(startTime)) + ) + ).toList(); + + } + + void addMeetingRoom(int id, Location location, int capacity) { + MeetingRoom meetingRoom = new MeetingRoom(); + meetingRoom.setId(id); + meetingRoom.setLocation(location); + meetingRoom.setCapacity(capacity); + meetingRoom.setBooked(false); + + // Create and add initial intervals to simulate existing bookings + Calender calendar = new Calender(); + List initialIntervals = new ArrayList<>(); + + // Example: Booked on 2024-10-11 from 9:00 to 10:30 + Interval interval1 = new Interval(LocalDate.of(2024, 10, 11),LocalTime.of(9, 0),LocalTime.of(10, 30)); + + initialIntervals.add(interval1); + + // Example: Booked on 2024-10-12 from 14:00 to 15:30 + Interval interval2 = new Interval(LocalDate.of(2024, 10, 12), + LocalTime.of(14, 0), + LocalTime.of(15, 30)); + + initialIntervals.add(interval2); + + calendar.setIntervalList(initialIntervals); // Set intervals to the calendar + meetingRoomCalenderMap.put(meetingRoom, calendar); // Add to calendar map + meetingRoom.setCalender(calendar); + meetingRoomList.add(meetingRoom); + } + String bookMeetingRoom(int meetingRoomId, LocalTime start, LocalTime end, LocalDate date){ + + List list = meetingRoomList.stream().map(e -> e.getId()).toList(); + if(list.contains(meetingRoomId)) { + MeetingRoom meetingRoom = meetingRoomList.stream().filter(e->e.getId()==meetingRoomId).findFirst().get(); + meetingRoom.bookRoom(meetingRoomId, start, end, date, meetingRoomCalenderMap); + return meetingRoomId + "booked sucessfully "; + } + + return "invalid meetingRoomId"; + } +} + diff --git a/meetingroom/MeetingScheduler.java b/meetingroom/MeetingScheduler.java new file mode 100644 index 00000000..9dc9ed0e --- /dev/null +++ b/meetingroom/MeetingScheduler.java @@ -0,0 +1,26 @@ +package meetingroom; + +import java.time.LocalDate; +import java.time.LocalTime; +import java.util.List; + +public class MeetingScheduler { + + static MeetingRoomManager meetingRoomManager; + + public static void main(String[] args) { + meetingRoomManager = new MeetingRoomManager(); + meetingRoomManager.addMeetingRoom(1,new Location(1,11),10); + List availableMeetingRooms = meetingRoomManager.getAvailableMeetingRooms(5,LocalTime.of(9, 0),LocalTime.of(10, 30),LocalDate.of(2024, 10, 11)); + System.out.println("available meeting rooms::"+availableMeetingRooms); + if(!availableMeetingRooms.isEmpty()) { + String s = meetingRoomManager.bookMeetingRoom(1, LocalTime.of(11, 0), LocalTime.of(12, 15), LocalDate.of(2024, 11, 19)); + System.out.println(s); + } + else { + System.out.println("meeting room is not available at that schedule"); + } + // sendNotification(); + } +} + diff --git a/out/production/machine-coding-feedback/.gitignore b/out/production/machine-coding-feedback/.gitignore new file mode 100644 index 00000000..36b741e6 --- /dev/null +++ b/out/production/machine-coding-feedback/.gitignore @@ -0,0 +1,10 @@ +**/*.class +**/*.out +**/*.pyo +**/__pycache__ +tests/out + +.idea +.DS_Store +.* +!.gitignore diff --git a/out/production/machine-coding-feedback/README.md b/out/production/machine-coding-feedback/README.md new file mode 100644 index 00000000..86e402a6 --- /dev/null +++ b/out/production/machine-coding-feedback/README.md @@ -0,0 +1,8 @@ +# Machine Coding Review Repo +Get your [practice machine coding](https://workat.tech/machine-coding/practice) solutions reviewed by [Gaurav Chandak](https://www.linkedin.com/in/gcnit/) and get feedback before your machine coding round. + +Steps: +- [Fork this repo and clone it in your laptop/desktop](https://workattech.github.io/machine-coding-feedback/#setup) +- Start solving [one of the practice problems](https://workat.tech/machine-coding/practice) in a timed manner. Follow the [best practices](https://workat.tech/machine-coding/article/how-to-ace-machine-coding-round-hi8lnpp8tlmo). +- [Push the code](https://workattech.github.io/machine-coding-feedback/#submission) +- Wait for review. Message us on Whatsapp (9732130450) if you need to get it done urgently. diff --git a/out/production/machine-coding-feedback/docs/clone-1.png b/out/production/machine-coding-feedback/docs/clone-1.png new file mode 100644 index 00000000..e0df3b2f Binary files /dev/null and b/out/production/machine-coding-feedback/docs/clone-1.png differ diff --git a/out/production/machine-coding-feedback/docs/clone.png b/out/production/machine-coding-feedback/docs/clone.png new file mode 100644 index 00000000..e3bde132 Binary files /dev/null and b/out/production/machine-coding-feedback/docs/clone.png differ diff --git a/out/production/machine-coding-feedback/docs/fork.png b/out/production/machine-coding-feedback/docs/fork.png new file mode 100644 index 00000000..62014114 Binary files /dev/null and b/out/production/machine-coding-feedback/docs/fork.png differ diff --git a/out/production/machine-coding-feedback/docs/git.md b/out/production/machine-coding-feedback/docs/git.md new file mode 100644 index 00000000..bba78f4a --- /dev/null +++ b/out/production/machine-coding-feedback/docs/git.md @@ -0,0 +1,83 @@ +# Create Github Account +1. Create account at: https://github.com/join by choosing an unique username +2. Check your email for verification email and click on verification link + +# Install Git Locally + +## Windows +- Download git from https://gitforwindows.org/ +- When you've successfully started the installer, you should see the Git Setup wizard screen. Follow the Next and Finish prompts to complete the installation. The default options are pretty sensible for most users. +- Open a Command Prompt (or Git Bash if during installation you elected not to use Git from the Windows Command Prompt). +- Run the following commands to configure your Git username and email using the following commands, replacing Emma's name and email with your own. These details will be associated with any commits that you create: +``` +git config --global user.name "Emma Paris" +git config --global user.email "eparis@atlassian.com" +``` + +## Linux +- From your shell, install Git using apt-get: +``` +sudo apt-get update +sudo apt-get install git +``` +- Verify the installation was successful by typing git --version which should return the version number: +``` +git --version +``` +- Run the following commands to configure your Git username and email using the following commands, replacing Emma's name and email with your own. These details will be associated with any commits that you create: +``` +git config --global user.name "Emma Paris" +git config --global user.email "eparis@atlassian.com" +``` + +## Mac +- From your shell, install Git using Homebrew: +``` +brew install git +``` +- Verify the installation was successful by typing git --version which should return the version number: +``` +git --version +``` +- Run the following commands to configure your Git username and email using the following commands, replacing Emma's name and email with your own. These details will be associated with any commits that you create: +``` +git config --global user.name "Emma Paris" +git config --global user.email "eparis@atlassian.com" +``` + +These commands have been taken from Atlassian's website. + +# Fork +- In the repository page, click on "Fork" +![Fork](./fork.png) +- After clicking on Fork, you'll be redirected to a new page with a copy of the repository. +- This new repository is where you'll make your code changes. +- Then click on clone in this new page + +# Clone +- In the repository page, click on "Clone or download" + +![Clone](./clone.png) + +- Then click on copy link button + +![Clone-1](./clone-1.png) + +- Go to the terminal and clone the repository on your machine by typing: +```git clone``` followed by the link you copied in previous step and hit enter. + +# Push local changes to remote +Execute these commands on the terminal: +- ```cd machine-coding-feedback``` +- ```git add .``` +- ```git commit -m "solved the problem"``` +- ```git push``` + +# PR +- Open the repository in your profile. The URL would be of this format: ```https://github.com//machine-coding-feedback``` +- Click on "New Pull Request". +![pr](./pr.png) +- Then click on "Create pull request" in the page that opened. +![pr-1](./pr-1.png) +- Again click on the new button that says "Create pull request" +- After this step, a new page would load which would be your pull request. diff --git a/out/production/machine-coding-feedback/docs/index.md b/out/production/machine-coding-feedback/docs/index.md new file mode 100644 index 00000000..4f62c017 --- /dev/null +++ b/out/production/machine-coding-feedback/docs/index.md @@ -0,0 +1,45 @@ +# Please go through this document to get your machine coding code reviewed by workat.tech + +## Why Practice for Machine Coding Round? +- In companies like Flipkart, Uber, Swiggy, Ola, Cred, etc the first onsite round is the machine coding round. +- You're given a design problem (like design a parking lot) with a set of requirements. +- Then you need to create a clean, modular and extensible coding solution for the same. +- The code is supposed to be written in a matter of 90 mins. +- After the round, you sit with an interviewer who goes through your code and tries to understand your design decisions and also tries to see if your code works for all the requirements. +- The interviewer may ask you to extend your solution based on some new requirement. +- It is a pretty crucial round since most of the people get eliminated in this round and it is completely different from what everyone generally practices for. + +## How to prepare? +Please go through our article on 'How to prepare for machine coding round?'. + +## Setup +- Ensure that you've a github account. If you do not have one, check this page. +- Ensure that you've git set up locally on your Laptop/PC. If it is not set up, check this page. +- Go to machine-coding-feedback repository. +- Fork the repository. If you're new to git, follow the steps mentioned in the fork section here +- Clone the repository in your local machine.If you're new to git, follow the steps mentioned in the clone section here + +## Coding +- After the setup step, a new folder will be created in your laptop/PC with the name: machine-coding-feedback. +- Open that folder in an IDE of your choice and start coding. + +## Expectations +- Make sure that you have a working and demonstrable code +- Make sure that the code is functionally correct +- Code should be modular and readable +- Separation of concern should be addressed +- Please do not write everything in a single file +- Code should easily accommodate new requirements and minimal changes +- There should be a main method from where the code could be easily testable +- [Optional] Write unit tests, if possible +- No need to create a GUI + +## Submission +- After you're done with coding, you need to commit and push your changes to github. +- You should push your changes to the master branch of your forked repository. If you're new to git, follow the steps mentioned in the push local changes to remote section here +- Create a pull request to our master branch. If you're new to git, follow the steps mentioned in the PR section here + +## Evaluation +- We'll be reviewing everyone's submission and try to provide feedback on how to improve through code review comments on GitHub. +- We also have some volunteers who will help with the review. +- Anyone can volunteer to review. diff --git a/out/production/machine-coding-feedback/docs/pr-1.png b/out/production/machine-coding-feedback/docs/pr-1.png new file mode 100644 index 00000000..3ade58aa Binary files /dev/null and b/out/production/machine-coding-feedback/docs/pr-1.png differ diff --git a/out/production/machine-coding-feedback/docs/pr.png b/out/production/machine-coding-feedback/docs/pr.png new file mode 100644 index 00000000..d798f596 Binary files /dev/null and b/out/production/machine-coding-feedback/docs/pr.png differ diff --git a/out/production/machine-coding-feedback/flighbookingsystem/Readme b/out/production/machine-coding-feedback/flighbookingsystem/Readme new file mode 100644 index 00000000..2223d40c --- /dev/null +++ b/out/production/machine-coding-feedback/flighbookingsystem/Readme @@ -0,0 +1,31 @@ +MakeMyTrip.com/Yatra/Booking.com + +Functional Requirements: +1.User should be able to search flights based on arrival + destination+ date of travel +2.User should be able to login to application. +3.Select the flight based on time/preference. +4.Enter the personal details. +5.Make payment in your application. +6.Notification to the email. + +Non-Functional Requirements +1.Scalable +2.Reliable +3.Modular + +Finding the actors +1.User +2.Airline authority +3.Admin + +Entities: +1.User +2.Flights +3.Booking +4.Payment +5.Notification +6.Airline + + + + diff --git a/parkingLot/Account.java b/parkingLot/Account.java new file mode 100644 index 00000000..d566f42e --- /dev/null +++ b/parkingLot/Account.java @@ -0,0 +1,14 @@ +package parkingLot; + +public abstract class Account { + private String userName; + private String password; + private Person person; + private AccountStatus status; + + public abstract boolean resetPassword(); + + // Getters and Setters + // ... +} + diff --git a/parkingLot/AccountStatus.java b/parkingLot/AccountStatus.java new file mode 100644 index 00000000..3d9c6da2 --- /dev/null +++ b/parkingLot/AccountStatus.java @@ -0,0 +1,10 @@ +package parkingLot; + +enum AccountStatus { + ACTIVE, + CLOSED, + CANCELED, + BLACKLISTED, + NONE +} + diff --git a/parkingLot/Address.java b/parkingLot/Address.java new file mode 100644 index 00000000..427cfb54 --- /dev/null +++ b/parkingLot/Address.java @@ -0,0 +1,13 @@ +package parkingLot; + +public class Address { + private int zipCode; + private String address; + private String city; + private String state; + private String country; + + // Getters and Setters + // ... +} + diff --git a/parkingLot/Admin.java b/parkingLot/Admin.java new file mode 100644 index 00000000..0953ca66 --- /dev/null +++ b/parkingLot/Admin.java @@ -0,0 +1,29 @@ +package parkingLot; + +public class Admin extends Account { + public boolean addParkingSpot(ParkingSpot spot) { + // Logic to add a parking spot + return true; + } + + public boolean addDisplayBoard(DisplayBoard displayBoard) { + // Logic to add a display board + return true; + } + + public boolean addEntrance(Entrance entrance) { + // Logic to add an entrance + return true; + } + + public boolean addExit(Exit exit) { + // Logic to add an exit + return true; + } + + public boolean resetPassword() { + // Logic to reset password + return true; + } +} + diff --git a/parkingLot/Car.java b/parkingLot/Car.java new file mode 100644 index 00000000..983b79da --- /dev/null +++ b/parkingLot/Car.java @@ -0,0 +1,8 @@ +package parkingLot; + +public class Car extends Vehicle { + public void assignTicket(ParkingTicket ticket) { + // Logic to assign a ticket to the car + } +} + diff --git a/parkingLot/Cash.java b/parkingLot/Cash.java new file mode 100644 index 00000000..9ebe8f32 --- /dev/null +++ b/parkingLot/Cash.java @@ -0,0 +1,9 @@ +package parkingLot; + +public class Cash extends Payment { + public boolean initiateTransaction() { + // Logic to initiate a cash transaction + return true; + } +} + diff --git a/parkingLot/Compact.java b/parkingLot/Compact.java new file mode 100644 index 00000000..4592b077 --- /dev/null +++ b/parkingLot/Compact.java @@ -0,0 +1,9 @@ +package parkingLot; + +public class Compact extends ParkingSpot { + public boolean assignVehicle(Vehicle vehicle) { + // Logic to check if the vehicle can be assigned + return true; + } +} + diff --git a/parkingLot/CreditCard.java b/parkingLot/CreditCard.java new file mode 100644 index 00000000..2319635b --- /dev/null +++ b/parkingLot/CreditCard.java @@ -0,0 +1,9 @@ +package parkingLot; + +public class CreditCard extends Payment { + public boolean initiateTransaction() { + // Logic to initiate a credit card transaction + return true; + } +} + diff --git a/parkingLot/DisplayBoard.java b/parkingLot/DisplayBoard.java new file mode 100644 index 00000000..3675d3dc --- /dev/null +++ b/parkingLot/DisplayBoard.java @@ -0,0 +1,27 @@ +package parkingLot; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class DisplayBoard { + private int id; + private Map> parkingSpots; + + public DisplayBoard(int id) { + this.id = id; + this.parkingSpots = new HashMap<>(); + } + + public void addParkingSpot(String spotType, List spots) { + parkingSpots.put(spotType, spots); + } + + public void showFreeSlot() { + // Logic to show free slots + } + + // Getters and Setters + // ... +} + diff --git a/parkingLot/Entrance.java b/parkingLot/Entrance.java new file mode 100644 index 00000000..d8f629af --- /dev/null +++ b/parkingLot/Entrance.java @@ -0,0 +1,14 @@ +package parkingLot; + +public class Entrance { + private int id; + + public ParkingTicket getTicket() { + // Logic to get a parking ticket + return new ParkingTicket(); + } + + // Getters and Setters + // ... +} + diff --git a/parkingLot/Exit.java b/parkingLot/Exit.java new file mode 100644 index 00000000..ceff5b0e --- /dev/null +++ b/parkingLot/Exit.java @@ -0,0 +1,13 @@ +package parkingLot; + +public class Exit { + private int id; + + public void validateTicket(ParkingTicket ticket) { + // Logic to validate a parking ticket + } + + // Getters and Setters + // ... +} + diff --git a/parkingLot/Handicapped.java b/parkingLot/Handicapped.java new file mode 100644 index 00000000..63703b28 --- /dev/null +++ b/parkingLot/Handicapped.java @@ -0,0 +1,9 @@ +package parkingLot; + +public class Handicapped extends ParkingSpot { + public boolean assignVehicle(Vehicle vehicle) { + // Logic to check if the vehicle can be assigned + return true; + } +} + diff --git a/parkingLot/Large.java b/parkingLot/Large.java new file mode 100644 index 00000000..f368d369 --- /dev/null +++ b/parkingLot/Large.java @@ -0,0 +1,9 @@ +package parkingLot; + +public class Large extends ParkingSpot { + public boolean assignVehicle(Vehicle vehicle) { + // Logic to check if the vehicle can be assigned + return true; + } +} + diff --git a/parkingLot/MotorVehicle.java b/parkingLot/MotorVehicle.java new file mode 100644 index 00000000..dfe58d81 --- /dev/null +++ b/parkingLot/MotorVehicle.java @@ -0,0 +1,8 @@ +package parkingLot; + +public class MotorVehicle extends Vehicle { + public void assignTicket(ParkingTicket ticket) { + // Logic to assign a ticket to the motorcycle + } +} + diff --git a/parkingLot/Motorcycle.java b/parkingLot/Motorcycle.java new file mode 100644 index 00000000..509d93c7 --- /dev/null +++ b/parkingLot/Motorcycle.java @@ -0,0 +1,9 @@ +package parkingLot; + +public class Motorcycle extends ParkingSpot { + public boolean assignVehicle(Vehicle vehicle) { + // Logic to check if the vehicle can be assigned + return true; + } +} + diff --git a/parkingLot/ParkingAttendant.java b/parkingLot/ParkingAttendant.java new file mode 100644 index 00000000..bbbb1be2 --- /dev/null +++ b/parkingLot/ParkingAttendant.java @@ -0,0 +1,14 @@ +package parkingLot; + +public class ParkingAttendant extends Account { + public boolean processTicket(String ticketNumber) { + // Logic to process a parking ticket + return true; + } + + public boolean resetPassword() { + // Logic to reset password + return true; + } +} + diff --git a/parkingLot/ParkingLot.java b/parkingLot/ParkingLot.java new file mode 100644 index 00000000..cdcf6d22 --- /dev/null +++ b/parkingLot/ParkingLot.java @@ -0,0 +1,54 @@ +package parkingLot; + +import java.util.HashMap; + +public class ParkingLot { + private int id; + private String name; + private String address; + private ParkingRate parkingRate; + + private HashMap entrance; + private HashMap exit; + + private HashMap tickets; + + private static ParkingLot parkingLot = null; + + private ParkingLot() { + this.entrance = new HashMap<>(); + this.exit = new HashMap<>(); + this.tickets = new HashMap<>(); + } + + public static ParkingLot getInstance() { + if (parkingLot == null) { + parkingLot = new ParkingLot(); + } + return parkingLot; + } + + public boolean addEntrance(Entrance entrance) { + // Logic to add an entrance + return true; + } + + public boolean addExit(Exit exit) { + // Logic to add an exit + return true; + } + + public ParkingTicket getParkingTicket(Vehicle vehicle) { + // Logic to generate a parking ticket + return new ParkingTicket(); + } + + public boolean isFull(ParkingSpot type) { + // Logic to check if the parking lot is full + return false; + } + + // Getters and Setters + // ... +} + diff --git a/parkingLot/ParkingRate.java b/parkingLot/ParkingRate.java new file mode 100644 index 00000000..2bad4bbf --- /dev/null +++ b/parkingLot/ParkingRate.java @@ -0,0 +1,14 @@ +package parkingLot; + +public class ParkingRate { + private double hours; + private double rate; + + public void calculate() { + // Logic to calculate the rate + } + + // Getters and Setters + // ... +} + diff --git a/parkingLot/ParkingSpot.java b/parkingLot/ParkingSpot.java new file mode 100644 index 00000000..9c98a22a --- /dev/null +++ b/parkingLot/ParkingSpot.java @@ -0,0 +1,23 @@ +package parkingLot; + +public abstract class ParkingSpot { + private int id; + private boolean isFree; + private Vehicle vehicle; + + public boolean getIsFree() { + return isFree; + } + + public abstract boolean assignVehicle(Vehicle vehicle); + + public boolean removeVehicle() { + this.vehicle = null; + this.isFree = true; + return true; + } + + // Getters and Setters + // ... +} + diff --git a/parkingLot/ParkingTicket.java b/parkingLot/ParkingTicket.java new file mode 100644 index 00000000..cc8ed4c5 --- /dev/null +++ b/parkingLot/ParkingTicket.java @@ -0,0 +1,20 @@ +package parkingLot; + +import java.util.Date; + +public class ParkingTicket { + private int ticketNo; + private Date timestamp; + private Date exit; + private double amount; + private boolean status; + + private Vehicle vehicle; + private Payment payment; + private Entrance entrance; + private Exit exitIns; + + // Getters and Setters + // ... +} + diff --git a/parkingLot/Payment.java b/parkingLot/Payment.java new file mode 100644 index 00000000..9aceb50e --- /dev/null +++ b/parkingLot/Payment.java @@ -0,0 +1,15 @@ +package parkingLot; + +import java.util.Date; + +public abstract class Payment { + private double amount; + private PaymentStatus status; + private Date timestamp; + + public abstract boolean initiateTransaction(); + + // Getters and Setters + // ... +} + diff --git a/parkingLot/PaymentStatus.java b/parkingLot/PaymentStatus.java new file mode 100644 index 00000000..f70819a7 --- /dev/null +++ b/parkingLot/PaymentStatus.java @@ -0,0 +1,10 @@ +package parkingLot; + +enum PaymentStatus { + COMPLETED, + FAILED, + PENDING, + UNPAID, + REFUNDED +} + diff --git a/parkingLot/Person.java b/parkingLot/Person.java new file mode 100644 index 00000000..0e3c3df5 --- /dev/null +++ b/parkingLot/Person.java @@ -0,0 +1,12 @@ +package parkingLot; + +public class Person { + private String name; + private String address; + private String phone; + private String email; + + // Getters and Setters + // ... +} + diff --git a/parkingLot/Truck.java b/parkingLot/Truck.java new file mode 100644 index 00000000..7514182a --- /dev/null +++ b/parkingLot/Truck.java @@ -0,0 +1,8 @@ +package parkingLot; + +public class Truck extends Vehicle { + public void assignTicket(ParkingTicket ticket) { + // Logic to assign a ticket to the truck + } +} + diff --git a/parkingLot/Van.java b/parkingLot/Van.java new file mode 100644 index 00000000..48d7007d --- /dev/null +++ b/parkingLot/Van.java @@ -0,0 +1,8 @@ +package parkingLot; + +public class Van extends Vehicle { + public void assignTicket(ParkingTicket ticket) { + // Logic to assign a ticket to the van + } +} + diff --git a/parkingLot/Vehicle.java b/parkingLot/Vehicle.java new file mode 100644 index 00000000..8afd5aca --- /dev/null +++ b/parkingLot/Vehicle.java @@ -0,0 +1,11 @@ +package parkingLot; + +public abstract class Vehicle { + private int licenseNo; + + public abstract void assignTicket(ParkingTicket ticket); + + // Getters and Setters + // ... +} + diff --git a/snakeandladder/Board.java b/snakeandladder/Board.java new file mode 100644 index 00000000..4961385d --- /dev/null +++ b/snakeandladder/Board.java @@ -0,0 +1,37 @@ +package snakeandladder; + +import java.util.HashMap; +import java.util.Map; + +public class Board { + private final int size; + private final Map snakes; + private final Map ladders; + + public Board(int size) { + this.size = size; + this.snakes = new HashMap<>(); + this.ladders = new HashMap<>(); + } + + public void addSnake(int head, int tail) { + snakes.put(head, tail); + } + + public void addLadder(int start, int end) { + ladders.put(start, end); + } + + public int getSize() { + return size; + } + + public int getNextPosition(int position) { + if (snakes.containsKey(position)) { + return snakes.get(position); + } else if (ladders.containsKey(position)) { + return ladders.get(position); + } + return position; + } +} diff --git a/snakeandladder/Dice.java b/snakeandladder/Dice.java new file mode 100644 index 00000000..da377ad4 --- /dev/null +++ b/snakeandladder/Dice.java @@ -0,0 +1,17 @@ +package snakeandladder; + +import java.util.Random; + +public class Dice { + private static final int MIN = 1; + private static final int MAX = 6; + private final Random random; + + public Dice() { + this.random = new Random(); + } + + public int roll() { + return random.nextInt(MAX - MIN + 1) + MIN; + } +} diff --git a/snakeandladder/Game.java b/snakeandladder/Game.java new file mode 100644 index 00000000..38b58c74 --- /dev/null +++ b/snakeandladder/Game.java @@ -0,0 +1,44 @@ +package snakeandladder; + + +import java.util.Queue; + +public class Game { + private final Board board; + private final Dice dice; + private final Queue players; + + public Game(Board board, Dice dice, Queue players) { + this.board = board; + this.dice = dice; + this.players = players; + } + + public void play() { + boolean gameWon = false; + while (!gameWon) { + Player currentPlayer = players.poll(); + int initialPosition = currentPlayer.getPosition(); + int diceValue = dice.roll(); + int newPosition = initialPosition + diceValue; + + // Check for board limits + if (newPosition <= board.getSize()) { + newPosition = board.getNextPosition(newPosition); + currentPlayer.setPosition(newPosition); + } + + System.out.printf("%s rolled a %d and moved from %d to %d%n", + currentPlayer.getName(), diceValue, initialPosition, currentPlayer.getPosition()); + + if (currentPlayer.getPosition() == board.getSize()) { + System.out.printf("%s wins the game%n", currentPlayer.getName()); + gameWon = true; + } else { + players.add(currentPlayer); + } + } + StringBuilder sb = new StringBuilder(); + sb.insert(0,"abc"); + } +} diff --git a/snakeandladder/Main.java b/snakeandladder/Main.java new file mode 100644 index 00000000..fce81bf8 --- /dev/null +++ b/snakeandladder/Main.java @@ -0,0 +1,52 @@ +package snakeandladder; + + + +import java.util.LinkedList; +import java.util.Queue; +import java.util.Scanner; + +public class Main { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + // Board setup + Board board = new Board(100); + System.out.print("Enter the number of snakes: "); + int numSnakes = scanner.nextInt(); + System.out.println("Enter the snake heads and tails:"); + for (int i = 0; i < numSnakes; i++) { + int head = scanner.nextInt(); + int tail = scanner.nextInt(); + board.addSnake(head, tail); + } + + System.out.print("Enter the number of ladders: "); + int numLadders = scanner.nextInt(); + System.out.println("Enter the ladder starts and ends:"); + for (int i = 0; i < numLadders; i++) { + int start = scanner.nextInt(); + int end = scanner.nextInt(); + board.addLadder(start, end); + } + + // Player setup + Queue players = new LinkedList<>(); + System.out.print("Enter the number of players: "); + int numPlayers = scanner.nextInt(); + scanner.nextLine(); // Consume newline + System.out.println("Enter player names:"); + for (int i = 0; i < numPlayers; i++) { + String name = scanner.nextLine(); + players.add(new Player(name)); + } + + // Initialize game components + Dice dice = new Dice(); + Game game = new Game(board, dice, players); + + // Start game + System.out.println("\nGame started!"); + game.play(); + } +} diff --git a/snakeandladder/Player.java b/snakeandladder/Player.java new file mode 100644 index 00000000..094da80e --- /dev/null +++ b/snakeandladder/Player.java @@ -0,0 +1,23 @@ +package snakeandladder; + +public class Player { + private final String name; + private int position; + + public Player(String name) { + this.name = name; + this.position = 0; + } + + public String getName() { + return name; + } + + public int getPosition() { + return position; + } + + public void setPosition(int position) { + this.position = position; + } +} diff --git a/splitwise/Balance.java b/splitwise/Balance.java new file mode 100644 index 00000000..99ad5e4e --- /dev/null +++ b/splitwise/Balance.java @@ -0,0 +1,24 @@ +package splitwise; + +public class Balance { + double amountOwe; + double amountGetBack; + + public double getAmountOwe() { + return amountOwe; + } + + public void setAmountOwe(double amountOwe) { + this.amountOwe = amountOwe; + } + + public double getAmountGetBack() { + return amountGetBack; + } + + public void setAmountGetBack(double amountGetBack) { + this.amountGetBack = amountGetBack; + } + +} + diff --git a/splitwise/BalanceSheetController.java b/splitwise/BalanceSheetController.java new file mode 100644 index 00000000..cb651605 --- /dev/null +++ b/splitwise/BalanceSheetController.java @@ -0,0 +1,80 @@ +package splitwise; + +import java.util.List; +import java.util.Map; + +public class BalanceSheetController { + public void updateUserExpenseBalanceSheet(User expensePaidBy, List splits, double totalExpenseAmount){ + + //update the total amount paid of the expense paid by user + UserExpenseBalanceSheet paidByUserExpenseSheet = expensePaidBy.getUserExpenseBalanceSheet(); + paidByUserExpenseSheet.setTotalPayment(paidByUserExpenseSheet.getTotalPayment() + totalExpenseAmount); + + for(SplitDetails split : splits) { + + User userOwe = split.getUser(); + UserExpenseBalanceSheet oweUserExpenseSheet = userOwe.getUserExpenseBalanceSheet(); + double oweAmount = split.getAmountOwe(); + + if(expensePaidBy.getUserId().equals(userOwe.getUserId())){ + paidByUserExpenseSheet.setTotalYourExpense(paidByUserExpenseSheet.getTotalYourExpense()+oweAmount); + } + else { + + //update the balance of paid user + paidByUserExpenseSheet.setTotalYouGetBack(paidByUserExpenseSheet.getTotalYouGetBack() + oweAmount); + + Balance userOweBalance; + if(paidByUserExpenseSheet.getUserVsBalance().containsKey(userOwe.getUserId())) { + + userOweBalance = paidByUserExpenseSheet.getUserVsBalance().get(userOwe.getUserId()); + } + else { + userOweBalance = new Balance(); + paidByUserExpenseSheet.getUserVsBalance().put(userOwe.getUserId(), userOweBalance); + } + + userOweBalance.setAmountGetBack(userOweBalance.getAmountGetBack() + oweAmount); + + + //update the balance sheet of owe user + oweUserExpenseSheet.setTotalYouOwe(oweUserExpenseSheet.getTotalYouOwe() + oweAmount); + oweUserExpenseSheet.setTotalYourExpense(oweUserExpenseSheet.getTotalYourExpense() + oweAmount); + + Balance userPaidBalance; + if(oweUserExpenseSheet.getUserVsBalance().containsKey(expensePaidBy.getUserId())){ + userPaidBalance = oweUserExpenseSheet.getUserVsBalance().get(expensePaidBy.getUserId()); + } + else{ + userPaidBalance = new Balance(); + oweUserExpenseSheet.getUserVsBalance().put(expensePaidBy.getUserId(), userPaidBalance); + } + userPaidBalance.setAmountOwe(userPaidBalance.getAmountOwe() + oweAmount); + } + } + } + + public void showBalanceSheetOfUser(User user){ + + System.out.println("---------------------------------------"); + + System.out.println("Balance sheet of user : " + user.getUserId()); + + UserExpenseBalanceSheet userExpenseBalanceSheet = user.getUserExpenseBalanceSheet(); + + System.out.println("TotalYourExpense: " + userExpenseBalanceSheet.getTotalYourExpense()); + System.out.println("TotalGetBack: " + userExpenseBalanceSheet.getTotalYouGetBack()); + System.out.println("TotalYourOwe: " + userExpenseBalanceSheet.getTotalYouOwe()); + System.out.println("TotalPaymnetMade: " + userExpenseBalanceSheet.getTotalPayment()); + for(Map.Entry entry : userExpenseBalanceSheet.getUserVsBalance().entrySet()){ + + String userID = entry.getKey(); + Balance balance = entry.getValue(); + + System.out.println("userID:" + userID + " YouGetBack:" + balance.getAmountGetBack() + " YouOwe:" + balance.getAmountOwe()); + } + + System.out.println("---------------------------------------"); + + } +} diff --git a/splitwise/EqualExpenseSplit.java b/splitwise/EqualExpenseSplit.java new file mode 100644 index 00000000..23aa41e7 --- /dev/null +++ b/splitwise/EqualExpenseSplit.java @@ -0,0 +1,19 @@ +package splitwise; + +import java.util.List; + +public class EqualExpenseSplit implements ExpenseSplit{ + + + @Override + public void validateSplitRequest(List splitList, double totalAmount) { + //validate total amount in splits of each user is equal and overall equals to totalAmount or not + double amountShouldBePresent = totalAmount/splitList.size(); + for(SplitDetails split: splitList) { + if(split.getAmountOwe() != amountShouldBePresent) { + //throw exception + } + } + } +} + diff --git a/splitwise/Expense.java b/splitwise/Expense.java new file mode 100644 index 00000000..04fd6afb --- /dev/null +++ b/splitwise/Expense.java @@ -0,0 +1,30 @@ +package splitwise; + + +import java.util.ArrayList; +import java.util.List; + +public class Expense { + + String expenseId; + + String description; + + double expenseAmount; + + User paidByUser; + + ExpenseSplitType splitType; + + List splitDetails = new ArrayList<>(); + + public Expense(String expenseId, String description, double expenseAmount, User paidByUser, ExpenseSplitType splitType, List splitDetails) { + this.expenseId = expenseId; + this.description = description; + this.expenseAmount = expenseAmount; + this.paidByUser = paidByUser; + this.splitType = splitType; + this.splitDetails.addAll(splitDetails); + } +} + diff --git a/splitwise/ExpenseController.java b/splitwise/ExpenseController.java new file mode 100644 index 00000000..58359d83 --- /dev/null +++ b/splitwise/ExpenseController.java @@ -0,0 +1,25 @@ +package splitwise; + +import java.util.List; + +public class ExpenseController { + + BalanceSheetController balanceSheetController; + + public ExpenseController() { + balanceSheetController = new BalanceSheetController(); + } + + public Expense createExpense(String expenseId, String description, double expenseAmount, + List splitDetails, ExpenseSplitType splitType, User paidByUser) { + + ExpenseSplit expenseSplit = SplitFactory.getSplitObject(splitType); + expenseSplit.validateSplitRequest(splitDetails, expenseAmount); + + Expense expense = new Expense(expenseId, description, expenseAmount, paidByUser, splitType, splitDetails); + + balanceSheetController.updateUserExpenseBalanceSheet(paidByUser, splitDetails, expenseAmount); + + return expense; + } +} diff --git a/splitwise/ExpenseSplit.java b/splitwise/ExpenseSplit.java new file mode 100644 index 00000000..a38f1064 --- /dev/null +++ b/splitwise/ExpenseSplit.java @@ -0,0 +1,10 @@ +package splitwise; + +import java.util.List; + +public interface ExpenseSplit { + + public void validateSplitRequest(List splitList, double totalAmount); +} + + diff --git a/splitwise/ExpenseSplitType.java b/splitwise/ExpenseSplitType.java new file mode 100644 index 00000000..5b57188d --- /dev/null +++ b/splitwise/ExpenseSplitType.java @@ -0,0 +1,9 @@ +package splitwise; + +public enum ExpenseSplitType { + + EQUAL, + UNEQUAL, + PERCENTAGE +} + diff --git a/splitwise/Group.java b/splitwise/Group.java new file mode 100644 index 00000000..a381898e --- /dev/null +++ b/splitwise/Group.java @@ -0,0 +1,48 @@ +package splitwise; + +import java.util.ArrayList; +import java.util.List; + +public class Group { + + String groupId; + String groupName; + List groupMembers; + + List expenseList; + + ExpenseController expenseController; + + Group(){ + groupMembers = new ArrayList<>(); + expenseList = new ArrayList<>(); + expenseController = new ExpenseController(); + } + + //add member to group + public void addMember(User member){ + groupMembers.add(member); + } + + public String getGroupId() { + return groupId; + } + + public void setGroupId(String groupId) { + this.groupId = groupId; + } + + public void setGroupName(String groupName) { + this.groupName = groupName; + } + + public Expense createExpense(String expenseId, String description, double expenseAmount, + List splitDetails, ExpenseSplitType splitType, User paidByUser) { + + Expense expense = expenseController.createExpense(expenseId, description, expenseAmount, splitDetails, splitType, paidByUser); + expenseList.add(expense); + return expense; + } +} + + diff --git a/splitwise/GroupController.java b/splitwise/GroupController.java new file mode 100644 index 00000000..c63da801 --- /dev/null +++ b/splitwise/GroupController.java @@ -0,0 +1,40 @@ +package splitwise; + +import java.util.ArrayList; +import java.util.List; + +public class GroupController { + + List groupList; + + public GroupController(){ + groupList = new ArrayList<>(); + } + + //create group + public void createNewGroup(String groupId, String groupName, User createdByUser) { + + //create a new group + Group group = new Group(); + group.setGroupId(groupId); + group.setGroupName(groupName); + + //add the user into the group, as it is created by the USER + group.addMember(createdByUser); + + //add the group in the list of overall groups + groupList.add(group); + } + + public Group getGroup(String groupId){ + + for(Group group: groupList) { + + if(group.getGroupId().equals(groupId)){ + return group; + } + } + return null; + } +} + diff --git a/splitwise/Main.java b/splitwise/Main.java new file mode 100644 index 00000000..7c46a390 --- /dev/null +++ b/splitwise/Main.java @@ -0,0 +1,9 @@ +package splitwise; + +public class Main { + public static void main(String args[]){ + + SplitWise splitwise = new SplitWise(); + splitwise.demo(); + } +} diff --git a/splitwise/PercentageExpenseSplit.java b/splitwise/PercentageExpenseSplit.java new file mode 100644 index 00000000..54ef3591 --- /dev/null +++ b/splitwise/PercentageExpenseSplit.java @@ -0,0 +1,11 @@ +package splitwise; + +import java.util.List; + +public class PercentageExpenseSplit implements ExpenseSplit { + @Override + public void validateSplitRequest(List splitList, double totalAmount) { + + } + +} diff --git a/splitwise/SplitDetails.java b/splitwise/SplitDetails.java new file mode 100644 index 00000000..23bc8778 --- /dev/null +++ b/splitwise/SplitDetails.java @@ -0,0 +1,30 @@ +package splitwise; + + +public class SplitDetails { + + User user; + double amountOwe; + + public SplitDetails(User user, double amountOwe){ + this.user = user; + this.amountOwe = amountOwe; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public double getAmountOwe() { + return amountOwe; + } + + public void setAmountOwe(double amountOwe) { + this.amountOwe = amountOwe; + } + +} diff --git a/splitwise/SplitFactory.java b/splitwise/SplitFactory.java new file mode 100644 index 00000000..13e2c68e --- /dev/null +++ b/splitwise/SplitFactory.java @@ -0,0 +1,19 @@ +package splitwise; + +public class SplitFactory { + + public static ExpenseSplit getSplitObject(ExpenseSplitType splitType) { + + switch (splitType) { + case EQUAL: + return new EqualExpenseSplit(); + case UNEQUAL: + return new UnequalExpenseSplit(); + case PERCENTAGE: + return new PercentageExpenseSplit(); + default: + return null; + } + } +} + diff --git a/splitwise/SplitWise.java b/splitwise/SplitWise.java new file mode 100644 index 00000000..3b06581f --- /dev/null +++ b/splitwise/SplitWise.java @@ -0,0 +1,74 @@ +package splitwise; + +import java.util.ArrayList; +import java.util.List; + +public class SplitWise { + + UserController userController; + GroupController groupController; + + BalanceSheetController balanceSheetController; + SplitWise(){ + userController = new UserController(); + groupController = new GroupController(); + balanceSheetController = new BalanceSheetController(); + } + + public void demo(){ + + setupUserAndGroup(); + + //Step1: add members to the group + Group group = groupController.getGroup("G1001"); + group.addMember(userController.getUser("U2001")); + group.addMember(userController.getUser("U3001")); + + //Step2. create an expense inside a group + List splits = new ArrayList<>(); + SplitDetails split1 = new SplitDetails(userController.getUser("U1001"), 300); + SplitDetails split2 = new SplitDetails(userController.getUser("U2001"), 300); + SplitDetails split3 = new SplitDetails(userController.getUser("U3001"), 300); + splits.add(split1); + splits.add(split2); + splits.add(split3); + group.createExpense("Exp1001", "Breakfast", 900, splits, ExpenseSplitType.EQUAL, userController.getUser("U1001")); + + List splits2 = new ArrayList<>(); + SplitDetails splits2_1 = new SplitDetails(userController.getUser("U1001"), 400); + SplitDetails splits2_2 = new SplitDetails(userController.getUser("U2001"), 100); + splits2.add(splits2_1); + splits2.add(splits2_2); + group.createExpense("Exp1002", "Lunch", 500, splits2, ExpenseSplitType.UNEQUAL, userController.getUser("U2001")); + + for(User user : userController.getAllUsers()) { + balanceSheetController.showBalanceSheetOfUser(user); + } + } + + public void setupUserAndGroup(){ + + //onboard user to splitwise app + addUsersToSplitwiseApp(); + + //create a group by user1 + User user1 = userController.getUser("U1001"); + groupController.createNewGroup("G1001", "Outing with Friends", user1); + } + + private void addUsersToSplitwiseApp(){ + + //adding User1 + User user1 = new User("U1001", "User1"); + + //adding User2 + User user2 = new User ("U2001", "User2"); + + //adding User3 + User user3 = new User ("U3001", "User3"); + + userController.addUser(user1); + userController.addUser(user2); + userController.addUser(user3); + } +} diff --git a/splitwise/UnequalExpenseSplit.java b/splitwise/UnequalExpenseSplit.java new file mode 100644 index 00000000..7711d4e7 --- /dev/null +++ b/splitwise/UnequalExpenseSplit.java @@ -0,0 +1,14 @@ +package splitwise; + +import java.util.List; + +public class UnequalExpenseSplit implements ExpenseSplit{ + + + @Override + public void validateSplitRequest(List splitList, double totalAmount) { + + } + +} + diff --git a/splitwise/User.java b/splitwise/User.java new file mode 100644 index 00000000..15f404d6 --- /dev/null +++ b/splitwise/User.java @@ -0,0 +1,20 @@ +package splitwise; + +public class User { + String userId; + String userName; + UserExpenseBalanceSheet userExpenseBalanceSheet; + + public User(String id, String userName){ + this.userId = id; + this.userName = userName; + userExpenseBalanceSheet = new UserExpenseBalanceSheet(); + } + public String getUserId() { + return userId; + } + + public UserExpenseBalanceSheet getUserExpenseBalanceSheet() { + return userExpenseBalanceSheet; + } +} diff --git a/splitwise/UserController.java b/splitwise/UserController.java new file mode 100644 index 00000000..47114cd2 --- /dev/null +++ b/splitwise/UserController.java @@ -0,0 +1,33 @@ +package splitwise; + +import java.util.ArrayList; +import java.util.List; + +public class UserController { + + List userList; + + public UserController(){ + userList = new ArrayList<>(); + } + + //add user + public void addUser(User user) { + userList.add(user); + } + + public User getUser(String userID) { + + for (User user : userList) { + if (user.getUserId().equals(userID)) { + return user; + } + } + return null; + } + + public List getAllUsers(){ + return userList; + } +} + diff --git a/splitwise/UserExpenseBalanceSheet.java b/splitwise/UserExpenseBalanceSheet.java new file mode 100644 index 00000000..840c188f --- /dev/null +++ b/splitwise/UserExpenseBalanceSheet.java @@ -0,0 +1,60 @@ +package splitwise; + +import java.util.HashMap; +import java.util.Map; + +public class UserExpenseBalanceSheet { + Map userVsBalance; + double totalYourExpense; + + double totalPayment; + + double totalYouOwe; + double totalYouGetBack; + + public UserExpenseBalanceSheet(){ + + userVsBalance = new HashMap<>(); + totalYourExpense = 0; + totalYouOwe = 0; + totalYouGetBack = 0; + } + + public Map getUserVsBalance() { + return userVsBalance; + } + + public double getTotalYourExpense() { + return totalYourExpense; + } + + public void setTotalYourExpense(double totalYourExpense) { + this.totalYourExpense = totalYourExpense; + } + + public double getTotalYouOwe() { + return totalYouOwe; + } + + public void setTotalYouOwe(double totalYouOwe) { + this.totalYouOwe = totalYouOwe; + } + + public double getTotalYouGetBack() { + return totalYouGetBack; + } + + public void setTotalYouGetBack(double totalYouGetBack) { + this.totalYouGetBack = totalYouGetBack; + } + + public double getTotalPayment() { + return totalPayment; + } + + public void setTotalPayment(double totalPayment) { + this.totalPayment = totalPayment; + } + +} +