*Spring Security로 로그인 한 사용자 리디렉션 (tistory.com)*  - 출처 -

 

 

private boolean isAuthenticated() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || AnonymousAuthenticationToken.class.
                isAssignableFrom(authentication.getClass())) {
            return false;
        }
        return authentication.isAuthenticated();
}

  //로그인 페이지
    @GetMapping("/")
    public ModelAndView login(ModelAndView mav) {
        if(isAuthenticated()){
            mav.setViewName("/main");
            return mav;
        }
        mav.setViewName("views/login/login");
        return mav;

    }

1. 쓰레드를 생성하고 실행하는 것 까지는 간단하다.

2. 쓰레드를 중단하거나, 쓰레드를 여러개 생성해놓고 특정 쓰레드를 종료시키는 것은 조금 고민을 해봐야할 문제이다.

 

1) 쓰레드를 중단하는 방법은?

    -> 해당 객체를 호출하면, 쓰레드별로 종료하는 메서드를 지원하기 때문에 사용하면된다.

2) 그럼 쓰레드를 여러개 생성하여 각 쓰레드를 저장하고, 쓰레드를 종료시키려면 어떻게 해야하나?

    -> Map으로 관리한다.

    -> Key 로 해당 쓰레드를 찾아가서 종료시키거나 삭제한다.

JavaScript 에서 보내는 데이터


 

var options = [];
options.push('1123');
options.push('1159');
options.push('1300');

var formdata = {
					"date" : 20211129,
					"address" : 'busan dongrae',
					"tel1" : '010',
					"tel2" : '1234',
					"tel3" : '1234',
					"times" : options,
			}
fetch(url, {
				method : "POST",
				headers : {
					"Content-Type" : "application/json",
				},
				body : JSON.stringify(formdata),
			}).then((response) => console.log(response));

 

보내지는 데이터 구조 ( Json 데이터 내부구조에 Array 형이 있는 경우가 많은데 여태 통째로 String 으로 받은다음 JsonParser API로 파싱해서 사용했었음)


{
      'date' : '20211129',
      'address' : 'busan dongrae',
      'tel1' : '010',
      'tel2' : '1234', 
      'tel3' : '1234',
      'times' : ['1123', '1159', '1300']
}

 

Spring 에서 받을 때, 보내주는 형태로 클래스를 설계하고,

주의할 점은 보내는 json key 값과 클래스의 변수명이 일치해야 자동으로 매핑


import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@ToString
public class SendData {
	private String date;
	private String address;
	private String tel1;
	private String tel2;
	private String tel3;
	private String[] times;
	
	@Getter
	@Setter
	@ToString
	public static class Times {
		private String time;
	}
}

 

컨트롤러에서  @RequestBody ClassName Object 형태로 받을 수 있음


@ResponseBody
	@RequestMapping(value = "test", method = RequestMethod.POST)
	public String reservation(HttpSession session, @RequestBody SendData sendData)
			throws IOException {
            
            "";
	}

[TIP]


년+"-"+월+"-"+일

 

 

import org.junit.jupiter.api.Test;
import java.sql.Date;

public class DateTest {

    private Date date;
    private String birth_year = "1999";
    private String birth_month = "01";
    private String birth_day = "30";

    @Test
    public void date(){
        this.date = Date.valueOf(this.birth_year + "-" + this.birth_month + "-" + this.birth_day);
        System.out.println(this.date);
    }
}

시간 초과 남

import java.util.Scanner;

public class Main {

    static int up = 0;
    static int down = 0;
    static int now = 0;
    static int vertical = 0;
    static int days = 0;

    public static int moveUp(int now, int up){
        now += up;
        return now;
    }

    public static int movedown(int now, int down){
        now -= down;
        return now;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        now = 0;
        up = sc.nextInt();
        down = sc.nextInt();
        vertical = sc.nextInt();

        // 1. 낮 -> 체크
        // 2. 체크 > v return 종료
        // 2. 체크 < v -> 밤 -> 1

        while(true){
            //System.out.println("before [ " + " now : " + now + " up : " + up + " down : " + down + " vertical : " + vertical + " ]");
            now = moveUp(now, up);

            //올라간 후 목표높이보다 더올라가면 종료
            if(now >= vertical){
                days++;
                break;
            }
            //올라간 후 목표높이보다 낮으면 밤
            else{
                now = movedown(now, down);
            }
            //한사이클 돌았으니 날짜 +1
            days ++;
            //System.out.println("after [ " + " now : " + now + " up : " + up + " down : " + down + " vertical : " + vertical + " ]");
        }
        System.out.println(days);
    }
}

 

