728x90

`Promise.all()`은 여러 개의 프로미스 객체를 받아 이들이 모두 완료될 때까지 기다리는 JavaScript의 비동기 처리 메서드입니다. 다음은 `Promise.all()`의 장단점입니다:

장점:
1. 병렬 실행: `Promise.all()`은 여러 프로미스를 병렬로 실행하므로 여러 개의 비동기 작업을 동시에 처리할 수 있습니다. 이는 성능 향상에 도움이 됩니다.
2. 대기 시간 최소화: 모든 프로미스가 완료될 때까지 대기하므로, 모든 작업이 완료되는 데 가장 긴 시간을 기다리는 것만큼의 시간이 소요됩니다. 이는 대기 시간을 최소화하고 효율적인 처리를 가능하게 합니다. (장점이 아닌 것처럼 보일 수 있습니다만, 순서대로 실행시키고 기다리는 시간보다 병렬로 실행하면 가장 긴 시간과 가장 적은 시간의 호출을 동시에 시작하게 만들 수 있다는 뜻으로 보입니다) E.g. 1초가 걸리는 호출을 3번 호출하면 응답에 필요한 시간은 총 3초. 반면에 1초가 걸리는 호출을 병렬로 실행하면 응답에 필요한 시간은 총 1초

단점:
1. 하나의 프로미스 실패 시 실패: `Promise.all()`은 모든 프로미스가 성공적으로 완료되어야 전체가 성공으로 처리됩니다. 하나의 프로미스라도 실패하면 전체 `Promise.all()`이 실패합니다. 이것은 실패 처리 및 오류 복구가 어려울 수 있습니다.
2. 순서 보장 없음: `Promise.all()`은 프로미스의 순서를 보장하지 않습니다. 따라서 프로미스가 완료되는 순서에 의존하지 않아야 합니다.
3. 모든 프로미스 필요: 모든 프로미스가 필요하며, 일부만 완료되더라도 결과를 얻을 수 없습니다.

`Promise.all()`을 사용할 때는 이러한 장단점을 고려하여 프로젝트 요구사항에 맞게 적절하게 사용해야 합니다.

 

async function a() {
  return 'a';
}

async function b() {
  return 'b';
}

await Promise.all([a(), b()]);

 

출처: ChatGPT 3.0, OpenAI

728x90
728x90
728x90
728x90

Click! 👉 https://www.youtube.com/watch?v=wSSwgFFH5v8&feature=youtu.be

Github: https://github.com/DasolPark/AriTeam_FullStack_Chatbot_Aribot

대학 생활 편의를 위한 챗봇웹앱졸업 작품으로 개발하였습니다.

👓사용한 기술
Front-End: JavaScript, HTML/CSS, Bootstrap
Back-End: Node.js
Database: MySQL, MongoDB
Cloud Server: AWS EC2
Chatbot Platform: danbee.Ai

📳챗봇: 학사 규칙, 빈 강의실 조회/예약, 부서 위치/전화번호 안내, 학교 식당 메뉴 안내, 편의 시설 위치 안내 등
💻웹앱: 빈 강의실 조회/예약, 개설 강좌 안내, 챗봇 소개, 데이터 관리자 페이지 등

클라우드와_인공지능을_이용한_대학교_학사행정지원_챗봇과_웹앱.pdf
1.83MB

728x90

https://www.acmicpc.net/problem/2292

Code

 

최종 제출 답안
벌집 문제 힌트

😢 보자마자 위에서 표시해 놓은 부분들이 눈에 띄었다.
각 범위를 한 바퀴 돌고 다음 범위로 넘어가는 부분인데, 각 수를 계산해보니 6, 12, 18, 24로 등차수열을 이루고 있었다.
그래서 등차수열을 이용해서 푸는 문제인가? 하고 계산식을 넣으려고 하다가 시간을 좀 낭비했다.

😊 패턴을 찾았다면 프로그래밍적으로 단순하게 작성해 나가면 된다.
최소 거리는 1부터 시작할 것이고, 범위도 1부터 시작한다. 
증가하는 범위는 1,(2~)7, (8~)19, (20~)37...이므로 '기존 범위+(count된)최소 거리*6' 이다.
while loop을 이용해 범위가 입력 받은 N보다 작을 때까지 반복해주면 된다.

Full Code (https://github.com/DasolPark/Algorithm_JavaScript/tree/master/Baekjoon)

// Honey Comb
 
// 1st Solution - Good
 
// For submit
 
// const fs = require('fs');
// const N = Number(fs.readFileSync('/dev/stdin').toString().trim());
 
// For local test
const N = 58;
let counter = 1;
let range = 1;
 
while (range < N) {
range += counter++ * 6;
}
console.log(counter);
728x90

https://www.acmicpc.net/problem/2839

Code

최종 제출 답안

😢 이런저런 조건들을 떠올리다보니 산으로 갔던 문제
역시 조건 그대로 코드를 작성하기 보다는, 다른 시각으로 바라보는 조건이 핵심

😊 가장 최고의 조건을 걸어두고 하나씩 물러나며 최선의 조건을 찾아야한다.

최종 제출 답안)

