package template;

import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;

public class TestCase {

    private boolean isSolved;
    private Object solution;
    private Map<String, Integer> intProperties;
    private Map<String, ArrayList<Integer>> intArrayProperties;
    private Map<String, ArrayList<ArrayList<Integer>>> intArray2DProperties;
    private Map<String, Double> doubleProperties;
    private Map<String, ArrayList<Double>> doubleArrayProperties;
    private Map<String, ArrayList<ArrayList<Double>>> doubleArray2DProperties;
    private Map<String, String> stringProperties;
    private Map<String, ArrayList<String>> stringArrayProperties;
    private Map<String, ArrayList<ArrayList<String>>> stringArray2DProperties;
    private Map<String, Boolean> booleanProperties;
    private Map<String, ArrayList<Boolean>> booleanArrayProperties;
    private Map<String, ArrayList<ArrayList<Boolean>>> booleanArray2DProperties;
    private Map<String, Long> longProperties;
    private Map<String, ArrayList<Long>> longArrayProperties;
    private Map<String, ArrayList<ArrayList<Long>>> longArray2DProperties;
    private int ref;
    private double time;

    public TestCase() {
        initialise();
    }

    private void initialise() {
        isSolved = false;
        intProperties = new HashMap<>();
        intArrayProperties = new HashMap<>();
        intArray2DProperties = new HashMap<>();
        doubleProperties = new HashMap<>();
        doubleArrayProperties = new HashMap<>();
        doubleArray2DProperties = new HashMap<>();
        stringProperties = new HashMap<>();
        stringArrayProperties = new HashMap<>();
        stringArray2DProperties = new HashMap<>();
        booleanProperties = new HashMap<>();
        booleanArrayProperties = new HashMap<>();
        booleanArray2DProperties = new HashMap<>();
        longProperties = new HashMap<>();
        longArrayProperties = new HashMap<>();
        longArray2DProperties = new HashMap<>();
        ref = 0;
    }

    public void setSolution(Object o) {
        solution = o;
        isSolved = true;
    }
    
    public Object getSolution() {
        if (!isSolved) {
            Utils.die("getSolution on unsolved testcase");
        }

        return solution;
    }

    public void setRef(int i) {
        ref = i;
    }
    public int getRef() {
        return ref;
    }

    public void setTime(double d) {
        time = d;
    }
    public double getTime() {
        return time;
    }
    
    public void setInteger(String s, Integer i) {
        intProperties.put(s, i);
    }
    
    public Integer getInteger(String s) {
        return intProperties.get(s);
    }

    public void setIntegerList(String s, ArrayList<Integer> l) {
        intArrayProperties.put(s, l);
    }

    public void setIntegerMatrix(String s, ArrayList<ArrayList<Integer>> l) {
        intArray2DProperties.put(s, l);
    }

    public ArrayList<Integer> getIntegerList(String s) {
        return intArrayProperties.get(s);
    }

    public Integer getIntegerListItem(String s, int i) {
        return intArrayProperties.get(s).get(i);
    }

    public ArrayList<ArrayList<Integer>> getIntegerMatrix(String s) {
        return intArray2DProperties.get(s);
    }
    
    public ArrayList<Integer> getIntegerMatrixRow(String s, int row) {
        return intArray2DProperties.get(s).get(row);
    }
    
    public Integer getIntegerMatrixItem(String s, int row, int column) {
        return intArray2DProperties.get(s).get(row).get(column);
    }

    public ArrayList<Integer> getIntegerMatrixColumn(String s, int column) {
        ArrayList<Integer> out = new ArrayList();
        
        for(ArrayList<Integer> row : intArray2DProperties.get(s)) {
            out.add(row.get(column));
        }
        return out;
    }


    public void setDouble(String s, Double i) {
        doubleProperties.put(s, i);
    }
    
    public Double getDouble(String s) {
        return doubleProperties.get(s);
    }

    public void setDoubleList(String s, ArrayList<Double> l) {
        doubleArrayProperties.put(s, l);
    }

    public void setDoubleMatrix(String s, ArrayList<ArrayList<Double>> l) {
        doubleArray2DProperties.put(s, l);
    }

