728x90

✨ if else 문법을 간단하게 쓰고 싶을 때 사용하는 ternary operator(삼항 조건 연산자)

💻Example Code

const a = 11;
const b = 77;

a < b ? console.log('true') : console.log('false');

실행 결과(a는 b보다 작기 때문에 true를 출력)

😋 if else는 많은 줄을 차지하는 반면에, ternary operator(삼항 연산자)를 사용하면 최소 한 줄로 줄일 수 있다.
간결한 코드 작성을 원할 때, 매우 유용하다.

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

 

Conditional (ternary) operator

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execu

developer.mozilla.org

 

'JavaScript > Grammar' 카테고리의 다른 글

for...in  (0) 2019.12.27
for...of  (0) 2019.12.27
728x90

Q. 주어진 n만큼 1개씩 #(또는 *)을 계단모양으로 증가시켜라.
(n은 양수이며, 나머지 오른쪽 공백은 space로 입력)

--- Examples
steps(2)
'# '
'##'
steps(3)
'#  '
'## '
'###'
steps(4)
'#   '
'##  '
'### '
'####'

Code

https://github.com/DasolPark/Algorithm_DataStructure_JavaScript-Stephen-/blob/2d0c64627731b45be6d9e0dbc2492c894d2a5846/exercises/steps/index.js

😢 도형은 신기하다. 쉬워보이는데, 해보면 생각보다 쉽지는 않다. 특히, 재귀사용을 위해서는 재귀에 대한 높은 이해가 필요하다.

😊 Solution 1)
중첩 for loop을 이용해서 간단하게 해결이 가능하다.
직사각형 형태이기 때문에, 외부 for loop과 내부 for loop 모두 0부터 그리고 n보다 작을 때까지 index를 증가시키면 된다.
그리고 내부 for loop에서 column(열)이 row(행)보다 작거나 같으면 '#'을, 크다면 ' '을 대입해주면 된다.

Solution 2)
재귀적 용법으로 문제를 해결했다.

먼저 row=0, stair=''로 default를 선언해준다.
그리고 만약 n이 row(행)와 같다면 함수를 return;해준다.(n만큼 행을 출력했으니까 더 이상 출력할 필요 없음)
그리고 만약 값을 저장하는 stair의 길이가 n과 같으면 row(행)+1함수를 실행시켜준다.
(여기서 return을 필수적으로 해줘야한다. 해주지 않으면 밑으로 내려가 불필요한 재귀를 다시 실행해주기 때문이다)
그 밑으로는 Solution 1)과 마찬가지로 stair.length가 row보다 작거나 같으면 '#', 아니라면 ' '를 대입해준다.
(stair.length는 Solution 1)의 column을 대체한다) 그리고 steps(n, row, stair+add)를 재귀적으로 실행하면 된다.

Full Code

function steps(n, row = 0, stair = '') {
if (n === row) {
return;
}
 
if (n === stair.length) {
console.log(stair);
return steps(n, row + 1);
}
 
const add = stair.length <= row ? '#' : ' ';
steps(n, row, stair + add);
}
 
// function steps(n) {
// for (let row = 0; row < n; row++) {
// let stair = '';
 
// for (let column = 0; column < n; column++) {
// if (column <= row) {
// stair += '#';
// } else {
// stair += ' ';
// }
// }
 
// console.log(stair);
// }
// }
728x90

Q. 주어진 String(문장)에서 각 단어의 첫 알파벳을 대문자로 바꿔라.

--- Examples
capitalize('a short sentence') --> 'A Short Sentence'
capitalize('a lazy fox') --> 'A Lazy Fox'
capitalize('look, it is working!') --> 'Look, It Is Working!'

Code

https://github.com/DasolPark/Algorithm_DataStructure_JavaScript-Stephen-/blob/08ffc38c2f7b32b8baa35a6ecfc6c1d367559b1c/exercises/capitalize/index.js

😢 배열(Array)의 index을 이용해서 원초적 해결하려 했더니 조금 힘들었다.

😊 Solution 1)
입력받은 str을 split(' ')을 이용해 각 단어별로 나눠진 Array를 만들어주고,
for ... of loop 안에서 각 단어를 하나씩 가져와, 첫 번째 알파벳은 대문자로, 나머지 값은 slice(1)로 붙여주었다.
그리고 join(' ')을 이용해 다시 String(문장)으로 만들어 반환해주었다.

Solution 2)
classic for loop을 이용해 각 index의 앞(i-1)이 ' '(space)라면 해당 index(i)를 대문자로 변환하여 저장한다.
그게 아니라면, 해당 index(i)를 단순 저장해준다.

✔ toUpperCase()

소문자를 대문자로 변환해준다.

✔ split(' ')

String을 ' '(space)기준으로 나눠서 array에 저장해준다

