

ingredient배열을 순회하면서 "1231"이라는 연속된 배열을 찾고
그 수를 리턴해줘야한다.
ingredient배열을 새로운 compareArray에 하나씩 복사해서 넣고
배열의 길이가 4이상이였을 때 뒤에서부터 "1231"이라는 숫자를 찾아야한다.
찾았을 때 그 수를 리턴해주고, pop()해주고 다음 반복한다.
function solution(ingredient) {
const hamburger = "1231";
let compareArray = [];
let count = 0;
ingredient.forEach((item)=>{
compareArray.push(item);
if(compareArray.length >= 4){
let str = compareArray.slice(-4).join('');
if( str === "1231"){
for(let i = 0; i < 4; i++){
compareArray.pop();
}
count ++;
}
}
})
return count;
}
다른 사람의 풀이를 보니 기발하다..
for문의 i의 값을 변경해서 좀 더 간단하게 코드를 짰다.
이러한 방식이 있다는건 처음 알았다.
function solution(ingredient) {
let count = 0;
for (let i = 0; i < ingredient.length; i++) {
if (ingredient.slice(i, i + 4).join('') === '1231') {
count++;
ingredient.splice(i, 4);
i -= 3;
}
}
return count;
}