잡다한 배똥월드

728x90
코딩 테스트 풀이 체크리스트
2시간 내에 풀었는가? O
본인의 실력으로 풀었는가? O

 

 

10828번: 스택

첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지

www.acmicpc.net

 

 

 

 

 

import java.io.*;
import java.util.*;
public class Main {
	public static void main(String[] args) throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		
		//명령 수
		int t = Integer.parseInt(br.readLine());
		//스택을 구현할 ArrayList
		ArrayList<String> stack = new ArrayList<>();
		
		//명령 수 만큼 반복
		for (int i = 0; i < t; i++) {
			//push를 위해 String배열로 입력값 가져오기
			String[] code = br.readLine().split(" ");
			
			//이외에는 문제의 설명대로 push, pop, top, size, empty의 경우에 맞게 출력값 작성하기
			if (code[0].equals("push")) {
				stack.add(code[1]);
			} else {
				if (code[0].equals("pop")) {
					bw.write((stack.size() == 0 ? "-1" : stack.get(stack.size()-1)));
					if (stack.size() > 0) stack.remove(stack.size()-1);
				} else if (code[0].equals("size")) {
					bw.write(Integer.toString(stack.size()));
				} else if (code[0].equals("empty")) {
					bw.write(stack.size() == 0 ? "1" : "0");
				} else {
					bw.write((stack.size() == 0 ? "-1" : stack.get(stack.size()-1)));
				}
				bw.write("\n");
			}
		}
		bw.flush();
		bw.close();
	}
}

 

문제 결과 메모리 시간 코드 길이
10828 맞았습니다!! 19592 KB 184 ms 1006 B

 

 

 

 

 

 

728x90
728x90
코딩 테스트 풀이 체크리스트
2시간 내에 풀었는가? O
본인의 실력으로 풀었는가? O

 

 

4948번: 베르트랑 공준

베르트랑 공준은 임의의 자연수 n에 대하여, n보다 크고, 2n보다 작거나 같은 소수는 적어도 하나 존재한다는 내용을 담고 있다. 이 명제는 조제프 베르트랑이 1845년에 추측했고, 파프누티 체비쇼

www.acmicpc.net

 

 

 

 

 

import java.io.*;
import java.util.*;
public class Main {
	public static void main(String[] args) throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
	
		//임의의 자연수를 받기 위한 변수		
		int num;

		//시간복잡도를 잡기 위해서 이미 확인한 숫자들은 소수인지 아닌지 boolean으로 구분하며 해시맵에 담아둠
		HashMap<Integer, Boolean> map = new HashMap<>();
		
		//숫자를 받아오면서 바로 num에 담고, 담은 숫자가 0일 때까지 반복
		while ((num = Integer.parseInt(br.readLine())) != 0) {

			//출력용 숫자를 모을 변수
			int result = 0;
			
			//임의의 자연수 n보다 크고, 2n보다 작거나 같아야 하기 때문에 범위는 n+1 ~ 2n까지임
			for (int i = num + 1; i <= 2 * num; i++) {
				//만약 map에 숫자가 없으면
				if (map.getOrDefault(i, null) == null) {
				  //소수인지 파악하기
					boolean check = true;
					for (int j = 2; j <= Math.sqrt(i); j++) {
						if (i % j == 0) {
							check = false;
							break;
						}
					}
					//check가 true이면 소수, false이면 소수가 아닌 숫자
				  //그대로 map에 넣고, result 값도 추가
					map.put(i, check);
					result += check ? 1 : 0;
				} else { //만약 map에 있으면 map의 boolean에 따라 result 값 추가
					result += map.get(i) ? 1 : 0;
				}
			}		
			bw.write(result + "\n");
		}
		
		bw.flush();
		bw.close();
	}
}

 

문제 결과 메모리 시간 코드 길이
4948 맞았습니다!! 218672 KB 648 ms 835 B

 

 

 

 

 

 