✔ slice(1)

index 1부터 끝까지 모두 slice해준다

✔ for ... of

Array의 안에 있는 값을 index 순서대로 하나씩 가져온다

✔ join(' ')

' '(space)기준으로 Array를 String(문장)으로 합쳐준다

Full Code

function capitalize(str) {
let result = str[0].toUpperCase();
 
for (let i = 1; i < str.length; i++) {
if (str[i - 1] === ' ') {
result += str[i].toUpperCase();
} else {
result += str[i];
}
}
 
return result;
}
 
// function capitalize(str) {
// const words = [];
 
// for (let word of str.split(' ')) {
// words.push(word[0].toUpperCase() + word.slice(1));
// }
 
// return words.join(' ');
// }
728x90

✨ 문자열로 바꾸고싶을 때, toString() 대신에 사용하는 new String();
(e.g., const numToStr = new String(num)) 왼쪽처럼 선언하여 Number를 String으로 사용한다.

💻Example Code

const num = 77;
const numToStr = new String(num);

console.log( num );
console.log( numToStr );
console.log( numToStr.split('') ); // 활용 예시

실행 결과(Number 77, String 77, split된 77)

😋 [String: '77']의 정확한 의미는 모르겠지만, 일반 String처럼 사용 가능하다. 아마 Object가 생성되는 것 같다.
(조금 더 학습할 필요성이 있다)

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

 

String

The String global object is a constructor for strings or a sequence of characters.

developer.mozilla.org

 

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

String.prototype.match()  (0) 2019.12.31
String.charCodeAt()  (0) 2019.12.31
new Array()  (0) 2019.12.29
Array.prototype.메소드() 만들기  (0) 2019.12.29
Array.prototype.fill()  (0) 2019.12.29
728x90

✨ 원하는 개수만큼 array를 선언하는 방법
(e.g., const arr = new Array(100)) 왼쪽처럼 선언하면 간단하게 100개의 array를 생성할 수 있다.

💻Example Code

const arr = new Array(100);

console.log( arr );
console.log( arr.length);

실행 결과(100개의 비어있는 Array 값, Array의 길이는 100)

😋 가끔 큰 index의 Array를 다룰 때, undefined보다는 하나의 값을 전체적으로 지정해주고 싶을 때가 있다. 그때 사용하면 된다.
백준 4673 셀프 넘버(Self Number)에서 유용하게 사용했다.

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

 

Array

The JavaScript Array class is a global object that is used in the construction of arrays; which are high-level, list-like objects.

developer.mozilla.org

 

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

String.charCodeAt()  (0) 2019.12.31
new String()  (0) 2019.12.29
Array.prototype.메소드() 만들기  (0) 2019.12.29
Array.prototype.fill()  (0) 2019.12.29
String.prototype.replace()  (0) 2019.12.29
728x90

✨ Array.prototype.name() 을 지정하여 내가 원하는 helper method를 만들 수 있다.
(e.g., Array.prototype.name()) 왼쪽처럼 선언 후 arr.name()로 method를 실행시킬 수 있다.

💻Example Code

const arr = [ 1, 2, 3, 4, 5 ];

Array.prototype.sumTest = function(){
return this.reduce((acc, val) => {
return acc + val;
})
};

console.log( arr.sumTest() );

실행 결과(1+2+3+4+5=15)

😋 생활코딩에서 학습했었지만, 백준 4673번 문제를 풀면서 실전에서 사용해본 방법이다.

👉 실전에서 자주 사용할 수 있도록 조금 더 연습하고 이해할 필요가 있다.

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

new String()  (0) 2019.12.29
new Array()  (0) 2019.12.29
Array.prototype.fill()  (0) 2019.12.29
String.prototype.replace()  (0) 2019.12.29
Object.keys() & Object.values()  (0) 2019.12.29
728x90

✨ Array의 모든 index에 값을 한 번에 채워주거나, 원하는 구간만큼 값을 채워줄 수 있는 helper method

(e.g., arr.fill(false) or arr.fill(0, 2, 4)) 왼쪽처럼 Array의 모든 값을 false로 채우거나, index 2부터 3까지 0을 채워줄 수 있다.
(Array.prototype.slice()와 마찬가지로 구간을 지정할 때, end-1까지 진행된다는 점을 명심하자)

💻Example Code

const arr = [ 1, 2, 3, 4, 5, 6 ];

console.log( arr.fill(0, 1, 3) );

실행 결과(index 1부터 3까지 지정했지만, 2까지 변한 것을 볼 수 있다)

😋 매우 큰 Array의 값을 한 번에 초기화 해줄 때, 또는 원하는 index 구간만큼 값을 바꿔줄 때 매우 유용하다.
백준 4673번 셀프 넘버(Self Number)문제를 풀 때 사용했다.

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

 

