https://imslo.tistory.com/21

 

AWS 사용해 웹페이지 배포해보기

AWS Elastic Beanstalk 무료버전을 사용해 지금까지 만든 웹페이지를 배포해보았다. 1.해외결제 가능한 카드 준비 2.Root 유저 가입 3.모든 권한이 있는 Root유저로 작업할 시 위험요소가 있으므로 IAM 사

imslo.tistory.com

 

'일기 > TIL' 카테고리의 다른 글

23.04.03 // Java공부 - 1  (0) 2023.04.16
23.04.01 // ajax async, 웹 관련  (0) 2023.04.16
23.03.25 // MongoDB, Flask 서버만들기  (0) 2023.04.16
23.03.24 // API 활용, 웹크롤링  (0) 2023.04.16
23.03.23 // Youtube Api활용, Git Bash  (0) 2023.04.16

https://imslo.tistory.com/20

https://imslo.tistory.com/19

 

API 활용 / 웹스크래핑

Youtube API로 영상 받아오기 : https://imslo.tistory.com/17 Youtube Api 활용, 특정채널 영상 URL 가져오기 https://console.cloud.google.com/getting-started 들어가서 로그인하고, 좌측 탭에 API 및 서비스 클릭 Google Cloud co

imslo.tistory.com

 

https://imslo.tistory.com/17

 

Youtube Api 활용, 특정채널 영상 URL 가져오기

https://console.cloud.google.com/getting-started 들어가서 로그인하고, 좌측 탭에 API 및 서비스 클릭 Google Cloud console console.cloud.google.com 프로젝트 생성하고, 사용자 인증 정보 탭 -> +사용자 인증 정보 -> API

imslo.tistory.com

git  : https://imslo.tistory.com/18

 

Git Bash

Git Bash란? Bourne Again SHell ==> Steve Bourne이 개발한 유닉스 쉘 프로그램의 확장판 리눅스는 유닉스 운영체제를 기반으로 만들어짐 Git Bash를 설치하면 우리가 사용하는 운영체제인 윈도우 OS환경에서

imslo.tistory.com

 

https://imslo.tistory.com/16

HTML : https://imslo.tistory.com/13

 

HTML

 

imslo.tistory.com

 

CSS : https://imslo.tistory.com/14

 

CSS

- 백그라운드 사진과 텍스트를 담은 박스 - width, height로 크기 조절, - border-radius로 테두리 둥글게 - text-align 글씨 가운데 정렬 - padding으로 글씨 위치 조절 (padding한 만큼 width와 height도 변함) - backgr

imslo.tistory.com

 

 

https://school.programmers.co.kr/learn/courses/30/lessons/150368

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

이모티콘의 최대 개수가 7개, 할인율의 종류가 4개이므로 최대 4^7 경우의 수를 탐색해야했다.

재귀를 써본적이 없어서 7중 for문을 써서 풀려고 했다 😅 하지만 이모티콘의 개수에 따라 for문을 다르게 중첩해야 하기에 그렇게 풀기는 어려웠다.

 

재귀를 써서 DFS로 풀기로 하고 함수를 작성했다.

<로직>

할인율의 조합을 담는 rates 배열을 가지고 재귀호출을 하면서, rates 배열의 모든 경우의 수를 탐색.

재귀함수가 처음 호출될 때는 rates배열이 다 0으로 초기화되어있다. 호출 될 때마다, 현재 index에 할인율을 지정된 할인율을 담음. 지정된 할인율은 재귀호출의 파라미터로 넘어오는데, 0~3의 인덱스로 각 RATES[idx]로 표현된다.

할인율을 담았으면 현재 길이를 확인한다. cur + 1 == emoticons.length  이면 재귀를 종료하고 문제에서 요구한 계산 실행.

아직 length가 부족하면 다음 할인율을 담아야하니 재귀호출을 한다. 이 때, 현재 rates의 배열에서 파생되는 모든 경우의 수(다음거 10, 20, 30, 40)를 탐색해야하므로 모든 경우의 수에 대해 재귀호출을 한다. 하나의 재귀 프로세스는 rates가 꽉차서 계산이 실행될때만 종료되기 때문에, 메모리걱정은 안해도 된다.\

문제에서 요구하는 계산 = 그냥 할인율,이모티콘 곱해서 가격구하고 몇명이 사는지, 그리고 최대인원이 살 때 매출 얼마인지. ==> MAXREG 변수가 최대로 갱신될 때 MAXREV 갱신. MAXREG가 동률일 때 MAXREV 비교

 

<구현>

 

 

DFS를 처음 짜봤는데, search함수 내에서 calculate라는 함수를 미리 넣어놓고, 나중에 짰다. 이렇게 하니까 search함수의 재귀 종료 시점에서 어떤 계산이 일어나야하는지, 그 때 필요한 파라미터는 뭐가있는지, 어떤 반환값을 가져야하는지를 미리 생각해볼 수 있어서 좋은 것 같다.

 

import java.util.*;
class Solution {
    public static int MAXREG = 0;
    public static int MAXREV = 0;
    public static int[] RATES = {10, 20, 30, 40};
    
    public int[] solution(int[][] users, int[] emoticons) {
        int[] answer = new int[2];
        int[] rates = new int[emoticons.length];
        for(int i = 0; i< RATES.length; i++){
            search(users, emoticons, rates, 0, i);
        }
        
        answer[0] = MAXREG;
        answer[1] = MAXREV;
        return answer;
    }
    
