PS/프로그래머스
[!][Level2][Javascript] 조이스틱
returnzero
2022. 6. 27. 18:14
function solution(name) {
var answer = 0;
let char_list= name.split("");
char_list.forEach((e,i)=>{
// console.log(e);
answer+=Math.min(e.charCodeAt(0)-'A'.charCodeAt(0), 1+'Z'.charCodeAt(0)-e.charCodeAt(0));
})
char_list[0]='A';
let indices=new Array(char_list.length).fill(1);
char_list.forEach((e,i)=>{
if(e!=='A'){
indices[i]=0;
}
})
// console.log(indices);
let move=0;
let current=0;
let places=[];
for(let i=0; i<indices.length;i++){
if (indices[i]!==1) places.push(i);
}
while(places.length){
// console.log(places);
let is=0;
let next=places[0];
let min=Math.min( Math.abs(places[0]-current), Math.abs(indices.length-1-places[0]+1+current), Math.abs(indices.length-current+places[0]));
places.forEach((e,i)=>{
let small= Math.min(Math.abs(e-current), Math.abs(indices.length-1-e+1+current),Math.abs(indices.length-current+e))
if( small< min ){
min= small;
next=e;
is=i;
}
});
places.splice(is,1);
console.log("MIN is ",min,"NEXT is ",next)
move+=min;
current=next;
indices[current]=1;
}
answer+= move;
return answer;
}
77점짜리 풀이인데, Greedy 기법이라고 되어 있어서 greedy로 구현했는데 틀린다고 주장한다..자세히 생각해보면 엄밀하게는 그리디가 아니다..