728x90
728x90
코딩 테스트 풀이 체크리스트
2시간 내에 풀었는가? O
본인의 실력으로 풀었는가? O

 

 

4673번: 셀프 넘버

셀프 넘버는 1949년 인도 수학자 D.R. Kaprekar가 이름 붙였다. 양의 정수 n에 대해서 d(n)을 n과 n의 각 자리수를 더하는 함수라고 정의하자. 예를 들어, d(75) = 75+7+5 = 87이다. 양의 정수 n이 주어졌을 때,

www.acmicpc.net

 

 

 

 

 

 

import java.io.*;
public class Main {
	public static void main(String[] args) throws IOException{
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		
        //체크용 boolean 배열
		boolean[] list = new boolean[10001];
		
        //1부터 10000까지 d() 함수로 보내고 체크하기
		for (int i = 1; i <= 10000; i++) {
			int num = d(i); //d함수 리턴값 : 정수
            
            //만약 리턴값이 10000보다 작고, 만들어진 적 없는 숫자라면 true로 체크하기
			if (num <= 10000 && !list[num]) list[num] = true;
		}
		
        //1부터 10000까지 방문 기록이 없는 숫자는 출력하기
		for (int i = 1; i < list.length; i++) {
			if (!list[i]) bw.write(i + "\n");
		}
		
		bw.flush();
		bw.close();
	}
	
	public static int d(int num) {
		int result = num;
		while (num > 0) {
			result += (num % 10);
			num /= 10;
		}
		return result;
	}
}

 

문제 결과 메모리 시간 코드 길이
4673 맞았습니다!! 14484 KB 144 ms 592 B

 

 

 

 

 

 

728x90
728x90
코딩 테스트 풀이 체크리스트
2시간 내에 풀었는가? O
본인의 실력으로 풀었는가? O

 

 

1296번: 팀 이름 정하기

연두는 프로그래밍 대회에 나갈 팀 이름을 정하려고 한다. 미신을 믿는 연두는 이환이에게 공식을 하나 받아왔고, 이 공식을 이용해 우승할 확률이 가장 높은 팀 이름을 찾으려고 한다. 이환

www.acmicpc.net

 

 

 

 

 

import java.io.*;
public class Main {
	public static void main(String[] args) throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		String name = br.readLine();
		int nameLength = name.length();
        //연두 이름 기준 L, O, V, E 개수
		int L = nameLength - name.replaceAll("L", "").length();
		int O = nameLength - name.replaceAll("O", "").length();
		int V = nameLength - name.replaceAll("V", "").length();
		int E = nameLength - name.replaceAll("E", "").length();
		
        //팀 개수
		int t = Integer.parseInt(br.readLine());
		
        //확률의 가장 작은 숫자 0과 팀 이름의 사전적으로 가장 마지막인 ZZZZZZZZZZZZZZZZZZZZ로 설정
		int max = 0;
		String result = "ZZZZZZZZZZZZZZZZZZZZ";
		
        //팀 명 하나씩 꺼내면서 확률 측정하기
		for (int i = 0; i < t; i++) {
			String team = br.readLine();
			int teamLength = team.length();
			int tL = teamLength - team.replaceAll("L", "").length();
			int tO = teamLength - team.replaceAll("O", "").length();
			int tV = teamLength - team.replaceAll("V", "").length();
			int tE = teamLength - team.replaceAll("E", "").length();
			
			int total = sum(L+tL, O+tO, V+tV, E+tE);
			
			if (max < total) {
				max = total;
				result = team;
			} else if (max == total) {
				if (result.compareTo(team) > 0) {
					result = team;
				}
			}
		}
		
		System.out.println(result);
	}
	
	public static int sum(int l, int o, int v, int e) {
		return ((l+o) * (l+v) * (l+e) * (o+v) * (o+e) * (v+e)) % 100;
	}
}

 

문제 결과 메모리 시간 코드 길이
1296 맞았습니다!! 14500 KB 140 ms 1360 B

 

 

 

 

 

 