    public static void search(int[][] users, int[] prices, int[] rates, int cur, int idx){
        rates[cur] = RATES[idx];
        if (cur + 1 == rates.length){
            int[] infos = calculate(users, prices, rates);
            if (infos[0] > MAXREG){
                MAXREG = infos[0];
                MAXREV = infos[1];
            }
            else if (infos[0] == MAXREG){
                MAXREV = Math.max(MAXREV, infos[1]);
            }
        }
        else{
            for(int i = 0; i<RATES.length; i++){
                search(users, prices, rates, cur + 1, i);
            }
        }
    }
    
    public static int[] calculate(int[][] users, int[] prices, int[] rates){
        int[] ans = {0,0};
        
        for (int[] user:users){
            int buyrate = user[0];
            int buylimit = user[1];
            int pricesum = 0;
            for(int i = 0; i<prices.length; i++){
                if(rates[i] >= buyrate){
                    pricesum += (100 - rates[i]) * prices[i] / 100;
                }
            }
            if (pricesum >= buylimit){
                ans[0] += 1;
                pricesum = 0;
            }
            else{
                ans[1] += pricesum;
            }
        }
        return ans;
        
    }
}

@Entity

-JPA에 해당 클래스가 DB의 테이블 역할이라는 것을 알려줌

-@Id  : Id

-@GeneratedValue(strategy = GenerationType.AUTO) : 자동생성 및 증가

-@Column : 컬럼임을 알려줌 (nullable, unique 옵션 boolean으로 줄 수 있음) 

 

 

<TimeStamp>

★SpringBootApplication 있는 class에 @EnableJpaAuditing 추가해주기

@Getter
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class) 
public class Timestamped {

    @CreatedDate
    @Column(updatable = false)
    private LocalDateTime createdAt;

    @LastModifiedDate
    @Column
    private LocalDateTime modifiedAt;
}

==> Entity에 extend 받아서 사용하면, createdAt 컬럼과 modifiedAt 컬럼이 생김

 

============================================================================================

@RequestMapping("/resonse") ==>  response로 들어온 request를 해당 애노테이션이 붙은 곳으로 매핑해줌

@GetMapping("URL") ==> Get Method로 들어온 요청을 해당 메소드로 매핑해줌

@PostMapping   @PutMapping   @DeleteMapping  이하동문

★RequestMapping은 클래스와 메소드에 쓸 수 있고, 나머지는 메소드에만 쓸 수 있다.

==> RequestMapping("/response") 클래스 안에 있는 @GetMapping("/test")의 요청 URL은 /response/test 가 된다.

 

@Controller ==> 해당 클래스 / 메소드가 MVC 패턴의 Controller에 해당한다는 것을 알려줌

-기본적으로 @Controller는 view를 반환하게 되어있다. 따라서, return "hello"는 String 타입의 hello를 반환하는 것이 아니라, view로서 hello.html을 반환하게 된다.

bye.html은 없고 hello.html만 있을 때, @Controller인 함수가 view 형태의 bye.html을 찾을 수 없다고 알려줌.

하지만 모든 요청이 view를 요청하는 것은 아니다. 데이터를 JSON형태로 받아야 할 경우에는 

@ResponseBody  annotation을 붙여준다. Controller이긴 하지만, view가 아닌 데이터를 반환하는 메서드임을 알려준다.

JSON처럼 생긴 String으로 반환된 모습.

@RestController 는 @Controller와 @ResponseBody를 합쳐놓은 것.

==> RESTful한 설계(백엔드에서는 데이터만 전송)에서는 @RestController를 주로 사용

 

============================================================================================

@Autowired : 빈으로 등록된 클래스를 자동 주입(인스턴스화 하지 않아도 사용 가능)

@Service : 빈으로 등록함

 

 

@Transactional : Transactional이 붙은 연산들을 같이 관리하며, 서로간의 간섭이 없게 한다. Transaction이 끝날 때까지 외부에서 연산결과를 볼 수 없으며, 충돌 없이 Transaction들이 끝난 후에 데이터베이스에 반영된다. 그렇지 않으면 롤백된다. @Transaction시 데이터 업데이트 할 때, 엔티티만 업데이트 해주면 반영됨 - 추가공부하기()

 

 

@EnableJpaAuditing : @SpringBootApplication 있는곳에 붙여주면, Timestemp 사용가능↓↓↓

@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class Timestamped {

@CreatedDate
private LocalDateTime createdAt;

@LastModifiedDate
private LocalDateTime modifiedAt;
}

 

 

@Configuration --> 아래에 @Bean  : Bean을 생성하고, 등록가능

 

@RequiredArgsConstructor : final변수에 bean 자동주입 (@Autowired 안써도됨)

 

@NoArgsConstructor : 기본생성자 만들어줌 (@Entity는 이게 있어야함)

 

JpaRepository.saveAndFlush(~~~~) : 영속성컨텍스트에 저장하지 않고, 바로 DB에 반영

 

@Scheduled(cron = " 0 0 1 * * *")  // 초 분 시 일 월 주

==> 지정된 시간마다 메서드 호출

 

 

JWT dependency :

build.gradle에

compileOnly group: 'io.jsonwebtoken', name: 'jjwt-api', version: '0.11.2'
runtimeOnly group: 'io.jsonwebtoken', name: 'jjwt-impl', version: '0.11.2'
runtimeOnly group: 'io.jsonwebtoken', name: 'jjwt-jackson', version: '0.11.2'

Application properties에 jwt.secret.key = asdfasdfasdfasfasdf

'공부 > 잡다' 카테고리의 다른 글

QueryDSL 사용법  (0) 2023.05.03
IntelliJ 콘솔창 한글 깨질때  (0) 2023.04.15
웹 동작 간략개괄  (0) 2023.04.14
IntelliJ 디버거 활용 - Exception 조건설정  (0) 2023.04.10
Twitter recommendation system code revealed  (0) 2023.04.06

+ Recent posts