    public ArrayList<Double> getDoubleList(String s) {
        return doubleArrayProperties.get(s);
    }

    public Double getDoubleListItem(String s, int i) {
        return doubleArrayProperties.get(s).get(i);
    }

    public ArrayList<ArrayList<Double>> getDoubleMatrix(String s) {
        return doubleArray2DProperties.get(s);
    }
    
    public ArrayList<Double> getDoubleMatrixRow(String s, int row) {
        return doubleArray2DProperties.get(s).get(row);
    }
    
    public Double getDoubleMatrixItem(String s, int row, int column) {
        return doubleArray2DProperties.get(s).get(row).get(column);
    }

    public ArrayList<Double> getDoubleMatrixColumn(String s, int column) {
        ArrayList<Double> out = new ArrayList();
        
        for(ArrayList<Double> row : doubleArray2DProperties.get(s)) {
            out.add(row.get(column));
        }
        return out;
    }

    
    public void setString(String s, String t) {
        stringProperties.put(s, t);
    }
    
    public String getString(String s) {
        return stringProperties.get(s);
    }

    public void setStringList(String s, ArrayList<String> l) {
        stringArrayProperties.put(s, l);
    }

    public void setStringMatrix(String s, ArrayList<ArrayList<String>> l) {
        stringArray2DProperties.put(s, l);
    }

    public ArrayList<String> getStringList(String s) {
        return stringArrayProperties.get(s);
    }

    public String getStringListItem(String s, int i) {
        return stringArrayProperties.get(s).get(i);
    }

    public ArrayList<ArrayList<String>> getStringMatrix(String s) {
        return stringArray2DProperties.get(s);
    }
    
    public ArrayList<String> getStringMatrixRow(String s, int row) {
        return stringArray2DProperties.get(s).get(row);
    }
    
    public String getStringMatrixItem(String s, int row, int column) {
        return stringArray2DProperties.get(s).get(row).get(column);
    }

    public ArrayList<String> getStringMatrixColumn(String s, int column) {
        ArrayList<String> out = new ArrayList();
        
        for(ArrayList<String> row : stringArray2DProperties.get(s)) {
            out.add(row.get(column));
        }
        return out;
    }

    
    public void setBoolean(String s, Boolean b) {
        booleanProperties.put(s, b);
    }
    
    public Boolean getBoolean(String s) {
        return booleanProperties.get(s);
    }

    public void setBooleanList(String s, ArrayList<Boolean> l) {
        booleanArrayProperties.put(s, l);
    }

    public void setBooleanMatrix(String s, ArrayList<ArrayList<Boolean>> l) {
        booleanArray2DProperties.put(s, l);
    }

    public ArrayList<Boolean> getBooleanList(String s) {
        return booleanArrayProperties.get(s);
    }

    public Boolean getBooleanListItem(String s, int i) {
        return booleanArrayProperties.get(s).get(i);
    }

    public ArrayList<ArrayList<Boolean>> getBooleanMatrix(String s) {
        return booleanArray2DProperties.get(s);
    }
    
    public ArrayList<Boolean> getBooleanMatrixRow(String s, int row) {
        return booleanArray2DProperties.get(s).get(row);
    }
    
    public Boolean getBooleanMatrixItem(String s, int row, int column) {
        return booleanArray2DProperties.get(s).get(row).get(column);
    }

    public ArrayList<Boolean> getBooleanMatrixColumn(String s, int column) {
        ArrayList<Boolean> out = new ArrayList();
        
        for(ArrayList<Boolean> row : booleanArray2DProperties.get(s)) {
            out.add(row.get(column));
        }
        return out;
    }

    public void setLong(String s, Long b) {
        longProperties.put(s, b);
    }
    
    public Long getLong(String s) {
        return longProperties.get(s);
    }

    public void setLongList(String s, ArrayList<Long> l) {
        longArrayProperties.put(s, l);
    }

    public void setLongMatrix(String s, ArrayList<ArrayList<Long>> l) {
        longArray2DProperties.put(s, l);
    }

    public ArrayList<Long> getLongList(String s) {
        return longArrayProperties.get(s);
    }

    public Long getLongListItem(String s, int i) {
        return longArrayProperties.get(s).get(i);
    }