728x90
728x90
코딩 테스트 풀이 체크리스트
2시간 내에 풀었는가? O
본인의 실력으로 풀었는가? O

 

 

1110번: 더하기 사이클

0보다 크거나 같고, 99보다 작거나 같은 정수가 주어질 때 다음과 같은 연산을 할 수 있다. 먼저 주어진 수가 10보다 작다면 앞에 0을 붙여 두 자리 수로 만들고, 각 자리의 숫자를 더한다. 그 다음,

www.acmicpc.net

 

 

 

 

 

 

import java.io.*;
public class Main {
	public static void main(String[] args) throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
        //주어진 숫자
		int n = Integer.parseInt(br.readLine());
		
        //왼쪽 숫자
		int first = n / 10;
		//오른쪽 숫자
        int second = n % 10;
		
        //리턴할 횟수
		int result = 0;
        
        //while문은 계속 반복하다가 조건에 맞으면 탈출할 수 있도록 true 넣기
		while (true) {
			//while문이 시작하자마자 바로 횟수 + 1
            result++;
			
            //왼쪽 숫자와 오른쪽 숫자를 더해서 새로운 숫자를 만들고
			int create = first + second;
			
            //왼쪽 숫자에는 오른쪽 숫자를 재할당
            first = second;
            //오른쪽 숫자에는 새로 만든 숫자의 1의 자리 숫자를 할당
			second = create % 10;
			
            //만약 왼쪽 숫자와 오른쪽 숫자가 처음 주어진 숫자와 동일하다면 break
			if (first == n / 10 && second == n % 10) break;
		}		
		System.out.println(result);
	}
}

 

문제 결과 메모리 시간 코드 길이
1110 맞았습니다!! 14172 KB 124 ms 493 B

 

 

 

 

 

 

728x90
728x90
 

'2021 Dev-Matching: 웹 프론트엔드 개발자(상반기)' 기출 문제 해설

'Dev-Matching 웹 프론트엔드 개발자'의 과제 테스트는 어떠셨나요? 내가 무엇을 잘못하였고, 무엇을 잘했는지 궁금하시지 않으셨나요? 우리 모두 해설을 보고 한번 점검하는 시간을 가지도록 해요.

prgms.tistory.com

 

 

위의 공식 문제 해설을 기반으로 작성한 코드입니다.

제대로 작동이 되지 않아 개인적으로 수정한 내용도 있으며, 추가한 내용도 있습니다.

 

 

▽ 깃허브로 편하게 보기 ▽

 

GitHub - b-sseung/21_DevMatching_1

Contribute to b-sseung/21_DevMatching_1 development by creating an account on GitHub.

github.com

 

 

 

 

📌 index.html

 

<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>고양이 사진첩!</title>
        <link rel="stylesheet" href="./src/styles/style.css">
        <script src="./src/index.js" type="module"></script>
    </head>
    <body>
        <h1>고양이 사진첩</h1>
        <main class="app">
        </main>
  </body>
</html>

 

 

 




📌 index.js

 

import App from './App.js';

new App(document.querySelector('.app'));

 

 

 




📌 App.js

 

import ImageView from './ImageView.js';
import Breadcrumb from './Breadcrumb.js';
import Nodes from './Nodes.js';
import { request } from './api.js';
import Loading from './Loading.js';


const cache = {};

