반응형
https://programmers.co.kr/learn/courses/30/lessons/64061
코딩테스트 연습 - 크레인 인형뽑기 게임
[[0,0,0,0,0],[0,0,1,0,3],[0,2,5,0,1],[4,2,4,4,2],[3,5,1,3,1]] [1,5,3,5,1,2,1,4] 4
programmers.co.kr
나의 코드
function solution(board, moves) {
var answer = 0;
var box = [];
let boards = board
for( i=0; i < moves.length; i++){
let moving = moves[i]
for(k=0; k<moves.length; k++){
let local = boards[k] || []
if(local[moving - 1]){
box.push(local[moving - 1])
local.splice(eval(`${moving}-1`), 1, 0)
break
}
}
}
let toto = box.reduce((unique, item) => {
return unique[unique.length - 1] === item ? unique.slice(0,-1) : [...unique, item]
}, []);
answer = box.length - toto.length
return answer;
}
문제가 참 신선했다.
일단 for중첩을 사용해야겠다고 생각했다.
그리고 해당되는 숫자를 뽑은 뒤 box에 넣고 연속되는 숫자 모두를 제거한 배열을 만들어서 box랑 비교한 값이 정답이 되게 했다.
여기서 어려웠던 점은
reduce를 사용해서 딱 연속되는 중첩만 모두 제거 하는 것 이었다.
여기서 시간이 오래걸렸지만 결국 해결하였다.
<위 코드 에서 let local = boards[k] || [] 이 부분 더 공부해야한다 >
https://html-jc.tistory.com/314
[오류 해결] Cannot read Property '0' of Undefined in JS
the "Cannot read property '0' of undefined" error occurs when trying to access the index '0' on a variable that stores an 'undefined' value. 이것을 해결하기 위해서는 array 이나 string 같은 인덱스 엑..
html-jc.tistory.com
반응형
'알고리즘 > 프로그래머스 - JS' 카테고리의 다른 글
[프로그래머스-JS] level.1 내적 (0) | 2022.06.27 |
---|---|
[프로그래머스-JS] level.1 음양 더하기 (0) | 2022.06.27 |
[프로그래머스-JS] level.1 키패드 누르기 (0) | 2022.06.26 |
[프로그래머스-JS] level.1 숫자 문자열과 영단어 (0) | 2022.06.14 |
[프로그래머스-JS] level.1 신규아이디 추천 (0) | 2022.06.11 |