-
항해 99 5기 TIL_10항해 99 2022. 1. 19. 14:34
▶ Today I Learned
<알고리즘 기초>
[하샤드 수]
https://programmers.co.kr/learn/courses/30/lessons/12947
소요시간: 14분 13초
내가 짠 코드
function solution(x) { let arr = x.toString().split('') let divisionNum = arr.reduce((acc, cur) => acc/1 + cur/1) return x % divisionNum == 0 ? true : false }
변수명도 잘 썼고 비교적 간단하게 구현한 것 같다.
이렇게하면 양의 정수가 몇이 나오던 상관없이 알맞은 답을 구할 수 있다.
이것보다도 효율적인 코드가 있을까?
예를 들어 숫자를 문자열로 바꾸어 연산하는 것이 없다던가..?
프로그래머스 답안
function Harshad(n){ return !(n % (n + "").split("").reduce((a, b) => +b + +a )); }
내가 짠것과 사실상 같은 구조이다.
!가 바로 앞에 붙는 것은 찾아보니 함수 바로 앞에 붙으면 함수를 바로 실행시키는 기능인듯 하다.
https://ychooni.tistory.com/479
하지만 여기서는 반환되는 값이 참인지 거짓인지를 판별해주는 구문으로 보인다.
!없이 반환시키면 0, 붙여서 반환시키면 true가 나온다.
찾아보니 논리부정 연산자라고 한다. 피연산자의 값이 truth이면 false, false이면 true를 반환해준단다.
즉, 논리연산을 거꾸로 하는 것이다. 어쩐지 0인데 true가 나오더라..!
답안 2
function solution(x) { let num = x; let sum = 0; do { sum += x%10; x = Math.floor(x/10); } while (x>0); return !(num%sum); }
아... 숫자로도 나올 수 있을 거라 생각했는데 이 방법이 또 나왔다...
이쯤되면 다음번에 숫자의 자리값을 활용해야할 때 한번 써볼만 한 듯 하다.
[제일 작은 수 제거하기]
https://programmers.co.kr/learn/courses/30/lessons/12935
소요시간: 아직 미정
처음 짠 코드
let arr = [1,3,4,2] let i = 0 let j = 0 let temporary = 0 for (i ; i < arr.length ; i++) { if (arr[i] < arr[i+1]) { temporary = arr[i+1] arr[i+1] = arr[i] arr[i] = temporary i-- } } console.log(arr)
이런 식으로 sort()를 이용한 정리 없이 해보고 싶었다.
하지만 이렇게 되면 사실상 인덱스의 첫번째 값만 대소에따라 이동하는 거라 [3,4,2,1]과 같이 출력되어 나머지 숫자들이 제대로 고려되지 않았다.
그렇담 우선 sort()로 구현하고 다시 해보아야지 생각하며 진행했다.
function solution(arr) { let answer = arr.sort((a,b) => b - a) console.log(answer) if (answer.length == 1){ answer[0] = -1 return answer } else { answer = answer.slice(0,-1) return answer } }
보기 케이스들은 문제없이 통과했다.
하지만 제출 시 실패했다.. 왜지...하며 궁금해하던 중 질문하기에서 배열의 정렬을 바꾸면 안된다고 했다.
하긴..문제를 다시 읽어보면 배열 내에서 가장 작은 값을 빼고 반환하라고 되어있다.
값만 빼고 반환하랬지 순서를 바꾸라곤 안했다...
그럼 정렬없이 가장 작은 값을 찾아보아야 겠다.
우선 시간이 늦었으니 내일 다시해보아야지..!
<쿠키, 세션, 캐시>
짚고 넘어가야할 HTTP를 통한 데이터 통신 특징 2가지
1. Connectionless
: 클라이언트가 Request를 서버에 보내면 서버에서는 Response를 하고 접속을 끊어버림
2. Stateless
: 클라이언트의 정보를 별도로 가지고 있지 않음, 첫 번째 통신에서 데이터를 주고 받았다 해도 두 번째 통신에서 그것을 유지하진 않음.
예를 들어 상세페이지에서 장바구니에 물건을 담고 결제를 누른다.
결제 페이지로 이동이 되었지만 담겨 있는 물건이 없다..!
페이지를 이동하면서 통신이 바뀌었고 데이터는 날아갔기 때문이다..!
또 어떤 페이지의 어느 부분을 보다가 다른 곳으로 넘어간 후 뒤로 가기를 눌렀다.
이때 보던 부분이 아닌 맨 처음 부분부터 보여주게 된다.
왜냐면 데이터는 날아갔으니까..!
이를 방지하고자 쿠키, 세션을 써서 정보를 저장해주는 것이다.
[Cookie]
: 웹 브라우저에 웹 서버로 부터 받은 일련의 문자열 데이터,
HTTP으로 통신 시 발생하는 문제를 해결하고자 쓰이고 있음
통신 방식
클라이언트에서 서버에 데이터 요청 (ex: 로그인 정보 입력 후 로그인 상태로 만들어 달라고 하기)
-> 서버에서는 Request Header를 확인한 후 쿠키가 없다면 쿠키에 ID, PW, 방문횟수 등의 정보를 담아
클라이언트에게 전달 (Response) -> 클라이언트는 다음 요청부터 Request Header에 쿠키 포함
특징
- 브라우저에 저장 (ex: 사파리에서 네이버에 들어가 로그인한 정보가 웨일 브라우저로 들어갔을 때도
유지되진 않는다.)
- 지정한 만료기간이 있어 그 기간 후에는 자동으로 만료된다.
- 주로 장바구니 담기, 하루동안 이 창 보지않기, 팝업띄우지 않기, 로그인 등에 쓰인다.
- 데이터는 Key : Value 형태 (이름, 값, 만료시기, 도메인, 쿠키 반환경로, 보안연결설정... )
- 저장 가능 용량은 4KB 미만이다.
- 한 클라이언트당 300개까지 저장가능 (But 하나의 도메인 당 20개 까지!)
- 초과시가장적게사용한것부터삭제
- 1개의 도메인에 한정됨
장점
속도가 세션에 비해 좋은 편이다. 쿠키가 있으면 브라우저에서 별도로 서버에 요청을 하지 않고
가지고 있는 정보로 바로 작업을 처리한다.
단점
쿠키에는 사용자 관련 정보가 담겨있을 수 있는데 브라우저에서 보관하고 있는 것이기 때문에 비교적
보안에 취약하다고 할 수 있다.
[Session]
: 서버에 정보를 임시 저장한 파일, 주로 중요한 데이터를 다룰 때 사용됨
특징
- 쿠키와 비슷하게 사용자 정보 저장이나 로그인 유지에 주로 사용된다.
- 브라우저가 종료될 때 까지 유지됨 (유효기간 설정가능하지만 그전에 브라저 종료해도 사라짐)
- 서버와 클라이언트 통신 때 주로 쿠키에 담겨져 전달된다.
통신방식
클라이언트가 웹사이트에 접속 시 세션 ID 을 발급한다.
-> 서버에서는 그 세션 ID를 쿠키에 저장한다.
-> 클라이언트가 다시 접속 시 쿠키에 저장된 세션 ID를 서버에 전달한다.
-> 서버는 해당 세션 ID를 보고 클라이언트를 판별한다.
장점
쿠키에 비해 보안성이 좋다 (클라이언트는 세션 ID에 대해서만 암, 정작 정보는 서버에 있음)
단점
속도가 느림 (서버에 정보가 저장되어있으므로 클라이언트에서 서버를 거쳐 정보를 받아야함
동시 사용 유저가 많으면 메모리 과부하까지 걸릴 수 있음)
=> 그러나 튜터팀의 피드백으론 세션이라고 해서 반드시 느린 것은 아니라고 하셨다.
서버내 DB에서 바로 데이터를 불러오는 것이 아니라
메모리를 따로 바깥에 두고 서버들이 필요 시 그 메모리에서 데이터를 가져오는 방식이 있다고 하셨다.
ex) Redis 이용
[Cache]
: 데이터나 파일들의 임시 저장소, 같은 웹 페이지에 접속할 때 사용자의 로컬PC에서 로드됨
주로 또 쓰일 것 같은 파일들을 저장해두는 곳
(css, js, 이미지, 비디오..)
장점
페이지 로딩 속도 향상 (페이지의 일정 부분 데이터를 서버에 요청하지 않아도 됨)
불필요한 데이터 전송이 없어 데이터 전송 비용 절약
서버로 들어오는 요청 역시 적기 때문에 네트워크 상 데이터 병목(데이터가 동시다발적으로 요청되어 특정 구간에 몰리는 현상,
처리가 지연됨)이 줄어듬
단점
삭제 시 직접해야 함 (ex: 구글에서 캐시된 이미지 또는 파일 지우기)
▶ 느낀 점
오늘 하루도 정신없이 지나갔다. 알고리즘 문제 풀이도 해야했지만 쿠키와 세션, 캐시에 대해 발표를 해야했기에 부랴부랴 자료를 준비했다.
급하게 준비했어서 조금 긴장되기도하고 깊이있는 정보를 전달하지 못해 아쉬움이 있었다. 그래도 생각 외로 이해하기 쉬웠고 말도 잘했다는 평을 들어서 꽤 괜찮은 편이었나보다 싶어 뿌듯했다 :) 좀 더 보완했으면 하는 지식에 대한 피드백도 받았는데 이렇게 직접 기술 튜터님에게 Redis 와 같은 새로운 지식들, 기본 관념에 대한 새로운 관점을 배울 수 있어 보람찼다. 당장 모든 걸 조사할 순 없지만 우선은 특징과 관련된 것으로 무엇이 있다 정도로 이해해두고 차차 깊이 있게 조사해보려고 한다.
지금은 잘 몰라도 수료할 때쯤엔 더 깊게 이해하는 내가 되어보자!
코딩은 코딩대로, 지식은 지식대로 점차 늘려나가는 나의 모습이 꽤 멋있다고 생각한다.
더 멋있어져야지 :)
▶ 공부 시 참고 링크들
https://brunch.co.kr/@b30afb04c9f54dc/7
https://brunch.co.kr/@dighty/22
https://velog.io/@hyeondev/Redis-%EB%9E%80-%EB%AC%B4%EC%97%87%EC%9D%BC%EA%B9%8C
'항해 99' 카테고리의 다른 글
항해 99 5기 TIL_12 (0) 2022.01.22 항해 99 5기 TIL_11 (0) 2022.01.21 항해 99 5기 TIL_9 (0) 2022.01.18 항해 99 5기 TIL_8 (0) 2022.01.18 항해 99 5기 WIL_1 (0) 2022.01.16