export default function App($app) {
this.state = {
     isRoot: true,
        nodes: [],
        depth: [],
        selectedFilePath: null,
        isLoading: true
    }
    
    const breadcrumb = new Breadcrumb({
     $app,
        initialState: this.state.depth,
        onClick: (index) => {
            if (index === null) {
                this.setState({
                    ...this.state,
                    depth: [],
                    isRoot: true,
                    nodes: cache.root
                })
            } else {
                if (index === this.state.depth.length - 1) return;

                const nextState = {...this.state};
                const nextDepth = this.state.depth.slice(0, index+1);

                this.setState({
                    ...nextState,
                    depth: nextDepth,
                    isRoot: false,
                    nodes: cache[nextDepth[nextDepth.length - 1].id]
                })
            }
        }
    })
    
    const nodes = new Nodes({
     $app,
        initialState: {
         isRoot: this.state.isRoot,
            nodes: this.state.nodes
        },
        onClick: async (node) => {
            try {
                if (node.type === 'DIRECTORY') {
                    if (cache[node.id]) {
                        this.setState({
                            ...this.state,
                            isRoot: false,
                            depth: [...this.state.depth, node],
                            nodes: cache[node.id]
                        });
                    } else {
                        const nextNodes = await request(node.id);
                        this.setState({
                            ...this.state,
                            isRoot: false,
                            depth: [...this.state.depth, node],
                            nodes: nextNodes
                        });
                        cache[node.id] = nextNodes;
                    }
                } else if (node.type === 'FILE') {
                    this.setState({
                        ...this.state,
                        isRoot: false,
                        selectedFilePath: node.filePath
                    })
                }
            } catch (e) {
                //에러처리하기
            }
        },
        onBackClick: async() => {
            try {
                const nextState = {...this.state};
                nextState.depth.pop();

                const prevNodeId = nextState.depth.length === 0 ? null : nextState.depth[nextState.depth.length - 1].id;
                if (prevNodeId === null) {
                    this.setState({
                        ...nextState,
                        isRoot: true,
                        nodes: cache.root
                    })
                } else {
                    this.setState({
                        ...nextState,
                        isRoot: false,
                        nodes: cache[prevNodeId],
                    })
                }
            } catch (e) {
                //에러 처리
            }
        }
    })

    const imageView = new ImageView({
        $app,
        initialState: this.state.selectedNodeImage,
        onClick: async () => {
            this.setState({
                selectedFilePath: null
            })
        }
    })

    const loading = new Loading({
        $app,
        initialState: this.state.isLoading
    });

    this.setState = (nextState) => {
        this.state = nextState;
        breadcrumb.setState(this.state.depth);
        nodes.setState({
            isRoot: this.state.isRoot,
            nodes: this.state.nodes
        });
        imageView.setState(this.state.selectedFilePath);
        loading.setState(this.state.isLoading);
        this.state.selectedFilePath = null;
    }

    const init = async () => {
        try {
            const rootNodes = await request();
            this.setState({
                ...this.state,
                isRoot: this.state.isRoot,
                nodes: rootNodes,
                isLoading: false
            });

            cache.root = rootNodes;
        } catch (e) {
            //에러처리 하기
        }
    }

    init();
}

 

 

 




📌 Nodes.js

 

export default function Nodes({ $app, initialState, onClick, onBackClick }) {
this.state = initialState;
    this.$target = document.createElement('ul');
    this.$target.className = 'Nodes';
    $app.appendChild(this.$target);
    
    this.setState = (nextState) => {
     this.state = nextState;
        this.render();
    }
    
    this.onClick = onClick;
    this.onBackClick = onBackClick;
    
    this.render = () => {
     if (this.state.nodes) {
            const nodesTemplate = this.state.nodes.map(node => {
                const iconPath = node.type === 'FILE' ? './assets/file.png' : './assets/directory.png';
                
                return `
                    <div class="Node" data-node-id="${node.id}">
                        <img src="${iconPath}"/>
                        <div>${node.name}</div>
                    </div>
                `
            }).join('');
            this.$target.innerHTML = this.state.isRoot ? nodesTemplate : `<div class="Node"><img src="./assets/prev.png"></div>${nodesTemplate}`;
        }
    };

    this.$target.addEventListener('click', (e) => {
        const $node = e.target.closest('.Node');
        if ($node) {
            const { nodeId } = $node.dataset;
            if (!nodeId) this.onBackClick();
            
            const selectedNode = this.state.nodes.find(node => node.id === nodeId)
            if (selectedNode) this.onClick(selectedNode);
        
        }    
        
    })
    
    this.render();
}

 

 

 




