[2024.04.29 TIL] 내일배움캠프 11일차 (알고리즘 특강, 자료구조, 정렬, 개인 과제, 피드백)

My_Code·2024년 4월 29일
0

TIL

목록 보기
14/113
post-thumbnail

본 내용은 내일배움캠프에서 활동한 내용을 기록한 글입니다.


💻 TIL(Today I Learned)

📌 Today I Done

✏️ 알고리즘 특강 참여 (4일차)

  • 오늘은 스택, 큐, 정렬에 대해서 학습함

  • 스택 (Stack) => FILO (First In Last Out)

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

// top == head
class Stack {
    constructor(value) {
        this.head = new Node(value);
    }

    peek() {
        if (this.head === null) {
            return null;
        }
        return this.head;
    }

    push(value) {
        let newNode = new Node(value);
        newNode.next = this.head;
        this.head = newNode;
    }

    pop() {
        if (this.head === null) {  // head가 비어있으면 null 반환
            return null;
        }
        let top = this.peek();  // top에 있는 node를 가져옴
        this.head = top.next;  // top을 가리키는 this.head를 top의 next로 변경

        return top;
    }

    printNode() {
        let cur = this.head;

        while (cur !== null) {
            console.log(cur.data);
            cur = cur.next;
        }
    }
}



const stack = new Stack(1);
stack.push(2);
stack.push(3);
stack.push(4);

console.log(stack.peek().next);

console.log();
stack.printNode();

console.log(stack.pop());
console.log(stack.pop());

console.log();
stack.printNode();

  • 큐 (Queue) => FIFO (First In First Out)
class Node {
    constructor(value) {
        this.data = value;
        this.next = null;
    }
}


class Queue {
    constructor(value) {
        this.head = null;
        this.tail = null;
    }

    enqueue(value) {
        const newNode = new Node(value);

        if (this.head === null) {
            this.head = newNode;
            this.tail = newNode;
            return;
        }

        this.tail.next = newNode;
        this.tail = newNode;
    }

    dequeue() {
        if (this.head === null) {
            return null;
        }

        let front = this.head;
        this.head = front.next;

        return front;
    }

    printNode() {
        let cur = this.head;

        while (cur !== null) {
            console.log(cur.data);
            cur = cur.next;
        }
    }
}


const queue = new Queue();

queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.enqueue(4);

console.log();
queue.printNode();

console.log(queue.dequeue());
queue.enqueue(5);
console.log(queue.dequeue());

console.log();
queue.printNode();

  • 버블정렬 => O(n^2)
    => 1회전 후 가장 큰 값이 제일 뒤로 감

// 버블정렬
function bubbleSort(arr) {
    for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < arr.length - i - 1; j++) {
            if (arr[j] > arr[j+1]) {
                let temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }
    }
}


const arr = [2, 1, 5, 3, 4];
console.log();
console.log(arr);

bubbleSort(arr);

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

  • 선택정렬 => O(n^2)
    => 1회전 후 제일 작은 값이 제일 앞으로 오게 됨

