import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;

public class ReadFile {
	public static void main(String[] args) throws Exception {
		String srcFile = "C:" + File.separator + "Documents and Settings"
				+ File.separator + "rohit" + File.separator + "My Documents"
				+ File.separator + "Downloads" + File.separator
				+ "C-small-attempt1.in.txt";
		String destFile = "C:" + File.separator + "Documents and Settings"
				+ File.separator + "rohit" + File.separator + "My Documents"
				+ File.separator + "Downloads" + File.separator
				+ "C-small-attempt0.out";
		File file = new File(srcFile);
		List<String> readData = new ArrayList<String>();
		FileReader fileInputStream = new FileReader(file);
		BufferedReader bufferedReader = new BufferedReader(fileInputStream);
		StringBuilder stringBuilder = new StringBuilder();
		String line = null;
		while ((line = bufferedReader.readLine()) != null) {
			readData.add(line);
		}
		stringBuilder.append(generateOutput(readData));
		File writeFile = new File(destFile);
		if (!writeFile.exists()) {
			writeFile.createNewFile();
		}
		FileWriter fileWriter = new FileWriter(writeFile);
		BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
		bufferedWriter.write(stringBuilder.toString());
		bufferedWriter.close();
		System.out.println("output" + stringBuilder);
	}

	/**
	 * @param number
	 * @return
	 */
	private static String generateOutput(List<String> number) {
		StringBuilder stringBuilder = new StringBuilder();
		for (int i = 0; i < number.size(); i++) {
			if (i == 0) {
				continue;
			} else {
				String tempString = number.get(i);
				String[] temArr = tempString.split(" ");
				stringBuilder.append("Case #" + i + ": ");
				stringBuilder.append(getRecNumbers(temArr[0], temArr[1]));
				stringBuilder.append("\n");
			}
		}
		if (stringBuilder.length() > 0) {
			stringBuilder.deleteCharAt(stringBuilder.length() - 1);
		}
		return stringBuilder.toString();
	}

	// /* This method accepts method for google code jam */
	// private static String method(String value) {
	// int intValue = Integer.valueOf(value);
	// double givenExpr = 3 + Math.sqrt(5);
	// double num = Math.pow(givenExpr, intValue);
	// String valArr[] = (num + "").split("\\.");
	// int finalVal = Integer.valueOf(valArr[0]) % 1000;
	//
	// return String.format("%1$03d", finalVal);
	//
	// }
	//
	// /* This method accepts method for google code jam */
	// private static String method2(String value) {
	// StringTokenizer st = new StringTokenizer(value, " ");
	// String test[] = value.split(" ");
	// StringBuffer str = new StringBuffer();
	//
	// for (int i = 0; i < test.length; i++) {
	// // test[i]=test[test.length-i-1];
	// str.append(test[test.length - i - 1]);
	// str.append(" ");
	// }
	// str.deleteCharAt(str.length() - 1);
	// String strReversedLine = "";
	//
	// while (st.hasMoreTokens()) {
	// strReversedLine = st.nextToken() + " " + strReversedLine;
	// }
	//
	// return str.toString();
	// }

	private static int getRecNumbers(String no1, String no2) {

		int a = Integer.valueOf(no1);
		int b = Integer.valueOf(no2);
		Set<String> dupC = new HashSet<String>();
		for (int i = a; i <= b; i++) {
			int n = i;
			List<String> value = findPerm(n);
			for (String val : value) {
				if (Integer.valueOf(val) <= b && Integer.valueOf(val) >= a
						&& n < Integer.valueOf(val)) {
					dupC.add(n + "-" + val);
				}
			}
		}
		return dupC.size();
	}

	private static List<String> findPerm(int num) {
		String numString = String.valueOf(num);
		List<String> value = new ArrayList<String>();
		for (int i = 0; i < numString.length(); i++) {
			String temp = charIns(numString, i);
			if (!temp.equalsIgnoreCase(numString)) {
				value.add(charIns(numString, i));
			}
		}
		return value;

	}

	public static String charIns(String str, int j) {
		String begin = str.substring(0, j);
		String end = str.substring(j);
		return end + begin;
	}
}
package es.saspelo.codejam.recyclednumbers;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Scanner;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.martiansoftware.jsap.FlaggedOption;
import com.martiansoftware.jsap.JSAP;
import com.martiansoftware.jsap.JSAPResult;