Array.prototype.fill()

The fill() method changes all elements in an array to a static value, from a start index (default 0) to an end index (default array.length). It returns the modified array.

developer.mozilla.org

 

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

new Array()  (0) 2019.12.29
Array.prototype.메소드() 만들기  (0) 2019.12.29
String.prototype.replace()  (0) 2019.12.29
Object.keys() & Object.values()  (0) 2019.12.29
Array.prototype.sort()  (0) 2019.12.28
728x90

Code

최종 제출 코드
기존 제출 코드

😢 무언가 원초적인 방법으로 풀었던 문제, 어떻게 풀어 나갈지에 대한 고민을 조금 했다.

😊 기존 제출 Solution) array를 선언하고, 모든 index 값을 0으로 초기화해준 후 Self Number가 아니라면 해당 index에 1을 넣어주었다.
그리고 마지막에 for loop의 i를 이용해 array[i]의 값이 1이 아니라면(=Self Number라면) Self Number인 i를 출력하도록 했다.

[추가] 최종 제출 Solution)
while loop 안에서 각 자릿수 나눠주기 + 나눠준 값 더하기를 진행하여 코드의 복잡도를 줄여줬다. 또한 시간도 더 빨라졌다.
그리고  배열 10000개 만큼 false로 채워주고, 셀프 넘버가 아니라면 true로 변경시켜주었다. 따라서 false로 남아있다면 그건 셀프 넘버다.


각 자릿수를 구하는 것은 매우 원초적인 방법으로 진행했다.
54321인 다섯 자리를 기준으로 설명하자면,
parseInt( 54321/10000 )(=5.4321)은 5
parseInt( (54321%10000) / 1000 )(=4.321)은 4
parseInt( (54321%1000) / 100 )(=3.21)은 3
parseInt( (54321%100) / 10 )(=2.1)은 2
54321 % 10 은 1
아래 Full Code에는 위의 자릿수 나누는 방식을, 다른 방법으로 접근한 Code가 있다.

✔ while loop을 이용한 자릿수 나누고, 바로 더하기

let temp = 나눌값;
let sum = temp;

while( 0 > temp){
sum += temp%10;
temp = parseInt(temp/10); }

또한, 다른 사람들이 푼 풀이가 매우 흥미로워서 그 방법들도 함께 연습했다. 세상에는 대단한 사람들이 참 많다.

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

// Self Number
 
// 4th Solution
 
const n = 10000;
const isSelfNum = new Array(n + 1);
isSelfNum.fill(true);
 
function d(n) {
const N = n.toString().split('');
 
return n + N.reduce((acc, num) => (acc += +num), 0);
}
 
for (let i = 1; i <= n; i++) {
isSelfNum[d(i)] = false;
}
 
for (let i = 1; i <= n; i++) {
if (isSelfNum[i]) {
console.log(i);
}
}
 
// 3rd Solution
 
// function d(n) {
// let temp = n;
// let sum = temp;
 
// while (temp > 0) {
// sum += temp % 10;
// temp = parseInt(temp / 10);
// }
 
// return sum;
// }
 
// const N = 10000;
// const selfNumCheckArr = new Array(N);
// selfNumCheckArr.fill(false);
 
// for (let i = 1; i <= N; i++) {
// selfNumCheckArr[d(i)] = true;
// if (!selfNumCheckArr[i]) {
// console.log(i);
// }
// }
 
// 1st solution
 
// const N = 10000;
// let arr = [];
 
// for (let i = 0; i <= N; i++) {
// d(i);
// }
 
// function d(n) {
// if (n < 10) {
// arr[n + n] = 1;
// } else if (n < 100) {
// arr[n + parseInt(n / 10) + (n % 10)] = 1;
// } else if (n < 1000) {
// arr[n + parseInt(n / 100) + parseInt((n % 100) / 10) + (n % 10)] = 1;
// } else if (n < 10000) {
// arr[
// n +
// parseInt(n / 1000) +
// parseInt((n % 1000) / 100) +
// parseInt((n % 100) / 10) +
// (n % 10)
// ] = 1;
// } else {
// arr[
// n +
// parseInt(n / 10000) +
// parseInt((n % 10000) / 1000) +
// parseInt((n % 1000) / 100) +
// parseInt((n % 100) / 10) +
// (n % 10)
// ] = 1;
// }
// }
 
// for (let i = 1; i <= N; i++) {
// if (!(arr[i] === 1)) {
// console.log(i);
// }
// }
 
// 2nd solution(string - array[index])
 
// const N = 10000;
// const arr = [];
 
// for (let i = 0; i <= N; i++) {
// arr[i] = 0;
// }
 
// for (let i = 1; i <= N; i++) {
// d(i);
// }
 
