728x90
반응형

1. 문자열 출력하기

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

let input = [];

rl.on('line', function (line) {
    input = [line];
}).on('close',function(){
    str = input[0];
    // 바뀐 부분
    console.log(input.toString());
});

 

2. a와 b 출력하기

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

let input = [];

rl.on('line', function (line) {
    input = line.split(' ');
}).on('close', function () {
	// 바뀐 부분 
    console.log(`a = ${Number(input[0])}\nb = ${Number(input[1])}`);
});

 

3. 문자열 반복해서 출력하기

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

let input = [];

rl.on('line', function (line) {
    input = line.split(' ');
}).on('close', function () {
    str = input[0];
    n = Number(input[1]);
    
    // 추가한 부분
    console.log(str.repeat(n))
});

 

4. 문자열 겹쳐쓰기

const solution = (my_string, overwrite_string, s) => {
    let answer = [...my_string];
    
    answer.splice(s, overwrite_string.length, overwrite_string);
    
    return answer.join("");
}

 

5. 더 크게 합치기

const solution = (a, b) => {
    let answer = 0;
    
    let first = `${a}` + `${b}`
    let second = `${b}` + `${a}`
    
    answer = first > second ? first : second
    
    return Number(answer);
}
728x90
반응형

'쓰윽터디 > 코딩테스트' 카테고리의 다른 글

스택이란..?  (0) 2023.02.20
코딩테스트_03  (0) 2023.01.21
코딩테스트_02-2  (0) 2023.01.13
코딩테스트_02-1  (0) 2023.01.10
코딩테스트_01  (0) 2023.01.08
728x90
반응형

💥 스택이란?

가장 늦게 저장되는 데이터가 가장 먼저 나오는 자료구조를 말한다.

LIFO(Last In First Out: 후입선출) 

 

음.. 프링글스 과자를 생각해보자!

공장에서 통안에 과자를 집어 넣으면 차곡차곡 집어 넣겠지만,

우리가 먹을때는 가장 늦게 집어넣은 과자가 먼저 빠진다.

이게 스택 구조이다.

 

❓코드로 알아보자

아래는 스택 자료구조를 코드로 만든 것이다.

 

class Node {
  constructor(data, next = null) {
    this.data = data;
    this.next = next;
  }
}

class Stack {
  constructor() {
    this.top = null;
    this.size = 0;
  }

  push(data) {
    let newNode = new Node(data, null);

    // 비어있다면?
    if(this.isEmpty()){
      this.top = newNode;
      this.size++;

      return;
    }

    // 비어있지 않다면?
    newNode.next = this.top;
    this.top = newNode;

    this.size++;
  }

  pop() {

  }

  // LIFO
  print() {
    let cur = this.top;

    console.log(`크기: ${this.getSize()}`);
    while (cur != null) {
      console.log(cur.data);

      cur = cur.next;
    }
  }
  
  getSize() {
    return this.size
  }

  isEmpty() {
    return !this.size
  }
}

 

Push()

 

  push(data) {
    let newNode = new Node(data, null);

    // 비어있다면?
    if(this.isEmpty()){
      this.top = newNode;
      this.size++;

      return;
    }

    // 비어있지 않다면?
    newNode.next = this.top;
    this.top = newNode;

    this.size++;
  }

 

* 새로운 노드가 push될 때, 새로운 노드의 next는 top이 가리키는 노드를 가리키고, top은 새로운 노드를 가리킨다.

 

결과

 

pop()
  pop() {
    if (this.isEmpty()) {
      return;
    }

    let cur = this.top;
    this.top = this.top.next;

    this.size--;
    console.log(`pop: ${cur.dat}`);
  }

 

** top을 top의 next로 이동시킨다. 이때, pop한 노드를 리턴하고자 한다면 변수를 하나 만들어 pop될 노드를 관리한다.

 

결과

 

💦 스택을 활용한 알고리즘 문제

 

const solution = (progresses, speeds) => {
    let answer = [0];
    let workDays = progresses.map((progress, idx) => Math.ceil((100 - progress) / speeds[idx]));
    let maxDay = workDays[0];
    
    for(let i = 0, j = 0; i < workDays.length; i++){
        if(workDays[i] <= maxDay){
            answer[j] += 1;
        }     
        else {
            answer[++j] = 1;
            maxDay = workDays[i];
        }
    }
    return answer;
}
728x90
반응형

'쓰윽터디 > 코딩테스트' 카테고리의 다른 글

[프로그래머스] Lv. 0  (0) 2023.06.21
코딩테스트_03  (0) 2023.01.21
코딩테스트_02-2  (0) 2023.01.13
코딩테스트_02-1  (0) 2023.01.10
코딩테스트_01  (0) 2023.01.08
728x90
반응형

3 주차

<프로그래머스>

<leetcode>

[ 2023.01.16 - 2023.01.22 ]

문제 1. 과일 장수

난이도: Lv.1

Answer:

const solution = (k, m, score) => {
    let answer = 0;
    
    if(score.length < m) { return 0; }
    
    score.sort((a, b) => a - b);
        
    while(score.length >= m){
        let box = score.splice(score.length - m, m);
        let prize = m * box[0];
        answer += prize;
    }
    
    return answer;
}

 

** 야무진 풀이법

solution = (_, m, s) 
	=> s.sort().filter((_, i)
    	=> !((s.length - i) % m)).reduce((a, v) => a + v, 0) * m

문제 2. 명예의 전당(2)

난이도: Lv.1

Answer:

const solution = (k, score) => {
    let answer = [];
    let hof = [];
    
    for(let i = 0 ; i < score.length ; i ++) {
        if(i < k) {
            hof.push(score[i]);
        }
     
        if(Math.min(...hof) < score[i]) {
            hof.pop();
            hof.push(score[i]);
            hof.sort((a, b) => b - a);
        }
     
        answer.push(hof.at(-1));
    }
    
    return answer;
}

문제 3. 귤 고르기

난이도: Lv.2

Answer:

const solution = (k, tangerine) => {
    let answer = 0;
    const tmpObj = {};
    
    tangerine.forEach(el => {
        tmpObj[el] = ++tmpObj[el] || 1;
    });

    const sortObjArr = Object.values(tmpObj).sort((a, b) => b - a);
    let sum = 0;

    for (let num of sortObjArr) {
        answer++;
        sum += num;
        
        if (sum >= k) break;
    }

    return answer;
}

문제 4. 콜라츠 추측

난이도: Lv.1

Answer:

const solution = (num) => {
    let answer = 0;
    
    answer = collatzCalc(num, answer);
    
    if(answer > 500) return -1; 
    
    return answer;
}

const collatzCalc = (num,count = 0) => {
    if(num === 1) return count;
    
    let tmpNum = 0;
    
    if(num % 2 === 0) {
        tmpNum = num / 2;
        count++;
        return collatzCalc(tmpNum, count)
    } else {
        tmpNum = num * 3 + 1;
        count++;
        return collatzCalc(tmpNum, count)
    }
}

문제 5. 구명보트

난이도: Lv.2

Answer:

const solution = (people, limit) => {
    let answer = 0;
    let sortPeople = people.sort((a, b) => a - b);
    
    for(let i = 0, j = sortPeople.length - 1; i < j; j--) {
        if(sortPeople[i] + sortPeople[j] <= limit) {
            i++;
        };
        
        answer = sortPeople.length - i;
    };
    
    return answer;
}
728x90
반응형

'쓰윽터디 > 코딩테스트' 카테고리의 다른 글

[프로그래머스] Lv. 0  (0) 2023.06.21
스택이란..?  (0) 2023.02.20
코딩테스트_02-2  (0) 2023.01.13
코딩테스트_02-1  (0) 2023.01.10
코딩테스트_01  (0) 2023.01.08
728x90
반응형

2 주차

[ 2023.01.09 - 2023.01.15 ]

문제 1. Length of Last Word

 

난이도: 상 중 

Given a string s consisting of words and spaces, return the length of the last word in the string.

A word is a maximal substring consisting of non-space characters only.

  •  

Example 1:

Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.

Example 2:

Input: s = "   fly me   to   the moon  "
Output: 4
Explanation: The last word is "moon" with length 4.

Example 3:

Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy" with length 6.

Constraints:

  • 1 <= s.length <= 104
  • s consists of only English letters and spaces ' '.
  • There will be at least one word in s.

Answer:

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLastWord = function(s) {
   let answer = 0;
   answer = s.trim().split(' ').at(-1).length;
   
   return answer
};

문제 2. Remove Element

난이도: 상 중 

 

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Return k after placing the final result in the first k slots of nums.

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

 

Example 1:

Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,_,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 2.
It does not matter what you leave beyond the returned k (hence they are underscores).

Example 2:

Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.
Note that the five elements can be returned in any order.
It does not matter what you leave beyond the returned k (hence they are underscores).

 

Constraints:

  • 0 <= nums.length <= 100
  • 0 <= nums[i] <= 50
  • 0 <= val <= 100

Answer:

/**
 * @param {number[]} nums
 * @param {number} val
 * @return {number}
 */
var removeElement = function(nums, val) {
    let count = 0;
    
    for(let i = 0; i < nums.length; i++) {
        if(nums[i] === val) {
            delete nums[i];
        } else {
            count++;
        }
    }

    nums.sort((a, b) => a - b);
    nums.length = count;
    return count;
};

 

728x90
반응형

'쓰윽터디 > 코딩테스트' 카테고리의 다른 글

[프로그래머스] Lv. 0  (0) 2023.06.21
스택이란..?  (0) 2023.02.20
코딩테스트_03  (0) 2023.01.21
코딩테스트_02-1  (0) 2023.01.10
코딩테스트_01  (0) 2023.01.08

+ Recent posts