728x90
반응형

심심하니까 푸는 프로그래머스 코테 문제

 

이번에 푼 문제는 '완주하지 못한 선수'

 

코딩테스트 연습 - 완주하지 못한 선수

수많은 마라톤 선수들이 마라톤에 참여하였습니다. 단 한 명의 선수를 제외하고는 모든 선수가 마라톤을 완주하였습니다. 마라톤에 참여한 선수들의 이름이 담긴 배열 participant와 완주한 선수

programmers.co.kr

문제 캡쳐본

예전에 한 번 C++로 풀어봤다. 이런저런 방법으로 풀다가 결국 해설을 봤던 것 같다.

#include <string>
#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

string solution(vector<string> participant, vector<string> completion) {
    string answer = "";
    sort(participant.begin(), participant.end());
    sort(completion.begin(), completion.end());
    
    for(int i = 0; i < participant.size(); i++){
        if(participant[i] != completion[i])
            return participant[i];
    }

    return participant[participant.size()];
}

 


 

이번에 고랭으로 풀어보려고 했는데 C++로 어떻게 풀었는지 이미 봐버려서 그대로 풀어버렸습니다 ㅠㅠ  근데 이 문제는 고랭은 지원하지 않아서 그냥 맞겠지 하고 풀었어요 ㅎㅎ

package main

import (
	"fmt"
	"sort"
)

func solution(participant []string, completion []string) string {
	sort.Strings(participant)
	sort.Strings(completion)
	
	for i:=0; i < len(completion); i++{
		if(participant[i] != completion[i]){
			return participant[i]
		}
	}
	return participant[len(participant)-1]
}

func main() {
	participant := []string{"leo", "kiki", "eden"}
	completion := []string{"eden", "kiki"}
	ret := solution(participant, completion)
	fmt.Println(ret)
}

sort 내장 모듈을 지원해주니 이 모듈을 사용했고 정확히 C++로 푼 방법과 똑같이 풀어버렸습니다 ㅋㅋㅋ 그래도 고랭 익숙해지는 거라고 생각하면 여전히 문제 풀어보는 건 좋지요!

728x90
반응형
728x90
반응형

프로그래머스 level1 문자열 다루기 기본 golang 풀이

 

요즘에는 golang을 공부하고 있다. 간단하게 프로그래머스 쉬운 문제들을 풀어보고 있는데 syntax에 익숙하지 않으니 좀 어렵기도 하다.

 

제일 쉬워보이는 문제 풀면서 문자열 좀 익숙해 지려고 해봤다. 아래는 문제 캡쳐이고,

 

아래는 내가 아스키 코드 사용하여 풀이한 코드이다. 아스키 코드 모를 때는 직접 찍어보면 된다. 다른 모듈 Import한 것 없이 길이 확인하고 숫자만 있는지 확인하고 return해준다.

func solution(s string) bool {
    if len(s) == 4 || len(s) == 6{
        for i := 0; i < len(s); i++ {
            if 48 <= s[i] && s[i] <= 57 {
                continue
            } else{
                return false
            }
        }
    }else{
        return false
    }
    return true
}

 

아래는 다른 사람의 풀이인데 strconv라는 모듈을 Import 하여 풀었다. C언어에서도 많이 봤듯이 atoi 사용하여 string to int 해주었다. 그리고 err 변수 사용하여 에러 있는지도 받아주어 에러 메시지가 들어오면 return false해주고 아니라면 true 하여 간단하게 구현했다.

import "strconv"

func solution(s string) bool {
    _, err := strconv.Atoi(s)
    if err != nil || len(s) != 4 && len(s) != 6 {return false}
    return true
}

 

고랭은 어려워~.~

728x90
반응형
728x90
반응형

programmers.co.kr/learn/courses/30/lessons/12939

 

코딩테스트 연습 - 최댓값과 최솟값

문자열 s에는 공백으로 구분된 숫자들이 저장되어 있습니다. str에 나타나는 숫자 중 최소값과 최대값을 찾아 이를 (최소값) (최대값)형태의 문자열을 반환하는 함수, solution을 완성하세요. 예를

programmers.co.kr

 

#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <cstdlib>
#include <stdlib.h>

using namespace std;

vector<string> split(string input, char delimiter) {
    vector<string> answer;
    stringstream ss(input);
    string temp;

    while (getline(ss, temp, delimiter)) {
        answer.push_back(temp);
    }
    return answer;
}

string solution(string s) {
    string answer = "";
    vector<string> nums = split(s, ' ');
    vector<int> num;
    int max = -9874;
    int min = 9874;

    for(int i= 0; i < nums.size(); i++){
        num.push_back(atoi(nums[i].c_str()));
        if(num[i] > max)
            max = num[i];
        if(num[i] < min)
            min = num[i];
    }
    answer = to_string(min) + " " + to_string(max);
    return answer;
}
728x90
반응형
728x90
반응형

