// 프로그래머스: 가위 바위 보
// 문자열 rsp의 각 글자(가위2/바위0/보5)를 이기는 패로 변환하여 반환
// 핵심 개념: 문자열 순회, 조건 분기(switch), 동적 메모리 할당(malloc)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* solution(const char* rsp) {
int len = strlen(rsp); // 입력 문자열 길이 저장
char* answer = (char*)malloc(len + 1); // 결과 문자열 메모리 할당 (+1은 '\0' 자리)
answer[len] = '\0'; // 문자열 끝 표시 (널 문자)
for (int i = 0; i < len; i++) { // 문자열을 한 글자씩 순회
switch (rsp[i]) {
case '2': // 가위(2) → 바위(0)로 이김
answer[i] = '0';
break;
case '0': // 바위(0) → 보(5)로 이김
answer[i] = '5';
break;
case '5': // 보(5) → 가위(2)로 이김
answer[i] = '2';
break;
}
}
return answer;
}
// 테스트용 main 함수
int main() {
printf("%s\n", solution("2")); // 출력: 0
printf("%s\n", solution("205")); // 출력: 052
return 0;
}
// 프로그래머스: 암호 해독
// cipher에서 code의 배수 번째 글자만 추출하여 반환
// 핵심 개념: 문자열 인덱싱, 나머지 연산(%), 동적 메모리 할당(malloc)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* solution(const char* cipher, int code) {
int len = strlen(cipher); // 암호 문자열 길이
int result_len = len / code; // 결과 문자열 길이 (배수 개수)
char* answer = (char*)malloc(result_len + 1); // 결과 저장 공간 할당
answer[result_len] = '\0'; // 문자열 끝 표시
int idx = 0; // answer에 저장할 위치
// i는 1부터 시작 (문제에서 "1번째 글자"부터 셈)
for (int i = 1; i <= len; i++) {
if (i % code == 0) { // code의 배수 번째 글자인지 확인
answer[idx] = cipher[i - 1]; // 배열 인덱스는 0부터라 -1 필요
idx++;
}
}
return answer;
}
// 테스트용 main 함수
int main() {
printf("%s\n", solution("dfjardstddetckdaccccdegk", 4)); // 출력: cock
printf("%s\n", solution("pfqallllabwaoclk", 2)); // 출력: fallback
return 0;
}
// 프로그래머스: 배열 회전시키기
// direction("left"/"right")에 따라 배열을 한 칸 회전시켜 반환
// 핵심 개념: 배열 복사, 문자열 비교(strcmp), 동적 메모리 할당(malloc)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int* solution(int numbers[], size_t numbers_len, const char* direction) {
// 결과 배열 메모리 할당 (int 크기 * 배열 길이)
int* answer = (int*)malloc(sizeof(int) * numbers_len);
if (strcmp(direction, "right") == 0) { // "right" 회전
// 마지막 원소를 맨 앞에 저장
answer[0] = numbers[numbers_len - 1];
// 나머지 원소를 한 칸씩 오른쪽으로 밀기
for (int i = 1; i < numbers_len; i++) {
answer[i] = numbers[i - 1]; // 원래 i-1번째 → i번째로
}
} else { // "left" 회전
// 첫 번째 원소를 맨 뒤에 저장
answer[numbers_len - 1] = numbers[0];
// 나머지 원소를 한 칸씩 왼쪽으로 밀기
for (int i = 0; i < numbers_len - 1; i++) {
answer[i] = numbers[i + 1]; // 원래 i+1번째 → i번째로
}
}
return answer;
}
// 테스트용 main 함수
int main() {
int arr1[] = {1, 2, 3};
int* r1 = solution(arr1, 3, "right");
for (int i = 0; i < 3; i++) printf("%d ", r1[i]); // 출력: 3 1 2
printf("\n");
int arr2[] = {4, 455, 6, 4, -1, 45, 6};
int* r2 = solution(arr2, 7, "left");
for (int i = 0; i < 7; i++) printf("%d ", r2[i]); // 출력: 455 6 4 -1 45 6 4
printf("\n");
free(r1); // 동적 할당한 메모리 해제
free(r2);
return 0;
}