MoyaSystem

もやしです。

新人プログラマの女の子を手伝ってみた

新人女子プログラマの書いたコードを直すだけの簡単なお仕事をやってみました。めでたくランクSを獲得。よかった。
使える言語の中でまともに書けそうなのがJavaしかなかったのでJavaで挑戦。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class Main {
    public static void main (String[] args) {
        // Java sun-jdk-1.7.0_10
    try {
    		int n; // 商品個数
    		int d; // キャンペーン日数
    		ArrayList<Integer> itemPrices = new ArrayList<Integer>();
    		ArrayList<Integer> campaignPrices = new ArrayList<Integer>();

    		BufferedReader br =
    			new BufferedReader(new InputStreamReader(System.in));
    		String s = br.readLine();
    		n = new Integer(s.split(" ")[0]);
    		d = new Integer(s.split(" ")[1]);

    		for(int i=0;i<n;i++){
    			itemPrices.add(new Integer(br.readLine()));
            }

    		for(int j=0;j<d;j++){
    			campaignPrices.add(new Integer(br.readLine()));
    		}

    		for(int k=0;k<campaignPrices.size();k++){
    			int bestPrice = 0; // 条件を満たす最大価格
    			int canpaignPrice = campaignPrices.get(k);
    			for(int index=0;index<itemPrices.size()-1;index++){
    				int price = itemPrices.get(index);
    				if(canpaignPrice <= price) continue; // キャンペーン価格が商品価格以下の場合、次の商品に移動
    				for(int anotherIndex=index+1;anotherIndex<itemPrices.size();anotherIndex++){
    					// 別の商品との合計金額を計算
    					int anotherPrice = itemPrices.get(anotherIndex);
    					int totalPrice = price + anotherPrice;
    					if(totalPrice == canpaignPrice){
    						bestPrice = totalPrice;
    						continue; // 条件を満たす最大価格がキャンペーン価格と等しい場合、即出力
    					}
    					if(totalPrice < canpaignPrice && totalPrice > bestPrice){
    						bestPrice = totalPrice; // 最大価格を更新
    					}
    				}
    				if(bestPrice == canpaignPrice) break; // 条件を満たす最大価格がキャンペーン価格と等しい場合、ループを抜け即出力
    			}
    			System.out.println(bestPrice);
    		}
    } catch (Exception e) {
    		System.err.println("Error:" + e.getMessage());
    	}
    }
}

パフォーマンス改善のために注意したところは

  • 商品金額 >= キャンペーン金額 の場合は組み合わせ候補から即外れるので次の要素に移動
  • 組み合わせの確認は、インデックスがiの商品に対してi+1以上の商品との組み合わせのみ確認するロジックとし、確認の重複を回避
  • 合計金額 = キャンペーン金額 となった場合はループを抜けて即出力

こんなところでしょうか。まだ改善の余地があるのかよくわかりませんが、僕のコードで野田さんが救われたことを祈ります。