bigMax 변수에 가장 큰 봉지인 BIG(5)으로 설탕 무게를 나눴을 때, 나오는 숫자를 저장한다.
그리고 bigMax가 음수로 떨어지지 않을 때까지 while loop을 열어준다.

임시로 만든 tempSugar 변수에는 앞에서 계산한 bigMax 무게만큼 SUGAR를 빼준다.
만약 tempSugar가 작은 봉지인 SMALL(3)으로 나눴을 때 나머지가 없다면 최선의 조건이기 때문에 출력하고 계산을 끝내준다.
하지만, 만약 조건에 맞지 않는다면 bigMax를 1만큼 빼준다.
그런 후 tempSugar의 크기를 5만큼 높여주고 다시 3으로 나눠본다.

이런식으로 계속 반복하며 다시 5씩 늘려보고 다시 3으로 나눠봤을 때 나머지가 0이라면 계산이 가능한 설탕 무게이고,
그렇지 않고 bigMax가 음수로 떨어진다면 그건 계산할 수 없는 설탕 무게이므로 -1을 출력한다.

다른 정답자들 중에 배울 수 있었던 답안)

다른 정답자의 답안

😊 먼저, SMALL(3)의 개수를 담아두기 위한 bags 변수를 선언해준다. while loop을 무한으로 돌리면서,
설탕을 BIG(5)으로 나눴을 때 나머지가 0이라면 BIG으로 나눈 값과 bags를 합쳐 출력한다.
그리고 만약 SUGAR가 0이하로 떨어지면 -1을 출력해준다.
둘 다 해당되지 않으면 설탕을 SMALL(3)만큼 빼주고, bags를 1 증가시켜준다. (설탕을 3으로 나눈 것과 같은 의미)

즉, 이것도 역시 최고의 방법인 5를 우선으로 나눠주고, 그게 되지 않는다면 3을 하나씩 늘려가는 방법으로 해결했다.
이것도 굉장히 훌륭한 방법이라고 생각한다.

 