시간제한이 0.25초 라서 공식을 만들어 풀이를 해야 통과가 가능하다고함

 

첫째날 : 높이(0) + An < h(높이)

둘째날 : 높이(0) + (An - Bn) + An < h(높이)

...n 째  : 높이(0) + (n - 1)(An - Bn) + An < h

 

일절 반복문 사용은 불가능함

-> 주의 : double 형으로 나누어서 소수점 자리를 잃어버리지 않아야함

import java.util.Scanner;

public class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int An = sc.nextInt();
            int Bn = sc.nextInt();
            int V = sc.nextInt();
            System.out.println( (int)Math.ceil((double) (V-An) / (An - Bn)) + 1 );
        }
}

 

메모리 초과...

 

배열 객체를 생성하고, 꺼내고 집어넣고를 반복해서 그런것 같다.

좀 더 간단한 방법을 찾아봐야겠다.

import java.util.Scanner;

public class Main {

    public static int[] makeDeck(int num){
        int[] deck = new int[num];
        for(int i = 0; i < deck.length; i++){
            deck[i] = i+1;
        }
        return deck;
    }

    public static void status(int[] Card){
        //덱확인
        for(int i = 0; i < Card.length; i++){
            System.out.println(Card[i]);
        }
    }

    public static void arrange(int[] Card) {
        int size = Card.length;

        int save = 0;
        int[] renew = new int[size - 1];

        for(int i = 0; i < renew.length; i++){
            renew[i] = Card[i+1];
        }
        //status(renew);
        save = renew[0];
        for (int i = 0; i < renew.length - 1; i++) {
            renew[i] = renew[i+1];
        }
        renew[renew.length - 1] = save;
        if(renew.length != 1){
            arrange(renew);
        }
        if(renew.length == 1){
            System.out.println(renew[0]);
        }
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        //카드덱 생성
        int[] Card = makeDeck(sc.nextInt());

        //로직 구현
        arrange(Card);
    }
}

TIP

마지막 것을 지우므로 순서가 보장되는 ArrayList 나 LinkedList 사용.

순차적인 추가나 접근은 속도에서 ArrayList > LinkedList 이므로 ArrayList를 사용

 

Stream API로 합구하는방법

collection객체.stream().mapToInt(e->e).sum(); 

import java.util.ArrayList;
import java.util.Scanner;

public class Main {

    public static ArrayList<Integer> delete(ArrayList<Integer> arrayList){
        ArrayList<Integer> delete = arrayList;
        delete.remove(delete.size()-1);
        return delete;
    }

    public static ArrayList<Integer> add(ArrayList<Integer> arrayList, int addNumber){
        ArrayList<Integer> add = arrayList;
        add.add(addNumber);
        return add;
    }

    public static int ArraySum(ArrayList<Integer> arrayList){

        return arrayList
                .stream()
                .mapToInt(e->e)
                .sum();
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        //라인 수
        int K = sc.nextInt();

        //ArrayList : 순서보장, LinkedList 보다 순차 추가 는 빠름
        ArrayList<Integer> numbers = new ArrayList<>();

        //입력을 받자 숫자 K개
        while(K > 0){
            //숫자 입력받기
            int num = sc.nextInt();
            int delete = 0;

            if(num == delete){
                numbers = delete(numbers);
            }
            else{
                numbers = add(numbers, num);
            }
            K--;
        }
        System.out.println(ArraySum(numbers));
    }
}

TIP !


유클리드 호제법

GCD(A, B) = GCD (B, A % B)

if A%B = 0 -> GCD = B

       else GCD (B, A%B)

 

 

import java.util.Scanner;

public class Main {

    public static int greatest_common_factor(int a, int b){
        int A = a;
        int B = b;
        int r = a % b;

        if( r == 0)
            return B;

        int res = greatest_common_factor(B , r);

        return res;
    }

    public static int least_common_multiple(int ab, int greatest_common_factor){
        return ab / greatest_common_factor;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int a = sc.nextInt();
        int b = sc.nextInt();
        int greatest_common_factor = greatest_common_factor(a, b);
        int least_common_multiple = least_common_multiple(a*b,greatest_common_factor);
        System.out.println(greatest_common_factor);
        System.out.println(least_common_multiple);
    }
}

'AREA(지속적인 일상) > 02_백준' 카테고리의 다른 글

