Reputation: 41
I have this structure of a class:
public class Parking {
private int[] arr;
public Parking(int capacity) {
arr = new int[capacity];
}
public boolean arrive(int k) {
if (arr[k] == 0) {
arr[k] = 1;
System.out.println("true");
return true;
}
return false;
}
public boolean depart(int k) {
return true;
}
}
arrive() method returns true if it was possible to park the car
If the place k is occupied, then it goes to the right until it finds an empty place.
If there is no free place up to the end of the parking, then the free place is searched from the beginning of the parking.
If all places are occupied, then the state of parking does not change (the car leaves).
With the capacity of 4, the result would look like:
parking.arrive(2) // 0010, true
parking.arrive(3) // 0011, true
parking.arrive(2) // 1011, true
parking.arrive(2) // 1111, true
parking.arrive(2) // 1111, false
parking.depart(1) // 1011, true
parking.depart(1) // 1011, false
How should I implement arrive() method correctly? When the cell is already busy
Upvotes: 0
Views: 892
Reputation: 166
just search for the next empty location till you find a position where arr[k] is 0. You can do slight modifications to your code so that it looks like this.
public boolean arrive(int k) {
int start = k;
while(arr[k] != 0) {
k = (k+1)%arr.length;
if(k==start)
{
return false;
}
}
arr[k] = 1;
System.out.println("true");
return true;
}
Upvotes: 1