    public ArrayList<ArrayList<Long>> getLongMatrix(String s) {
        return longArray2DProperties.get(s);
    }
    
    public ArrayList<Long> getLongMatrixRow(String s, int row) {
        return longArray2DProperties.get(s).get(row);
    }
    
    public Long getLongMatrixItem(String s, int row, int column) {
        return longArray2DProperties.get(s).get(row).get(column);
    }

    public ArrayList<Long> getLongMatrixColumn(String s, int column) {
        ArrayList<Long> out = new ArrayList();
        
        for(ArrayList<Long> row : longArray2DProperties.get(s)) {
            out.add(row.get(column));
        }
        return out;
    }

    

    


}

package codejam;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import fixjava.Split;

/**
 * Put this class in a package that ends with the name of the problem, e.g. proba => problem A, with input A-large.in etc.
 * 
 * Then save the sample problem to DirConsts.INPUT_DIR as X-test.in, where X is the problem letter. Save small and large attempt input files to that dir also.
 * 
 * */
public abstract class CodeJam {

	PrintWriter writer;
	BufferedReader reader;
	ArrayList<String> currLineTokens = new ArrayList<String>();
	int caseNum = 0;

	private String getStaticField(String name) {
		try {
			return (String) (this.getClass().getDeclaredField(name).get(null));
		} catch (Exception e) {
			return null;
		}
	}

