1차 실행 오류
Vector를 삭제하는 과정에서 앞에서부터 진행을 하면 인덱스가 꼬이게 되어서 삭제 과정이 원활히 진행되지 않음.
import java.util.Vector;
class Server {
private int remainingRuntime; // 남은 가동 시간
public Server(int remainingRuntime) {
this.remainingRuntime = remainingRuntime;
}
public void discountRemainingRuntime() { // 가동 시간 줄이기
remainingRuntime -= 1;
}
public int getRemainingRuntime() { // 가동 시간 반환
return remainingRuntime;
}
}
class Solution {
public int solution(int[] players, int m, int k) {
int answer = 0;
int capacity = m;
Vector<Server> runningServers = new Vector<Server>();
for (int i = 0; i < players.length; i++) {
capacity = m;
discountRemainingRuntime(runningServers);
capacity *= runningServers.size() + 1;
if (players[i] >= capacity) {
answer += serverExpansion(runningServers, players[i], capacity, m, k);
}
}
return answer;
}
// 서버 증설
public int serverExpansion(Vector<Server> v, int players, int capacity,
int m, int k) {
int count = 0;
while (true) {
if (capacity > players) {
break;
}
v.add(new Server(k));
capacity += m;
count++;
}
return count;
}
// 현재 실행되는 모든 서버의 남은 시간을 줄임
public void discountRemainingRuntime(Vector<Server> v) {
for (int i = 0; i < v.size(); i++) {
v.get(i).discountRemainingRuntime();
if (v.get(i).getRemainingRuntime() == 0) { // 서버의 남은 실행 시간이 없을 때
v.remove(i); // 그 서버 중지(삭제)
}
}
}
}
코드에 오류가 생겼을 때 위에서부터 차례대로 진행해보는 과정을 통해 어디서 오류가 발생했는지 찾을 수 있었음.
소요 시간: 1시간 13분
import java.util.Vector;
class Server {
private int remainingRuntime; // 남은 가동 시간
public Server(int remainingRuntime) {
this.remainingRuntime = remainingRuntime;
}
public void discountRemainingRuntime() { // 가동 시간 줄이기
remainingRuntime -= 1;
}
public int getRemainingRuntime() { // 가동 시간 반환
return remainingRuntime;
}
}
class Solution {
public int solution(int[] players, int m, int k) {
int answer = 0;
int capacity = m;
Vector<Server> runningServers = new Vector<Server>();
for (int i = 0; i < players.length; i++) {
capacity = m;
discountRemainingRuntime(runningServers);
capacity *= runningServers.size() + 1;
if (players[i] >= capacity) {
answer += serverExpansion(runningServers, players[i], capacity, m, k);
}
}
return answer;
}
// 서버 증설
public int serverExpansion(Vector<Server> v, int players, int capacity,
int m, int k) {
int count = 0;
while (true) {
if (capacity > players) {
break;
}
v.add(new Server(k));
capacity += m;
count++;
}
return count;
}
// 현재 실행되는 모든 서버의 남은 시간을 줄임
public void discountRemainingRuntime(Vector<Server> v) {
for (int i = v.size() - 1; i >= 0; i--) {
v.get(i).discountRemainingRuntime();
if (v.get(i).getRemainingRuntime() == 0) { // 서버의 남은 실행 시간이 없을 때
v.remove(i); // 그 서버 중지(삭제)
}
}
}
}