📌 Breadcrumb.js

 

export default function Breadcrumb({ $app, initialState, onClick }) {
this.state = initialState;
    
    this.$target = document.createElement('nav');
    this.$target.className = 'Breadcrumb';
    $app.appendChild(this.$target);

    this.onClick = onClick;

    this.setState = nextState => {
     this.state = nextState;
        this.render();
    }
    
    this.render = () => {
        console.log("호출");
     this.$target.innerHTML = 
         `<div class="nav-item">root</div>${
         this.state.map(
             (node, index) => 
                        `<div class="nav-item" data-index="${index}">${node.name}</div>`
         ).join('')}`;
    }

    this.$target.addEventListener('click', (e) => {
        const $navItem = e.target.closest('.nav-item');

        if ($navItem) {
            const { index } = $navItem.dataset;
            this.onClick(index ? parseInt(index, 10) : null);
        }
    })

    this.render();
}

 

 

 


 

📌 ImageView.js

 

const IMAGE_PATH_PREFIX = 'https://fe-dev-matching-2021-03-serverlessdeploymentbuck-t3kpj3way537.s3.ap-northeast-2.amazonaws.com/public'

export default function ImageView({ $app, initialState, onClick }) {
    this.state = initialState;
    this.$target = document.createElement('div');
    this.$target.className = 'Modal ImageView';

    $app.appendChild(this.$target);
    this.onClick = onClick;
    this.setState = (nextState) => {
        this.state = nextState;
        this.render();
    }

    this.render = () => {
        console.log(this.state);
        this.$target.innerHTML = `<div class="content">${this.state ? `<img src="${IMAGE_PATH_PREFIX}${this.state}">` : '' }</div>`
        this.$target.style.display = this.state ? 'block' : 'none';
    }

    this.$target.addEventListener('click', (e) => {
        this.$target.style.display = 'none';
    })
    this.render();
}

 

 

 


 


📌 api.js

 

const API_END_POINT = 'https://zl3m4qq0l9.execute-api.ap-northeast-2.amazonaws.com/dev';

export const request = async (nodeId) => {
    try {
        const res = await fetch(`${API_END_POINT}/${nodeId ? nodeId : ''}`);

        if (!res.ok) {
            throw new Error('서버의 상태가 이상합니다!');
        }

        return await res.json();
    } catch (e) {
        throw new Error(`무언가 잘못 되었습니다! ${e.message}`);
    }
}

 

 

 

 


 

📌 Loading.js

 

export default function Loading({ $app, initialState }) {
  this.state = initialState;
  this.$target = document.createElement('div');
  this.$target.className = "Loading Modal";

  $app.appendChild(this.$target);

  this.setState = (nextState) => {
    this.state = nextState;
    this.render();
  }

  this.render = () => {
    this.$target.innerHTML = `<div class="content"><img src="./assets/nyan-cat.gif"></div>`;
    this.$target.style.display = this.state ? 'block' : 'none';
  }

  this.render();
}



 

 

 

 

 

728x90
728x90
코딩 테스트 풀이 체크리스트
2시간 내에 풀었는가? X
본인의 실력으로 풀었는가? O

 

 

20551번: Sort 마스터 배지훈의 후계자

지훈이는 Sort 마스터다. 오랫동안 Sort 마스터 자리를 지켜온 지훈이는 이제 마스터 자리를 후계자에게 물려주려고 한다. 수많은 제자들 중에 후계자를 고르기 위해서 지훈이는 제자들에게 문제

www.acmicpc.net

 

 

 

 

 

 