[백준] - 2164 - 카드2  (0) 2021.09.07
[백준] - 10773 - 제로  (0) 2021.09.07
[백준] - 참고. 자릿수 구하기  (0) 2021.08.30
[백준] - 1546 - 평균  (0) 2021.08.26
[백준] - 3052 - 나머지  (0) 2021.08.26
//승수 구하기
    public static int nofn(int input){
        int n = 0;
        while(true){
            if(input < 10){
                break;
            }else{
                input = input / 10;
                n++;
            }
        }
        return n;
    }
package p1546;

import java.util.Arrays;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.Scanner;

public class Main {

    public static double result(int[] score){
        //최댓값
        int maxScore = calMaxValue(score);

        //조작한 점수 넣기
        double[] modScore = new double[score.length];
        
        //최댓값 기준으로 점수 조작
        for(int i = 0 ; i < score.length; i++){
            modScore[i] = modifyScore(score[i], maxScore);
        }
        //평균 구하기
        double result = average(modScore);
        return result;
    }

    public static double average(double [] modScore){
        OptionalDouble opt = Arrays.stream(modScore).average();
        return opt.getAsDouble();
    }

    public static float modifyScore (int score, float maxScore){
        float modifyScore = score / maxScore * 100;
        return modifyScore;
    }

    public static int calMaxValue(int [] score){
        OptionalInt maxValue= Arrays.stream(score).max();
        return maxValue.getAsInt();
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int numberOfSubject = sc.nextInt();

        int[] score = new int[numberOfSubject];

        for(int i = 0 ; i < score.length; i++){
            score[i] = sc.nextInt();
        }
        System.out.println(result(score));
    }
}

tip 1. 입력 받고 바로, 배열에 42로 나눈 나머지를 담아서 저장.

tip 2. 입력 후 remainder 함수에서 distinct() 중복제거 후 count() 로 갯수 세어주면 끝

 

package P3052;

import java.util.Arrays;
import java.util.Scanner;

public class Main {

    public static long remainder(int[] dividend, int divisor){
        return  Arrays.stream(dividend)
                .distinct()
                .count();
    }

    public static void main(String[] args) {
        //input 10s
        //% 42

        Scanner sc = new Scanner(System.in);

        //제수
        int[] dividend = new int[10];

        //피제수
        final int divisor = 42;

        for (int i = 0; i < dividend.length; i++){
            dividend[i] = sc.nextInt();
            dividend[i] %= divisor;
        }
        sc.close();
        System.out.println(remainder(dividend, divisor));
    }
}
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Stream;

public class Main {


    public static int multiply(int A, int B, int C){
        return A * B * C;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int A = sc.nextInt();
        int B = sc.nextInt();
        int C = sc.nextInt();

        int multiply = multiply(A,B,C);

        int[] intArray = Stream.of(String.valueOf(multiply).split("")).mapToInt(Integer::parseInt).toArray();

        long count = 0L;

        for(int i = 0; i < 10; i ++){
            int a = i;
            count = Arrays.stream(intArray)
                    .filter(n -> n == a)
                    .count();
            System.out.println(count);
        }
    }
}

'AREA(지속적인 일상) > 02_백준' 카테고리의 다른 글

[백준] - 1546 - 평균  (0) 2021.08.26
[백준] - 3052 - 나머지  (0) 2021.08.26
[백준] - 2562 - 최댓값  (0) 2021.08.26
[백준] - 10871번 - X 보다 작은 수  (0) 2021.08.25
[백준] - 2884 - 알람 시계  (0) 2021.08.24
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.IntStream;

public class Main {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int[] numbers = new int[9];

        for(int i=0; i <numbers.length; i++){
            numbers[i] = sc.nextInt();
        }

        IntStream max = Arrays.stream(numbers);
        int maxnumber = max.max().getAsInt();

        System.out.println(maxnumber);

        for(int i = 0; i < numbers.length; i ++){
            if(numbers[i] == maxnumber) {
                System.out.println(i+1);
            }
        }
    }
}
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

public class Main {

    public static Main Main(){
        return new Main();
    }

    //정수 N개로 이루어진 수열 A와 정수 X가 주어진다.
    //이때, A에서 X보다 작은 수를 모두 출력하는 프로그램을 작성하시오.

    //첫째 줄에 N과 X가 주어진다 (1 <= N, X<= 10000)
    //둘째 줄에 수열 A를 이루는 정수 N개가 주어진다. 주어지는 정수는 모두 1보다 크거나 같고, 10000 보다 작거나 같은 정수이다

    //출력 : X 보다 작은 수를 입력받은 순서대로 공백으로 구분해 출력한다. X보다 작은 수는 적어도 하나 존재한다

    public static ArrayList<Integer> lessThan(int X, int[] array){

        int lessThan = X;
        ArrayList<Integer> result = new ArrayList<>();

        for(int i = 0; i < array.length; i++){
            if( lessThan > array[i])
            {
                result.add(array[i]);
            }
        }
        return result;
    }