// function d(n) {
// const str = n.toString();
 
// if (n < 10) {
// arr[n + n] = 1;
// } else if (n < 100) {
// arr[n + parseInt(str[0]) + parseInt(str[1])] = 1;
// } else if (n < 1000) {
// arr[n + parseInt(str[0]) + parseInt(str[1]) + parseInt(str[2])] = 1;
// } else if (n < 10000) {
// arr[
// n +
// parseInt(str[0]) +
// parseInt(str[1]) +
// parseInt(str[2]) +
// parseInt(str[3])
// ] = 1;
// } else {
// arr[
// n +
// parseInt(str[0]) +
// parseInt(str[1]) +
// parseInt(str[2]) +
// parseInt(str[3]) +
// parseInt(str[4])
// ];
// }
// }
 
// for (let i = 1; i <= N; i++) {
// if (arr[i] === 0) {
// console.log(i);
// }
// }
728x90

✨ pattern과 맞는 String을 교체해주는 helper method

(e.g., str.replace('dog', 'cat')) 왼쪽처럼 dog을 cat으로 교체하는 것이 가능하다.
간단하게 설명하자면,
첫 번째 parameter에는 RegExp(Regular Expressions) 또는 String을 넣을 수 있고(즉, 찾을 pattern)
두 번째 parameter에는 새로 넣을 new string을 넣을 수 있다(즉, 새로 넣을 replacement)

💻Example Code

1) 간단한 단어 교체

const str = 'Hi there!';
const afterReplace = str.replace('Hi', 'Hello');

console.log(afterReplace);

실행 결과(Hi가 Hello로 교체된 것을 볼 수 있다)

2) RegExp를 이용한 교체(alphabet만 남기기)

const strTwo = 'Hi! there~@!';
const afterReplaceTwo = strTwo.replace(/[^\w]/g, '');

console.log(afterReplaceTwo);

실행 결과(특수문자, 공백이 제거된 것을 볼 수 있다)

📌replace(/[^\w]/g, '')를 자세히 살펴보겠다.
1. RegExp의 시작과 끝은 /(slash)
2. []는 []안에 어느 것이라도 매치된다면 이라는 뜻이다. (다시 알아볼 필요가 있음)
3. ^ 는 무효화 시킨다는 뜻이다(반전이라고 생각하면 될듯하다)
4. \w은 글자와 숫자(alphanumeric)를 뜻한다.
5. g는 global이라는 뜻. 한 번 매치되어도 끝까지 매치되는 것을 찾게 한다.

즉, [^\w]을 이용해 글자와 숫자 이외의 모든 문자는 제거한다. 라고 보면 편하다.

😋 Anagrams(철자를 바꾼 말) Algorithm에서 공백, 구두점 그리고 특수문자를 제거하기 위해 사용하였다.
Regular Expressions은 문자열을 다루기에 매우 유용하다. 어렵기 때문에 하나씩 차근차근 쌓아가는 것이 필요하다.

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

 

String.prototype.replace()

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement.

developer.mozilla.org

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

 

RegExp

The RegExp constructor creates a regular expression object for matching text with a pattern.

developer.mozilla.org

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

 

Regular expressions

Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the exec() and test() methods of RegExp, and with the match(), matchAll(), replace(), search

developer.mozilla.org

 

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

Array.prototype.메소드() 만들기  (0) 2019.12.29
Array.prototype.fill()  (0) 2019.12.29
Object.keys() & Object.values()  (0) 2019.12.29
Array.prototype.sort()  (0) 2019.12.28
String.prototype.toLowerCase() & toUpperCase()  (0) 2019.12.28
728x90

✨ object의 keys 또는 values를 array로 반환하는 helper method

💻Example Code

const obj = { a: 'something', b: 2, c: 3 };

console.log( Object.keys(obj) );
console.log( Object.values(obj) );

실행 결과(keys와 values가 array로 반환되는 것을 볼 수 있다)

😋 Anagrams(철자를 바꾼 말) Algorithm 에서 같은 종류의 철자가 사용되었는지 확인할 때 유용하게 사용하였다.
(Algorithm 카테고리의 Anagrams Algorithm 문제에서 확인 가능하다)
이 외에도 다양한 곳에서 사용 가능하다.

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

 

Object.keys()

The Object.keys() method returns an array of a given object's own enumerable property names, in the same order as we get with a normal loop.

developer.mozilla.org

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values

 

Object.values()

The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

developer.mozilla.org

 

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

Array.prototype.fill()  (0) 2019.12.29
String.prototype.replace()  (0) 2019.12.29
Array.prototype.sort()  (0) 2019.12.28
String.prototype.toLowerCase() & toUpperCase()  (0) 2019.12.28
Array.prototype.includes()  (0) 2019.12.26

+ Recent posts