Full Code (https://github.com/DasolPark/Algorithm_JavaScript/tree/master/Baekjoon)

// Sugar Delivery
 
// 3rd Solution - Good
 
// For submit
 
// const fs = require('fs');
// let SUGAR = Number(fs.readFileSync('/dev/stdin'));
 
let SUGAR = 11; // 18 4 6 9 11
const BIG = 5;
const SMALL = 3;
 
let bigMax = Math.floor(SUGAR / BIG);
while (bigMax >= 0) {
let tempSugar = SUGAR - bigMax * BIG;
if (tempSugar % SMALL === 0) {
console.log(bigMax + tempSugar / SMALL);
return;
} else {
bigMax--;
}
}
console.log(-1);
 
// 1st Solution
 
// For submit
 
// const fs = require('fs');
// const SUGAR = parseInt(fs.readFileSync('/dev/stdin').toString().trim());
 
// For local test
// const SUGAR = 18; // 18 4 6 9 11
// const BIG = 5;
// const SMALL = 3;
 
// if (SUGAR >= SMALL) {
// let bigMax = Math.floor(SUGAR / BIG);
// if (bigMax <= 0) {
// if (SUGAR % SMALL === 0) {
// console.log(SUGAR / SMALL);
// return;
// } else {
// console.log(-1);
// return;
// }
// } else {
// while (bigMax >= 0) {
// let tempSugar = SUGAR - bigMax * BIG;
// if (tempSugar % SMALL === 0) {
// console.log(bigMax + tempSugar / SMALL);
// return;
// } else {
// bigMax--;
// }
// }
// console.log(-1);
// }
// } else {
// console.log(-1);
// }
 
// 2nd(other solution) - Good
 
// For submit
 
// const fs = require('fs');
// let SUGAR = parseInt(fs.readFileSync('/dev/stdin').toString().trim());
 
// For local test
// let SUGAR = 9; // 18 4 6 9 11
// let bags = 0;
 
// while (true) {
// if (SUGAR % 5 === 0) {
// console.log(SUGAR / 5 + bags);
// break;
// } else if (SUGAR <= 0) {
// console.log(-1);
// break;
// }
// SUGAR = SUGAR - 3;
// bags++;
// }
728x90

https://www.acmicpc.net/problem/1712

Code

https://github.com/DasolPark/Algorithm_JavaScript/blob/37d399b654275b31f94815eb86c2853ec8cc5b1b/Baekjoon/1712.js

😢 21억 조건을 못 보고 반복문을 돌려 counter를 하나씩 증가시키려고 했다.. 잘못된 방법!

😊 역시나 수학 카테고리답게 다항식을 이용해서 풀면 쉽게 풀 수 있다.
A는 고정 비용, B는 가변 비용, C는 판매 가격이다.
판매 누적 금액고정비용+가변 누적 비용을 넘어서면 손익분기점을 넘어간다.
식을 만들어 본다면, A + Bx < Cx로 만들 수 있다. 
식을 정리해보자. A < Cx - Bx로 Bx를 넘겨주고, A < (C-B)x 로 정리해주면 조금 더 보기 쉽다.
즉, C-B가 0이하(즉, 0 또는 음수)로 떨어지면 손익분기점은 없다. 계속 적자다..ㅎㅎ

손익분기점이 없어서 '-1'을 출력하는 조건문은 2가지 정도로 표현할 수 있다.
1. if(C-B <= 0) { console.log(-1); }
A < (C-B)x 식을 생각해서 C-B가 0이하면 손익분기점은 없다고 표현할 수 있다.
2. if(C <= B) { console.log(-1); }
C-B > 0이 돼야하므로, C <= B으로 정리해주면 손익분기점이 없다고 표현할 수 있다.

Full Code

// Break-Even Point
 
// 1st Solution(other)
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim().split(' ');
 
// For local test
const input = ['1000', '70', '170'];
const A = parseInt(input.shift());
const B = parseInt(input.shift());
const C = parseInt(input.shift());
const netProfit = C - B;
 
if (netProfit <= 0) {
console.log(-1);
} else {
console.log(Math.floor(A / netProfit) + 1);
}
 
// 2nd Solution(ohter)
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim().split(' ').map(num => parseInt(num));
 
// For local test
// const input = ['1000', '70', '170'].map(num => parseInt(num));
// const A = input.shift();
// const B = input.shift();
// const C = input.shift();
 
// if (C <= B) {
// console.log(-1);
// } else {
// console.log(Math.floor(A / (C - B)) + 1);
// }
728x90

https://www.acmicpc.net/problem/1316

Code

https://github.com/DasolPark/Algorithm_JavaScript/blob/a283e8643975b13a658de279d66a7d2f989d9cab/Baekjoon/1316.js

😢 간단한 문제지만, 어떻게 하면 효율적으로 풀 수 있을까 고민했던 문제. 결과적으로 그다지 효과적이지 않은..

😊 결국 중첩 for loop을 이용해서 각 word의 문자를 체크하는 방법으로 풀었다.
Object를 하나 만들어주고, 해당 문자가 이미 사용되었다면 charMap에 '문자': true로 넣어주었다.
만약 charMap에 이미 해당 문자가 있다면 해당 word의 index-1과 같은지 비교해주었다.
같다면 그룹단어, 그렇지 않다면 더 이상 검사할 필요가 없기 때문에 counter를 감소시켜주고, break으로 내부 for loop을 끝냈다.

다른 정답자들의 풀이도 좋은 소스가 되었다.

Full Code

// Group Word Checker
 
// 3rd Solution
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
 
// For local test
// const input = ['3', 'happy', 'new', 'year'];
const input = ['4', 'aba', 'abab', 'abcabc', 'a'];
const N = parseInt(input.shift());
let counter = N;
 
for (let i = 0; i < N; i++) {
const charMap = {};
for (let j = 0; j < input[i].length; j++) {
if (!charMap[input[i][j]]) {
charMap[input[i][j]] = true;
} else if (input[i][j] !== input[i][j - 1]) {
counter--;
break;
}
}
}
 
console.log(counter);
 
// 1st Solution
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
 
// For local test
// const input = ['3', 'happy', 'new', 'year'];
// const input = ['4', 'aba', 'abab', 'abcabc', 'a'];
// const N = parseInt(input[0]);
// let counter = N;
 
// for (let i = 1; i <= N; i++) {
// const charMap = {};
// for (let j = 0; j < input[i].length; j++) {
// if (!charMap[input[i][j]]) {
// charMap[input[i][j]] = true;
// } else if (charMap[input[i][j]] && input[i][j - 1] === input[i][j]) {
// continue;
// } else {
// counter--;
// break;
// }
// }
// }
// console.log(counter);
 
// 2nd solution(other)
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
 
// For local test
// const input = ['3', 'happy', 'new', 'year'];
// const input = ['4', 'aba', 'abab', 'abcabc', 'a'];
// const N = parseInt(input.shift());
// let counter = 0;
 
// function checkGroupWord(str) {
// const checker = [];
 
// for (let i = 0; i < str.length; i++) {
// if (checker.indexOf(str[i]) === -1) {
// checker.push(str[i]);
// } else {
// if (checker[checker.length - 1] !== str[i]) {
// return;
// }
// }
// }
// counter++;
// }
 
// for (let i = 0; i < N; i++) {
// checkGroupWord(input[i]);
// }
 
// console.log(counter);
728x90

https://www.acmicpc.net/problem/2941

Code

https://github.com/DasolPark/Algorithm_JavaScript/blob/89a6bd743bd70a7b83988da93eca0436672e31e4/Baekjoon/2941.js

😢 단순 조건문 처리로는 풀기 싫어서, 어렵게 풀려다가 생각하는 시간이 조금 걸렸다.
그리고 문제를 보자마자 Regular Expression이 떠올라서, RegExp로 풀려고 공부를 조금 했다.

😊 조건문으로만 풀기에는 뭔가 문제가 아까웠다. 그래서 이런 방법 저런 방법을 시도해봤다. (물론 단순 조건으로도 풀어봤다)

regex변수크로아티아 알파벳 조건들을 입력해주고 replace() 에 주입하여, 만약 일치하는 것이 있다면 공백(' ')으로 만들어줬다.
RegExp 구성을 살펴보겠다. 아주 간단하다.
=, -와 같은 문자들은 특수문자이기 때문에 특별하다는 뜻으로 \(backslash, escape라고도 부른다)를 앞에 붙여줘야 하고,
그 외 조건들은 |(or)문자를 사용해서 구분해주었고, g를 붙여 Global search를 해줬다.

결과적으로 2개 이상 문자를 갖는 크로아티아 알파벳은 공백으로 변경되어 1개의 문자를 갖게 된다.
따라서 결과의 length를 출력해주면 크로아티아 알파벳의 개수를 알 수 있다.
(조건 외의 알파벳은 1개로 치니까 따로 처리하지 않는다)

Full Code단순 조건문 처리로 푼 예제도 있으니 참고하길 바란다.

✔ String.prototype.replce()

크로아티아 알파벳만의 조건을 넣어서, 공백(' ')으로 변경해주기 위해 사용했다.

✔ Regular Expressions

문자열을 다루기 위한 정규표현식이다. 크로아티아 알파벳 조건을 표현하기 위해 사용하였다.

위의 Skill들은 JavaScript - helper methods 카테고리에서 간단한 사용방법을 확인할 수 있다.

Full Code

// Croatia Alphabet
 
// 1st Solution(Regular Expressions)
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim();
 
// For local test
const input = 'ljes=njak';
 
var regex = /c\=|c\-|dz\=|d\-|lj|nj|s\=|z\=/g;
const result = input.replace(regex, ' ');
 
console.log(result.length);
 
// 2nd Solution(while, idx, if else)
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim();
 
// For local test
// const input = 'ljes=njak';
// let idx = 0;
// let counter = 0;
 
// while (idx < input.length) {
// if (
// input[idx] === 'c' &&
// (input[idx + 1] === '=' || input[idx + 1] === '-')
// ) {
// idx += 2;
// counter++;
// } else if (
// input[idx] === 'd' &&
// input[idx + 1] === 'z' &&
// input[idx + 2] === '='
// ) {
// idx += 3;
// counter++;
// } else if (input[idx] === 'd' && input[idx + 1] === '-') {
// idx += 2;
// counter++;
// } else if (
// input[idx + 1] === 'j' &&
// (input[idx] === 'l' || input[idx] === 'n')
// ) {
// idx += 2;
// counter++;
// } else if (input[idx] === 's' && input[idx + 1] === '=') {
// idx += 2;
// counter++;
// } else if (input[idx] === 'z' && input[idx + 1] === '=') {
// idx += 2;
// counter++;
// } else {
// idx++;
// counter++;
// }
// }
 
// console.log(counter);
 
// 3rd Solution(shift, while, if else)
 
// For submit
 
// const fs = require('fs');
// const str = fs.readFileSync('/dev/stdin').toString().trim().split('');
 
// For local test
// const str = 'ljes=njak'.split('');
// let counter = 0;
 
// while (str.length) {
// if (str[0] === 'c' && (str[1] === '=' || str[1] === '-')) {
// counter++;
// str.shift();
// str.shift();
// } else if (str[0] === 'd' && str[1] === 'z' && str[2] === '=') {
// counter++;
// str.shift();
// str.shift();
// str.shift();
// } else if (str[0] === 'd' && str[1] === '-') {
// counter++;
// str.shift();
// str.shift();
// } else if (str[1] === 'j' && (str[0] === 'l' || str[0] === 'n')) {
// counter++;
// str.shift();
// str.shift();
// } else if (str[0] === 's' && str[1] === '=') {
// counter++;
// str.shift();
// str.shift();
// } else if (str[0] === 'z' && str[1] === '=') {
// counter++;
// str.shift();
// str.shift();
// } else {
// counter++;
// str.shift();
// }
// }
 
// console.log(counter);

+ Recent posts