    public static void main(String[] args) throws IOException {
        Main main = new Main();
        Scanner sc = new Scanner(System.in);

        int N = sc.nextInt();
        int X = sc.nextInt();

        int[] numbers = new int[N];


        int input = 0;

        for(int i = 0 ; i < N; i ++){
            input = sc.nextInt();
            numbers[i] = input;
        }

        ArrayList<Integer> result = lessThan(X, numbers);

        result.forEach(e -> {
            System.out.print(e + " ");
        });
    }
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {

    public static Main Main(){
        return new Main();
    }
    public void alarm (int t, int m){
        // 1) 시간이 바뀌는 경우
            // 1. 45분 미만
            // 2. 45분 미만이면서 0시 인경우 23시

        // 2) 시간이 안바뀌는 경우
            // 1. 45분 이상
            // 2. 입력된 시간 - 45
        if (t >= 0 && m > 45){
            t = t;
            m = m - 45;
        }
        else if (t > 0 && m > 45){
            t = t;
            m = m - 45;
        }
        else if (t > 0 && m < 45){
            t = t - 1;
            m = m + 60 - 45;
        }else if (t == 0 && m < 45){
            t = 23;
            m = m + 60 - 45;
        }else if (m == 45){
            t = t;
            m = 0;
        }

        System.out.println(t + " " + m);

    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        int t = Integer.parseInt(st.nextToken());
        int m = Integer.parseInt(st.nextToken());

        Main main = Main();
        main.alarm(t, m);

    }
}

'AREA(지속적인 일상) > 02_백준' 카테고리의 다른 글

[백준] - 2562 - 최댓값  (0) 2021.08.26
[백준] - 10871번 - X 보다 작은 수  (0) 2021.08.25
[백준] - 사분면 고르기 - 14681  (0) 2021.08.24
[백준] - 2753 - 윤년  (0) 2021.08.24
[백준] - 1330 대소 비교  (0) 2021.08.24
import java.io.IOException;
import java.util.Scanner;

public class Main {
    public static Main Main(){
        return new Main();
    }

    public static int selectQuadrant(int x, int y){
        int result = -1;
        if (x > 0 && y > 0) {result = 1;}
        if (x < 0 && y > 0) {result = 2;}
        if (x < 0 && y < 0) {result = 3;}
        if (x > 0 && y < 0) {result = 4;}
        return result;
    }

    public static void main(String[] args) throws IOException {

        Scanner s = new Scanner(System.in);
        int x = s.nextInt();
        int y = s.nextInt();
        System.out.println(selectQuadrant(x, y));
    }
}

'AREA(지속적인 일상) > 02_백준' 카테고리의 다른 글

[백준] - 10871번 - X 보다 작은 수  (0) 2021.08.25
[백준] - 2884 - 알람 시계  (0) 2021.08.24
[백준] - 2753 - 윤년  (0) 2021.08.24
[백준] - 1330 대소 비교  (0) 2021.08.24
[백준] 1009번 - 분산처리  (0) 2021.08.24

윤년 4의 배수, 100의 배수가 아닐 때 또는 400의 배수일 때

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static Main Main(){
        return Main();
    }

    // 윤년 4의 배수, 100의 배수가 아닐 때 또는 400의 배수일 때

    public static int cal(int years){
        int result = -1;

        if(years % 4 == 0 && years % 100 != 0 || years % 400 == 0 ){
            result = 1;
        }
        else
        {
            result = 0;
        }
        return result;
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int input = Integer.parseInt(br.readLine());
        int years = cal(input);
        System.out.println(years);
    }
}

'AREA(지속적인 일상) > 02_백준' 카테고리의 다른 글

[백준] - 2884 - 알람 시계  (0) 2021.08.24
[백준] - 사분면 고르기 - 14681  (0) 2021.08.24
[백준] - 1330 대소 비교  (0) 2021.08.24
[백준] 1009번 - 분산처리  (0) 2021.08.24
[백준] 2588 곱셈  (0) 2021.08.23

두 수 비교, <, >, == 출력

package p1330;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {
    public static Main Main(){
        return new Main();
    }

    public static String compareWith(int a, int b){
        String result = null;
        if (a > b){result = ">";}
        if (a < b){result = "<";}
        if (a == b){result = "==";}
        return result;
    }
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        int a = Integer.parseInt(st.nextToken());
        int b = Integer.parseInt(st.nextToken());
        System.out.println(compareWith(a, b));
    }
}

