Unlike the traditional cinemas, Alice's cinema has only one row, and each seat has a colour of either red, blue or green:
Every day, she encounters customers requesting for consecutive seats with a particular sequence of colours. To verify if the request is possible, she uses the following matching algorithm :
1 2 3 4 5 6 7 8 9 |
|
Which of the customer request will return false according to the algorithm but is actually true?
This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try
refreshing the page, (b) enabling javascript if it is disabled on your browser and,
finally, (c)
loading the
non-javascript version of this page
. We're sorry about the hassle.
The main problem with the code is in the last line:
What the for loop essentially does is go through the row, seeing if each color matches with the customer's request. Once one of the colors do not match, we know that this cannot be a valid seating, and it will start at the next index. The problem is that it doesn't account for overlaps !
To further illustrate idea, let's use indices. Our for loop starts from the start of the string. Let's say:
Here, this program will now start looking for a new string at Index 3. However, this is a problem, because the requested string could have started at Index 1 or Index 2 , and it would never be caught! The solution to this is to store our starting index. Then, once we get a character that doesn't match, we restart not from the current index + 1, but the starting index + 1.
However, that's not what this problem is asking. We just need to find which string doesn't work. The answer is R B R . Let's see why. Keep in mind that our row string is R R B R G G R B B .
We missed a seating! R B R does occur, and it starts at Index 1. However, we never compared Index 1 of our row to Index 0 of the customer string, because it skipped that to go directly to Index 2. Thus, our answer is R B R .
A side note: Similarly, the string R B would have been missed here for the same reason. However, this is not the answer, because R B is caught later on in the string.