英文:
Car Parking Algorithm
问题
public boolean arrive(int k) {
if (arr[k] == 0) {
arr[k] = 1;
System.out.println("true");
return true;
} else {
int n = arr.length;
int i = (k + 1) % n; // Start checking from the next cell
while (i != k) {
if (arr[i] == 0) { // Found an empty spot
arr[i] = 1;
System.out.println("true");
return true;
}
i = (i + 1) % n; // Move to the next cell
}
i = 0; // Start checking from the beginning
while (i < k) {
if (arr[i] == 0) { // Found an empty spot
arr[i] = 1;
System.out.println("true");
return true;
}
i++;
}
System.out.println("false"); // No empty spot found
return false;
}
}
英文:
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
答案1
得分: 1
只需搜索下一个空位置,直至找到一个位置其中 arr[k] 为 0。您可以对代码进行轻微修改,使其类似于以下内容。
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;
}
英文:
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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论