C++ Program to find room status after checking guest appearance record


Suppose we have a string S with 'L', 'R' and digits from 0 to 9. Consider there is a hotel with 10 rooms they are numbered from 0 to 9, from left to right. The hotel has two entrances-one from the left side, and another from the right side. When a customer arrives to the hotel through the left entrance, they get an empty room closest to the left entrance. Similarly, when a customer arrives at the hotel through the right entrance, they get an empty room closest to the right entrance. But we have lost the room assignment list. But we remember all of the customers: when a customer arrived, from which entrance, and when they left the hotel. Initially the hotel was empty. We have to recovers the room assignment list from the memory. In S, 'L' means the person came from left side, if it is 'R' he/she came from right side, and digit d indicates the customer leaves room d. We have to return room status. A string whose length is 10 and it that is 0, means room is empty, otherwise it is occupied.

So, if the input is like S = "LLRL1RL1", then the output will be "1010000011", because

First of all, all rooms are empty. Status 0000000000.

  • L − The customer arrives to the hotel through the left entrance. Status 1000000000.
  • L − Customer from the left entrance. Status 1100000000.
  • R − Customer from the right entrance. Status 1100000001.
  • L − Customer from the left entrance. Status 1110000001.
  • 1 − Customer in room 1 leaves. Status 1010000001.
  • R − Customer from the right entrance. Status 1010000011.
  • L − Customer from the left entrance. Status 1110000011.
  • 1 − Customer in room 1 leaves. Status 1010000011.

Steps

To solve this, we will follow these steps −

n := size of S
a := "0000000000"
for initialize i := 0, when i < n, update (increase i by 1), do:
   if S[i] is same as 'L', then:
      set left most 0 in a to 1
   if S[i] is same as 'R', then:
      set right most 0 in a to 1
   Otherwise
      set S[i]th place in a to 0
return a

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;

string solve(string S) {
   int n = S.size();
   string a = "0000000000";
   for (int i = 0; i < n; i++) {
      if (S[i] == 'L')
         a[a.find('0')] = '1';
      if (S[i] == 'R')
         a[a.rfind('0')] = '1';
      else
         a[S[i] - '0'] = '0';
   }
   return a;
}
int main() {
   string S = "LLRL1RL1";
   cout << solve(S) << endl;
}

Input

"LLRL1RL1"

Output

1010000011

Updated on: 04-Mar-2022

217 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements