728x90

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

Code

최종 제출 코드

😢 이쁘게 풀어주려다가 그냥 조건문으로 끝낸 문제

😊 가끔은 단순한게 좋은 방법인듯 하다.

일단 x좌표가 같은 것이 있다면, 이미 평행한 좌표가 있는 것이고
y좌표가 같은 것이 있다면, 역시 평행한 좌표가 있는 것이다.
따라서, x 또는 y가 한 번만 존재하는 좌표를 찾아내고 그 값을 넣어주면 된다.

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

// Fourth coordinate(in a rectangle)
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
 
// For local test
const input = ['30 20', '10 10', '10 20'];
const strToInt = input.map(coords =>
coords.split(' ').map(num => parseInt(num))
);
 
let x = 0;
let y = 0;
if (strToInt[0][0] !== strToInt[1][0]) {
if (strToInt[0][0] !== strToInt[2][0]) {
x = strToInt[0][0];
} else {
x = strToInt[1][0];
}
} else {
x = strToInt[2][0];
}
 
if (strToInt[0][1] !== strToInt[1][1]) {
if (strToInt[0][1] !== strToInt[2][1]) {
y = strToInt[0][1];
} else {
y = strToInt[1][1];
}
} else {
y = strToInt[2][1];
}
 
console.log(`${x} ${y}`);
728x90

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

Code

최종 제출 코드

😢 변의 길이 순서가 랜덤으로 들어오는 듯 하다.

😊 ||(or)으로 모든 경우를 넣어주든지
sort순서를 처리해주면 된다.

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

// A right-angled triangle(Pythagorean theorem)
 
// 2nd Soludion(sort)
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
 
// For local test
const input = ['6 8 10', '25 52 60', '5 12 13', '5 4 3', '0 0 0'];
 
for (let sides of input) {
const strToInt = sides
.split(' ')
.map(num => Math.pow(parseInt(num), 2))
.sort((a, b) => a - b);
const firstSidePow = strToInt.shift();
const secondSidePow = strToInt.shift();
const thirdSidePow = strToInt.shift();
if (firstSidePow === 0 && secondSidePow === 0 && thirdSidePow === 0) {
break;
}
 
if (firstSidePow + secondSidePow === thirdSidePow) {
console.log('right');
} else {
console.log('wrong');
}
}
 
// 1st Solution(or)
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
 
// For local test
// const input = ['6 8 10', '25 52 60', '5 12 13', '0 0 0'];
 
// for (let sides of input) {
// const strToInt = sides.split(' ').map(num => Math.pow(parseInt(num), 2));
// const firstSidePow = strToInt.shift();
// const secondSidePow = strToInt.shift();
// const thirdSidePow = strToInt.shift();
// if (firstSidePow === 0 && secondSidePow === 0 && thirdSidePow === 0) {
// break;
// }
 
// if (
// firstSidePow + secondSidePow === thirdSidePow ||
// firstSidePow + thirdSidePow === secondSidePow ||
// secondSidePow + thirdSidePow === firstSidePow
// ) {
// console.log('right');
// } else {
// console.log('wrong');
// }
// }
728x90

✨ 문자열과 변수를 함께 쓰는 형식(``)
(``는 백틱(Back-ticks)이라고 부른다)

💻Example Code

const TemplateStrings1 = `This is a template string.`;
const TemplateStrings2 = `In ES5 this is
not legal.`;
const name = 'David';
const TemplateStrings3 = `Hello ${name}, how are you?`;
const TemplateStrings4 = String.raw`In ES5 "\n" is a line-feed.`;

console.log(TemplateStrings1);
console.log(TemplateStrings2);
console.log(TemplateStrings3);
console.log(TemplateStrings4);

실행 결과

😋 TemplateString1처럼 일반적인 문자열처럼 사용할 수 있으며,
TemplateString2처럼 line-feed 입력 없이 줄바꿈을 할 수 있다.
TemplateString3처럼 문자열에 변수를 섞어 쓸 수 있으며,
TemplateString4처럼 String.raw와 함께 이스케이프 문자를 그대로 표현할 수 있다.

사용할 때 `을 열고 `로 닫아주면 되며, 문자열 안에 변수를 넣고 싶을 때는 ${변수명}을 작성해 주면 된다.

API를 사용할 때 Template Strings를 사용하면 굉장히 편리하다.

fetch에서 URL에 Template Strings를 적용한 코드

그리고 아래와 같이 안에 삼항연산자를 넣어 값을 비교할 수도 있다.

Template Strings안에 Ternary(삼항연산자)를 사용한 코드

👉 자세한 내용은 https://babeljs.io/docs/en/learn/#template-strings

 

Babel · The compiler for next generation JavaScript

The compiler for next generation JavaScript

babeljs.io

 

'JavaScript > ES5, ES6+' 카테고리의 다른 글

Default + Rest + Spread  (0) 2019.12.31
728x90

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

Code

최종 제출 코드

😢 이렇게 쉬울 거라고 생각하지 못 했던 문제

😊 x, y는 현재 나의 위치이며 w, h는 직사각형의 오른쪽 위 꼭짓점, 0,0은 왼쪽 아래 꼭짓점이다.

                  10,3
(w, h)
          6,2
(x, y)
       
0,0

                 

위 표을 좌표계라고 생각해보자. 그리고 벗어날 수 있는 모든 경우의 수를 배열에 저장해보자.
좌표 0,0 기준으로 직사각형을 벗어나려면 x, y값 그 자체로 움직여야 벗어날 수 있으므로 [x, y]를 배열에 우선 넣는다.(x-0, y-0)
좌표 w, h 기준으로 직사각형을 벗어나려면 w-x, h-y만큼 움직여야 벗어날 수 있다. 따라서, [w-x, h-y]를 추가적으로 배열에 넣는다.

결과적으로 [ x, y, w-x, h-y ] 총 4개의 경우의 수를 구할 수 있다(직사각형을 벗어날 수 있는 이동 값)
최종적으로 Math.min.apply(null, 배열)넣어서 최소값을 구하고 출력해주면 된다.

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

// Escape from Rectangle
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim().split(' ').map(num => parseInt(num));
 
// For local test
const input = [6, 2, 10, 3]; // x y w h
const x = input[0];
const y = input[1];
const w = input[2];
const h = input[3];
const counters = [x, y, w - x, h - y];
 
console.log(Math.min.apply(null, counters));
728x90

✨ DB를 이용해 게시판을 만들기 전에, 간단히 연습할 수 있는 방법입니다.

Chrome Browser - F12(or Inspect) - Application - Storage - Local Storage
위의 경로를 찾아 들어가면, 내 브라우저에만 저장되는 공간이 있다. 이걸 이용해 간단하게 게시판을 구현할 수 있다.

📢 Local Storage 사용법

1. 데이터 저장하기
localStorage.setItem( 명칭, 저장할 내용 );

2. 데이터 불러오기
localStorage.getItem( 명칭 )

글은 여러 개이며 하나의 글에 필요한 데이터번호, 제목, 내용, 작성자, 작성일, 조회이기 때문에
하나의 글을 저장할 때는 배열로 저장하고, 하나의 글에 들어간 데이터는 Object로 저장해주면 간단히 저장할 수 있다.
예를 들어, objArr = [ { num: 1, title: 'title1'... }, { num: 2, title: 'title2'... }, ... ] 형식으로 저장하면 된다.

📢 게시판을 만들어가는 작업 순서

1. input과 form tag를 이용해 글을 작성하는 부분을 만들어주고, 이 내용을 받아 localStorage에 저장해준다.
2. localStorage에서 데이터를 받아와, DOM을 이용해 목록을 출력해준다.
3. 글 제목을 누르면, 글 내용이 출력되도록 해준다.
4. 한 화면에는 최대 5개의 글만 보여주며, 그 이상의 글은 인덱스 처리를 해주고 눌렀을 때 해당 목록을 보여준다.

😃 보기 쉽게 하기 위해서, 싱글 페이지글 목록, 글 내용, 작성 부분을 한 번에 보여주도록 구성하였다.
이 과정에서 글 번호가 곧 데이터 index이므로 꼬이지 않도록 Sort해주는 작업이 필요하며,
각 글 목록마다 id를 다르게 부여하여, event를 받아줄 수 있도록 해주는 작업이 필요하다.

아래는 예제가 실제로 실행되는 모습이다.

페이지 실행 첫 번째 화면
글 제목을 눌렀을 때, 내용을 보여주는 화면
2번째 글 목록 화면
3번째 글 목록 화면
글 작성하는 부분
위에서 작성한 글 내용 보기

이렇게 연습을 하고, DB와 함께 진행할 때는 어떻게 적용하고 개발을 진행해 나가야 할지 고민하면 될 듯 하다.

궁금한 점이 있으시면 언제든 댓글 달아주세요!

Full Code (https://github.com/DasolPark/Play-Ground_JavaScript) board.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Board with Local Storage</title>
<link
href="https://fonts.googleapis.com/css?family=Jua&display=swap"
rel="stylesheet"
/>
<style>
* {
box-sizing: border-box;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
font-family: 'Jua', sans-serif;
}
body {
padding: 0px;
margin: 0px;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
width: 100%;
height: 95vh;
background-color: #f6f9fc;
}
 
.main__container {
height: 700px;
padding-top: 10px;
padding-bottom: 10px;
}
 
.board__container,
.contents__container,
.editor__container {
width: 700px;
display: flex;
justify-content: flex-start;
align-items: center;
flex-direction: column;
background-color: #ffffff;
}
 
.board__container {
margin: 10px 0px 0px 0px;
height: 220px;
padding-top: 10px;
padding-bottom: 10px;
border-radius: 15px;
box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.1);
position: relative;
}
 
.contents__container {
margin: 10px 0px;
height: 220px;
padding-top: 10px;
padding-bottom: 10px;
border-radius: 15px;
box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.1);
}
 
.editor__container {
margin: 10px 0px;
height: 220px;
padding-top: 10px;
padding-bottom: 10px;
border-radius: 15px;
box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.1);
}
 
/* Board Lists */
.board {
width: 600px;
text-align: center;
margin-bottom: 15px;
}
 
.board__index-container {
position: absolute;
bottom: 10px;
}
 
.board__index-link {
all: unset;
margin-right: 5px;
}
 
.board__index-link:hover {
cursor: pointer;
color: blue;
}
 
/* Contents */
.contents__titles {
width: 600px;
display: flex;
justify-content: space-between;
align-items: center;
padding-bottom: 10px;
border-bottom: 2px solid rgba(0, 0, 0, 0.08);
margin-bottom: 20px;
}
 
.contents__column {
width: 200px;
display: flex;
justify-content: space-around;
align-items: center;
}
 
.contents__content {
width: 600px;
display: flex;
justify-content: start;
align-items: center;
}
 
