Menu
CoddyTech

최종: 큐 모델 이식하기

Coddy의 C 개발자를 위한 PHP 코스 레슨. 48개 중 48번째.

challenge icon

챌린지

쉬움

입력은 [initial,operations] 형식입니다. 이 과제에 제공된 소스 참조 프로그램을 이식하세요. WorkQueue(initial array)는 문자열 항목을 저장합니다. push(string):void는 항목을 추가하며, pop():?string은 가장 오래된 항목을 제거하여 반환하고 비어 있을 때는 null을 반환합니다. size():int는 남은 개수를 반환합니다. 작업은 [push,text] 또는 [pop] 형식입니다. 드라이버는 pop한 값을 쉼표로 구분하여 출력하고, null 대신 EMPTY를 사용하며, 그 뒤에 |size를 붙여 출력합니다. 입력 항목은 ASCII 문자로만 구성됩니다.

제공된 메인 스크립트는 표준 입력에서 하나의 JSON 값을 읽어 지정된 퍼블릭 API를 확인하고 결과를 출력합니다. 출력 없이 모듈 선언을 구현하세요. 런처를 교체하거나 모듈에서 입력을 읽지 마세요. 입력은 명시된 타입과 범위를 충족합니다.

WorkQueue.php를 편집하세요. main.php는 잠긴 엔트리 파일입니다. 의존성은 상대 파일 이름과 함께 require_once __DIR__를 사용합니다.

C 참조 프로그램

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
struct WorkQueue { char **items; size_t count; };
static int queue_push(struct WorkQueue *queue, const char *text) {
    size_t length = strlen(text);
    if (length == SIZE_MAX || queue->count >= SIZE_MAX / sizeof *queue->items) return 0;
    char *copy = malloc(length + 1);
    if (copy == NULL) return 0;
    memcpy(copy, text, length + 1);
    char **grown = realloc(queue->items, (queue->count + 1) * sizeof *queue->items);
    if (grown == NULL) { free(copy); return 0; }
    queue->items = grown;
    queue->items[queue->count++] = copy;
    return 1;
}
/* A successful pop transfers ownership to the caller; NULL means empty. */
static char *queue_pop(struct WorkQueue *queue) {
    if (queue->count == 0) return NULL;
    char *first = queue->items[0];
    --queue->count;
    memmove(queue->items, queue->items + 1, queue->count * sizeof *queue->items);
    return first;
}
static size_t queue_size(const struct WorkQueue *queue) { return queue->count; }
static void queue_destroy(struct WorkQueue *queue) {
    for (size_t i = 0; i < queue->count; ++i) free(queue->items[i]);
    free(queue->items);
    *queue = (struct WorkQueue){NULL, 0};
}
static int queue_init(struct WorkQueue *queue, const char *const *initial, size_t count) {
    *queue = (struct WorkQueue){NULL, 0};
    for (size_t i = 0; i < count; ++i) {
        if (!queue_push(queue, initial[i])) { queue_destroy(queue); return 0; }
    }
    return 1;
}
int main(void) {
    const char *initial[] = {"a", "b"};
    struct WorkQueue queue;
    if (!queue_init(&queue, initial, 2)) return 1;
    char *first = queue_pop(&queue);
    if (!queue_push(&queue, "c")) { free(first); queue_destroy(&queue); return 1; }
    char *second = queue_pop(&queue);
    printf("%s,%s|%zu\n", first ? first : "EMPTY", second ? second : "EMPTY", queue_size(&queue));
    free(first); free(second); queue_destroy(&queue);
    return ferror(stdout) ? 1 : 0;
}

직접 해보기

<?php
declare(strict_types=1);
require_once __DIR__."/WorkQueue.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}
function queueReport(array $i):string{$q=new WorkQueue($i[0]);$out=[];foreach($i[1] as $op){if($op[0]==="push")$q->push($op[1]);else $out[]=$q->pop()??"EMPTY";}return implode(",",$out)."|".$q->size();}
$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
$a=new WorkQueue(["a"]);$b=new WorkQueue([]);ensure($a->pop()==="a" && $a->pop()===null && $b->size()===0,"queue independence");$a->push("z");ensure($a->size()===1 && $a->pop()==="z","queue API");
echo queueReport($input),"\n";

C 개발자를 위한 PHP의 모든 레슨

직접 연습해 보세요: 온라인 PHP 컴파일러