라인플러스 2019 상반기 인턴 채용 코딩테스트 

 

문제 해설 링크

 

2019년 상반기 LINE 인턴 채용 코딩테스트 문제 해설 - LINE ENGINEERING

LINE에서 개발 직군을 뽑을 때 신입이든 경력이든 가장 먼저 보는 것이 코딩 테스트입니다. LINE의 코딩 테스트는 일반적인 알고리즘 경진대회와는 경향이 조금 다른데요. 알고리즘 경진대회는 1��

engineering.linecorp.com

 

from collections import deque
def solution(conyPosition, brownPosition):
    time = 0
    visit = [[0]*2 for _ in range(200001)]
    q = deque()
    q.append((brownPosition, 0))
    
    while 1:
        conyPosition += time
        if conyPosition > 200000 or conyPosition < 0:
            return -1
        if visit[conyPosition][time%2]:
            return time
        for i in range(0, len(q)):
            current = q.popleft()
            currentPosition = current[0]
            newTime = (current[1]+1)%2
            
            newPosition = currentPosition - 1
            if newPosition >= 0 and not visit[newPosition][newTime]:
                visit[newPosition][newTime] = True
                q.append((newPosition, newTime))
            newPosition  = currentPosition + 1
            if newPosition < 200001 and not visit[newPosition][newTime]:
                visit[newPosition][newTime] = True
                q.append((newPosition, newTime))
            newPosition = currentPosition * 2
            if newPosition < 200001 and not visit[newPosition][newTime]:
                visit[newPosition][newTime] = True
                q.append((newPosition, newTime))
        time += 1
728x90
반응형
728x90
반응형

프로그래머스 연습문제

 

안녕하세요 :) 

오늘 가지고 온 문제는 카카오 인턴십 문제입니다. 

카카오 문제 치고 굉장히 쉬운 편에 속하는데요, 저는 좀 지저분하게 풀었습니다

문제 링크
 

코딩테스트 연습 - 키패드 누르기

[1, 3, 4, 5, 8, 2, 1, 4, 5, 9, 5] "right" "LRLLLRLLRRL" [7, 0, 8, 2, 8, 3, 1, 5, 7, 6, 2] "left" "LRLLRRLLLRR" [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] "right" "LLRLLRLLRL"

programmers.co.kr

 

문제에 나온 조건에만 맞추면 되는 쉬운 문제였습니다 ㅎㅎ 아래에 바로 코드 올려요!

from collections import deque
def checkLeft(num):
    possible = ['1', '4', '7', '2', '5', '8', '0']
    if num in possible:
        return True
    return False
def checkRight(num):
    possible = ['2', '5', '8', '0', '3', '6', '9']
    if num in possible:
        return True
    return False

def solution(numbers, hand):
    answer = ''
    numbers = deque(numbers)

    pads = {'1': (0, 0), '2': (0, 1), '3': (0, 2),
            '4': (1, 0), '5': (1, 1), '6': (1, 2),
            '7': (2, 0), '8': (2, 1), '9': (2, 2),
            '*': (3, 0), '0': (3, 1), '#': (3, 2)}
    
    left = pads['*']
    right = pads['#']
    for num in numbers:
        num = str(num)
        if checkLeft(num) and not checkRight(num):
            answer  += 'L'
            left = pads[num]
        elif not checkLeft(num) and checkRight(num):
            answer += 'R'
            right = pads[num]
        elif checkLeft(num) and checkRight(num): 
            leftDist = abs(pads[num][0] - left[0]) + abs(pads[num][1] - left[1])
            rightDist = abs(pads[num][0] - right[0]) + abs(pads[num][1] - right[1])
            if leftDist < rightDist:
                answer += 'L'
                left = pads[num]
            elif rightDist < leftDist:
                answer += 'R'
                right = pads[num]
            elif rightDist == leftDist:
                if hand == 'right':
                    answer += 'R'
                    right = pads[num]
                if hand == 'left':
                    answer += 'L'
                    left = pads[num]
    return answer

좀 지저분하긴 하네요..

 

그럼 이만 ㅎㅎ

728x90
반응형
728x90
반응형

프로그래머스 문제

 

안녕하세요! 왠지 오늘은 하나 더 풀고싶어서 풀어봤습니다!

프로그래머스에서 진행한 월간코드첼린지라는 게 있더라구요. 여기서 기출한 문제입니다.

문제링크

 

이 문제도 어렵지 않았는데, 파이썬으로 풀면 정말 쉬운 문제 유형인 것 같습니다.

중복 제거용으로 set 써주었고 sort 사용하여 정렬까지 해 주었습니다.

def solution(numbers):
    answer = []
    n2 = numbers.copy()
    for i in range(len(numbers)):
        for j in range(len(numbers)):
            if i == j:
                continue
            answer.append(numbers[i] + numbers[j])
    answer = list(set(answer))
    answer.sort()
    return answer

그럼 이만~!

728x90
반응형

+ Recent posts