Menu
CoddyTech

最終課題:C台帳

Coddyの「C開発者のためのJava」コースのレッスン 47/48。

challenge icon

チャレンジ

簡単

入力は、0 行以上のname quantityです。名前は小文字の ASCII 文字、数量は符号付き整数です。名前ごとに合計し、合計が 0 以下のものを除外して、アルファベット順に並べたname:totalの行を返します。残るものがなければ、empty を返します。すべての中間合計は int に収まります。

Exercise.solve(List<String> input)から、末尾に改行を付けずに結果のテキストをそのまま返してください。表示されている編集不可のMain.javaは、すべての入力行を読み取り、返されたテキストを末尾に改行を1つ付けて出力します。編集可能なメソッド内で出力しないでください。特に明記されていない限り、すべての整数と算術演算の結果は Java のintに収まります。

編集可能なファイル:Exercise.java、Text.java。Text.javaには、再利用可能な解析および書式設定用のヘルパーが用意されています。すべてのファイルは名前のないパッケージに属し、まとめてコンパイルされます。Main.javaが唯一のエントリポイントであり、編集できません。

以下の C の参照アルゴリズムを、指定された Java 実装に移植してください。集計、名前の並べ替え、0 以下の合計の除外を維持してください。付属のソースプログラムは、同じ5つの入力フィクスチャに対して実行されました。

#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オンラインコンパイラ