import java.io.*;
public class Main {
	public static void main(String[] args) throws IOException{
    	//입출력 객체들 선언
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        
        
       	//가장 첫 번째 줄은 배열의 길이와 질문의 개수가 나옴
        //띄어쓰기로 구분되어 있기 때문에
        //읽어 들이면서 split()으로 구분
		String[] nm = br.readLine().split(" ");
		
        //첫 번째 줄 숫자로 변환
		int n = Integer.parseInt(nm[0]);
		int m = Integer.parseInt(nm[1]);
		
        //배열 a 선언
		int[] a = new int[n];
        
        //입력 순서대로 정수로 변환하면서 배열 채우기
		for (int i = 0; i < n; i++) {
			a[i] = Integer.parseInt(br.readLine());
		}
		
        //퀵 정렬 호출
		quick(a, 0, a.length-1);
		
		for (int i = 0; i < m; i++) {
			bw.write(check(Integer.parseInt(br.readLine()), a, 0, a.length-1) + "\n");
		}
		
		bw.flush();
		bw.close();
	}
	
	public static int check(int num, int[] a, int start, int end) {
		while (start+1 < end) {
			int mid = (start + end) / 2;
			
			if (a[mid] >= num) {
				end = mid;
			} else {
				start = mid;
			}
		}
		
		return a[start] == num ? start : a[end] == num ? end : -1;
	}
	
    //퀵 정렬 함수
	public static void quick(int[] a, int start, int end) {
    	//cutting 함수 호출 - 리턴값 정수
		int cut = cutting(a, start, end);
        
        
		if (start < cut-1) quick(a, start, cut-1);
		if (cut < end) quick(a, cut, end);
	}
	
	public static int cutting(int[] a, int start, int end) {
    	//중간 위치와 중간 위치의 값인 피벗 선언하기
		int mid = (start + end) / 2;
		int pivot = a[mid];
		
        //start가 end보다 작거나 같을 때까지 반복
		while (start <= end) {
        	//start위치의 값이 피벗보다 큰 경우까지 탐색
			while (a[start] < pivot) start++;
            
            //end위치의 값이 피벗보다 작은 경우까지 탐색
			while (a[end] > pivot) end--;
			
            //만약 start가 end보다 작거나 같으면 두 위치의 숫자 바꾸기
            //그리고 그 다음 위치로 각각 이동
			if (start <= end) {
				change(a, start, end);
				start++;
				end--;
			}
		}
		
		return start;
	}
	
    //두 위치 간의 숫자 바꾸는 함수
    public static void change(int[] a, int n1, int n2) {
		int temp = a[n1];
		a[n1] = a[n2];
		a[n2] = temp;
	}
}

 

문제 결과 메모리 시간 코드 길이
20551 맞았습니다!! 53696 KB 716 ms 1530 B

 

 

 

 

 

 

728x90
728x90
코딩 테스트 풀이 체크리스트
2시간 내에 풀었는가? O
본인의 실력으로 풀었는가? O

 

 

2439번: 별 찍기 - 2

첫째 줄에는 별 1개, 둘째 줄에는 별 2개, N번째 줄에는 별 N개를 찍는 문제 하지만, 오른쪽을 기준으로 정렬한 별(예제 참고)을 출력하시오.

www.acmicpc.net

 

 

 

 

 

import java.io.*;
public class Main {
	public static void main(String[] args) throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        //숫자 가져오기
		int n = Integer.parseInt(br.readLine());
		
        //1부터 n번째 줄까지 줄 기준 for문
		for (int i = 1; i <= n; i++) {
        	//줄에 맞춰서 * 작성하는 for문
			for (int j = 1; j <= n; j++) {
            	//오른쪽 정렬을 위해 만약 n-j가 i보다 작을 경우 *, 아니면 띄어쓰기 입력
                //System.out.print는 줄 바꿈 안함
				if (n-j < i) System.out.print("*"); else System.out.print(" ");
			}
            //System.out.println은 줄 바꿈
			System.out.println("");
		}
	}
}

 

 

문제 결과 메모리 시간 코드 길이
2439 맞았습니다!! 15376 KB 264 ms  395 B

 

 

 

 

 

 

728x90

+ Recent posts