	public CodeJam() {
		// Get package name and extract problem letter
		String fullClassName = this.getClass().getName();
		int dotIdx = fullClassName.indexOf('.');
		String pkgName = fullClassName.substring(0, dotIdx).toLowerCase();
		if (!(pkgName.substring(0, pkgName.length() - 1).equals("prob")))
			throw new RuntimeException("Package name must be of the form 'probX'");
		final String problemLetter = pkgName.substring(pkgName.length() - 1).toUpperCase();

		File inpDir = new File(DirConsts.INPUT_DIR);
		if (!inpDir.exists())
			throw new RuntimeException("Directory " + DirConsts.INPUT_DIR + " not found");
		
		File outDir = new File(DirConsts.OUTPUT_DIR);
		if (!outDir.exists())
			throw new RuntimeException("Directory " + DirConsts.OUTPUT_DIR + " not found");

		File srcDir = new File(new File((getClass().getProtectionDomain().getCodeSource().getLocation().toString()).substring(5)).getParentFile(), "src");
		if (!srcDir.exists())
			throw new RuntimeException("src directory not found");

		// See if input file has been manually overriden by static field in Main class
		String OVERRIDE_INPUT_FILE = getStaticField("OVERRIDE_INPUT_FILE");

		try {
			// Package source into zipfile
			File zipFile = new File(outDir, problemLetter + "-source-latest.zip");
			System.out.println("Zipping source from " + srcDir);
			ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
			byte data[] = new byte[1024 * 1024];
			for (String dirName : srcDir.list()) {
				// Don't include probX directories for problems other than this one, but include everything else
				if (!dirName.startsWith("prob") || dirName.equals(pkgName)) {
					File dir = new File(srcDir, dirName);
					for (String srcFile : dir.list()) {
						String zipEntry = dirName + "/" + srcFile;
						System.out.println(" -> Adding: " + zipEntry);
						zipOut.putNextEntry(new ZipEntry(zipEntry));
						BufferedInputStream srcFileStream = new BufferedInputStream(new FileInputStream(new File(dir, srcFile)), data.length);
						for (int count; (count = srcFileStream.read(data, 0, data.length)) != -1;)
							zipOut.write(data, 0, count);
						srcFileStream.close();
					}
				}
			}
			zipOut.close();
			System.out.println("Wrote: " + zipFile.getPath() + "\n");

			// Determine input file to use
			String inpFileName;
			if (OVERRIDE_INPUT_FILE != null) {

				// Manual override
				inpFileName = problemLetter + "-" + OVERRIDE_INPUT_FILE + ".in";

			} else {

				// Find latest-ordered input file to use
				// Sort in order A-test.in, A-test0.in, A-test1.in, ..., A-small-attempt0.in, A-small-attempt1.in, ..., A-large.in

				String[] inpFiles = inpDir.list(new FilenameFilter() {
					@Override
					public boolean accept(File dir, String filename) {
						boolean matches = filename.matches(problemLetter + "-.*\\.in");
						if (matches && (filename.indexOf('(') >= 0 || filename.indexOf(')') >= 0)) {
							// Don't include otherwise-valid filenames with parens in, warn the user, as
							// there are probably downloads from multiple problem rounds in the same dir
							System.err.println("Filename " + filename + " contains parens -- skipping");
							return false;
						}
						return matches;
					}
				});
				if (inpFiles.length == 0)
					throw new IOException("No input files found for problem " + problemLetter);

				// Sort into correct order (see above)
				Arrays.sort(inpFiles, new Comparator<String>() {
					@Override
					public int compare(String arg0, String arg1) {
						String a = arg0.substring(2), b = arg1.substring(2);
						int aType = a.startsWith("test") ? 0 : a.startsWith("small") ? 1 : a.startsWith("large") ? 2 : -1;
						int bType = b.startsWith("test") ? 0 : b.startsWith("small") ? 1 : b.startsWith("large") ? 2 : -1;
						int typeDiff = aType - bType;
						if (typeDiff != 0)
							return typeDiff;
						int aDotIdx = a.lastIndexOf('.'), bDotIdx = b.lastIndexOf('.');
						if (aDotIdx < 1 || bDotIdx < 1)
							return arg0.compareTo(arg1);
						int aNumIdx = aDotIdx - 1;
						while (aNumIdx >= 0 && Character.isDigit(a.charAt(aNumIdx)))
							aNumIdx--;
						String aNumStr = a.substring(aNumIdx + 1, aDotIdx);
						int bNumIdx = bDotIdx - 1;
						while (bNumIdx >= 0 && Character.isDigit(b.charAt(bNumIdx)))
							bNumIdx--;
						String bNumStr = b.substring(bNumIdx + 1, bDotIdx);
						if (aNumStr.isEmpty() || bNumStr.isEmpty())
							return arg0.compareTo(arg1);
						int aNum = Integer.parseInt(aNumStr);
						int bNum = Integer.parseInt(bNumStr);
						return aNum - bNum;
					}
				});
				inpFileName = inpFiles[inpFiles.length - 1];
				// for (String inpFile : inpFiles)
				// System.out.println("Input file: " + inpFile);
			}

			File inpFile = new File(inpDir, inpFileName);
			File outFile = new File(outDir, inpFileName.replace(".in", ".out"));

			// Copy input file to output dir if it's not already there
			if (!inpDir.equals(outDir)) {
				System.out.println("Copying input file to output dir");
				reader = new BufferedReader(new FileReader(inpFile));
				writer = new PrintWriter(new File(outDir, inpFileName));
				for (String line; (line = reader.readLine()) != null;)
					writer.println(line);
				writer.close();
				writer = null;
				reader.close();
				reader = null;
			}

			System.out.println("Reading: " + inpFile.getPath() + "\n");
			reader = new BufferedReader(new FileReader(inpFile));
			writer = new PrintWriter(outFile); // = null; // to suppress output

			// Do the work
			solve();

			if (writer != null)
				writer.close();
			System.out.println("\nWrote: " + outFile.getPath() + "\n\nFinished.");
			reader.close();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void writeLineRaw(String outputLine) {
		System.out.println(outputLine);
		if (writer != null)
			writer.println(outputLine);
	}

	public void writeCaseNumThenLine(String outputLine) {
		writeLineRaw("Case #" + (++caseNum) + ": " + outputLine);
	}

	public void writeCaseNumThenLine(int intLine) {
		writeCaseNumThenLine("" + intLine);
	}

	public String readLine() {
		try {
			return reader.readLine();
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(1);
			return null;
		}
	}

	/** Read next token, splitting on space */
	public String readTok() {
		if (currLineTokens.size() > 0) {
			String tok = currLineTokens.get(0);
			currLineTokens.remove(0);
			return tok;
		} else {
			currLineTokens.addAll(Split.splitAsListOfString(readLine(), " "));
			return readTok();
		}
	}

	/** Read next int, splitting on space */
	public int readInt() {
		return Integer.parseInt(readTok());
	}

	public abstract void solve();
}
