Menu
CoddyTech

최종: C 장부

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

challenge icon

챌린지

쉬움

입력은 0개 이상의 name quantity 행으로 구성됩니다. 이름은 소문자 ASCII 문자이고 수량은 부호가 있는 정수입니다. 각 이름별로 합계를 구하고, 0 이하인 합계는 제외한 다음, 이름을 알파벳순으로 정렬한 name:total 행을 반환하세요. 남는 항목이 없으면 empty를 반환하세요. 모든 중간 합계는 int 범위에 들어갑니다.

Exercise.solve(List<String> input)에서 마지막 개행 없이 정확한 결과 텍스트를 반환하세요. 표시된 잠금 상태의 Main.java는 모든 입력 행을 읽고 반환된 텍스트를 마지막 개행 하나와 함께 출력합니다. 편집 가능한 메서드 안에서는 출력하지 마세요. 달리 명시되지 않는 한 모든 정수와 산술 연산 결과는 Java int 범위에 들어갑니다.

편집 가능한 파일: Exercise.java, Text.java. Text.java는 재사용 가능한 파싱 및 형식 지정 도우미를 제공합니다. 모든 파일은 이름 없는 패키지에 있으며 함께 컴파일됩니다. Main.java만이 진입점이며 편집할 수 없습니다.

다음 C 참조 알고리즘을 필요한 Java 구현으로 포팅하세요. 합산, 이름 정렬, 0 이하인 합계 제거를 유지하세요. 함께 제공된 소스 프로그램은 동일한 다섯 개 입력 테스트 데이터에 대해 실행되었습니다.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <stdint.h>

struct Entry { char *name; int total; };

static void *resize(void *p,size_t bytes) {
    void *result=realloc(p,bytes);
    if(!result) { free(p); exit(1); }
    return result;
}
static char *read_word(void) {
    int ch;
    do { ch=getchar(); } while(ch!=EOF && isspace((unsigned char)ch));
    if(ch==EOF) return NULL;
    size_t size=0,capacity=32;
    char *word=resize(NULL,capacity);
    do {
        if(size+1==capacity) {
            if(capacity>SIZE_MAX/2) exit(1);
            capacity*=2;
            word=resize(word,capacity);
        }
        word[size++]=(char)ch;
        ch=getchar();
    } while(ch!=EOF && !isspace((unsigned char)ch));
    word[size]='\0';
    return word;
}
static int compare_entries(const void *a,const void *b) {
    return strcmp(((const struct Entry *)a)->name,
                  ((const struct Entry *)b)->name);
}
int main(void) {
    struct Entry *entries=NULL;
    size_t size=0,capacity=0;
    char *name;
    while((name=read_word())!=NULL) {
        char *quantity=read_word(),*end;
        if(!quantity) return 1;
        errno=0;
        long parsed=strtol(quantity,&end,10);
        if(errno==ERANGE || end==quantity || *end!='\0'
           || parsed<INT_MIN || parsed>INT_MAX) return 1;
        free(quantity);
        size_t i=0;
        while(i<size && strcmp(entries[i].name,name)!=0) i++;
        if(i==size) {
            if(size==capacity) {
                size_t next=capacity ? capacity*2 : 8;
                if(next<capacity || next>SIZE_MAX/sizeof *entries) return 1;
                entries=resize(entries,next*sizeof *entries);
                capacity=next;
            }
            entries[size++]=(struct Entry){name,0};
        } else {
            free(name);
        }
        entries[i].total+=(int)parsed;
    }
    if(size>1) qsort(entries,size,sizeof *entries,compare_entries);
    int any=0;
    for(size_t i=0;i<size;i++) {
        if(entries[i].total>0) {
            printf("%s:%d\n",entries[i].name,entries[i].total);
            any=1;
        }
        free(entries[i].name);
    }
    if(!any) puts("empty");
    free(entries);
    return 0;
}

직접 해보기

import java.io.*;
import java.util.*;
public class Main {
    private static void check(boolean condition) {
        if (!condition) throw new AssertionError("Required public API behavior failed");
    }
    public static void main(String[] args) throws Exception {
        List<String> input = new ArrayList<>();
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String line;
        while ((line = reader.readLine()) != null) input.add(line);
        
        System.out.println(Exercise.solve(input));
    }
}

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

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