Checking the Elements of an ArrayList
The bookings
A theater's booking system keeps the seats sold for one show in
ArrayList<String> seats, in the order they were sold. Each seat is a row letter and a number."C7", "A2", "A3", "D1", "C7"
The checks below each end with one
boolean describing the list as a whole.At least one element
To find whether any seat in row A was sold,
rowA starts at false and the loop turns it on.boolean rowA = false;
for (String s : seats)
{
if (s.substring(0, 1).equals("A"))
{
rowA = true;
}
}
The second seat sets
rowA to true, and no statement in the loop sets it back, so the answer stays true.The check that every label has exactly two characters runs the other way. Its flag starts
true, and the if sets it to false at any label whose length() isn't 2. Here none fails, so it stays true.Consecutive pairs
Two sales in a row from the same row of the theater mean a group may have bought together. Each pass reads the seat at
i and the one at i + 1, so the index stops one short of the last position.boolean sameRow = false;
for (int i = 0; i < seats.size() - 1; i++)
{
String here = seats.get(i).substring(0, 1);
String next = seats.get(i + 1).substring(0, 1);
if (here.equals(next))
{
sameRow = true;
}
}
The pairs are C and A, A and A, A and D, and D and C. The second pair matches, so
sameRow ends true.Duplicates
A seat sold twice is a double booking. Any element could match any later one, so each element is compared with every element after it.
public static boolean doubleBooked(ArrayList<String> seats)
{
for (int i = 0; i < seats.size() - 1; i++)
{
for (int k = i + 1; k < seats.size(); k++)
{
if (seats.get(i).equals(seats.get(k)))
{
return true;
}
}
}
return false;
}
On the outer loop's first pass,
"C7" is compared with each later seat. The match at index 4 makes the method return true without checking any other pair. The comparison uses equals, which compares the characters. == would ask whether the two elements are the same String object. Two labels typed separately at the box office might not be.A double booking has nothing to do with neighbors. The two
"C7" labels are four positions apart, so the pairs loop above would never find them.