'AREA(지속적인 일상) > 02_백준' 카테고리의 다른 글

[백준] - 사분면 고르기 - 14681  (0) 2021.08.24
[백준] - 2753 - 윤년  (0) 2021.08.24
[백준] 1009번 - 분산처리  (0) 2021.08.24
[백준] 2588 곱셈  (0) 2021.08.23
[백준 1002] 터렛  (0) 2020.02.24

너무 복잡하게 생각했다.

간과한 사실이, 최대 반복되는 횟수는 4이다.

예를 들어 2로 끝나는 수는 2,4,8,6 이다. 그러면 1같은건 항상 1인데 어떻게 하느냐?

1,1,1,1 이렇게 생각했으면, 아래에 selectArray 같은 함수 만드는일은 없었을 텐데 좀 아쉽다.

 

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class Main {
    public static Main Main(){
        return new Main();
    }

    public static int selectArray(int a, int b){
        int result = 0;

        if(a % 10 == 0){
            int[] values = {10};
            return findNumber(b, values);
        }
        if (a % 10 == 1){
            int[] values = {1};
            return findNumber(b, values);
        }
        if (a % 10 == 2){
            int[] values = {2,4,8,6};
            return findNumber(b, values);
        }
        if (a % 10 == 3){
            int[] values = {3,9,7,1};
            return findNumber(b, values);
        }
        if (a % 10 == 4){
            int[] values = {4, 6};
            return findNumber(b, values);
        }
        if (a % 10 == 5){
            int[] values = {5};
            return findNumber(b, values);
        }
        if (a % 10 == 6){
            int[] values = {6};
            return findNumber(b, values);
        }
        if (a % 10 == 7){
            int[] values = {7,9,3,1};
            return findNumber(b, values);
        }
        if (a % 10 == 8){
            int[] values = {8,4,2,6};
            return findNumber(b, values);
        }
        if (a % 10 == 9){
            int[] values = {9, 1};
            return findNumber(b, values);
        }
        return result;
    }

    public static int findNumber(int b, int[] values){
        int result = 0;
        for (int i = 1; i < values.length + 1; i++)
        {
            if(b % values.length == 0) {result = values[values.length-1];}
            else {result = values[b % values.length - 1];}
        }

        return result;
    }

    public static int lastData(int a, int b){
        return selectArray(a, b);
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int count = Integer.parseInt(br.readLine());
        ArrayList<Integer> array =  new ArrayList<>();

        StringTokenizer st = null;

        while(0 < count){
            int a, b = 0;

            st = new StringTokenizer(br.readLine());
            a = Integer.parseInt(st.nextToken());
            b = Integer.parseInt(st.nextToken());
            array.add(lastData(a, b));
            count --;
        }
        array.forEach(list -> System.out.println(list));
    }
}

 

 

'AREA(지속적인 일상) > 02_백준' 카테고리의 다른 글

[백준] - 2753 - 윤년  (0) 2021.08.24
[백준] - 1330 대소 비교  (0) 2021.08.24
[백준] 2588 곱셈  (0) 2021.08.23
[백준 1002] 터렛  (0) 2020.02.24
[백준 15552] 빠른 A+B (Java)  (0) 2020.02.24
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    public static Main Main(){
        return new Main();
    }

    public int multiplication(int p, int q){
        return p * q;
    }

    public int units (int q){return (q % 100) % 10;}
    public int tens (int q){return (q % 100) / 10;}
    public int hundreds (int q){return q / 100;}

    public static int StringtoInteger(String p){return Integer.parseInt(p);}

    public static int sum(int p, int q, int r){
        return p + (q * 10) + (r * 100);
    }

    public static void main(String[] args) throws IOException {
        Main main = Main();

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String p = br.readLine();
        String q = br.readLine();

        int units = main.multiplication(StringtoInteger(p), main.units(StringtoInteger(q)));
        int tens = main.multiplication(StringtoInteger(p), main.tens(StringtoInteger(q)));
        int hundreds = main.multiplication(StringtoInteger(p), main.hundreds(StringtoInteger(q)));

        System.out.println(units);
        System.out.println(tens);
        System.out.println(hundreds);
        System.out.println(sum(units, tens, hundreds));

    }
}

'AREA(지속적인 일상) > 02_백준' 카테고리의 다른 글

[백준] - 2753 - 윤년  (0) 2021.08.24
[백준] - 1330 대소 비교  (0) 2021.08.24
[백준] 1009번 - 분산처리  (0) 2021.08.24
[백준 1002] 터렛  (0) 2020.02.24
[백준 15552] 빠른 A+B (Java)  (0) 2020.02.24