// 선택정렬
function selectSort(arr) {
    for (let i = 0; i < arr.length - 1; i++) {
        for (let j = i + 1; j < arr.length; j++) {
            if (arr[i] > arr[j]) {
                let temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
}

const arr = [2, 1, 5, 3, 4];
console.log();
console.log(arr);

selectSort(arr);

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

  • 삽입정렬 => O(n^2), 최고 O(n)

// 삽입정렬
function insertSort(arr) {
    for (let i = 1; i < arr.length; i++) {
        // ex) [3, 1, 4, 2, 5] => 초기
        //     [1, 3, 4, 2, 5] => 1회전 결과 (arr[i]가 1일 때)
        //     [1, 3, 4, 2, 5] => 2회전 결과 (arr[i]가 4일 때)
        //     [1, 3, 4, 2, 5] => 3회전 결과 (arr[i]가 4일 때)
        //     [1, 3, 2, 4, 5] => 4회전 (arr[i]가 2일 때)
        //     [1, 2, 3, 4, 5] => 4회전 결과 (arr[i]가 2일 때)
        //     실제로는 swap하지만 4회전에서 2가 왼쪽으로 움직이는 것처럼 보임
        for (let j = i; j > 0; j--) {
            // swap하면서 arr[i]가 왼쪽으로 이동
            if (arr[j] < arr[j - 1]) {
                // swap
                let temp = arr[j - 1];
                arr[j - 1] = arr[j];
                arr[j] = temp;
            } else {
                break;
            }
        }
    }
}

const arr = [2, 1, 5, 3, 4];
console.log();
console.log(arr);

insertSort(arr);

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

✏️ 개인과제 피드백 적용

  • Styling (✔️)
    => 꼭 필요한 경우가 아니라면 inline style과 css 파일을 동시에 사용하는 것은 코드 관리를 어렵게 함

  • Image (✔️)
    => image 태그를 사용할 때에는 가능한한 alt를 데이터에 맞게 넣어주는 것이 좋음
    => 이는 SEO(검색 엔진 최적화), 시각장애인 지원 등에 좋은 영향을 줌

  • 전역 변수 (✔️)
    => 여기서 전역 변수는 사용하지 않는 것이 더 좋음
    => 코드의 직관성이 떨어지기 때문
    => 기존의 전역변수를 캡슐화, 모듈화를 통해서 전용 함수로 접근하게끔 수정

let movieDataList = [];

export const getMovieDataList = () => {
    return movieDataList;
}

export const addMovieData = (item) => {
    movieDataList.push(item);
}

export const clearMovieDataList = () => {
    movieDataList.length = 0;
}

  • 함수명 (✔️)
    => 함수명은 직관적인 것이 가장 좋음
    => 조금 더 알아보기 쉽게 함수의 이름을 변경

<변경 전>

// Top 이동 버튼
export const moveTop = () => { 
	$moveTopBtn.addEventListener("click", () => { 
		window.scrollTo({ top: 0, behavior: "smooth" }); 
	}); 
}

// Bottom 이동 버튼 
export const moveBottom = () => { 
	$moveBottomBtn.addEventListener("click", () => { 
		window.scrollTo({ top: document.body.scrollHeight, behavior: "smooth" }); 
	}); 
}

<변경 후>

// Top 이동 버튼
export const scrollToTop = () => {
    $moveTopBtn.addEventListener("click", () => {
        window.scrollTo({ top: 0, behavior: "smooth" });
    });
}

// Bottom 이동 버튼
export const scrollToBottom = () => {
    $moveBottomBtn.addEventListener("click", () => {
        window.scrollTo({ top: document.body.scrollHeight, behavior: "smooth" });
    });
}


📌 Tomorrow's Goal

✏️ 개인 공부

  • 개인과제가 빨리 끝나서 개인 공부를 가질 예정

  • SQL 강의 듣기

  • 자바스크립트 문법 추가 공부

✏️ GIT 심화 특강



📌 Today's Goal I Done

✔️ 알고리즘 특강 참여

  • 오늘은 알고리즘 특강 마지막 날

  • 스택, 큐를 클래스로 만드는 방법은 약간 생소했음

  • 그래도 개념을 알았기에 구현에 문제가 없었음

  • 정렬에서는 삽입정렬에서 생각보다 바로 코드가 나오지 않아서 헤맴

  • 여러 정렬이 존재하기에 한번씩 자바스크립트로 공부해 보자!


✔️ 개인과제 피드백 적용

  • 페이지네이션 부분을 개선할 때 시간이 조금 걸렸음

  • 함수들간에 실행 순서에서 시간을 많이 소모함

  • 1차 피드백에 대한 수정이 끝나고 2차 피드백을 진행함

  • 튜터님께서 잘 구현되었다고 칭찬하셨음

  • 추가적으로 Readme 수정하고 코드에 불필요한 코드들을 수정함

  • 자바스크립트 문법을 바로바로 적용할 수 있는 기회가 되어서 굉장히 좋았음

  • 깃허브 페이지 배포 : https://jkc-mycode.github.io/Movie_Rank_Site/



⚠️ 구현 시 발생한 문제

✔️ 전역변수에 데이터 보관 X

  • 튜터님께서 전역변수를 사용하지 말라고 말씀하셨음

  • 객체지향프로그래밍을 적용해서 구현해보라고 말씀하셨음

  • 객체지향의 캡슐화를 사용해서 변수에 직접 접근하지 못하게 만듦

  • 영화 데이터가 담겨있는 변수에 접근하기 위해서는 전용 함수를 사용해야 함

  • 일종의 모듈화라고 함

let movieDataList = [];

export const getMovieDataList = () => {
    return movieDataList;
}

export const addMovieData = (item) => {
    movieDataList.push(item);
}

export const clearMovieDataList = () => {
    movieDataList.length = 0;
}

✔️ 페이지네이션 개선

  • 데이터가 10 page를 넘어가는 경우가 있을 것이기에 pagination 부분에 대한 고민 필요

  • pagination.js 의 함수들을 전체적으로 수정이 필요

  • 페이지네이션 버튼을 자바스크립트로 관리할 수 있도록 수정

  • 그렇기에 printPagination() 등 필요한 함수를 구현

  • 함수들간에 실행 순서에서 시간을 많이 소모함

import { loadData } from "./data_load.js";
import { clearMovieDataList } from "./data_manage.js";

const $movieCards = document.querySelector("#movieCards");
const $activeClass = document.getElementsByClassName("active");
const $pageGroup = document.getElementById('page_item_group');
const $prevGroupPage = document.getElementById('prev_group_page');
const $nextGroupPage = document.getElementById('next_group_page');
let groupPage = 1;


// 현재 그룹 페이지 반환 함수
export const getGroupPage = () => {
    return groupPage;
}
// 그룹 페이지 변수 수정 (이전 그룹 페이지)
const setPrevGroupPage = () => {
    if (groupPage - 10 > 0) {
        return groupPage -= 10;
    }
}
// 그룹 페이지 변수 수정 (다음 그룹 페이지)
const setNextGroupPage = () => {
    return groupPage += 10;
}


// 페이지 그룹 이동 버튼에 이벤트 추가 함수
export const initPrevNextBtn = () => {
    $prevGroupPage.addEventListener('click', () => {
        setPrevGroupPage();
        $pageGroup.replaceChildren();
        printPagination(getGroupPage());
        $pageGroup.firstChild.click();
    });

    $nextGroupPage.addEventListener('click', () => {
        setNextGroupPage();
        $pageGroup.replaceChildren();
        printPagination(getGroupPage());
        $pageGroup.firstChild.click();
    });
}


// Pagination 클릭 이벤트 구현
const pagination = (item) => {
    item.addEventListener("click", () => {
        // 페이지 버튼의 활성화를 위한 코드
        $activeClass[1].className = $activeClass[1].className.replace(" active", "");
        item.className += " active";
        
        // 기존의 Card 삭제
        $movieCards.replaceChildren();
        clearMovieDataList();  // 페이지 단위로 검색 가능하게 할려고
        loadData(item.value);
        window.scrollTo({ top: 0, behavior: "smooth" });
    });
}


// 페이지네이션 출력
export const printPagination = (startPageNum) => {
    let html_tmp = ``;

    for (let i = 0; i < 10; i++){
        if (i === 0) {
            html_tmp = `<li class="page-item active" value="${startPageNum}"><a class="page-link">${startPageNum}</a></li>`;
        } else {
            html_tmp = `<li class="page-item" value="${startPageNum + i}"><a class="page-link">${startPageNum + i}</a></li>`;
        }
        $pageGroup.insertAdjacentHTML("beforeend", html_tmp);

        let pageBtn = $pageGroup.lastChild;
        pagination(pageBtn);
    }
}

profile
조금씩 정리하자!!!

0개의 댓글