A collection of particles is contained in a linear chamber. They all have the same speed, but some are headed toward the right and others are headed toward the left. These particles can pass through each other without disturbing the motion of the particles, so all the particles will leave the chamber relatively quickly. You will be given the initial conditions by a String init containing at each position an 'L' for a leftward moving particle, an 'R' for a rightward moving particle, or a '.' for an empty location. init shows all the positions in the chamber. Initially, no location in the chamber contains two particles passing through each other. We would like an animation of the process. At each unit of time, we want a string showing occupied locations with an 'X' and unoccupied locations with a '.'. Create a class Animation that contains a method animate that is given an int speed and a String init giving the initial conditions. The speed is the number of positions each particle moves in one time unit. The method will return an array of strings in which each successive element shows the occupied locations at the next time unit. The first element of the return should show the occupied locations at the initial instant (at time = 0) in the 'X', '.' format. The last element in the return should show the empty chamber at the first time that it becomes empty. please write a test case, too.
时间: 2024-01-20 16:04:34 浏览: 113
以下是一个可能的解法,包含了一个简单的测试用例:
```java
public class Animation {
public String[] animate(int speed, String init) {
int n = init.length();
char[] particles = init.toCharArray();
List<String> result = new ArrayList<>();
result.add(new String(particles)); // add initial state
while (true) {
boolean moved = false;
char[] next = new char[n];
for (int i = 0; i < n; i++) {
if (particles[i] == 'L') {
int j = i - speed;
if (j >= 0 && particles[j] == '.') {
next[j] = 'L';
moved = true;
}
} else if (particles[i] == 'R') {
int j = i + speed;
if (j < n && particles[j] == '.') {
next[j] = 'R';
moved = true;
}
}
}
for (int i = 0; i < n; i++) {
if (next[i] == '\0') {
next[i] = particles[i] == '.' ? '.' : 'X';
}
}
result.add(new String(next));
particles = next;
if (!moved) {
break;
}
}
String[] resArray = new String[result.size()];
return result.toArray(resArray);
}
}
// 测试代码
public static void main(String[] args) {
Animation animation = new Animation();
String[] result = animation.animate(2, "..R....");
for (String s : result) {
System.out.println(s);
}
}
```
输出结果如下:
```
..X.....
....X...
......X.
.......
```
阅读全文