import es.saspelo.codejam.commons.CodeJamProblem;

public class RecycledNumbers implements CodeJamProblem {

	private static final Logger log = LoggerFactory.getLogger(RecycledNumbers.class);

	public void execute(InputStream in, OutputStream out) throws IOException {

		int testCases = 1;

		final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));

		final List<int[]> problemDatas = readInput(in);

		if (log.isDebugEnabled()) {
			log.debug("==== starting problem '{}' ====", RecycledNumbers.class.getSimpleName());
		}

		try {
			for (int[] minMax : problemDatas) {

				int recycled = 0;

				int[] numbersbettweenAandB = new int[minMax[1] - minMax[0] + 1];

				for (int i = 0; i < numbersbettweenAandB.length; i++) {
					numbersbettweenAandB[i] = minMax[0] + i;
				}

				for (int i = 0; i < numbersbettweenAandB.length; i++) {
					for (int j = i + 1; j < numbersbettweenAandB.length; j++) {
						if (isRecycled(numbersbettweenAandB[i], numbersbettweenAandB[j])) {
							recycled++;
						}
					}
				}

				writer.write("Case #" + testCases + ": " + recycled + "\n");
				testCases++;
			}
		} finally {
			writer.close();
		}
	}

	private boolean isRecycled(int m, int n) {
		String nAsChars = String.valueOf(n);
		String mAsChars = String.valueOf(m);

		for (int i = nAsChars.length() - 1; i >= 1; i--) {

			String front = nAsChars.substring(0, i);
			String back = nAsChars.substring(i, nAsChars.length());

//			if (log.isDebugEnabled()) {
//				log.debug("back: '{}', front: '{}'", back, front);
//			}
			
			String newNumber = back + front;

//			if (log.isDebugEnabled()) {
//				log.debug("n: '{}', m: '{}', newNumber: '{}'", new Object[] { nAsChars, mAsChars, newNumber });
//			}

			if (mAsChars.equals(newNumber)) {
				return true;
			}
		}

		return false;
	}

	private List<int[]> readInput(InputStream in) {

		final Scanner sc = new Scanner(in);

		int testCases = sc.nextInt();
		if (log.isDebugEnabled()) {
			log.debug("testCases: '{}'", testCases);
		}

		List<int[]> problemData = new ArrayList<int[]>(testCases);

		for (int i = 0; i < testCases; i++) {
			int[] minMax = new int[2];

			minMax[0] = sc.nextInt();
			minMax[1] = sc.nextInt();

			if (log.isDebugEnabled()) {
				log.debug("minMax: '{}'", minMax);
			}

			problemData.add(minMax);

		}

		sc.close();
		return problemData;
	}

	public static void main(String[] args) throws Exception {
		final JSAP jsap = new JSAP();

		final FlaggedOption inputFileName = new FlaggedOption("input").setStringParser(JSAP.STRING_PARSER)
		        .setShortFlag('i').setLongFlag(JSAP.NO_LONGFLAG);

		final FlaggedOption outputFileName = new FlaggedOption("output").setStringParser(JSAP.STRING_PARSER)
		        .setShortFlag('o').setLongFlag(JSAP.NO_LONGFLAG);

		inputFileName.setHelp("File name with input for the problem");
		outputFileName.setHelp("File name for problem output file");

		jsap.registerParameter(inputFileName);
		jsap.registerParameter(outputFileName);

		final JSAPResult config = jsap.parse(args);

		if (!config.success()) {

			System.err.println();

			// print out specific error messages describing the problems
			// with the command line, THEN print usage, THEN print full
			// help. This is called "beating the user with a clue stick."
			for (Iterator<?> errs = config.getErrorMessageIterator(); errs.hasNext();) {
				System.err.println("Error: " + errs.next());
			}

			System.err.println();
			System.err.println("Usage: java " + RecycledNumbers.class.getName());
			System.err.println("                " + jsap.getUsage());
			System.err.println();
			System.err.println(jsap.getHelp());
			System.exit(1);
		}

		InputStream in = System.in;
		OutputStream out = System.out;

		if (config.getString("input") != null) {
			in = new FileInputStream(new File(config.getString("input")));
		}

		if (config.getString("output") != null) {
			out = new FileOutputStream(new File(config.getString("output")));
		}

		RecycledNumbers problem = new RecycledNumbers();

		problem.execute(in, out);
	}
}
