https://school.programmers.co.kr/learn/courses/30/lessons/154539
ํด๋น ์๊ฐ์ ํ๋ ธ๋ค
์ฒซ๋ฒ์งธ
javaScript์ es6 ํจ์ (์ฆ, ๊ณ ์ฐจํจ์ map, filter ...)๋ break๊ฐ ์๋ํ์ง ์๋๋ค. ๊ทธ ์ด์ ๋ ๊ณต์๋ฌธ์์์ ์ฐพ์๋ค.
Description
map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values (including undefined).
์์ฝํ์๋ฉด ์ฃผ์ด์ง input array์ ๊ธธ์ด๋งํผ iterator๋ฅผ ๋๋ฆฌ๋ฉด์ ๊ทธ๋๋ง๋ค callback ํจ์๋ฅผ ๋๋ฆฐ๋ค. ์ฆ, callback์ ํธ์ถํ ์๊ฐ Loop์ ์ญํ ์ ๋๋๊ณ Loop์ ์ค๊ฐ์ break๋ฅผ ๊ฑธ ์ ์๊ฒ ๋๋ ๊ฒ์ด๋ค.
๋๋ฒ์งธ
๊ณ ์ฐจํจ์๋ฅผ ์ฌ์ฉํ์ง ์๊ณ for๋ฌธ์ ์ด์ฉํ์ฌ ์ฝ๋๋ฅผ ์์ฑํ๋ค. ํ์ง๋ง ๋ฌธ์ ์ numbers์ ํฌ๊ธฐ๋ฅผ ๊ณ ๋ คํ์ง ์๊ณ ์๊ฐ ์์ด ์ฝ๋๋ฅผ ์งฐ๊ธฐ ๋๋ฌธ์ ์๊ฐ ๋ณต์ก๋๊ฐ 1,000,000,000,000์ผ๋ก ๋๋ฌด ์ปค์ ธ ์๊ฐ์ด๊ณผ๊ฐ ๋ฐ์ํ๋ค.
const solution = (numbers) => {
let answer = [];
while(numbers.length > 0){
const firstNum = numbers[0];
const numList = numbers.slice(1);
let isBiggest = true;
for(let i = 0; i < numList.length; i++){
console.log(firstNum, numList[i])
if(numList[i] > firstNum){
answer.push(numList[i]);
isBiggest = false;
numbers = numList;
}
}
if(isBiggest === true) {
answer.push(-1);
numbers = numList;
}
}
return answer;
}
const solution = (numbers) => {
let answer = new Array(numbers.length).fill(0);
let stack = []
for(let i = 0; i < numbers.length; i++){
while (stack.length > 0 && numbers[stack[stack.length-1]] < numbers[i]){
answer[stack.pop()] = numbers[i]
}
stack.push(i)
}
while (stack.length > 0){
answer[stack.pop()] = -1
}
return answer;
}
https://school.programmers.co.kr/learn/courses/30/lessons/152996
cal.forEach((i)=>{
if( s = w * i, store[s] ){ //ํด๋น ๋น์จ์ ๊ณฑํ ๊ฐ์ด store์ ์กด์ฌํ ๊ฒฝ์ฐ
answer += store[s];
}
});
const solution = (weights) => {
let answer = 0;
const store = {};
const ratio = [1, 3 / 2, 2, 4 / 3];
weights
.sort((a, b) => b - a)
.forEach((w) => {
let s;
ratio.forEach((i) => {
if (((s = w * i), store[s])) {
answer += store[s];
}
});
if (!store[w]) store[w] = 1;
else store[w]++;
});
return answer;
};
https://school.programmers.co.kr/learn/courses/30/lessons/136797
=> ์๋ฅผ ๋ค์ด ["0111101100011110"]์ ๊ฒฝ์ฐ ๋์์ผํ๋ ๊ฐ์ ["0011011011011011"]์ด๋ค.
const answer = [];
const solution = (s) => {
for (let t = 0; t < s.length; t++) {
let str = s[t];
let stack = [];
let target = findTarget(str, stack);
if (target == "") answer.push(str);
else {
const tmpStr = stack.join("");
const idx = tmpStr.lastIndexOf("0") + 1;
answer.push(tmpStr.substring(0, idx) + target + tmpStr.substring(idx));
}
}
return answer;
};
const findTarget = (str, stack) => {
let target = "";
for (let i = 0; i < str.length; i++) {
const c = str.charAt(i);
if (stack.length >= 2) {
const b = stack.pop();
const a = stack.pop();
if (a == "1" && b == "1" && c == "0") {
target += "110";
continue;
}
stack.push(a);
stack.push(b);
}
stack.push(c);
}
return target;
};