/* Editor */
.editor__form {
width: 600px;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
 
input {
all: unset;
border-radius: 5px;
border: 1px solid rgba(0, 0, 0, 0.5);
}
 
.editor__title-input,
.editor__content-input {
width: 100%;
padding: 5px 10px;
margin-bottom: 10px;
}
 
.editor__content-input {
height: 100px;
}
 
.editor__btn {
all: unset;
border: 1px solid rgba(0, 0, 0, 0.5);
border-radius: 5px;
padding: 5px 10px;
}
 
button:active {
transform: scale(0.93);
}
</style>
</head>
<body>
<main class="main__container">
<div class="board__container">
<table class="board">
<thead class="board__table-head">
<tr class="board__titles">
<th class="board__column">번호</th>
<th class="board__column">제목</th>
<th class="board__column">작성자</th>
<th class="board__column">작성일</th>
<th class="board__column">조회</th>
</tr>
</thead>
<tbody class="board__contents" id="board-body"></tbody>
</table>
<div class="board__index-container" id="index-container"></div>
</div>
<div class="contents__container"></div>
<div class="editor__container">
<form action="#" class="editor__form" id="editor-form">
<input
type="text"
class="editor__title-input"
id="editor-title-input"
placeholder="제목"
/>
<input
type="text"
class="editor__content-input"
id="editor-content-input"
placeholder="내용"
/>
<button class="editor__btn" id="editor-submit-btn">작성 완료</button>
</form>
</div>
</main>
<script>
const boardTableBody = document.querySelector('#board-body');
 
const contentsContainer = document.querySelector('.contents__container');
 
const editorForm = document.querySelector('#editor-form');
const titleInput = document.querySelector('#editor-title-input');
const contentInput = document.querySelector('#editor-content-input');
 
const BOARDLIST_LS = 'boardLists';
const boardListsObj = [];
let nums = 0;
let author = 'David';
let date = new Date();
let views = Math.floor(Math.random() * 99) + 1;
 
function onTitleClick(e) {
contentsContainer.textContent = '';
const lists = JSON.parse(localStorage.getItem(BOARDLIST_LS));
const index = e.target.parentNode.id.replace(/[a-z|-]/gi, '');
 
const contentsTitles = document.createElement('div');
contentsTitles.classList.add('contents__titles');
 
const contentsColumnFirst = document.createElement('div');
contentsColumnFirst.classList.add('contents__column');
 
const contentsTitle = document.createElement('div');
contentsTitle.classList.add('contents__title');
contentsTitle.textContent = lists[index].title;
 
// contents__titles > column >author, date, views
const contentsColumnSecond = document.createElement('div');
contentsColumnSecond.classList.add('contents__column');
 
const contentsAuthor = document.createElement('div');
contentsAuthor.classList.add('contents__author');
contentsAuthor.textContent = lists[index].author;
 
const contentsDate = document.createElement('div');
contentsDate.classList.add('contents__date');
contentsDate.textContent = lists[index].date;
 
const contentsViews = document.createElement('div');
contentsViews.classList.add('contents__views');
contentsViews.textContent = lists[index].views;
 
const contentsContent = document.createElement('div');
contentsContent.classList.add('contents__content');
contentsContent.textContent = lists[index].content;
 
contentsColumnFirst.appendChild(contentsTitle);
 
contentsColumnSecond.appendChild(contentsAuthor);
contentsColumnSecond.appendChild(contentsDate);
contentsColumnSecond.appendChild(contentsViews);
 
contentsTitles.appendChild(contentsColumnFirst);
contentsTitles.appendChild(contentsColumnSecond);
 
contentsContainer.appendChild(contentsTitles);
contentsContainer.appendChild(contentsContent);
}
 
function assignIndex() {
const lists = JSON.parse(localStorage.getItem(BOARDLIST_LS));
if (!lists) {
nums = 0;
} else {
nums = parseInt(lists[lists.length - 1].num) + 1;
}
}
 
function onEditorFormSubmit(e) {
e.preventDefault();
 
const title = titleInput.value;
const content = contentInput.value;
 
const lists = JSON.parse(localStorage.getItem(BOARDLIST_LS));
if (!lists) {
const objArr = [];
objArr.push({
num: `${nums++}`,
title: `${title}`,
author: `${author}`,
date: `${date.getFullYear()}.${date.getMonth() +
1}.${date.getDate()}.`,
views: `${views++}`,
content: `${content}`
});
 
localStorage.setItem(BOARDLIST_LS, JSON.stringify(objArr));
} else {
lists.push({
num: `${nums++}`,
title: `${title}`,
author: `${author}`,
date: `${date.getFullYear()}.${date.getMonth() +
1}.${date.getDate()}.`,
views: `${views++}`,
content: `${content}`
});
 
localStorage.setItem(BOARDLIST_LS, JSON.stringify(lists));
}
 
titleInput.value = '';
contentInput.value = '';
titleInput.focus();
window.location.reload();
}
 
function showBoardLists() {
const lists = JSON.parse(localStorage.getItem(BOARDLIST_LS));
 
lists.forEach((list, index) => {
if (index < 5) {
const tr = document.createElement('tr');
tr.classList.add('board__content');
 
const tdNum = document.createElement('td');
tdNum.classList.add('board__content-column');
tdNum.textContent = list.num;
 
const aTitle = document.createElement('a');
aTitle.href = '#';
aTitle.id = `link-to-content${index}`;
 
const tdTitle = document.createElement('td');
tdTitle.classList.add('board__content-column');
tdTitle.textContent = list.title;
 
aTitle.appendChild(tdTitle);
 
const tdAuthor = document.createElement('td');
tdAuthor.classList.add('board__content-column');
tdAuthor.textContent = list.author;
 
const tdDate = document.createElement('td');
tdDate.classList.add('board__content-column');
tdDate.textContent = list.date;
 
const tdViews = document.createElement('td');
tdViews.classList.add('board__content-column');
tdViews.textContent = list.views;
 
tr.appendChild(tdNum);
tr.appendChild(aTitle);
tr.appendChild(tdAuthor);
tr.appendChild(tdDate);
tr.appendChild(tdViews);
 
boardTableBody.appendChild(tr);
const linkToContent = document.querySelector(
`#link-to-content${index}`
);
linkToContent.addEventListener('click', onTitleClick);
} else if (index === 5) {
const boardIndexMax = Math.ceil(lists.length / 5);
for (let i = 0; i < boardIndexMax; i++) {
const indexContainer = document.querySelector('#index-container');
 
const aIndex = document.createElement('a');
aIndex.classList.add('board__index-link');
 
const spanIndexText = document.createElement('span');
spanIndexText.classList.add('board__index');
spanIndexText.textContent = i + 1;
 
aIndex.appendChild(spanIndexText);
indexContainer.appendChild(aIndex);
 
aIndex.addEventListener('click', () => {
showBoardListsNewPage(i);
});
}
}
});
}
 
function showBoardListsNewPage(pageIndex) {
boardTableBody.textContent = '';
const lists = JSON.parse(localStorage.getItem(BOARDLIST_LS));
const limitPage = pageIndex * 5;
 
lists.forEach((list, index) => {
if (index >= limitPage && index < limitPage + 5) {
const tr = document.createElement('tr');
tr.classList.add('board__content');
 
const tdNum = document.createElement('td');
tdNum.classList.add('board__content-column');
tdNum.textContent = list.num;
 
const aTitle = document.createElement('a');
aTitle.href = '#';
aTitle.id = `link-to-content${index}`;
 
const tdTitle = document.createElement('td');
tdTitle.classList.add('board__content-column');
tdTitle.textContent = list.title;
 
aTitle.appendChild(tdTitle);
 
const tdAuthor = document.createElement('td');
tdAuthor.classList.add('board__content-column');
tdAuthor.textContent = list.author;
 
const tdDate = document.createElement('td');
tdDate.classList.add('board__content-column');
tdDate.textContent = list.date;
 
const tdViews = document.createElement('td');
tdViews.classList.add('board__content-column');
tdViews.textContent = list.views;
 
tr.appendChild(tdNum);
tr.appendChild(aTitle);
tr.appendChild(tdAuthor);
tr.appendChild(tdDate);
tr.appendChild(tdViews);
 
boardTableBody.appendChild(tr);
const linkToContent = document.querySelector(
`#link-to-content${index}`
);
linkToContent.addEventListener('click', onTitleClick);
}
});
}
 
editorForm.addEventListener('submit', onEditorFormSubmit);
 
if (boardTableBody) {
assignIndex();
showBoardLists();
}
</script>
</body>
</html>
728x90

✨ JavaScript에서 Hoisting이란, 변수 또는 함수 사용을 선언 전에 할 수 있다는 것(?)이다.

w3schools에서는 변수나 함수 선언부를 코드 최상위에 위치시키는 것이라고 말하고 있으며,
MDN에서는 위의 말처럼 가르치고 있지만, 실제로는 그렇지 않다고 한다.

https://www.w3schools.com/js/js_hoisting.asp

 

JavaScript Hoisting

JavaScript Hoisting Hoisting is JavaScript's default behavior of moving declarations to the top. JavaScript Declarations are Hoisted In JavaScript, a variable can be declared after it has been used. In other words; a variable can be used before it has been

www.w3schools.com

https://developer.mozilla.org/en-US/docs/Glossary/Hoisting

 

Hoisting

Hoisting is a term you will not find used in any normative specification prose prior to ECMAScript® 2015 Language Specification. Hoisting was thought up as a general way of thinking about how execution contexts (specifically the creation and execution phas

developer.mozilla.org

📢 예제 1(변수 - var)

예제 1(변수 var)

위의 코드처럼 할당(assign)을 먼저 하고, 실행 한 후, 선언(declare)을 해줘도 문제 없이 작동한다.

예제 1 결과

위 화면을 보면 문제 없이 7이 출력된 것을 볼 수 있다.

📢 예제 2(함수 - function)

이번에는 함수를 위와 같은 방식으로 실행해 보겠다.

예제 2(함수 function)

위 코드처럼 실행을 먼저 해주고, 나중에 선언을 해줘도 문제 없이 작동한다.

예제 2 결과

위 화면을 보면 문제 없이 'Hello'가 출력된 것을 볼 수 있다.

ES2015전에 정확히 명시된 문서는 없지만, ES2015에서 Hoisting을 정의하고 있다.
어렵게 생각하지 말고, 선언부를 코드 최상위로 끌어올린다고 생각하면 될 것 같다.
사실 위처럼 곤란한 상황은 var과 function을 사용해서 생기는 문제다.

위의 문제로 머리가 복잡해지기 싫다면 ES2015의 const와 let을 사용해주면 된다.
(function은 const functionName = () => {}로 사용)
그럼 debugging이 훨씬 수월할 것이다.

결론적으로

hoist의 사전적 정의

선언부를 코드 최상위로 '끌어올린다'라고 생각해주면 되고, 해당 버그를 방지하기 위해 const와 let을 사용하자!

728x90

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

Code

최종 제출 코드

😢 역시 에라토스테네스의 체를 이용하면 되고, 골드바흐의 파티션을 어떻게 구할지 생각을 해줘야 한다.

😊 31번째 줄 코드는 이전 문제에서 사용한 것과 같고, 33-37번째 줄 코드에서 2부터 n까지 소수를 저장해준다.

중첩 for loop을 열고, 입력 받은 n을 0으로 만들 수 있는 소수의 짝checkPrimePair 배열에 2차원 형식으로 저장해준다.
(checkPrimePair가 저장된 모습은 [ [2, 3], [3, 5] ] 같은 형식이라고 생각해주면 된다)

그리고 또 다시 for loop을 열고 checkPrimePair중 가장 작은 차이가 나는 소수 짝의 index를 구해준다.

마지막으로, 해당 index의 짝을 join(' ')형식으로 출력해주면 된다.

지금까지 풀었던 알고리즘 중에 가장 길지 않나 싶다. 다시 풀어보며 조금 더 개선할 수 있는 곳을 찾아봐야겠다.

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

// Goldbach's conjecture
 
// 1st Solution
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n').map(num => parseInt(num));
 
// For local test
const input = [3, 8, 10, 16];
const T = input.shift();
 
for (let i = 0; i < T; i++) {
const n = input.shift();
const isPrimeNumArr = new Array(n + 1);
const primeNumArr = [];
const checkPrimePair = [];
 
isPrimeNumArr.fill(true);
isPrimeNumArr[0] = isPrimeNumArr[1] = false;
 
for (let j = 2; j <= n; j++) {
if (Math.pow(j, 2) > 1000000) {
break;
} else {
for (let square = Math.pow(j, 2); square <= n; square += j) {
isPrimeNumArr[square] = false;
}
}
}
 
for (let i = 2; i <= n; i++) {
if (isPrimeNumArr[i]) {
primeNumArr.push(i);
}
}
 
for (let i = 0; i < primeNumArr.length; i++) {
for (let j = i; j < primeNumArr.length; j++) {
if (n - primeNumArr[i] - primeNumArr[j] === 0) {
checkPrimePair.push([primeNumArr[i]]);
checkPrimePair[checkPrimePair.length - 1].push(primeNumArr[j]);
}
}
}
 
let min = checkPrimePair[0][1] - checkPrimePair[0][0];
let indexOfMin = 0;
for (let i = 0; i < checkPrimePair.length; i++) {
if (checkPrimePair[i][1] - checkPrimePair[i][0] < min) {
min = checkPrimePair[i][1] - checkPrimePair[i][0];
indexOfMin = i;
}
}
console.log(checkPrimePair[indexOfMin].join(' '));
}
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

배열(array)의 값(element)을 하나씩 받아서 내가 작성한 function을 실행해주는 helper method

💻Example Code

const arr = [ 1, 2, 3 ];

const received = arr.forEach( num => console.log(num) );

console.log( arr );
console.log( received );

실행 결과

forEach는 제공 받은 function Array의 각 element마다 실행해주기만 한다.
function의 결과를 return 해주지 않는다. forEach의 return 값은 undefined다.

따라서 위의 결과처럼, arr를 한 번씩 실행해주고 있는 것을 볼 수 있으며, 기존 arr값이 변하지 않는 것을 볼 수 있다.
또한, return값이 있는지 확인하기 위해 선언했던 received를 출력하면 undefined가 출력되는 것을 볼 수 있다.

🎃실전 예제

forEach를 사용하여 ul에 li element를 추가해주는 예제
위의 예제가 실행된 HTML 페이지

위의 간단한 예제처럼 사용할 수 있다. objArr는 직접 작성해줬지만, 어딘가에서 받아올 data라 생각하면 된다.

😋 개발을 진행할 때, 많은 양의 데이터를 받아와서 하나씩 실행해줄 때 매우 유용하다.
매우 자주 쓰이는 helper method이므로 필수적으로 알고 있어야 한다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

 

Array.prototype.forEach()

The forEach() method executes a provided function once for each array element.

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Math.abs()  (0) 2020.01.28
Math.PI  (0) 2020.01.28
Math.pow()  (0) 2020.01.22
Math.random()  (0) 2020.01.18
Math.ceil()  (0) 2020.01.18
728x90

Click! 👉 https://dasolpark.github.io/Dasol_JS_Momentum_Clone/

 

Welcome to Momentum Clone

 

dasolpark.github.io

Github 👉 https://github.com/DasolPark/Dasol_JS_Momentum_Clone

 

DasolPark/Dasol_JS_Momentum_Clone

Let's make momentum clone with Vanilla JS. Contribute to DasolPark/Dasol_JS_Momentum_Clone development by creating an account on GitHub.

github.com

항상 이용하고 있는 Chrome Extension Momentum
HTML/CSS/JavaScript
를 사용하여 나만의 스타일로 재구성 해봤습니다.

🌳배경 이미지는 무작위로 생성되며, 😃본인의 이름을 저장할 수 있고, ⛅간단한 날씨 정보도 얻을 수 있습니다.
또한, 📑해야 할 일 목록을 작성하여 체크하거나 삭제하며 사용할 수 있습니다.

날씨 APIopenweathermap, 배경 이미지 APIunsplash를 이용하였으며
이름과 해야 할 일 데이터Local Storage에 저장하였습니다.

브라우저 앱이기 때문에, 노트북이나 데스크톱 브라우저에 최적화되어 있습니다.

첫 번째 화면,이름을 묻는 페이지

 

두 번째 화면, 사용자를 반겨주며 오늘 가장 중요한 일을 작성할 수 있습니다.
세 번째 화면, 사용자를 반겨주며 작성된 오늘 가장 중요한 일을 확인할 수 있습니다.
네 번째 화면, 오늘 가장 중요한 일을 완료 표시 할 수 있습니다.
다섯 번째 화면, 해야 할 일 목록을 작성할 수 있습니다.
여섯 번째 화면, 해야 할 일 목록을 완료 표시 또는 삭제할 수 있습니다.

+ Recent posts