function solution(n, stations, w) {
let beforeStation = 0;
let distance = 0;
const allWidth = 2*w+1;
let answer = 0 ;
for(let i=0;i<=stations.length;i++)
{
if(i===stations.length && stations[i-1] + w < n){
answer += Math.ceil((n-stations[i-1] -w ) / allWidth);
}
else if(i !==stations.length){
distance = stations[i] - beforeStation -1 -w;
answer += Math.ceil(distance / allWidth);
beforeStation = stations[i]+ w ;
}
}
return answer
}
왼쪽에서 기지국을 발견할 때마다 왼쪽의 기지국과 닿지않는 거리를 구해 기지국이 최소한으로 설치하는 양 만큼 설치 시키는 값을 추가시키는 것을 반복하며
마지막 기지국 후에 기지국과 닿지않는 오른쪽 부분은 따로 처리한다.
반복은 가장 최소한으로 하기위해 stations의 배열값만큼 반복을 진행하고 이때 if문(마지막 기지국 설치후 오른쪽 기지국과 닿지않는 경우)를 진행시키고 else if문으로 다른 기지국들에 대해 계산을 처리해준다.
else if 문
distance = stations[i] - beforeStation -1 -w;
answer += Math.ceil(distance / allWidth);
beforeStation = stations[i]+ w ;
첫번째 stations에서 왼쪽 기지국의 영역만큼(w) 빼고 자신을 포함하는 영역이기에 1을 더 빼준 distance(기지국이 닿지않는 부분)을 구하고 그곳에 최소한의 기지국을 설치하는 값인
Math.ceil(distance / allWidth)
를 더해준다.
if문
if(i===stations.length && stations[i-1] + w < n){
answer += Math.ceil((n-stations[i-1] -w ) / allWidth);```
>제일 먼 n부터 마지막 기지국을 빼고 그 기지국이 차지하는 영역(w)를 뺀 값을 기지국 최소한의 갯수를 설치하게 나눈 값의 반올림을 추가해준다.
- 굳이 마지막에서만 실행되는 if문을 먼저 사용하면 코드 진행시 시간 낭비가 될 것이라 본다. 따라서 조금 다르게 기존의 if문과 else if 문의 내용을 바꾸어준다.
if(i===stations.length && stations[i-1] + w < n)
의 뒤의조건은 굳이 필요는 없을 것 같다. 기지국이 맨끝에 있어서 실행이 되어도n-stations[i-1]-w
은 결국 0보다 작기때문에 answer에 영향을 주지않는다.
function solution(n, stations, w) {
let beforeStation = 0;
let distance = 0;
const allWidth = 2*w+1;
let answer = 0 ;
for(let i=0;i<=stations.length;i++)
{
if(i !==stations.length){
distance = stations[i] - beforeStation -1 -w;
answer += Math.ceil(distance / allWidth);
beforeStation = stations[i]+ w ;
}
else if(i===stations.length){
answer += Math.ceil((n-stations[i-1] -w ) / allWidth);
}
}
return answer
}