TIL) 코딩테스트 입문 Day 9 ~ 10 with Java

2024. 12. 24. 20:29코딩테스트 리뷰(프로그래머스)/코딩 기초 트레이닝 with Java

1) 개미 군단

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

class Solution {
    public int solution(int hp) {
        int result = 0;
        for( int attack : new int[]{5,3,1} ) {
            result += hp / attack;
            hp = hp % attack;
        }
        return result;
    }
}

 



2) 모스부호 (1)

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

import java.util.*;
class Solution {
    public String solution(String letter) {
        StringBuilder sb = new StringBuilder();
        Map<String, String> morse = Map.ofEntries(
                Map.entry(".-","a"),
                Map.entry("-...","b"),
                Map.entry("-.-.","c"),
                Map.entry("-..","d"),
                Map.entry(".","e"),
                Map.entry("..-.","f"),
                Map.entry("--.","g"),
                Map.entry("....","h"),
                Map.entry("..","i"),
                Map.entry(".---","j"),
                Map.entry("-.-","k"),
                Map.entry(".-..","l"),
                Map.entry("--","m"),
                Map.entry("-.","n"),
                Map.entry("---","o"),
                Map.entry(".--.","p"),
                Map.entry("--.-","q"),
                Map.entry(".-.","r"),
                Map.entry("...","s"),
                Map.entry("-","t"),
                Map.entry("..-","u"),
                Map.entry("...-","v"),
                Map.entry(".--","w"),
                Map.entry("-..-","x"),
                Map.entry("-.--","y"),
                Map.entry("--..","z")
        );

        for( String str : letter.split(" ") ) {
            sb.append(morse.get(str));
        }

        return sb.toString();
    }
}

 

풀이 해석

해당 문제에서 바로 Map.of 메소드를 찾아서 사용을 하려했지만 오류가 발생하는 모습을 확인할 수 있다.

Map.of는 10개 까지만 문제가 없이 동작하기 때문에 ofEntries 메소드를 사용해서 추가를 해주거나

put을 사용해서 여러개를 넣을 수 있다.

 

참조

 

Java HashMap 생성 및 초기화하는 방법 6가지

Java의 HashMap은 매우 유용하며 자주 사용되는 Map 인터페이스의 구현체입니다. 이 글에서는 여러 가지 방법으로 HashMap을 생성하고 초기화하는 예제들을 소개하겠습니다. 예제 1. 기본 생성 및 초기

statuscode.tistory.com

 

 

Map.of() 를 통한 Map 초기화 주의할 점

Java 9부터 사용할 수 있는 Map.of()를 통해 맵 데이터를 초기화하다가 주의할 점이 몇 가지 있어서 포스팅을 남기려 합니다.기존에는 맵을 초기화할 때 아래와 같이 진행했었습니다.하지만 Java 9 이

velog.io

 

 

[Java] HashMap을 초기화하는 방법: map.put(), Map.of(), Map.ofEntries()

Java에서 HashMap을 초기화하는 방법은 여러 가지가 있다. 가장 일반적인 방법은 생성자를 사용하여 초기화하는 건데, Java 9 이상부터는 간단한 초기화를 위해 `Map.of()`를 사용할 수 있다. `map.put()` Ha

hyunrian.tistory.com

 

 

3) 가위 바위 보

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

class Solution {
    public String solution(String rsp) {
        StringBuilder sb = new StringBuilder();
        for( String s : rsp.split("") ) {
            if( s.equals("2") ) sb.append("0");
            else if ( s.equals("0")) sb.append("5");
            else if ( s.equals("5")) sb.append("2");
        }
        return sb.toString();
    }
}

 

 

4) 구슬을 나누는 경우의 수

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

import java.math.BigInteger;

class Solution {
    public int solution(int balls, int share) {
        BigInteger front = BigInteger.valueOf(1);
        for( int i = 0; i < share; i++) {
            BigInteger temp = BigInteger.valueOf(balls);
            temp = temp.add(BigInteger.valueOf(-i));
            front = front.multiply(temp);
        }
        BigInteger back = BigInteger.valueOf(1);
        for( int i = 0; i < share; i++) {
            BigInteger temp = BigInteger.valueOf(share);
            temp = temp.add(BigInteger.valueOf(-i));
            back = back.multiply(temp);
        }

        BigInteger sum = front.divide(back);

        return sum.intValue();
    }
}

다르게 풀이 한 분들이 있는데 코드 이해를 못해서 코드를 리뷰 및 해석을 해보도록 하겠습니다.

 

 

5) 점의 위치 구하기

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

class Solution {
    public int solution(int[] dot) {
        if( dot[0] > 0 && dot[1] > 0) return 1;
        else if( dot[0] < 0 && dot[1] > 0) return 2;
        else if( dot[0] < 0 && dot[1] < 0) return 3;
        else return 4;
    }
}

 

 

6) 2차원으로 만들기

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

class Solution {
    public int[][] solution(int[] num_list, int n) {
        int[][] answer = new int[num_list.length/n][n];
        for( int i = 0; i < num_list.length; i++) {
            answer[i / n][i % n] = num_list[i];
        }
        return answer;
    }
}

 

 

풀이 해석

 

컴퓨터 과학의 기초 내용이다.

실제로 메모리는 배열형식으로 저장을 가지고 있는 것이 아니라, 값을 넣고 그 위치에 index라는 것으로 위치를 표기해주는 것이다.

실제로 우리가 값을 만들어도 배열이 [1,2,3,4,5,6], [[1,2],[3,4],[5,6]] 을 넣어도 메모리에 저장되는 형식은 똑같다.

어떻게 참조하는지가 다른 방법이다.

 

어렵게 설명을 했지만,

각 숫자가 진수라고 생각하면서 올리면 풀이가 된다. 03이면 n 이 즉 3진수 로 변경 10 으로 된다.

 

 

7) 공 던지기

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

class Solution {
    public int solution(int[] numbers, int k) {
        int count;
        int num = 0;
        for( count = 1; count != k; count++ ) {
            num += 2;
            num %= numbers.length;
        }
        return numbers[num];
    }
}

 

 

8) 배열 회전 시키기

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

class Solution {
    public int[] solution(int[] numbers, String direction) {
        
        int[] result = new int[numbers.length];
        
        for( int i = 0; i < numbers.length; i++) {
            if( direction.equals("right")) {
                result[i] = numbers[ i - 1 < 0 ? numbers.length-1 : i-1];
            } else {
                result[i % numbers.length] = numbers[(i+1) % numbers.length];
            }
        }
        return result;
    }
}

 

 

느낀 점

뭔가 실제 수학이랑 연결된 코딩테스트는 기초 & 입문 단계에서 처음본 것인데,

이건 진짜 수학적인 해결 방법을 많이 알아야겠다는 생각이 든다..

수학 공부도 해야되나 라는 생각이 든다.