B12085,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package gcj; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.Scanner; /** * * @author daniele */ public class GCJ_C { public static void main(String[] args) throws Exception{ Scanner in = new Scanner(new File(args[0])); FileWriter out = new FileWriter(""/home/daniele/Scrivania/Output""); int prove=in.nextInt(); int min,max; int cifre; int cifreaus; String temp; int aus; int count=0; ArrayList vals = new ArrayList(); int jcount=0; ArrayList perm = new ArrayList(); out.write(""""); out.flush(); for(int i=1;i<=prove;i++){ out.append(""Case #"" +i+"": "");out.flush(); min=in.nextInt(); max=in.nextInt(); for(int j=min;j<=max;j++){ if(!vals.contains(j)){ temp=""""+j; cifre=temp.length(); aus=j; perm.add(j); for(int k=1;k=min && aus<=max && aus!=j && cifreaus==cifre && nobody(vals,perm)){ perm.add(aus); jcount ++; } } while(jcount>0){count+=jcount; jcount--;} vals.addAll(perm); perm= new ArrayList(); } } out.append(count+""\n"");out.flush(); count=0; vals= new ArrayList(); } } static public int rotateOnce(int n){ String s=""""+n; if(s.length()>1){ s=s.charAt(s.length()-1) + s.substring(0,s.length()-1); n=Integer.parseInt(s); } return n; } static public boolean nobody(ArrayList v,ArrayList a){; for(int i=0;i { public abstract T nextCase() throws Exception; public abstract int getMaxCaseNumber(); } " B11421,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class Recycled { public static void main(String[] args) throws Exception{ String inputFile = ""C-small-attempt0.in""; BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile))); BufferedWriter output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(""output""))); long num_cases = Long.parseLong(input.readLine()); int current_case = 0; while (current_case < num_cases){ current_case++; String[] fields = input.readLine().split("" ""); int A = Integer.parseInt(fields[0]); int B = Integer.parseInt(fields[1]); int total = 0; for (int n = A; n < B; n++){ for (int m = n+1; m <= B; m++){ if (isRecycled(n,m)) total++; } } System.out.println(""Case #"" + current_case + "": "" + total); output.write(""Case #"" + current_case + "": "" + total + ""\n""); } output.close(); } private static boolean isRecycled(int n, int m) { String sn = """"+n; String sm = """"+m; if (sn.length() != sm.length()) return false; int totaln = 0, totalm = 0; for (int i = 0; i < sn.length(); i++){ totaln += sn.charAt(i); totalm += sm.charAt(i); } if (totaln != totalm) return false; for (int i = 0; i < sn.length()-1; i++){ sm = sm.charAt(sm.length() - 1) + sm.substring(0, sm.length() - 1); if (sm.equals(sn)) return true; } return false; } } " B10899,"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 readData = new ArrayList(); 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 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 dupC = new HashSet(); for (int i = a; i <= b; i++) { int n = i; List 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 findPerm(int num) { String numString = String.valueOf(num); List value = new ArrayList(); 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; } }" B10485," import java.util.Scanner; import java.util.Set; import java.util.TreeSet; import java.io.File; import java.io.IOException; import java.io.FileWriter; import java.io.BufferedWriter; public class Recycle { public static void main(String[] args) { /* Set perms = getPermutations(123456); for(Integer i: perms) System.out.println(i);*/ try { Scanner s = new Scanner(new File(""recycle.in"")); BufferedWriter w = new BufferedWriter(new FileWriter(new File(""recycle.out""))); int numCases = s.nextInt(); s.nextLine(); for(int n = 1;n <= numCases; n++) { int A = s.nextInt(); int B = s.nextInt(); int count = 0; for(int k = A; k <= B; k++) { count += getNumPairs(k, B); } w.write(""Case #"" + n + "": "" + count + ""\n""); } w.flush(); w.close(); } catch (IOException e) { e.printStackTrace(); } } public static int getNumPairs(int n, int B) { Set possibles = getPermutations(n); int count = 0; for(Integer i : possibles) if(i > n && i <= B) count++; return count; } public static Set getPermutations(int n) { Set perms = new TreeSet(); char[] digits = String.valueOf(n).toCharArray(); for(int firstPos = 1; firstPos < digits.length; firstPos++) { String toBuild = """"; for(int k = 0; k < digits.length; k++) toBuild += digits[(firstPos + k) % digits.length]; perms.add(Integer.parseInt(toBuild)); } return perms; } }" B10361,"package codejam; import java.util.*; import java.io.*; public class RecycledNumbers { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(""in.txt"")); PrintWriter out = new PrintWriter(new File(""out.txt"")); int T = Integer.parseInt(in.readLine()); for (int t = 1; t <= T; ++t) { String[] parts = in.readLine().split(""[ ]+""); int A = Integer.parseInt(parts[0]); int B = Integer.parseInt(parts[1]); int cnt = 0; for (int i = A; i < B; ++i) { String str = String.valueOf(i); int n = str.length(); String res = """"; Set seen = new HashSet(); for (int j = n - 1; j > 0; --j) { res = str.substring(j) + str.substring(0, j); int k = Integer.parseInt(res); if (k > i && k <= B) { //System.out.println(""("" + i + "", "" + k + "")""); if (!seen.contains(k)) { ++cnt; seen.add(k); } } } } out.println(""Case #"" + t + "": "" + cnt); } in.close(); out.close(); System.exit(0); } } " B10245,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recyclednumbers; import java.util.HashSet; /** * * @author vandit */ public class RecycleNumbers { private HashSet numbers = new HashSet(); private HashSet initialTempNumbers = new HashSet(); private HashSet finalTempNumbers = new HashSet(); HashSet numberPairs = new HashSet(); private void findRecycledNumbers(int start, int end, int places) { for (int i = start; i <= end; i++) { String initialNumber = Integer.toString(i); //if (!(numbers.contains(initialNumber) || finalTempNumbers.contains(initialNumber))) { StringBuffer tempNumber = new StringBuffer(initialNumber); int len = tempNumber.length(); int startIndexToMove = len - places; String tempString = tempNumber.substring(startIndexToMove); if ((places == 1 && tempString.equals(""0"")) || tempString.charAt(0) == '0') { continue; } tempNumber.delete(startIndexToMove, len); String finalTempNumber = tempString + tempNumber.toString(); if (! (finalTempNumber.equals(initialNumber) || Integer.parseInt(finalTempNumber) > end || Integer.parseInt(finalTempNumber) < Integer.parseInt(initialNumber))) { numbers.add(initialNumber); finalTempNumbers.add(finalTempNumber); Pair pair = new Pair(finalTempNumber,initialNumber); numberPairs.add(pair); } } } public HashSet findAllRecycledNumbers(int start, int end) { int length = Integer.toString(start).length(); for (int i = 1; i < length; i++) { findRecycledNumbers(start, end, i); } return numberPairs; } } " B12669,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package year_2012.qualification; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; /** * * @author paul * @date 14 Apr 2012 */ public class QuestionC { private static Set getCycle(int x) { String s = Integer.toString(x); Set set = new HashSet(); set.add(x); for (int c = 1; c < s.length(); c++) { String t = s.substring(c).concat(s.substring(0, c)); set.add(Integer.parseInt(t)); } return set; } private static Set mask(Set set, int a, int b) { Set result = new HashSet(); for (int x : set) { if (x >= a && x <= b) { result.add(x); } } return result; } public static void main(String[] args) throws FileNotFoundException, IOException { String question = ""C""; // String name = ""large""; String name = ""small-attempt0""; // String name = ""test""; String filename = String.format(""%s-%s"", question, name); BufferedReader input = new BufferedReader( new FileReader(String.format(""/home/paul/Documents/code-jam/2012/qualification/%s.in"", filename))); String firstLine = input.readLine(); PrintWriter pw = new PrintWriter(new File( String.format(""/home/paul/Documents/code-jam/2012/qualification/%s.out"", filename))); int T = Integer.parseInt(firstLine); // Loop through test cases. for (int i = 0; i < T; i++) { // Read data. String[] tokens = input.readLine().split("" ""); // int N = Integer.parseInt(input.readLine()); int A = Integer.parseInt(tokens[0]); int B = Integer.parseInt(tokens[1]); // System.out.format(""%d, %d\n"", A, B); boolean[] used = new boolean[B+1]; int total = 0; for (int n = A; n <= B; n++) { if (!used[n]) { Set set = mask(getCycle(n), A, B); int k = set.size(); total += (k * (k-1))/2; for (int m : set) { used[m] = true; } } } pw.format(""Case #%d: %d\n"", i + 1, total); } pw.close(); } } " B12941,"package com.menzus.gcj._2012.qualification.c; import com.menzus.gcj.common.InputBlockParser; import com.menzus.gcj.common.OutputProducer; import com.menzus.gcj.common.impl.AbstractProcessorFactory; public class CProcessorFactory extends AbstractProcessorFactory { public CProcessorFactory(String inputFileName) { super(inputFileName); } @Override protected InputBlockParser createInputBlockParser() { return new CInputBlockParser(); } @Override protected OutputProducer createOutputProducer() { return new COutputProducer(); } } " B12082,"package jp.funnything.competition.util; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import org.apache.commons.io.IOUtils; public class QuestionReader { private final BufferedReader _reader; public QuestionReader( final File input ) { try { _reader = new BufferedReader( new FileReader( input ) ); } catch ( final FileNotFoundException e ) { throw new RuntimeException( e ); } } public void close() { IOUtils.closeQuietly( _reader ); } public String read() { try { return _reader.readLine(); } catch ( final IOException e ) { throw new RuntimeException( e ); } } public BigDecimal[] readBigDecimals() { return readBigDecimals( "" "" ); } public BigDecimal[] readBigDecimals( final String separator ) { final String[] tokens = readTokens( separator ); final BigDecimal[] values = new BigDecimal[ tokens.length ]; for ( int index = 0 ; index < tokens.length ; index++ ) { values[ index ] = new BigDecimal( tokens[ index ] ); } return values; } public BigInteger[] readBigInts() { return readBigInts( "" "" ); } public BigInteger[] readBigInts( final String separator ) { final String[] tokens = readTokens( separator ); final BigInteger[] values = new BigInteger[ tokens.length ]; for ( int index = 0 ; index < tokens.length ; index++ ) { values[ index ] = new BigInteger( tokens[ index ] ); } return values; } public int readInt() { final int[] values = readInts(); if ( values.length != 1 ) { throw new IllegalStateException( ""Try to read single interger, but the line contains zero or multiple values"" ); } return values[ 0 ]; } public int[] readInts() { return readInts( "" "" ); } public int[] readInts( final String separator ) { final String[] tokens = readTokens( separator ); final int[] values = new int[ tokens.length ]; for ( int index = 0 ; index < tokens.length ; index++ ) { values[ index ] = Integer.parseInt( tokens[ index ] ); } return values; } public long readLong() { final long[] values = readLongs(); if ( values.length != 1 ) { throw new IllegalStateException( ""Try to read single interger, but the line contains zero or multiple values"" ); } return values[ 0 ]; } public long[] readLongs() { return readLongs( "" "" ); } public long[] readLongs( final String separator ) { final String[] tokens = readTokens( separator ); final long[] values = new long[ tokens.length ]; for ( int index = 0 ; index < tokens.length ; index++ ) { values[ index ] = Long.parseLong( tokens[ index ] ); } return values; } public String[] readTokens() { return readTokens( "" "" ); } public String[] readTokens( final String separator ) { return read().split( separator ); } } " B11696,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recycled; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.TreeSet; /** * * @author Alfred */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { try { FileInputStream fstream = new FileInputStream(""C-small-attempt0.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter outFile = new FileWriter(""out.txt""); PrintWriter out = new PrintWriter(outFile); String line; line = br.readLine(); int cases = Integer.parseInt(line); for (int i=1; i<=cases;i++){ line = br.readLine(); String[] values = line.split("" ""); int A = Integer.parseInt(values[0]); int B = Integer.parseInt(values[1]); int total=0; for (int n=A; n<=B;n++){ TreeSet solutions = new TreeSet(); for (int k=1;k n && !m.startsWith(""0"") && m.length()==Integer.toString(n).length() ) { solutions.add(m); } } total+=solutions.size(); } out.println(""Case #""+i+"": ""+total); } in.close(); out.close(); } catch (Exception e) {//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } private static String circshift(int n, int k) { String nString=Integer.toString(n); int len=nString.length(); String m = nString.substring(len-k)+nString.subSequence(0, len-k); //System.out.println(n+"" ""+m); return m; } } " B10149,"import java.io.FileInputStream; import java.util.HashMap; import java.util.Scanner; import java.util.TreeSet; // Recycled Numbers // https://code.google.com/codejam/contest/1460488/dashboard#s=p2 public class C { private static String process(Scanner in) { int A = in.nextInt(); int B = in.nextInt(); int res = 0; int len = Integer.toString(A).length(); for(int n = A; n < B; n++) { String str = Integer.toString(n); TreeSet set = new TreeSet(); for(int i = 1; i < len; i++) { int m = Integer.parseInt(str.substring(i, len) + str.substring(0, i)); if ( m > n && m <= B && ! set.contains(m) ) { set.add(m); res++; } } } return Integer.toString(res); } public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in.available() > 0 ? System.in : new FileInputStream(Thread.currentThread().getStackTrace()[1].getClassName() + "".practice.in"")); int T = in.nextInt(); for(int i = 1; i <= T; i++) System.out.format(""Case #%d: %s\n"", i, process(in)); } } " B11318,"import java.util.Scanner; class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t=sc.nextInt(); int casos=1, a, b, n, m, cont; while(t!=0){ a=sc.nextInt(); b=sc.nextInt(); if(a>b){ int aux=a; a=b; b=aux; } System.out.printf(""Case #%d: "",casos++); if(a==b){ System.out.printf(""%d\n"",0); }else{ cont=0; for(n=a;n 0){ permut = permut/10; no_of_digits++; } int lastDigit = currnum % 10; permut = currnum / 10; permut = permut + lastDigit * (int)Math.pow(10, no_of_digits-1); while(permut != currnum){ if(permut >= currnum && permut <= large){ count++; } lastDigit = permut % 10; permut = permut / 10; permut = permut + lastDigit * (int)Math.pow(10, no_of_digits-1); } } return count; } public static void main(String args[]){ RecycledNumbers d = new RecycledNumbers(); int no_of_cases = 0; String input = """"; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try{ no_of_cases = Integer.parseInt(br.readLine()); } catch(Exception e){ System.out.println(""First line is not a number""); } for(int i=1; i <= no_of_cases;i++){ try{ input = br.readLine(); } catch(Exception e){ System.out.println(""Number of test cases different from the number mentioned in first line""); } System.out.print(""Case #"" +i+"": ""); StringTokenizer t = new StringTokenizer(input); int small=0,large=0; if(t.hasMoreTokens()){ small = Integer.parseInt(t.nextToken()); } if(t.hasMoreTokens()){ large = Integer.parseInt(t.nextToken()); } System.out.println(d.getcount(small,large)); } } }" B11327,"package recycledNumbers; public class OutputData { private int[] Steps; public int[] getSteps() { return Steps; } public OutputData(int [] Steps){ this.Steps = Steps; for(int i=0;i 0){ mul = mul *10; tnum= tnum/10; } tnum = num; int n = 0; while(tnum > 0 && mul >= 10){ nMul = nMul * 10; n = (num % nMul) * mul + (num / nMul); mul = mul / 10; tnum = tnum / 10; for(int m=num;m<=B;m++){ if(n == m && m > num){ ctr++; } } } } System.out.println(""Case #""+(k+1)+"": ""+ctr); } } } " B10702,"import java.util.HashMap; import java.util.HashSet; import java.util.Scanner; public class Recycle { private static HashMap> map = new HashMap>(); private static HashSet toSkip = new HashSet(); /** * @param args */ public static void main(String[] args) { Scanner reader = new Scanner(System.in); int T = reader.nextInt(); for (int tc = 1; tc <= T; tc++) { int a = reader.nextInt(); int b = reader.nextInt(); long before = System.currentTimeMillis(); int res = doit(a, b); System.out.printf(""Case #%d: %d\n"", tc, res); long after = System.currentTimeMillis(); // System.out.println(""time taken: "" + (after - before)); } } private static int doit(int a, int b) { int count = 0; HashSet skip = new HashSet(toSkip); for (int i = a; i <= b; i++) { if (skip.contains(i)) continue; HashSet arr = generate(i); // if(arr.size() > 1) { // map.put(i, arr); // } // System.out.println(i + "" --> "" + // Arrays.deepToString(arr.toArray())); int temp = 0; if (arr.size() > 1) { for (int x : arr) { if (x >= a && x <= b) { temp++; skip.add(x); } } count += temp * (temp - 1) / 2; } // System.out.println(""not skipping "" + i + "" gen: "" + arr.size()+ "" "" + (temp * (temp - 1) / 2)); } return count; } private static HashSet generate(int num) { if(map.containsKey(num)) { HashSet list = map.get(num); return list; } HashSet list = new HashSet(); String s = """" + num; list.add(num); int len = s.length(); for (int i = 1; i < len; i++) { String temp = s.substring(i) + s.substring(0, i); // System.out.println(""temp: "" + temp); if (temp.charAt(0) == '0') continue; int x = Integer.parseInt(temp); if( x <= 2000000) { list.add(x); } } if(list.size() > 1) { map.put(num, list); } else { toSkip.add(num); } return list; } } " B10155,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; /** * * @author eblanco */ import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import javax.swing.JFileChooser; public class RecycledNumbers { public static String DatosArchivo[] = new String[10000]; public static int[] convertStringArraytoIntArray(String[] sarray) throws Exception { if (sarray != null) { int intarray[] = new int[sarray.length]; for (int i = 0; i < sarray.length; i++) { intarray[i] = Integer.parseInt(sarray[i]); } return intarray; } return null; } public static boolean CargarArchivo(String arch) throws FileNotFoundException, IOException { FileInputStream arch1; DataInputStream arch2; String linea; int i = 0; if (arch == null) { //frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); JFileChooser fc = new JFileChooser(System.getProperty(""user.dir"")); int rc = fc.showDialog(null, ""Select a File""); if (rc == JFileChooser.APPROVE_OPTION) { arch = fc.getSelectedFile().getAbsolutePath(); } else { System.out.println(""No hay nombre de archivo..Yo!""); return false; } } arch1 = new FileInputStream(arch); arch2 = new DataInputStream(arch1); do { linea = arch2.readLine(); DatosArchivo[i++] = linea; /* if (linea != null) { System.out.println(linea); }*/ } while (linea != null); arch1.close(); return true; } public static boolean GuardaArchivo(String arch, String[] Datos) throws FileNotFoundException, IOException { FileOutputStream out1; DataOutputStream out2; int i; out1 = new FileOutputStream(arch); out2 = new DataOutputStream(out1); for (i = 0; i < Datos.length; i++) { if (Datos[i] != null) { out2.writeBytes(Datos[i] + ""\n""); } } out2.close(); return true; } public static void echo(Object msg) { System.out.println(msg); } public static void main(String[] args) throws IOException, Exception { String[] res = new String[10000], num = new String[2]; int i, j, k, ilong; int ele = 1; ArrayList al = new ArrayList(); String FName = ""C-small-attempt0"", istr, irev, linea; if (CargarArchivo(""C:\\eblanco\\Desa\\CodeJam\\Code Jam\\test\\"" + FName + "".in"")) { for (j = 1; j <= Integer.parseInt(DatosArchivo[0]); j++) { linea = DatosArchivo[ele++]; num = linea.split("" ""); al.clear(); // echo(""A: ""+num[0]+"" B: ""+num[1]); for (i = Integer.parseInt(num[0]); i <= Integer.parseInt(num[1]); i++) { istr = Integer.toString(i); ilong = istr.length(); for (k = 1; k < ilong; k++) { if (ilong > k) { irev = istr.substring(istr.length() - k, istr.length()) + istr.substring(0, istr.length() - k); //echo(""caso: "" + j + "": isrt: "" + istr + "" irev: "" + irev); if ((Integer.parseInt(irev) > Integer.parseInt(num[0])) && (Integer.parseInt(irev) > Integer.parseInt(istr)) && (Integer.parseInt(irev) <= Integer.parseInt(num[1]))) { al.add(""("" + istr + "","" + irev + "")""); } } } } HashSet hs = new HashSet(); hs.addAll(al); al.clear(); al.addAll(hs); res[j] = ""Case #"" + j + "": "" + al.size(); echo(res[j]); LeerArchivo.GuardaArchivo(""C:\\eblanco\\Desa\\CodeJam\\Code Jam\\test\\"" + FName + "".out"", res); } } } } " B12074,"package jp.funnything.competition.util; import java.math.BigInteger; /** * Utility for BigInteger */ public class BI { public static BigInteger ZERO = BigInteger.ZERO; public static BigInteger ONE = BigInteger.ONE; public static BigInteger add( final BigInteger x , final BigInteger y ) { return x.add( y ); } public static BigInteger add( final BigInteger x , final long y ) { return add( x , v( y ) ); } public static BigInteger add( final long x , final BigInteger y ) { return add( v( x ) , y ); } public static int cmp( final BigInteger x , final BigInteger y ) { return x.compareTo( y ); } public static int cmp( final BigInteger x , final long y ) { return cmp( x , v( y ) ); } public static int cmp( final long x , final BigInteger y ) { return cmp( v( x ) , y ); } public static BigInteger div( final BigInteger x , final BigInteger y ) { return x.divide( y ); } public static BigInteger div( final BigInteger x , final long y ) { return div( x , v( y ) ); } public static BigInteger div( final long x , final BigInteger y ) { return div( v( x ) , y ); } public static BigInteger mod( final BigInteger x , final BigInteger y ) { return x.mod( y ); } public static BigInteger mod( final BigInteger x , final long y ) { return mod( x , v( y ) ); } public static BigInteger mod( final long x , final BigInteger y ) { return mod( v( x ) , y ); } public static BigInteger mul( final BigInteger x , final BigInteger y ) { return x.multiply( y ); } public static BigInteger mul( final BigInteger x , final long y ) { return mul( x , v( y ) ); } public static BigInteger mul( final long x , final BigInteger y ) { return mul( v( x ) , y ); } public static BigInteger sub( final BigInteger x , final BigInteger y ) { return x.subtract( y ); } public static BigInteger sub( final BigInteger x , final long y ) { return sub( x , v( y ) ); } public static BigInteger sub( final long x , final BigInteger y ) { return sub( v( x ) , y ); } public static BigInteger v( final long value ) { return BigInteger.valueOf( value ); } } " B13196,"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.Iterator; import java.util.List; public class Q3M { public static void main(String[] args) throws Exception { compute(); } private static void compute() throws Exception { BufferedReader br = new BufferedReader(new FileReader(new File( ""C:\\work\\Q3\\C-small-attempt0.in""))); String line = null; int i = Integer.parseInt(br.readLine()); List l = new ArrayList(); for (int j = 0; j < i; j++) { line = br.readLine(); String[] nums = line.split("" ""); l.add(calculate(nums)); } writeOutput(l); } private static int calculate(String[] nums) { int min = Integer.parseInt(nums[0]); int max = Integer.parseInt(nums[1]); int count = 0; List l = new ArrayList(); for (int i = min; i <= max; i++) { for (int times = 1; times < countDigits(i); times++) { int res = shiftNum(i, times); if (res <= max && i < res) { if ((!l.contains((i + "":"" + res)))) { l.add(i + "":"" + res); l.add(res + "":"" + i); count++; } } } } return count; } private static boolean checkZeros(int temp, int res) { if (temp % 10 == 0 || res % 10 == 0) return false; return true; } private static int shiftNum(int n, int times) { int base = (int) Math.pow(10, times); int temp2 = n / base; int placeHolder = (int) Math.pow((double) 10, (double) countDigits(temp2)); int res = placeHolder * (n % base) + temp2; if (countDigits(res) == countDigits(n)) { return res; } else { return 2000001; } } public static int countDigits(int x) { if (x < 10) return 1; else { return 1 + countDigits(x / 10); } } private static void writeOutput(List l) throws Exception { StringBuffer b = new StringBuffer(); int i = 1; BufferedWriter br = new BufferedWriter(new FileWriter(new File( ""C:\\work\\Q3\\ans.txt""))); for (Iterator iterator = l.iterator(); iterator.hasNext();) { br.write(""Case #"" + i++ + "": "" + iterator.next()); br.newLine(); } br.close(); } }" B10231,"import java.io.*; class code1 { public static void main(String args[]) throws Exception { File ii = new File (""C-small-attempt1.in""); FileInputStream fis = new FileInputStream(ii); BufferedReader br = new BufferedReader(new InputStreamReader (fis)); int cases = Integer.parseInt(br.readLine()); FileOutputStream fout = new FileOutputStream (""output.txt""); DataOutputStream dout = new DataOutputStream (fout); int total=0; for(int i=0;ij)total++; System.out.println(total); } } dout.writeBytes(""Case #""+(i+1)+ "": ""+total+""\n""); total=0; }//for close } private static int power(int i, int j) { int no=1; for(int a=0;a 0) { n /= 10; len++; } return len; } main() throws FileNotFoundException { Scanner sc = new Scanner(new File(""C-small-attempt0.in"")); PrintWriter out = new PrintWriter(""result.txt""); int tests = sc.nextInt(); for (int t = 1; t <= tests; t++) { int a = sc.nextInt(); int b = sc.nextInt(); int l = numberLength(a); int tt = (int) Math.pow(10, l - 1); int r = 0; for (int j = a; j <= b; j++) { int cr = j; int val = j; int per = numberPeriod(j, l); for (int k = 0; k < per; k++) { int c = val % 10; val = val / 10 + c * tt; if (val > cr && val <= b) { r++; } } } out.printf(""Case #%d: %d\n"", t, r); } out.flush(); } public static void main(String[] args) { try { main m = new main(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }" B11825,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; public class Recycled_Numbers_2 { /** * @param args */ public static void main(String[] args) { String strFileName = ""C-small-attempt0""; String strInputFileName = strFileName + "".in""; String strOutputFileName = strFileName + "".out""; int iCaseNumber=1; try { //////////////////////////////////////////////////////////////// BufferedReader in = new BufferedReader(new FileReader(strInputFileName)); BufferedWriter out = new BufferedWriter(new FileWriter(strOutputFileName)); String inString = """"; String outString = """"; String sTotalNumber = in.readLine(); while ((inString = in.readLine()) != null) { System.out.println(inString); // µÎ °³ÀÇ ¼ýÀÚ·Î ÀÌ·ç¾îÁ® ÀÖ´Ù. String[] saRange = inString.split("" ""); int iStart = Integer.parseInt(saRange[0]); int iEnd = Integer.parseInt(saRange[1]); System.out.println(String.format(""S:[%d], E:[%d]"", iStart, iEnd)); ArrayList listCompare = new ArrayList<>(); int iCount = 0; for (int iNumber = iStart; iNumber <= iEnd; iNumber++) { // ¼öÀÇ ÀÚ¸´¼ö ¾ò±â int iGetDigit = iNumber; int iDigitCount = 0; while (iGetDigit > 0) { iGetDigit /= 10; iDigitCount++; } //System.out.println(String.format(""%d's Digit is %d"",iNumber, iDigitCount)); boolean bFound = false; // ºñ±³ for (int idx = 0; idx < listCompare.size(); idx++) { int iCompareNumber = listCompare.get(idx); for (int iDigit = 1; iDigit <= iDigitCount-1; iDigit++) { int iFront = (int) (iNumber/(Math.pow(10, iDigit))); int iBack = (int) (iNumber%(Math.pow(10, iDigit))); int iModify = (int) (iBack * (Math.pow(10, iDigitCount-iDigit)) + iFront); // System.out.println(String.format(""Check: iNumber:[%d], iDigit:[%d], iFront:[%d], iBack:[%d], iModify:[%d]"" // , iNumber, iDigit, iFront, iBack, iModify)); if (iCompareNumber == iModify) { //System.out.println(String.format(""Compare:[%d], iNumber:[%d], iModify[%d], iDigit[%d]"", iCompareNumber, iNumber, iModify, iDigit)); iCount ++; //listCompare.remove(idx); bFound = true; //break; } } // if (bFound) { // break; // } } listCompare.add(iNumber); } System.out.println(String.format(""Count:[%d]"",iCount)); outString = String.format(""Case #%d: %d\n"", iCaseNumber++, iCount); System.out.print(outString); out.write(outString); } in.close(); out.close(); //////////////////////////////////////////////////////////////// } catch (IOException e) { System.err.println(""ERROR""); System.err.println(e); // ¿¡·¯°¡ ÀÖ´Ù¸é ¸Þ½ÃÁö Ãâ·Â System.exit(1); } } } " B12461,"import java.io.*; import java.util.*; public class test3 { public static void main(String[] args) throws Exception { new test3().run(); } PrintWriter out = null; int getCount(int d, int max) { String s = Integer.toString(d); int n = s.length(); HashSet hs = new HashSet(); for (int i = 1; i < n; i++) { StringBuffer sb = new StringBuffer(); sb.append(s.substring(n - i, n)); sb.append(s.substring(0, n - i)); int b = Integer.parseInt(sb.toString()); if (b > d && b <= max) hs.add(b); } return hs.size(); } void run() throws Exception { Scanner in = new Scanner(System.in); out = new PrintWriter(new FileWriter(""codejam.txt"")); int T = in.nextInt(); for (int i = 0; i < T; i++) { int A = in.nextInt(); int B = in.nextInt(); int total = 0; for (int j = A; j <= B; j++) total += getCount(j, B); out.printf(""Case #%d: %d\n"", i + 1, total); } out.close(); } } " B10781,"import java.io.BufferedReader; import java.io.IOException; import java.io.FileReader; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.StringTokenizer; public class TestJAM { public static void main (String[] args) { /* String nStr1 = ""12""; int numswindex1 = ; String nsw1 = nStr1.substring (numswindex1) + nStr1.substring (0, numswindex1); System.out.println (nStr1.substring (numswindex1)); System.out.println (nStr1.substring (0, numswindex1)); System.out.println (nsw1); if (1==1) return; */ BufferedReader br = null; PrintStream ps = null; try { int a; int b; int t; int count; String nStr; String mStr; String nsw; String line; StringTokenizer st; br = new BufferedReader (new FileReader (""C-small-attempt0.in"")); ps = new PrintStream (new FileOutputStream (""C-small-attempt0.out"")); line = br.readLine (); t = Integer.parseInt (line); for (int testCase = 0; testCase < t; testCase++) { count = 0; line = br.readLine (); st = new StringTokenizer (line); a = Integer.parseInt (st.nextToken ()); b = Integer.parseInt (st.nextToken ()); for (int n = a; n <= b; n++) { for (int m = n + 1; m <= b; m++) { nStr = String.valueOf (n); mStr = String.valueOf (m); int nlen = nStr.length (); int mlen = mStr.length (); if (nlen == mlen) { for (int numswindex = 0; numswindex < nlen; numswindex++) { nsw = nStr.substring (numswindex) + nStr.substring (0, numswindex); if (nsw.equalsIgnoreCase (mStr)) { count++; break; } } } else if (nlen > mlen) { break; } } } ps.println (""Case #"" + (testCase + 1) + "": "" + count); // System.out.println (count); } // ps.println (""test1 test1 test1""); // System.out.println (""Hola Mundo!!!""); } catch (IOException ioe) { ioe.printStackTrace (); } catch (NumberFormatException nfe) { nfe.printStackTrace (); } finally { if (ps != null) { ps.close (); } if (br != null) { try { br.close (); } catch (IOException ioe) { ioe.printStackTrace (); } } } } } " B12724,"import java.util.Scanner; public class C { public static void main(String[] args) { boolean[][] isPairs = new boolean[1001][1001]; for (int i = 1; i < 1000; i++) { for (int j = i+1; j < 1001; j++) { isPairs[i][j] = isPair(i, j); } } Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int i = 0; i < t; i++) { int a = sc.nextInt(); int b = sc.nextInt(); int count = 0; for (int j = a; j < b; j++) { for (int k = j+1; k <= b; k++) { if (isPairs[j][k]) { count++; } } } System.out.println(""Case #"" + (i+1) + "": "" + count); } } private static boolean isPair(int i, int j) { int digits = 0; int max = 1; int ac = i; while(ac > 0) { ac /= 10; digits++; max *= 10; } int min = max / 10; for (int k = 0; k < digits; k++) { int msb = i / min; i = i % min * 10 + msb; if (i == j) { return true; } } return false; } } " B12236,"package gcj2012; import java.io.File; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * @author Gaurav Prabhu Gaonkar * @date Apr 13, 2012 * */ public class RecycledNumbers { public static void main(String[] args) { String inputDir = ""C:\\GcjFiles\\2012\\Qualification""; String fileName = ""C-small-attempt0""; File inputFile = new File(inputDir + ""\\"" + fileName + "".in""); File outputFile = new File(inputDir + ""\\"" + fileName + "".out.txt""); try { PrintWriter out = new PrintWriter(outputFile); Scanner scanner = new Scanner(inputFile); //Read the first line String metadata = scanner.nextLine(); int numOfCases = Integer.parseInt(metadata); //System.out.println(numOfCases); for(int i = 1; i <= numOfCases; i++) { String input = scanner.nextLine(); //System.out.println(input); String[] params = input.split("" ""); int answer = solve(Integer.parseInt(params[0]), Integer.parseInt(params[1])); System.out.println(""Case #""+i+"": "" + answer); out.println(""Case #""+i+"": "" + answer); } // process next test case out.flush(); out.close(); } catch(Exception e) { System.out.println(""Exception Occured: "" + e); } } private static int solve(int a, int b) { int result = 0; if (a < 10) { a = 10; } Set candidates = new HashSet(); for (int i = a; i <= b; i++) { StringBuilder sb = new StringBuilder(); sb.append(i).append(i); int len = sb.length()/2; String str = sb.toString(); for (int j = 1; j <= len; j++) { candidates.add(str.substring(j,j+len)); } for (String candidate : candidates) { int test = Integer.parseInt(candidate); if (test > i && (test >= a && test <= b)) { result++; } } candidates.clear(); } return result; } } " B12112,"package com.renoux.gael.codejam.cj2012.qc; import java.util.HashSet; import java.util.Set; import com.renoux.gael.codejam.fwk.Solver; import com.renoux.gael.codejam.utils.ArrayUtils; import com.renoux.gael.codejam.utils.Input; import com.renoux.gael.codejam.utils.Output; public class QC extends Solver { public static void main(String... args) throws Exception { new QC().run(); } @Override protected void solveCase(Input in, Output out) { System.out.println(); int[] line = ArrayUtils.parseInts(in.readLine().split("" "")); int a = line[0]; int b = line[1]; Set pairs = new HashSet(); for (int i = a; i < b; i++) { String number = Integer.toString(i); for (int k = 1; k < number.length(); k++) { String modified = number.substring(k) + number.substring(0, k); int value = Integer.parseInt(modified); if (i < value && value <= b) { // System.out.println(i + "" "" + value); Pair p = new Pair(i, value); if (!pairs.add(p)) { // System.out.println(""Duplicata !!!""); } } } } out.writeLine(pairs.size()); } @Override protected String getProblemName() { return ""QC""; } @Override protected boolean disableSample() { return true; } @Override protected boolean disableLarge() { return true; } public static class Pair { public int m, n; public Pair(int m, int n) { this.m = m; this.n = n; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + m; result = prime * result + n; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (m != other.m) return false; if (n != other.n) return false; return true; } } } " B12346,"package gcj; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; class Recycled { Scanner sc; PrintWriter pw; int t, a, b, n, m, y; Recycled() { try { sc = new Scanner(new File(""C-small-attempt0.in"")); pw = new PrintWriter(new FileWriter(""out-small.txt"")); } catch (IOException e) { } t = sc.nextInt(); int caseNum = 1; while (caseNum <= t) { y = 0; a = sc.nextInt(); b = sc.nextInt(); n = a; m = b; while (n < m) { while (m > n) { recycle(n, m); m--; } n++; m = b; } pw.println(""Case #"" + caseNum + "": "" + y); caseNum++; } pw.flush(); pw.close(); } void recycle(int a, int b) { char[] n = String.valueOf(a).toCharArray(); char[] m = String.valueOf(b).toCharArray(); char[] shifted = null; for (int i = n.length - 1; i > 0; i--) { shifted = shift(n, i); if (equal(shifted, m)) { this.y++; return; } } } private char[] shift(char[] x, int start) { char[] ret = new char[x.length]; int i = start; for (int j = 0; j < x.length; j++) { if (i < x.length) { ret[j] = x[i]; i++; } else { i = 0; ret[j] = x[i]; i++; } } return ret; } boolean equal(char[] a, char[] b) { for (int i = 0; i < a.length; i++) { if (a[i] != b[i]) return false; } return true; } public static void main(String[] args) { new Recycled(); } } " B10359,"import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.PrintWriter; public class C { public static void main (String[] args) { try { //BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(new File(""src/C-small-attempt0.in"")))); PrintWriter pw = new PrintWriter(System.out); int cases = Integer.parseInt(in.readLine()); for (int i = 0; i < cases; i++) { String[] nums = in.readLine().split("" ""); int A = Integer.parseInt(nums[0]); int B = Integer.parseInt(nums[1]); int cont = 0; if(A!=1000 && A>=10) { if(A<100) { for (int j = A; j < B; j++) { if(j/10=100) { for (int j = A; j < B; j++) { int lef = j/100; int mid = (j-j/100*100)/10; int rig = j%10; if(lef==mid && lef==rig) continue; boolean a = lef hs = new HashSet(); String s = j.toString(); int length = s.length(); for (int k = 1; k < length; k++) { String t = s.substring(k, length) + s.substring(0, k); int newValue = Integer.parseInt(t); if (newValue > j && newValue <=B) { if (!hs.contains(t)) { hs.add(t); result++; } } } } System.out.println(""Case #"" + i + "": "" + result); } } }" B11143,"import java.io.*; import java.util.*; public class RecycledNumbers { private ArrayList input = new ArrayList(); public static void main(String argz[]) throws IOException{ RecycledNumbers r = new RecycledNumbers(); r.readInput(); r.generateAndCheck(); } public void generateAndCheck(){ int caseNo = 0; for(int i = 0; i < input.size(); i += 2){ int count = 0; int A = input.get(i); int B = input.get(i + 1); for(int n = A; n <= B; n++){ for(int m = n + 1; m <= B; m++){ if(check(n, m)) count++; } } System.out.print(""Case #"" + (++caseNo) + "": ""); System.out.println(count); } } public boolean check(int n, int m){ StringBuilder N = new StringBuilder(String.valueOf(n)); do{ N.insert(0, N.charAt(N.length() - 1)); N.deleteCharAt(N.length() - 1); if(Integer.parseInt(N.toString()) == m){ return true; } } while(Integer.parseInt(N.toString()) != n); return false; } private void readInput() throws IOException{ FileReader file = new FileReader(""in.in""); try { Scanner reader = new Scanner(file); int testCases = reader.nextInt(); while (testCases > 0){ input.add(reader.nextInt()); input.add(reader.nextInt()); testCases--; } } catch (Exception e){ System.err.println(""Error: "" + e.getMessage()); } } }" B11100,"import java.util.Scanner; public class GoogleNumbers { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int p = scan.nextInt(); int n, m; for(int i = 1; i <= p; i++) { int total = 0; n = scan.nextInt(); m = scan.nextInt(); for( ; n < m; n++) { for(int j=n+1; j <= m; j++) { if(recycled(n+"""",j+"""")) total++; } } System.out.println(""Case #""+i+"": ""+total); } } public static boolean recycled(String n, String m) { char[] cN = n.toCharArray(); char[] cM = m.toCharArray(); int tot1 = 0; int tot2 = 0; for(int i = 0; i < cN.length; i++) { tot1+= cN[i]; tot2+= cM[i]; } if(tot1!=tot2) return false; for(int j=0; j < cN.length; j++) { boolean found = true; for(int k=0; k < cN.length; k++) { if(cN[k] != cM[(k+j)%cN.length]) { found = false; break; } } if(found) return true; } return false; } } " B10480,"import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; public class Problem2 { public static void main (String[] args) throws IOException { File file = new File(""input1.txt""); Scanner scan = null; try { scan = new Scanner(file); } catch (FileNotFoundException e) { e.printStackTrace(); } FileWriter fstream = null; try { fstream = new FileWriter(""output.txt""); } catch (IOException e) { e.printStackTrace(); } BufferedWriter out = new BufferedWriter(fstream); int lineNumber; lineNumber = Integer.parseInt(scan.nextLine()); for (int i = 0; i < lineNumber; i++) { Scanner lineScan = new Scanner(scan.nextLine()); out.write(""Case #"" + (i + 1) + "": ""); int a = lineScan.nextInt(); int b = lineScan.nextInt(); int total = 0; ArrayList prev = new ArrayList(); for (int j = a; j <= b; j++) { String curr = String.valueOf(j); for (int k = 1; k < curr.length(); k++) { String second = curr.substring(k); String first = curr.substring(0, k); String afterStr = second + """" + first; int after = Integer.parseInt(afterStr); if (after > j && after <= b) { if (!prev.contains(after)) { total++; prev.add(after); } } } prev.clear(); } out.write(total + "" \n""); } out.close(); } } " B10800,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; public class Numbers { private static int[] pow10 = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000}; /* 0 1 2 3 4 5 6 7 8 */ /* n: number, s: total number of digits, i: rotation amount */ private static int rotate(int n, int s, int i) { int right = n % pow10[i]; if(right < pow10[i-1]) { // leading zeroes => forbidden return -1; } int left = n / pow10[i]; return right * pow10[s-i] + left; } private static int process(String l) { String[] parts = l.split("" ""); int A = Integer.parseInt(parts[0]); int B = Integer.parseInt(parts[1]); HashSet set = new HashSet(); int count = 0; for(int n=A; n n && m <= B) set.add(m); //System.out.println(n + "", "" + m); } count += set.size(); } return count; } public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(args[0])); PrintWriter out = new PrintWriter(args[1]); // number of testcases String sCount = in.readLine(); int count = Integer.parseInt(sCount); for(int idx=1; idx<=count; idx++) { String l = in.readLine(); out.println(""Case #"" + idx + "": "" + process(l)); } out.close(); } } " B10707,"import java.util.List; public class QC { public static void main( String args[]) { LeerArchivo leer = new LeerArchivo(); leer.abrirArchivo(""C-small-attempt0.txt""); EscribirArchivo escribir = new EscribirArchivo(); escribir.abrirArchivo(""respuesta.txt""); List lineasArchivo = leer.leer(); int numeroDeCasos = Integer.parseInt(lineasArchivo.get(0)); int contadorLineas =1; for(int contador=0; contador <= numeroDeCasos-1; contador++) { int A = Integer.parseInt(lineasArchivo.get(contadorLineas).split("" "")[0]); int B = Integer.parseInt(lineasArchivo.get(contadorLineas).split("" "")[1]); int respuesta = 0; for(int n = A; n <= B-1; n++) { for(int m = n+1; m<=B; m++) { //if(n ""+n+"" ""+m+"" --> ""+respuesta); //escribir.escribirLinea(""Encontrado --> ""+n+"" ""+m+"" --> ""+respuesta); } } escribir.escribirLinea(""Case #""+(contador+1)+"": ""+respuesta); contadorLineas++; } escribir.cerrarArchivo(); } public static int solve(int n, int m) { //Hago los shifts int temp = n; int tamano = Integer.toString(n).length(); int contador = 0; for(int i = 0; i<=tamano-1; i++) { //if(i!=0) int prueba = shift(temp,i); if(prueba == m) contador++; } return contador; } public static int shift(int number,int times) { String numeroString = Integer.toString(number); String numeroStringNew = """"; if(numeroString.length()>1) { for(int time = 0; time <= times-1; time++) { if(time>=1) { numeroString = numeroStringNew; numeroStringNew=""""; } for(int i = 1; i <= numeroString.length(); i++) { if(i!=numeroString.length()) numeroStringNew+=Character.toString(numeroString.charAt(i)); else numeroStringNew+=Character.toString(numeroString.charAt(0)); } } if(numeroStringNew.length()>1) { return Integer.parseInt(numeroStringNew); } else return Integer.parseInt(numeroString); } return Integer.parseInt(numeroString); } } " B10583,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { public static void main(String[] args) throws FileNotFoundException { Scanner scan = new Scanner(new File(""C-small-attempt0.in"")); System.setOut(new PrintStream(""C-small-attempt0.out"")); int t = scan.nextInt(); for (int c = 0; c < t; c++) { int a = scan.nextInt(); int b = scan.nextInt(); int ans = 0; int[] bDigits = digits(b); for (int n = a; n < b; n++) { int[] nDigits = digits(n); int digitCount = nDigits.length; Set done = new HashSet(); for (int i = 1; i < digitCount; i++) { int[] mDigits = rotate(nDigits, i); int m = normal(mDigits); if (isLess(nDigits, mDigits) && isLessEq(mDigits, bDigits) && !done.contains(m)) { ans++; done.add(m); /* * if (c == 3) { if (normal(nDigits) != n) throw new * AssertionError(); System.out.println(n + "" "" + m); if * (n < a || n >= m || m > b) throw new * AssertionError(); } */ } } } System.out.printf(""Case #%d: %d%n"", c + 1, ans); } } private static int[] digits(int n) { int num = 0; int temp = n; while (temp > 0) { num++; temp /= 10; } int[] dig = new int[num]; temp = n; for (int i = 0; i < num; i++) { dig[num - i - 1] = temp % 10; temp /= 10; } return dig; } private static int[] rotate(int[] num, int r) { int n = num.length; int[] ans = new int[n]; for (int i = 0; i < r; i++) { ans[i] = num[n - r + i]; } for (int i = 0; i < n - r; i++) { ans[r + i] = num[i]; } return ans; } private static int normal(int[] num) { int base = 1; int ans = 0; for (int i = 0; i < num.length; i++) { ans += num[num.length - 1 - i] * base; base *= 10; } return ans; } private static boolean isLess(int[] a, int[] b) { for (int i = 0; i < a.length; i++) { if (a[i] < b[i]) return true; if (a[i] > b[i]) return false; } return false; } private static boolean isLessEq(int[] a, int[] b) { for (int i = 0; i < a.length; i++) { if (a[i] < b[i]) return true; if (a[i] > b[i]) return false; } return true; } }" B13112,"package com.vp.common; import com.vp.fact.SolutionFactory; import com.vp.iface.Problem; public class ExecutorApp { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String inputFileName = ""C:/Workspace/GCJ2012/src/com/vp/data/sample_input.txt""; String outputFileName = ""C:/Users/dhananitin/Desktop/sample_output.txt""; //String outputFileName = ""C:/Workspace/GCJ2012/src/com/vp/data/sample_output.txt""; InputOutputProcessor inputOutputProcessor = new InputOutputProcessor(); inputOutputProcessor.initializeInput(inputFileName); int numberOfCases = inputOutputProcessor.getNumberOfCases(); String[] resultArray = new String[numberOfCases]; inputOutputProcessor.setDoesInputHaveDataSetLines(false); //inputOutputProcessor.setIndexOfDataSetLine(0); inputOutputProcessor.setNumberOfDataSetLines(1); for (int i = 1; i <= numberOfCases; i++) { try { String[] dataSet = inputOutputProcessor.getDataSet(); Problem problem = SolutionFactory.getInstance(Problem.RECYCLENUMBERS); resultArray[i-1] = ""Case #""+i+"": ""+ problem.solve(dataSet); } catch (Exception exp) { exp.printStackTrace(); inputOutputProcessor.closeScanner(); } } inputOutputProcessor.closeScanner(); inputOutputProcessor.writeOutput(outputFileName, resultArray); } } " B10419,"import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class MainClass { /** * @param args */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub Scanner sc = new Scanner(new File(""C-small-attempt0.in"")); PrintWriter out = new PrintWriter(new File(""RecycledNumbers.out"")); int N = sc.nextInt(); for (int i = 0; i < N; i++) { int A = sc.nextInt(); int B = sc.nextInt(); String s1, s2; int count = 0; for (int j = B; j > A; j--) { for (int k = A; k < j; k++) { s1 = """" + k; s2 = """" + j; s1 = s1 + s1; if (s1.contains(s2)) { count++; } } } out.println(""Case #"" + (i + 1) + "": "" + count); } out.close(); } } " B12380,"package trupti; import java.io.*; import java.io.FileNotFoundException; import java.util.Scanner; public class ok2 { public static void main(String[] args) { int cn=0; try { FileOutputStream out=new FileOutputStream(""out9.out""); Scanner scanner = new Scanner(new FileReader(""C-small-attempt6.in"")); int n=scanner.nextInt(); // scanner.nextLine(); while (n!=cn) { cn++; int q=0; int a=scanner.nextInt(); int b=scanner.nextInt(); int no=0; for(int r=a;r<=b;r++) { String str=r+""""; // System.out.println(""str""+str); do{ char c=str.charAt(0); String str1=str.substring(1, str.length()); str=str1+c; // System.out.println(str); no=Integer.parseInt(str); // System.out.println(""no""+no); if((no tasks = parseInputFile(""C-small-attempt0.in""); List results = new ArrayList(); for (Task task : tasks) { List result = new ArrayList(); for (int i = task.getA(); i <= task.getB(); i++) { generateRecycledNumbers(result, i, task.getB()); } results.add(result.size()); } writeOutputFile(results, ""c_output.txt""); } private static void writeOutputFile(List results, String fileName) throws IOException { BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter(fileName)); int i = 1; for (Integer result : results) { bw.write(""Case #"" + i++ + "": "" + result + ""\n""); } } finally { if (bw != null) { bw.close(); } } } private static List parseInputFile(String fileName) throws IOException { List result = new ArrayList(); BufferedReader bf = null; try { bf = new BufferedReader(new FileReader(fileName)); int numberOfStrings = Integer.parseInt(bf.readLine()); String line = bf.readLine(); while (line != null) { String[] tokens = line.split(""\\s""); int a = Integer.valueOf(tokens[0]); int b = Integer.valueOf(tokens[1]); result.add(new Task(a, b)); line = bf.readLine(); } if (result.size() != numberOfStrings) { throw new RuntimeException(""Incorrect input file. Expected number of strings = "" + numberOfStrings + "", actual number of strings = "" + result.size()); } } finally { if (bf != null) { bf.close(); } } return result; } private static void generateRecycledNumbers(List result, int number, int max) { if (number <= 11) { return; } String str = Integer.toString(number); for (int i = 1; i < str.length(); i++) { String begin = str.substring(0, i); String end = str.substring(i); int newNumber = Integer.valueOf(end + begin); if (newNumber > number && newNumber <= max) { Pair newPair = new Pair(number, newNumber); if (!result.contains(newPair)) { result.add(newPair); } } } } private static class Task { int a; int b; private Task(int a, int b) { this.a = a; this.b = b; } public int getA() { return a; } public int getB() { return b; } } private static class Pair { int n; int m; private Pair(int n, int m) { this.n = n; this.m = m; } public int getN() { return n; } public int getM() { return m; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; return n == pair.getN() && m == pair.getM() || n == pair.getM() && m == pair.getN(); } @Override public int hashCode() { int result = n; result = 31 * result + m; return result; } } } " B12227,"import java.io.*; import java.util.Scanner; public class functions { int solve(String A, String B){ int result = 0; int n = A.length(); int a = Integer.parseInt(A); int b = Integer.parseInt(B); int i = 0, j = 0, k = 0, index = 0; String temp_a = A; String temp2 = """"; int[] array = new int[8]; for(i = 0; i<8;i++) array[i] = -1; i = 0; int jj = 0,kk = 0; while(Integer.parseInt(A) < b-1){ for( index = 0; index <= n-2; index++){ temp2 = """"; kk = 0; for(j = index; j >= 0; j--){ temp2 = temp2 + A.charAt(n-1-j); } for(k = 0; k < n-index-1; k++){ temp2 = temp2 + A.charAt(k); } int c = Integer.parseInt(temp2); if ( c <= b && c > Integer.parseInt(A)) { for(jj = 0; jj < 8; jj++){ if(array[jj] == c){ break; } } if(jj == 8){ result = result + 1; array[kk++] = c; } System.out.println(""(""+A+"",""+temp2+"")""); } } A = Integer.toString(Integer.parseInt(A)+1); i++; } return result; } } " B10157,"import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.Scanner; public class RecycledNumbers { static int[] pow = { 1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000}; public static void main(String[] args) { PrintStream theOut=null; try { FileOutputStream o = new FileOutputStream(""./output.txt"", false); theOut = new PrintStream(o); } catch (Exception e) { e.printStackTrace(); return; } Scanner sc=null; try { //sc = new Scanner(new File(""./C-small.in"")); //sc = new Scanner(new File(""/home/duck/Downloads/B-large.in"")); sc = new Scanner(new File(""/home/duck/Downloads/C-small-attempt0.in"")); } catch (FileNotFoundException e) { e.printStackTrace(); } int nbCases = sc.nextInt(); mainloop: for(int curCase=1; curCase <= nbCases ;++curCase) { sc.nextLine(); long res = 0; int min = sc.nextInt(); int max = sc.nextInt(); ArrayList found = new ArrayList(); for(int i=min; i <= max ;++i) { int nbDigit = (int)Math.ceil(Math.log10((double)i)); found.clear(); for(int j= 1; j < nbDigit ; j++) { int low = i% pow[j]; int swap = low * pow[nbDigit - j] + (i-low) /pow[j]; if(swap > i && swap <= max && !found.contains(swap)) { found.add(swap); ++res; //System.out.println(i+"" ""+swap); } } } /*******************************************************************/ theOut.format(""Case #%d: %d\n"",curCase,res); System.out.format(""Case #%d: %d\n"",curCase,res); } } } " B11655,"package com.quosco.codejam.pre; import static java.lang.Math.*; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; public class Main { private static final String OUT_FORMAT = ""Case #%d: %d\n""; private static void solve() throws IOException { FileWriter fstream = new FileWriter(""out.txt""); BufferedWriter out = new BufferedWriter(fstream); Scanner s = new Scanner(Main.class.getResourceAsStream(""/input.txt"")); Integer nbOfCases = Integer.valueOf(s.nextLine()); for (int i = 0; i < nbOfCases; i++) { String[] caseInputs = s.nextLine().split(""\\s""); Integer start = Integer.valueOf(caseInputs[0]); Integer end = Integer.valueOf(caseInputs[1]); int result = solveCase(start, end, out); out.write(String.format(OUT_FORMAT, i + 1, result)); } out.close(); } private static int solveCase(Integer start, Integer end, BufferedWriter out) throws IOException { HashSet magicNumbers = new HashSet(); // int magicNumbers = 0; for (int i = start; i <= end; i++) { int nbOfDigits = (int) ceil(log10(i+1)); for (int j = 1; j < nbOfDigits; j++) { int isMagic = ismagic(i, j, start, end); if (isMagic > 0) { magicNumbers.add(i + "","" + isMagic); // magicNumbers++; } } } return magicNumbers.size(); // return magicNumbers; } private static int ismagic(int initialNumber, int numberOfDigits, Integer start, Integer end) { String stringValue = Integer.toString(initialNumber); int cutPoint = stringValue.length() - numberOfDigits; if (stringValue.charAt(cutPoint) == '0') { return -1; } String stringNewNumber = stringValue.substring(cutPoint) + stringValue.substring(0, cutPoint); int newNumber = Integer.parseInt(stringNewNumber); if (initialNumber < newNumber && newNumber >= start && newNumber <= end) { return newNumber; } return -1; } public static void main(String[] args) throws IOException { solve(); } } " B12763," import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class C { public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new File(C.class.getSimpleName() + "".in"")); PrintWriter out = new PrintWriter(new File(C.class.getSimpleName() + "".out"")); int T = in.nextInt(); for (int i = 0; i < T; i++) { String s = ""Case #"" + (i + 1) + "": "" + new C().solve(in); out.println(s); System.out.println(s); } out.close(); } private String solve(Scanner in) { int a = in.nextInt(); int b = in.nextInt(); int k = 1; int c = 1; while (k * 10 <= b) { k *= 10; c++; } int[] num = new int[10000000]; for (int n = a; n <= b; n++) { int min = n; int nn = n; for (int i = 0; i < c; i++) { nn = (nn / 10) + (nn % 10) * k; if (nn >= k) { min = Math.min(min, nn); } } num[min]++; } long res = 0; for (int n : num) { res += (1L * n * (n - 1)) / 2; } return """" + res; } }" B11187,"import java.util.Vector; public class MyNumbers { Vector numbers; MyNumbers(){ numbers = new Vector(); } void add(int num){ if(!numbers.contains(num)) numbers.add(num); } } " B12757,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; public class TestGoogle3 { public TestGoogle3() { try { // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(""C-small-attempt0.in""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; int line = -1; int curline = 0; // Read File Line By Line while ((strLine = br.readLine()) != null) { // Print the content on the console if (line == -1) line = Integer.parseInt(strLine); else if (curline < line) { System.out.print(""Case #"" + ++curline + "": ""); System.out.println(this.calculate(strLine)); } } in.close(); } catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } public int calculate(String input) { String[] result = input.split(""\\s""); int n = Integer.parseInt(result[0]); int s = Integer.parseInt(result[1]); return getRecycledNumber(n, s); } public int getRecycledNumber(int low, int high) { int counter = 0; ArrayList list = new ArrayList(); for (int i = low; i < high; i++) { int li = i; // System.out.println(""cleared:""); list.clear(); while (li > 0) { list.add(li % 10); li = li / 10; } int[] temp = new int[list.size()]; for (int j = 0; j < list.size(); j++) { // System.out.println(""current number:"" + list.get(j)); for (int k = 0; k < list.size(); k++) { temp[k] = (int) (temp[k] + list.get(j) * (Math.pow(10, ((k + list.size() + j) % list .size())))); } } for (int m = 0; m < list.size(); m++) { if (temp[m] > i && temp[m] <= high) { boolean flag = false; // skip duplicates for (int n = 0; n < m; n++) { if (temp[m] == temp[n]) { System.out.println(""i "" + i); System.out.println(""duplicate"" + i); flag = true; } } if (!flag) counter++; } } } return counter; } /** * @param args */ public static void main(String[] args) { new TestGoogle3(); } } " B11247,"import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; public class RecycledNums { public static String rootDir = System.getProperty(""user.dir"") + File.separator; public static String filesDir = rootDir + ""files"" + File.separator; private FileWriter fw; private int tests; private int[] a; private int[] b; private int[] pow10 = {1,10,100,1000,10000,100000,1000000,10000000}; public static void main(String[] args) { RecycledNums r = new RecycledNums(); r.go(); } public RecycledNums() { try { Scanner input = new Scanner(new File(filesDir + ""recycled.txt"")); Scanner line; tests = Integer.parseInt(input.nextLine()); a = new int[tests]; b = new int[tests]; for (int c = 0; c < tests; c++) { line = new Scanner(input.nextLine()); a[c] = line.nextInt(); b[c] = line.nextInt(); } } catch (FileNotFoundException e) { e.printStackTrace(); } // for (int i = 0; i < a.length; i++) { // System.out.println(a[i] + "" "" + b[i]); // } } public void go() { open(); int[] r; int count; HashMap h; for (int c = 0; c < tests; c++) { count = 0; h = new HashMap(); for (int n = a[c]; n <= b[c]; n++) { if (digits(n) < 2) continue; if (h.containsKey(n)) continue; r = getRecycledNums(n); for (int i = 0; i < r.length; i++) { for (int j = i + 1; j < r.length; j++) { if (r[i] < a[c] || r[i] > b[c] || r[j] < a[c] || r[j] > b[c]) continue; if (digits(r[i]) != digits(r[j])) continue; if (r[i] == r[j]) continue; count++; } } add(r,h); } write(""Case #"" + (c+1) + "": "" + count); if (c != tests-1) write(""\n""); System.out.println(""Case #"" + (c+1) + "": "" + count); } close(); } private void add(int[] r,HashMap h) { for (int n : r) if (!h.containsKey(n)) h.put(n, n); } private int digits(int n) { if (n == 0) return 0; return 1 + digits(n/10); } private int[] getRecycledNums(int n) { int[] digits = new int[digits(n)]; int[] nums = new int[digits.length]; int start; int num; for (int i = 0; i < digits.length; i++) digits[i] = (n/pow10[i])%10; for (int i = 0; i < digits.length; i++) { start = i; num = 0; for (int j = 0; j < digits.length; j++) { num += digits[start]*pow10[j]; start = (start+1)%digits.length; } nums[i] = num; } return check(nums); } private int[] check(int[] n) { ArrayList list = new ArrayList(); for (int i : n) if (!list.contains(i)) list.add(i); return toIntArray(list); } private int[] toIntArray(ArrayList list) { int[] temp = new int[list.size()]; for (int i = 0; i < list.size(); i++) temp[i] = list.get(i).intValue(); return temp; } private void open() { try { fw = new FileWriter(new File(filesDir + ""recycledAns.txt"")); } catch (IOException e) { e.printStackTrace(); } } private void close() { try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } private void write(String s) { try { fw.write(s); } catch (IOException e) { e.printStackTrace(); } } } " B12127,"import java.io.*; import java.util.HashMap; public class RecycledNumbers { public static void main(String[] arg) { String output,line = null; int t,a,b, count, caseNum; String[] inp; try { BufferedReader is = new BufferedReader(new FileReader(""infile.txt"")); FileWriter writer = new FileWriter(""output.txt""); line = is.readLine(); t = Integer.parseInt(line); for(caseNum=1; caseNum<=t; caseNum++) { line = is.readLine(); inp = line.split("" ""); a = Integer.parseInt(inp[0].trim()); b = Integer.parseInt(inp[1].trim()); count = generateRotatedNumbersCount(a, b); output = ""Case #"" + caseNum + "": "" + count + ""\n""; writer.write(output.toCharArray()); } writer.close(); } catch (NumberFormatException ex) { System.out.println(""Not a valid number: "" + line); } catch (IOException e) { System.out.println(""Unexpected IO ERROR: "" + e); } } public static int generateRotatedNumbersCount(int a, int b) { HashMap map; HashMap masterList = new HashMap(); String num; char[] temp; int i,j,k,len; int n, count=0; for (k=a; k<=b; k++) { if (masterList.containsKey(k)) continue; num = Integer.toString(k); char[] digits = num.toCharArray(); len = digits.length; map = new HashMap(); for (i=0; i= a && n <= b) { map.put(n, true); masterList.put(n, true); } } len = map.size(); count += (len*(len-1))/2; } return count; } }" B12328,"package main; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.PriorityQueue; public class recycledNumbers { public static void main(String[] args) { File inputFile = new File(""input/"" + args[0]); if (!inputFile.exists()) { System.out.print(""File DNE""); return; } BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile))); Integer caseCount = new Integer(br.readLine()); Integer[] lowerList = new Integer[caseCount]; Integer[] upperList = new Integer[caseCount]; for (int i = 0; i < caseCount; i++) { String[] lineIn= br.readLine().split("" ""); lowerList[i] = new Integer(lineIn[0]); upperList[i] = new Integer(lineIn[1]); } File outputFile = new File(""output/"" + args[0] + "".out""); FileWriter fw = new FileWriter(outputFile); for (int i = 0; i < caseCount; i++) { foundPairs.clear(); int finalCount = 0; Integer val = lowerList[i]; while (val <= upperList[i]) { finalCount += rotate(val, lowerList[i], upperList[i]); val++; } System.out.println(""Case #"" + (i + 1) + "": "" + finalCount); fw.write(""Case #"" + (i + 1) + "": "" + finalCount + ""\n""); } fw.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static Map foundPairs = new HashMap(); private static int rotate(Integer val, Integer lowerBound, Integer upperBound) { char[] valString = val.toString().toCharArray(); List valCharArray = new ArrayList(valString.length); for (int i = 0; i < valString.length; i++) valCharArray.add(valString[i]); int finalCount = 0; for (int i = 0; i < valString.length; i++) { valCharArray.add(valCharArray.remove(0)); String testValString = new String(""""); for (int j = 0; j < valCharArray.size(); j++) testValString += valCharArray.get(j); Integer testVal = new Integer(testValString); String key1 = val.toString() + ""_"" + testVal.toString(); String key2 = testVal.toString() + ""_"" + val.toString(); if (foundPairs.get(key1) != null || foundPairs.get(key2) != null) continue; if (testVal > val && testVal <= upperBound) { foundPairs.put(key1,true); foundPairs.put(key2,true); finalCount++; } } return finalCount; } } " B12815,"import java.io.*; class recycle { public static void main(String args[])throws Exception { FileReader R=new FileReader(""input.txt""); BufferedReader ds=new BufferedReader(R); int n=Integer.parseInt(ds.readLine()); for(int j=1;j<=n;j++) { int i; String l=ds.readLine(); for(i=0;iInteger.parseInt(x) && Integer.parseInt(y)<=b) cnt++; p++; y=x.substring(p)+x.substring(0,p); } } System.out.println(""Case #""+j+"": ""+cnt); } } }" B10966,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.HashSet; import java.util.Set; /** * */ /** * @author antonio081014 * @time: Apr 13, 2012, 5:01:31 PM */ public class Main { /** * @param args */ public static void main(String[] args) throws Exception { Main main = new Main(); main.run(); System.exit(0); } public void run() throws Exception { BufferedReader br = new BufferedReader(new FileReader(""input.in"")); BufferedWriter out = new BufferedWriter(new FileWriter(""output.out"")); int T = Integer.parseInt(br.readLine()); for (int t = 1; t <= T; t++) { out.write(""Case #"" + Integer.toString(t) + "": ""); String[] strs = br.readLine().split(""\\s""); int A = Integer.parseInt(strs[0]); int B = Integer.parseInt(strs[1]); Set set; int count = 0; for (int n = A; n <= B; n++) { String tmp = Integer.toString(n); set = new HashSet(); for (int i = 0; i < tmp.length(); i++) { String a = tmp.substring(i) + tmp.substring(0, i); int m = Integer.parseInt(a); if (m > n && m <= B) { set.add(m); } } count += set.size(); } out.write(Integer.toString(count) + ""\n""); } out.close(); } }" B11641,"import java.io.*; public class Test3 { final static String INPUT_FILE_NAME = ""input3""; int T = 0; int q = 0; public static void main(String args[]) { try { Test3 tst = new Test3(); tst.getInput(); } catch (Exception e) { e.printStackTrace(); } } private void getInput() throws Exception { File file = new File(INPUT_FILE_NAME); FileReader fis = new FileReader(file); BufferedReader br = new BufferedReader(fis); String strT = br.readLine(); T = getInt(strT); for (int i=0; i0) { counts[sortNumber(i)]++; } } for (int i=0; i<=B;i++) { //System.out.println(""i=""+i+"" counts=""+counts[i]); rtn += counts[i] * (counts[i]-1) / 2; } System.out.println(""Case #""+(t+1)+"": ""+rtn); //System.out.println(""Hello WorldI""); } private int sortNumber(int i) { String str = String.valueOf(i); int keta = str.length(); int min = i; String slideStr = str; for (int k=0; k getInt(slideStr)) { min = getInt(slideStr); } } return min; } private int getInt(String a) { return Integer.parseInt(a, 10); } private int getIntx(String a) { if (a.equals(""."")) { return 0; } return 1; } } " B11434,"import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; public class GCJ2012QA { public static void main(String[] args) throws Exception { ExecutorService executor = Executors.newFixedThreadPool(8); Scanner sc = new Scanner(new FileReader(""A-input.txt"")); PrintWriter pw = new PrintWriter(new FileWriter(""A-output.txt"")); final int CASE_COUNT = sc.nextInt(); for(int caseNum = 1; caseNum <= CASE_COUNT; caseNum++) { pw.print(""Case #"" + caseNum + "": ""); int ans = 0; int A = sc.nextInt(); int B = sc.nextInt(); //int toGo = A + ((B - A) / 2); List> ress = new ArrayList>(); for(int i = A; i <= B; i++) { Future resf = executor.submit(new Calculate(A, B, i)); ress.add(resf); } for(Future aa : ress){ ans += aa.get(); } // PUT ANSWER HERE pw.println(ans); } executor.awaitTermination(100, TimeUnit.MILLISECONDS); executor.shutdown(); pw.flush(); pw.close(); sc.close(); } private static class Calculate implements Callable{ final int A, B, num; public Calculate(int A, int B, int i){ this.A = A; this.B = B; this.num = i; } @Override public Integer call() throws Exception { return rotateCount(A, B, num); } } private static int rotateCount(int A, int B, int num) { Set cache = new HashSet(); if(num < 10) { return 0; } int res = 0; char[] a = String.valueOf(num).toCharArray(); int size = a.length; for(int i = 1; i < size; i++) { int kk = Integer.parseInt(rotate(a,1)); //System.out.println(num + "" ("" + Thread.currentThread().getName() + "") "" + kk); if(kk > num && kk <= B && !cache.contains(kk)) { //System.out.println(num + "","" + kk); res++; cache.add(kk); } } return res; } private static String rotate( final char[] a, final int n ) { for(int i = 0; i < n; i++) { char tmp = a[a.length-1]; for(int j = a.length-1; j >= 0; j--) { a[j] = j == 0 ? tmp : a[(j-1+a.length)%a.length]; } } return new String(a); } } " B11181,"/** * Created by IntelliJ IDEA. * User: Administrator * Date: 3/3/12 * Time: 11:00 AM * To change this template use File | Settings | File Templates. */ import SRMLib.MathLibrary; import SRMLib.TestSRMLib; import com.sun.org.apache.bcel.internal.generic.F2D; import java.io.*; import java.util.*; import java.util.logging.Handler; import java.util.zip.Inflater; public class SRM { public static void main(String[] args) throws IOException { //TestSRMLib.run(); codeJam.main(); return; } } class codeJam { public static void main() throws IOException { String inputPath = ""E:\\input.txt""; String outputPath = ""E:\\output.txt""; BufferedReader input = new BufferedReader(new FileReader(inputPath)); BufferedWriter output = new BufferedWriter(new FileWriter(outputPath)); String line; line = input.readLine(); int T = Integer.parseInt(line); for (int i = 1; i <= T; ++i) { line = input.readLine(); String[] words = line.split("" ""); Integer A = Integer.parseInt(words[0]); Integer B = Integer.parseInt(words[1]); int res = 0; int l = A.toString().length(); int multiplier = 1; for (int k = 1; k < l; ++k) multiplier *= 10; for (int n = A; n < B; ++n) { int m = n; Set set = new HashSet(); for (int j = 1; j < l; ++j) { m = (m % multiplier) * 10 + m / multiplier; if ((n < m) && (m <= B)) { if (!set.contains(m)) { res++; set.add(m); } } } } output.write(""Case #"" + i + "": "" + res); output.newLine(); } input.close(); output.close(); } }" B10843,"import java.io.File; import java.io.FileWriter; import java.util.*; public class Recycled { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new File(""./src/recycledS-input.txt"")); FileWriter fw = new FileWriter(""./src/recycledS-output.txt""); int total = sc.nextInt(); for(int turn = 1; turn <= total; turn++) { int res = 0; int A = sc.nextInt(), B = sc.nextInt(); for(int i = A; i < B; i++) { //Translating the integer into an array String si = """"+i; String Ai = """"+A; int li = Ai.length(); int[] tab = new int[li]; //fw.write(""The length is "" + li + ""\n""); for ( int j=0; j= 1 && num2 <= 1000){ for(int n = num1; n <= num2; n++){ for(int m = n + 1; m <= num2; m++){ if(isRecycled(n, m)) result++; } } } System.out.println(result); } in.close(); }catch (Exception e){ System.err.println(""Error: "" + e.getMessage()); } } } " B13124,"import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) { Scanner mark = new Scanner(System.in); int t = mark.nextInt(); int A, B, counter; mark.nextLine(); for (int i = 0; i < t; i++) { A = mark.nextInt(); B = mark.nextInt(); counter = 0; mark.nextLine(); // This is for N for (int n = A; n < B; n++) { HashSet ans = new HashSet(); String strval = String.valueOf(n).trim(); int count = strval.length(); for (int j = 1; j < count; j++) { String beg = strval.substring(0, j); String end = strval.substring(j); // System.out.println(beg+end+"" ""+end+beg); int m = Integer.parseInt( end.concat(beg) ); if( (m > n) && (m <= B)) ans.add(m); } counter += ans.size(); } System.out.printf(""Case #%d: %d\n"",i+1,counter); } } } " B11242,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); int count = 0; try { count = Integer.parseInt(input.readLine()); } catch (Exception e) { System.out.println(e.toString()); System.exit(1); } DataModel[] dm = new DataModel[count]; for(int i = 1; i<=count; i++) { try { dm[i-1] = new DataModel(input.readLine(),i); dm[i-1].run(); } catch (IOException e) { System.out.println(e.toString()); System.exit(1); } } for(int i = 1; i<=count;i++) { while(!dm[i-1].isDone()) {} dm[i-1].getOutput(); } } } " B12454,"import java.io.*; public class RecycledNumbers { public static void main(String[] args) throws IOException { BufferedReader bfr = new BufferedReader( new InputStreamReader(System.in)); PrintWriter pr = new PrintWriter(System.out); int n = Integer.parseInt(bfr.readLine()); for (int i = 1; i <= n; i++) { String input[] = bfr.readLine().split("" ""); int max = Integer.parseInt(input[1]); int count = 0; int min = Integer.parseInt(input[0]); for (; min < max; min++) { String moved = String.valueOf(min).charAt( String.valueOf(min).length() - 1) + String.valueOf(min).substring(0, String.valueOf(min).length() - 1); if (Integer.parseInt(moved) <= max && Integer.parseInt(moved) > min) count++; while (Integer.parseInt(moved) != min) { moved = moved.charAt(moved.length() - 1) + moved.substring(0, moved.length() - 1); if (Integer.parseInt(moved) <= max && Integer.parseInt(moved) > min) count++; } } pr.printf(""Case #%d: %d\n"", i, count); pr.flush(); } } } " B10394," import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class SmallMain { public static void main( String arg[] ) throws IOException { BufferedReader reader = new BufferedReader( new InputStreamReader( System.in ) ); String line = null; int test = 0; int testCases = 0; while( ( line = reader.readLine() ) != null && test <= testCases ) { if( line != null && !line.isEmpty() ) { String tokens[] = line.split( "" "" ); if( tokens.length == 1 && testCases == 0 ) { testCases = Integer.parseInt( tokens[ 0 ] ); } else if( tokens.length == 2 ) { ++test; int start = Integer.parseInt( tokens[ 0 ] ); int end = Integer.parseInt( tokens[ 1 ] ); int counter = 0; for( int i = start; i <= end; ++i ) { for( int j = start; j <= end; ++j ) { if( i < j ) { for( int s = 1; s < ( """" + j ).length(); ++s ) { if( i == moveDigits( j, s ) ) { ++counter; break; } } } } } System.out.println( ""Case #"" + ( test ) + "": ""+ counter ); } else { System.out.println( ""Invalid length: "" + tokens.length + "" line: "" + line ); } } } reader.close(); } private static int moveDigits( int number, int digits ) { int r; String n = """" + number; String end = n.substring( n.length() - digits ); String start = n.substring( 0, n.length() - digits ); // System.out.println( ""N: "" + number + "" d: "" + digits + "" start: "" + start + "" end: "" + end ); r = Integer.parseInt( end + start ); return r; } } " B12775," import java.util.HashSet; import java.util.Scanner; public class C { public static void main(String args[]) { Scanner in = new Scanner(System.in); int t = in.nextInt(); for (int i = 0; i < t; i++) { int a = in.nextInt(); int b = in.nextInt(); int ans = 0; int bten = 1; for (int j = a; j <= b; j++) { while (j/bten*10!=0) bten*=10; int l = 0; HashSet aa = new HashSet(); for (int ten = 10;j/ten>0;ten*=10) { int f = j / ten; int s = j % ten; int m =s * (bten/ten) + f; if (m>j && m<=b) { aa.add(m); } } ans+=aa.size(); } System.out.println(""Case #""+(i+1)+"": ""+ans); } } } " B11717,"import java.util.ArrayList; import java.util.Scanner; public class QuestionC extends Question{ private int A; private int B; private int significant; private int digits; public QuestionC(Result result, Counter counter) { super(result, counter); } @Override public void readInput(Scanner scanner) { A = scanner.nextInt(); B = scanner.nextInt(); digits = Integer.toString(A).length(); significant = (int)Math.pow(10, digits-1); } @Override public String solution() { int counter = 0; ArrayList used = new ArrayList(); for (int i = A; i < B; i++) { int shifted = i; for (int j = 0; j < digits-1; j++) { shifted = (shifted%10)*significant+shifted/10; if (shifted > i && shifted <= B && !used.contains(shifted)) { counter++; used.add(shifted); } } used.clear(); } return Integer.toString(counter); } } " B11276,"package Jam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; public class ProblemC { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub ProblemC p = new ProblemC(); p.readAndOutput(); } public int cmp(byte[] s1,int start,byte[]s2) { int tmp = 0; for( int i = 0;i hm; public void print(byte[] tmp,int st) { StringBuffer sb = new StringBuffer(); for( int i = 0;i= tmp.length ) { if( st == -1 ) return 0; if( cmp(tmp,0,min) >=0 && cmp(tmp,0,max) <=0 && cmp(tmp,st,min) >=0 && cmp(tmp,st,max) <=0 ) { print(tmp,st); return 1; }else { return 0; } } int sum = 0; byte k; if( st == -1 ) { k = (byte) (tmp[0] + 1); for(;k<=max[0];k++) { tmp[pos] = k; sum += l_cal(tmp,pos+1,pos); } } for( k = '0'; k <= '9'; k++ ) { tmp[pos] = k; sum += l_cal(tmp,pos+1,st); } return sum; } public int m_cal(byte[] tmp,int pos,int st) { if( pos >= tmp.length ) { if( st == -1 ) return 0; if( cmp(tmp,st,tmp) > 0 && cmp(tmp,0,min) >=0 && cmp(tmp,0,max) <=0 && cmp(tmp,st,min) >=0 && cmp(tmp,st,max) <=0 ) { print(tmp,st); return 1; }else { return 0; } } int sum = 0; byte k; if( st == -1 ) { tmp[pos] = tmp[0]; sum += m_cal(tmp,pos+1,pos); } for( k = '0'; k <= '9'; k++ ) { tmp[pos] = k; sum += m_cal(tmp,pos+1,st); } return sum; } public int cal() { int sum = 0; byte tmp[] = new byte[min.length]; int range = max[0] - min[0] + 1; int len = min.length; hm = new HashMap(); for( int i = 0; i map; int counter; public Algorithm(String line){ Scanner scan = new Scanner(line); A = scan.nextInt(); B = scan.nextInt(); half = (B-A)/2; map = new ArrayList(); counter = 0; } public int getOutput(){ return counter; } public void solve(){ for(int x = B; x >= A; x--){ String xString = Integer.toString(x); for(int y = 1; y<=xString.length()/2; y++){ for (int i = 0; i j && iRecycl <= B) { n++; } } } resultat += """" + n; } fWriter.append(resultat + ""\r\n""); i++; } scanner.close(); fWriter.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } " B10430,"package codejam; import java.io.*; public class FileRead { String fileName; FileReader fr; BufferedReader br; FileRead(String fileName) { this.fileName=fileName; File f=new File(""K:\\CodeJam\\Input\\""+fileName);//Create a file object FileReader fr; try { fr = new FileReader(f); br=new BufferedReader(fr); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //function to read next line. public String readNextLine(){ String text=null; try { text=br.readLine(); } catch (IOException e) { e.printStackTrace(); } return text; } public int readNextInt(){ int n = 0; try{ n=Integer.parseInt(br.readLine().trim()); }catch(Exception e){ System.out.println(""Invalid integer""); } return n; } public int [] readNextIntArray(){ int []n=null; try{ String []numarray=br.readLine().split("" ""); n=new int[numarray.length]; for(int i=0;i= 0 ; i--) { mTemp = nTemp.substring(i) + nTemp.substring(0,i); if(mTemp.startsWith(""0"")) { continue; } else { int temp = Integer.parseInt(mTemp); if(temp > n && temp <= B) { if(checkForNewM(temp, m, totalMForThisN)) { m[totalMForThisN] = temp; totalMForThisN++; counter++; } } } } } // Print the content in the output file out.write(""Case #"" + counterCases + "": "" + counter); if(counterCases < totalNumberOfCases) { out.write(""\n""); } counterCases++; } //Close the input stream in.close(); //Close the output Stream out.close(); } catch(Exception e) { //Catch exception if any System.err.println(""Error: "" + e.getMessage() + "" : "" + e); } } }" B11063,"package fixjava; import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * A work queue that allows the work queue to continue to increase in size if it is discovered that subdivision of work is * necessary. Call hasIdleWorkers() to see if there are idle workers, and have the worker subdivide their work further by calling * enqueueWork(). */ public class ParallelWorkQueueDynamic { private int numThreads; private ExecutorService threadPool; private CompletionService completionService; private int numWorkUnitsEnqueued = 0; private Object lock = new Object(); public ParallelWorkQueueDynamic(int numThreads) { this.numThreads = numThreads; threadPool = Executors.newFixedThreadPool(numThreads); completionService = new ExecutorCompletionService(threadPool); } /** * Enqueue work. Called by the main thread to start processing, and can also be called by workers to subdivide their work. */ public void enqueueWork(Callable workUnit) { synchronized (lock) { numWorkUnitsEnqueued++; } completionService.submit(workUnit); } /** * Test if there are any idle workers. Should only be called from within a worker so that the total number of workers is greater * than zero (to avoid a race). */ public boolean hasIdleWorkers() { return numWorkUnitsEnqueued < numThreads; } /** * Wait for all work submitted by workers to be completed. Throws IllegalArgumentException if any of the worker threads throw an * exception (this causes an ExecutionException). */ public void waitForAllWorkersToQuit() { try { while (numWorkUnitsEnqueued > 0) { // .take() waits for completion of next task and returns a Future for it completionService.take().get(); synchronized (lock) { numWorkUnitsEnqueued--; } } } catch (InterruptedException e) { e.printStackTrace(); throw new IllegalArgumentException(""waitForAllWorkersToQuit() failed with "" + e.getMessage(), e); } catch (ExecutionException e) { e.printStackTrace(); throw new IllegalArgumentException(""waitForAllWorkersToQuit() failed with "" + e.getMessage(), e); } } public void shutdown() { threadPool.shutdown(); } } " B10754,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.HashSet; import java.util.Set; public class G3 { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new FileReader(""d:\\C-small-attempt0.in"")); int n = Integer.parseInt(in.readLine()); BufferedWriter out = new BufferedWriter(new FileWriter(""d:\\g3o.txt"")); int from, to; for (int i = 1; i <= n; i++) { String[] s = in.readLine().split("" ""); from = Integer.parseInt(s[0]); to = Integer.parseInt(s[1]); int answer = solve(from, to); System.out.println(""Case #"" + i + "": "" + answer); out.write(""Case #"" + i + "": "" + answer); out.newLine(); } out.close(); } private static int solve(int from, int to) { int result = 0; int digits = (int) Math.floor(Math.log10(from)); Set set = new HashSet(); for (int i = from; i <= to; i++) { int base10 = 10; int baseBig10 = (int) Math.pow(10., digits); for (int l = 0; l < digits; l++) { int cycled = baseBig10 * (i % base10) + (i/base10); if (cycled != i && cycled>=from && cycled <= to) { result++; if (!set.add(String.valueOf(i)+"" ""+cycled)) System.err.println(i +"" <->""+cycled); } base10 *= 10; baseBig10 /= 10; } } return set.size()/2; } } " B10606,"import java.io.*; import java.util.*; public class Prob3 { public static void main (String[] args) throws IOException { BufferedReader in = new BufferedReader (new FileReader (""C-small-attempt0.in"")); PrintWriter out = new PrintWriter (new FileWriter (""OUT3.txt"")); int T = Integer.parseInt (in.readLine ().trim ()), c, a, b; StringTokenizer st; String temp, hold; ArrayList p; for (int x = 0 ; x < T ; x += 1) { c = 0; st = new StringTokenizer (in.readLine ()); a = Integer.parseInt (st.nextToken ()); b = Integer.parseInt (st.nextToken ()); for (int y = a ; y < b ; y += 1) { if (y > 10) { temp = Integer.toString (y); p = new ArrayList (); for (int z = 0 ; z < temp.length () - 1 ; z += 1) { hold = temp.substring (z + 1) + temp.substring (0, z + 1); if (hold.charAt (0) != '0' && Integer.parseInt (hold) > Integer.parseInt (temp) && Integer.parseInt (hold) <= b && p.contains (hold) == false) { c += 1; p.add (hold); } } } } out.println (""Case #"" + (x + 1) + "": "" + c); } out.close (); } } " B12660,"package codejam; import java.util.Formatter; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { //Counting numbers within a given range, having same sequence of digits public static void main(String[] args) { Scanner in = new Scanner(System.in); int cases = in.nextInt(); for(int i=1;i<=cases;i++){ int a = in.nextInt(); int b = in.nextInt(); int digitCount = new Integer(a).toString().toCharArray().length; HashSet pairs = new HashSet(); for(int num=a; num num && tempNum <=b) pairs.add(new Formatter().format(""[%d, %d]"", num,tempNum).toString()); } } System.out.println(""Case #""+i+"": ""+pairs.size()); } } } " B12221,"import java.util.*; import java.io.*; public class QR_Csmall { public static void main(String[] args) throws Exception{ // Scanner sc = new Scanner(System.in); // PrintWriter pw = new PrintWriter(System.out); // Scanner sc = new Scanner(new FileReader(""input.in"")); // PrintWriter pw = new PrintWriter(new FileWriter(""output.out"")); Scanner sc = new Scanner(new FileReader(""C-small-attempt0.in"")); PrintWriter pw = new PrintWriter(new FileWriter(""C-small-attempt0.out"")); int T; int A, B; int n, m; int ncnt; int cnt; int[] check = new int[3]; boolean ok; T = sc.nextInt(); for(int times = 1; times <= T; times++){ A = sc.nextInt(); B = sc.nextInt(); cnt = 0; for(int i = A; i < B; i++){ n = i; m = 0; ncnt = 0; for(int k = 0; k < check.length; k++){ check[k] = -1; } while(n > 0){ n /= 10; ncnt++; } for(int j = 1; j < ncnt; j++){ ok = true; m = 0; m = (i / (int)Math.pow(10, j)) + ((i % (int)Math.pow(10, j)) * (int)Math.pow(10, ncnt-j)); if(i < m && m <= B){ check[j - 1] = m; for(int l = 0; l < j - 1; l++){ if(check[l] == m){ ok = false; break; } } if(ok) cnt++; } } } System.out.print(""Case #"" + times + "": ""); System.out.print(cnt); System.out.println(); pw.print(""Case #"" + times + "": ""); pw.print(cnt); pw.println(); } sc.close(); pw.close(); } } " B10961,"import java.util.*; import java.lang.*; public class recyce{ public static int count(int A, int B) { HashSet set; int count = 0; int n = (int) Math.log10(A)+1; for(int num = A; num <= B; num++) { int rem = num; int base = 1; set = new HashSet(); for(int k = 1; k < n; k++) { base *= 10; int love = rem/base + (num%base)*((int)Math.pow(10.,n-k)); if(love > num && love >= A && love <= B) { if(!set.contains(love)) { set.add(love); count++; // System.out.println(num + "" "" + love); } } } } return count; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); int A,B; for(int i = 0; i < T; i++) { A = in.nextInt(); B = in.nextInt(); System.out.println(""Case #"" + (i+1) + "": "" + count(A,B)); } } } " B12309,"package com.brootdev.gcj2012.common; import java.io.*; public class Data { public final BufferedReader in; public final PrintWriter out; public Data(String inFile, String outFile) throws IOException { in = new BufferedReader(new FileReader(inFile)); out = new PrintWriter(new BufferedWriter(new FileWriter(outFile))); } public long readLongLine() throws IOException { return DataUtils.readLongLine(in); } public long[] readLongsArrayLine() throws IOException { return DataUtils.readLongsArrayLine(in); } public void writeCaseHeader(long case_) { DataUtils.writeCaseHeader(out, case_); } } " B11656," import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintStream; import java.util.HashMap; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author ale */ public class RecycledNumbers { public static int[][] parseInput(String path) throws FileNotFoundException, IOException{ BufferedReader reader = new BufferedReader(new FileReader(path)); int size = Integer.parseInt(reader.readLine()); int[][] result = new int[size][2]; for (int i = 0; i < size; i++){ String[] nums = reader.readLine().split("" ""); result[i][0] = Integer.parseInt(nums[0]); result[i][1] = Integer.parseInt(nums[1]); } return result; } // somebody has to explain me why it doesn't work // public static int solveInstance(int N, int M){ // boolean[] done = new boolean[M+1]; // int total = 0; // int D = (""""+N).length() -1; // int divisor = (int) Math.round(Math.pow(10, D)); // for (int i = 0; i < N; i++){ // done[i] = true; // } // for (int i = N; i <= M; i++){ // done[i] = false; // } // for (int i = N; i <= M; i++){ // if (!done[i]){ // done[i] = true; // int rotation = i; // int accepted = 1; // for (int j = 0; j < D; j++){ // int msd = rotation/divisor; // rotation = (rotation - divisor*msd)*10 + msd; // if (N <= rotation && rotation <= M && !done[rotation]){ //// if (accepted == 1){System.out.print(""\n@@@@@@@@@@\n""+i + "" "");} //// System.out.print(rotation+"" ""); // done[rotation] = true; // accepted ++; // } // // } // total += accepted*(accepted-1)/2; // } // } // return total; // } // somebody has to explain me why it doesn't work public static int solveInstance(int N, int M){ HashMap map = new HashMap(); int total = 0; int D = (""""+N).length() -1; int divisor = (int) Math.round(Math.pow(10, D)); for (int i = N; i <= M; i++){ int rotation = i; int minimum = i; for (int j = 0; j < D; j++){ int msd = rotation/divisor; rotation = (rotation - divisor*msd)*10 + msd; if (rotation < minimum){ // if (accepted == 1){System.out.print(""\n@@@@@@@@@@\n""+i + "" "");} // System.out.print(rotation+"" ""); minimum = rotation; } } Integer previous = map.put(minimum, 1); if (previous != null){ map.put(minimum, (previous + 1)); } } for (Integer i : map.values()){ total += (i*(i-1))/2; } return total; } public static void main(String[] args) throws FileNotFoundException, IOException{ String dir = ""C:/Users/ale/Desktop/GoogleCodeJam/""; String[] files = new File(dir).list(); int[][] instances = parseInput(dir+files[0]); //parseInput(""C:/Users/ale/Desktop/GoogleCodeJam/C-small-attempt0.in""); PrintStream writer = new PrintStream(new File(""C:/Users/ale/workspace/GoogleCodeJam/src/output.out"")); for (int i = 0; i < instances.length; i++){ int sol = solveInstance(instances[i][0], instances[i][1]); writer.println(""Case #""+(i+1)+"": ""+sol); } writer.close(); } } " B12705,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.util.*; import java.math.*; /** * * @author . */ public class C { public static class Num { int number; String num; ArrayList recycled; Num(int number) { this.number = number; num = new String(); num += number; recycled = new ArrayList(); //pl(number); findAllRecycleds(); } void findAllRecycleds() { String sub; int subValue; for (int i = 1; i < num.length(); i++) { sub = num.substring(i, num.length()) + num.substring(0, i); //pl(""-"" + sub); if (sub.length() == 0 || sub.charAt(0) == '0') { continue; } subValue = Integer.parseInt(sub); if (subValue > number) { recycled.add(subValue); } } Collections.sort(recycled); } int countRecycleds(int max) { int count = 0; for (Integer i : recycled) { if (i <= max) { count++; } else { break; } } return count; } } public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = Integer.parseInt(in.nextLine()); ArrayList array = new ArrayList(2000000); int MIN = 0; int MAX = 10000; for (int i = MIN; i <= MAX; i++) { array.add(new Num(i)); // if (i % 10000 == 0) { // pl(i); // } } for (int kase = 1; kase <= T; kase++) { int A = in.nextInt(); int B = in.nextInt(); //---------------------------------------------------- int count = 0; for (int i = A; i <= B; i++) { count += array.get(i).countRecycleds(B); } pl(""Case #"" + kase + "": "" + count); } } public static void pf(String s, Object... o) { System.out.printf(s, o); } public static void pl(Object o) { System.out.println(o); } public static void pr(Object o) { System.out.print(o); } } " B12408,"package de.pat.dev.y2012.qualification.c; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; /** * @author pat.dev@alice.de * @since 17.04.12 */ public class Main { public static void main(String[] args) { try { BufferedReader reader = new BufferedReader(new FileReader(args[0])); long numberOfTestCases = nextLong(reader); for (int i = 0; i < numberOfTestCases; i++) { RecycledNumber recycledNumber = toRecycledNumber(reader.readLine().trim()); System.out.printf(""Case #%d: %d\n"", i + 1, recycledNumber.pairs().size()); } } catch (IOException e) { e.printStackTrace(); } } private static RecycledNumber toRecycledNumber(String line) { String[] values = line.split(""\\s+""); return new RecycledNumber(toLong(values[0]),toLong(values[1])); } private static long toLong(String value) { return Long.parseLong(value); } private static long nextLong(BufferedReader reader) throws IOException { return toLong(reader.readLine().trim()); } } " B10411,"import java.util.Scanner; import java.io.*; import java.lang.*; class recycle { static int attempts; public static void main(String args[]) throws IOException {int a[]=new int[50],b[]=new int[50],x; recycle obj=new recycle(); int i,m,n,result[]=new int[50]; Scanner cin=new Scanner(System.in); int k=cin.nextInt(); for(i=0;i3) return 0; if(temp1.equals(temp2)) return 1; else { char [] bArray=temp2.toCharArray(); int l=2,temp; temp=bArray[l]; while(l>0) {bArray[l]=bArray[l-1];l--;} bArray[0]=(char )temp; String str = new String(bArray); return three(temp1,str); } } public int four(String temp1, String temp2) { attempts++; if(attempts>4) return 0; if(temp1.equals(temp2)) return 1; else { char [] bArray=temp2.toCharArray(); int l=3,temp; temp=bArray[l]; while(l>0) {bArray[l]=bArray[l-1];l--;} bArray[0]=(char)temp; String str = new String(bArray); return four(temp1,str); } } }" B11704,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jam_c; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author dkozyrev */ public class Jam_C { /** * @param args the command line arguments */ public static void main(String[] args) { List cases = readFile(""C:\\tmp\\testA.txt""); int counter = 1; String delimiter = "" ""; for (Map caseItem : cases) { List lines = Arrays.asList(caseItem.get(""str"").split(delimiter)); int res = findMax(lines); System.out.println(""Case #""+counter+"": "" + res); counter++; } } public static int findMax(List lines) { int max = 0; //10 //40 //10 ? n < m ? 40 // A ? n < m ? B int A = Integer.parseInt(lines.get(0)); int B = Integer.parseInt(lines.get(1)); //System.out.println(isRecycled(123405, 340512)); if (true) return 1; // ArrayList distinct = new ArrayList(); for(int m=A+1 ; m <= B ; m++) { //A ? n < m ? B for(int n=A ; n < m ; n++) { // if(n >=m) // { // continue; // } // if(distinct.contains(m+""""+n)) // { // continue; // } if (isRecycled(n,m) ) { //System.out.println(""compare n and m: "" + n + "" "" + m); max++; // distinct.add(m+""""+n); } } } return max; } public static boolean isRecycled(int n, int m) { //120345 String compareStr = """"; String replaceStr = """"; String nInput = n+""""; String mInput = m+""""; boolean isRecycled = false; int counter = nInput.length()-1; while (n > 0) { replaceStr = (n % 10) + replaceStr; n = n / 10; //System.out.println(replaceStr); if(counter == 0) { break; } compareStr = replaceStr + nInput.substring(0, counter); //System.out.println(compareStr); counter--; if(compareStr.equals(mInput)) { //System.out.println(mInput); return true; } } return isRecycled; } public static List readFile(String fname) { List casesList = new ArrayList(); { FileReader input = null; try { input = new FileReader(fname); BufferedReader bufRead = new BufferedReader(input); String line; int count = 0; line = bufRead.readLine(); Integer cases = Integer.parseInt(line); count++; while (line != null) { if (count == 1) { line = bufRead.readLine(); count++; continue; } Map params = new HashMap(); params.put(""str"", line); line = bufRead.readLine(); casesList.add(params); count++; } bufRead.close(); } catch (FileNotFoundException ex) { Logger.getLogger(Jam_C.class.getName()).log(Level.SEVERE, null, ex); }catch (ArrayIndexOutOfBoundsException e){ System.out.println(""Usage: java ReadFile filename\n""); }catch (IOException e){ System.out.println(e.getMessage()); } finally { try { input.close(); } catch (IOException ex) { Logger.getLogger(Jam_C.class.getName()).log(Level.SEVERE, null, ex); } } } return casesList; } }" B12633,"import java.util.*; public class Recycle { public static void main(String[] args) { Scanner br=new Scanner(System.in); int test=br.nextInt(); int i,j,k,total=0,start,end,temp; String s,t; ArrayList a=new ArrayList(); for(i=0;ij && temp<=end) { if(!a.contains(temp)) { total++; a.add(temp); } } } } System.out.println(""Case #""+(i+1)+"": ""+total); } } } " B13207,"import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; public class ProblemC { static Scanner kb = null; static FileWriter fw = null; public static void main(String [] args) { try { kb = new Scanner(new File(""input.in"")); } catch (FileNotFoundException e) {} int T = kb.nextInt(); //int result = solve(1111, 2222); //System.out.println(""Case #""+2+"": ""+result); FileWriter fstream = null; try { fstream = new FileWriter(""output.txt""); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } BufferedWriter out = new BufferedWriter(fstream); for(int i=1; i<=T; i++) { int A = kb.nextInt(); int B = kb.nextInt(); int result = solve(A, B); try { out.append(""Case #""+i+"": ""+result+""\n""); //out.write(""Case #""+i+"": ""+result); } catch (IOException e) { System.out.println(""error ""+e.getMessage() ); } //System.out.println(""Case #""+i+"": ""+result); } try { out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static int solve(int A, int B) { // 100 500 int count = 0; for(int i=A; i<=B; i++) { String istr = i+""""; // 100 String icyc = istr + istr; // 100100 int len = istr.length(); //System.out.println(""cyc: ""+icyc); ArrayList savedInts = new ArrayList(); savedInts.add(i); for(int j=1; j ""+recycInt); if(recycInt <= B && recycInt>=A && !savedInts.contains(recycInt)) { //System.out.println(""*""); savedInts.add(recycInt); count++; } } } return count/2; } } " B12511,"import java.util.Scanner; public class ProblemC { public static void main(String args[]){ Scanner scanner = new Scanner(System.in); int noTestCases = Integer.parseInt(scanner.nextLine()); for(int i=0;i0){ c=c/10; d++; } System.out.println(d); for(j=a;j<=b;j++){ //System.out.println(j); for(k=1;k<=d-1;k++){ qd=0;dr=0; p=(int)Math.pow(10,k); // System.out.println(p); q=j/p; //System.out.println(q); qs=q; while(qs>0){ qs=qs/10; qd++; } r=q+(j%p)*((int)Math.pow(10,qd)); System.out.println(j); System.out.println(r); System.out.println(m[j][r]); System.out.println(m[r][j]); rs=r; while(rs>0){dr++; rs=rs/10;} System.out.println(dr); System.out.println(""++++++++++""); if(m[j][r]!=1&&m[r][j]!=1&&dr==d&&r<=b&&j NUMSET; public C() { Scanner scan = new Scanner(System.in); int NCASES = scan.nextInt(); for (int ZZ = 1; ZZ <= NCASES; ZZ++) { int A = scan.nextInt(); int B = scan.nextInt(); NUMSET = new TreeSet(); int nDigits = String.valueOf(A).length(); long count = 0; for (int i = A; i <= B; i++) { count += rot(i, A, B, nDigits); } System.out.println(""Case #""+ZZ+"": ""+count); } } private int rot(int num, int min, int max, int len) { NUMSET.clear(); for (int i = 1; i < len; i++) { int divisor = (int) (Math.pow(10, i)); int mult = (int) (Math.pow(10, len-i)); int one = num / divisor; int two = (num % divisor)*mult; int next = two+one; if (next > num && next <= max) { NUMSET.add(next); } } return NUMSET.size(); } }" B10228,"import java.io.*; class yo { public static void main(String args[]) throws IOException { try { FileWriter fs=new FileWriter(""o1.out""); FileInputStream f1=new FileInputStream(""C-small-attempt3 (1).in""); DataInputStream d=new DataInputStream(f1); BufferedReader br=new BufferedReader(new InputStreamReader(d)); BufferedWriter out=new BufferedWriter(fs); String s,s1; s=br.readLine(); int T=Integer.parseInt(s); int cnt=0,nn,f,ll,ul,p; String w1; char temp; for(int i=0;i0;l--) { c[l]=c[l-1]; } c[0]=temp; w1=""""; for(int m=0;mll) if(nn>f) if(nn<=ul) cnt=cnt+1; } f=f+1; } String h=Integer.toString(cnt); out.write(h); out.write(""\r\n""); cnt=0; } out.close(); br.close(); } catch(Exception e){ System.out.println(""Error :""+e); } } }" B10804,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; public class RecycledNumbers { public static String SMALL_IN_FILE_NAME = ""./input.txt""; static PrintStream out = null; /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { File smallIn = new File(SMALL_IN_FILE_NAME); BufferedReader br = new BufferedReader(new FileReader(smallIn)); String s = br.readLine(); int caseCount = Integer.parseInt(s); File smallOut = new File(""./output.txt""); smallOut.createNewFile(); out = new PrintStream(smallOut); // out = System.out; for (int i = 0; i < caseCount; i ++) { out.printf(""Case #%d: "", i+1); s = br.readLine(); TestCase t = new TestCase(s); out.println(t.solve()); } } } " B10463,"package se.pathed.codejam.practice.recycled; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; public class RecycledNumbers { public static void main(String[] args) throws NumberFormatException, IOException{ new RecycledNumbers().run(); } public File getFileFromDisk(String fileName){ String dataFolder = ""C:\\Users\\Patrik\\workspaces\\codejam\\Practis\\data\\""; return new File(dataFolder + fileName); } public static class Problem { int first; int last; } public Problem[] parseInput() throws NumberFormatException, IOException{ Problem[] probs; File f = getFileFromDisk(""C-small-attempt0.in""); FileReader fReader = new FileReader(f); BufferedReader reader = new BufferedReader(fReader); int numCases = Integer.parseInt(reader.readLine()); probs = new Problem[numCases]; for(int i = 0; i < numCases; i++){ String[] res = reader.readLine().split("" ""); Problem p = new Problem(); p.first = Integer.parseInt(res[0]); p.last = Integer.parseInt(res[1]); probs[i] = p; } reader.close(); return probs; } private void run() throws NumberFormatException, IOException { Problem[] problems = parseInput(); File outputFile = getFileFromDisk(""out.txt""); if( outputFile.exists()) outputFile.delete(); PrintWriter outFile = new PrintWriter(outputFile); for(int i = 0; i < problems.length; i++){ int solution = solve(problems[i]); outFile.println(""Case #"" + (i+1) + "": "" + solution); } outFile.flush(); } private int solve(Problem p){ int first = p.first; int last = p.last; int count = 0; HashMap found = new HashMap(); int[] foundInts = new int[Integer.toString(p.last).length() ]; for(int x = first; x <= last; x++){ String s = Integer.toString(x); int foundCount = 0; if(s.length() > 1){ //System.out.println(""Testing value: "" + x); for(int v=1; v < s.length(); v++){ String next = s.substring(v) + s.substring(0,v); //System.out.println(""Testing value: "" + next); if(next.charAt(0) != '0'){ int val = Integer.parseInt(next); if( val <= last && val > x){ // Already submitted boolean f = false; for(int i = 0; i < foundCount; i++){ if( foundInts[i] == val){ f = true; } } if(f != true){ foundInts[foundCount] = val; foundCount++; if( found.containsKey(val) && found.get(val) == x){ System.out.println(""ERROR found duplicate: "" + val); count++; } else { found.put(val, x); count++; } } } } } } } return count; } } " B10113,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; public class ProblemC { public void write(String m){ try{ FileWriter fstream = new FileWriter(""out.txt""); BufferedWriter out = new BufferedWriter(fstream); out.write(m); out.close(); } catch (Exception e){//Catch exception if any System.err.println(""Error: in writing"" + e.getMessage()); } } public static void main(String[] args) { ProblemC r = new ProblemC(); String result = """"; try{ FileInputStream fstream = new FileInputStream(""input.txt""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine = br.readLine(); int cases = Integer.parseInt(strLine); for (int i = 0 ; i < cases ; i++){ String []m = br.readLine().split("" ""); int x1 = Integer.parseInt(m[0]); int x2 = Integer.parseInt(m[1]); result += ""Case #""+(i+1)+"": ""+r.solve(x1,x2)+""\n""; } in.close(); } catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } r.write(result); } private String solve(int x1 , int x2) { String n = """"; int c = 0; for (int i = x1 ; i < x2 ; i++){ int [] x = array(i); for (int j = 0 ; j < x.length ; j++){ if (x[j] <= x2 && x[j] > i){ c++; // n+= i+"" ""+x[j]+""\n""; } } } n += c+""""; return n; } private int[] array(int x) { String m = x+""""; int [] array = new int[m.length()]; array[0] = x; for (int i = 1 ; i < m.length() ; i++){ String g = m.substring(i,m.length())+m.substring(0,i); array[i] = Integer.parseInt(g); } return array; } } " B12031,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; public class Prob3 { public static void main(String[] args) throws NumberFormatException, IOException { // String filePath = ""C://Users//Apoorv//Desktop//test1.txt""; String filePath = ""C://Users//Apoorv//Downloads//C-small-attempt0.in""; BufferedReader br2 = new BufferedReader(new InputStreamReader( new DataInputStream(new FileInputStream(filePath)))); FileWriter fstream = new FileWriter( ""C://Users//Apoorv//Dropbox//Code//workspace//CodeJam//src//tempAnswer.txt""); BufferedWriter out = new BufferedWriter(fstream); String str = null; long count = 0; Integer numCases = 0; numCases = Integer.parseInt(br2.readLine()); for (int curCase = 0; curCase < numCases; curCase++) { System.out.print(""Case #"" + (curCase + 1) + "": ""); out.write(""Case #"" + (curCase + 1) + "": ""); str = br2.readLine(); String[] tokens = str.split("" ""); int num1 = Integer.parseInt(tokens[0]); int num2= Integer.parseInt(tokens[1]); int curLength = getLength(num1); int countOfPossibilities=0; for (Integer curNumber = num1;curNumber1;curIteration--){ char[] charArrayBuilding = new char[charArray1.length]; for(int i=0;icurNumber && newNumber<=num2 && getLength(newNumber)==curLength){ countOfPossibilities++; System.out.print(newNumber + "",""); // out.write(newNumber + "",""); } } } System.out.println(countOfPossibilities); out.write(countOfPossibilities + ""\n""); } out.close(); } private static int getLength(int num1) { int exponent = 1; while(true){ num1/=10; if(num1==0){ return exponent; } else exponent++; } } } " B12493,"import java.util.*; import java.io.*; import java.text.CharacterIterator; import java.text.StringCharacterIterator; public class q_b { public static void main(String [] args) { // Open files try { // Open input file FileInputStream iStream = new FileInputStream(""Sample.in""); // Get the DataInputStream object DataInputStream in = new DataInputStream(iStream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); System.out.println(""Input file opened""); // Create output file FileWriter oStream = new FileWriter(""Sample.out""); BufferedWriter out = new BufferedWriter(oStream); System.out.println(""Output file opened""); // Read File Line By Line (and read first line) String strLine = br.readLine(); int testN = Integer.parseInt(strLine); int caseN = 1; while ((strLine = br.readLine()) != null) { String[] nums = strLine.split("" ""); int a = Integer.parseInt(nums[0]); int b = Integer.parseInt(nums[1]); int nDigits = nums[0].length(); out.write(""Case #"" + caseN + "": ""); System.out.println(a+"" ""+b+"" \tCase #"" + caseN + "": ""); if (nDigits < 2) { out.write(""0""); out.newLine(); System.out.println(""0""); caseN++; continue; } int pow = 1; for(int i=0;i b || j == k) continue; nPairs++; System.out.print(""*** ""); k = j; } System.out.println(); } String result = Integer.toString(nPairs); System.out.println(result); out.write(result); if (caseN != testN) out.newLine(); caseN++; } // Close the streams in.close(); out.close(); }catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } }" B10048,"import java.io.File; import java.io.FileNotFoundException; import java.util.*; import static java.lang.Math.*; public class ProC { /** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { // TODO Auto-generated method stub File file = new File(""A-small-practice.in""); Scanner scr = new Scanner(file); int i= scr.nextInt(); int count =0; for (int a =1; a<= i; a++) { int j =scr.nextInt(); int k =scr.nextInt(); for (int b=j; b<=k;b++){ for (int c =1; cb){ count ++; // System.out.println(b+"" ""+num); } } } System.out.println(""Case #"" +a+"": ""+count); count=0; } } } " B11653,"import java.io.*; import java.util.*; public class RecycledNumbers { public static void main(String[] args) { try { Scanner in = new Scanner(new File(""C:/Users/Ross/Downloads/C-small-attempt1.in"")); int T = in.nextInt(); String out = """"; for(int i = 0; i < T; i++) { int A = in.nextInt(); int B = in.nextInt(); int count = 0; for(int j = A; j < B; j++) { String num = Integer.toString(j); ArrayList pairs = new ArrayList(); for(int k = 1; k < num.length(); k++) { String num2 = num.substring(num.length()-k,num.length())+num.substring(0,num.length()-k); int nnum = Integer.parseInt(num2); if(nnum > j && nnum <= B && Integer.toString(nnum).length()==num.length()){ if(pairs.indexOf(nnum) == -1) { count++; pairs.add(nnum); } } } } out += ""Case #"" + (i+1) + "": ""; out += count + ""\n""; } System.out.println(out); } catch(Exception e) { e.printStackTrace(); } } } " B10687,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.Arrays; /** * Created by IntelliJ IDEA. * User: Abhishek * Date: 4/14/12 * Time: 1:09 PM * To change this template use File | Settings | File Templates. */ public class RecNum { public int recycled(String a, String b){ int a1 = Integer.parseInt(a); int b1 = Integer.parseInt(b); int num = a1; int count=0; while(num<=b1){ String x = String.valueOf(num); ArrayList store = new ArrayList(10); for(int i=1; inum && !store.contains(y)){ count++; store.add(y); } } num++; } return count; } public static void main(String[] args) { RecNum spk = new RecNum(); try { BufferedReader buff = new BufferedReader(new FileReader(""C-small-attempt0.in"")); FileWriter fstream = new FileWriter(""out1.txt""); BufferedWriter out = new BufferedWriter(fstream); int numTest = Integer.parseInt(buff.readLine()); if (numTest < 1 || numTest > 50) System.exit(0); for (int k = 0; k < numTest; k++) { String[] inp = buff.readLine().split("" ""); out.write(""Case #"" + (k + 1) + "": "" + spk.recycled(inp[0],inp[1])); out.write(""\n""); // System.out.println(""Case #"" + (k + 1) + "": "" + spk.recycled(inp[0],inp[1])+""\n""); } out.close(); } catch (Exception e) { System.out.println(""Exception"" + e); } } } " B12028,"import java.util.*; import java.io.*; public class Main { final static String FNAME = ""A-small-practice""; public BufferedReader in; public PrintWriter out; void open() throws IOException { in = new BufferedReader( new FileReader( new File( FNAME + "".in"" ) ) ); out = new PrintWriter( new File( FNAME + "".out"" ) ); } void close() throws IOException { out.close(); } void run() throws IOException { String str = in.readLine(); String[] input; int min,max,firstdigit, count; String newNum, converted; int num = new Integer( str ); int[] array; for(int i = 0; inew Integer(newNum) && new Integer(converted)<=max && notsame) { count++; } } } out.println( ""Case #"" + (i+1) + "": ""+ count ); } } public static void main( String[] args ) throws IOException { new Thread() { public void run() { try { Main solution = new Main(); solution.open(); solution.run(); solution.close(); } catch ( Exception e ) { throw new RuntimeException( e ); } } }.start(); } }" B13241,"package codejam; import java.io.*; import java.util.Scanner; public final class ReadWriteTextFile { /** Constructor. */ ReadWriteTextFile(){ try { out =new BufferedWriter(new FileWriter(""output.in"")); scanner = new Scanner(new FileInputStream(""input.in"")); } catch (FileNotFoundException ex) { }catch (IOException ex) { } } /** Write fixed content to the given file. */ void writeNextLine(int text) { try { out.write(""Case #""+lineNumber +"": ""+text+""\r\n""); System.out.println(""Case #""+lineNumber +"": ""+text); } catch (IOException ex) { } lineNumber++; } String readLine() { String output = scanner.nextLine(); return output; } int readIntLine(){ String output = scanner.nextLine(); return Integer.decode(output).intValue(); } int readInt(){ return scanner.nextInt(); } public void close() { try { out.close(); } catch (IOException ex) { } scanner.close(); } // PRIVATE private int lineNumber = 1; private BufferedWriter out = null; private Scanner scanner = null; }" B13213,"import java.io.*; import java.util.*; public class C { HashMap map = new HashMap(); public static void main(String args[]) { try { InputStreamReader isr = null; try { isr = new InputStreamReader(System.in, ""UTF-8""); BufferedReader br = null; try { br = new BufferedReader(isr); new C().solve(br); } finally { if (br != null) br.close(); } } finally { if (isr != null) isr.close(); } } catch (IOException ex) { ex.printStackTrace(); System.exit(1); } } public void solve(BufferedReader br) throws IOException { String line = null; int T = Integer.parseInt(br.readLine()); for (int count = 1; count <= T; count++) { doOne(count, br.readLine()); } } public void doOne(int count, String line) { TreeMap> map = new TreeMap>(); List list = null; List keys = null; String key = null; String nstr = null; String sstr = null; String lines[] = line.split("" ""); int startNum = Integer.parseInt(lines[0]); int endNum = Integer.parseInt(lines[1]); for (int n = startNum; n <= endNum; n++) { nstr = Integer.toString(n); keys = makeKeys(nstr); key = null;; for (int i = 0; i < keys.size(); i++) { key = keys.get(i); list = map.get(key); if (list != null) break; } if (list == null) { key = nstr; list = new ArrayList(); } list.add(nstr); map.put(key, list); } Set keySet = map.keySet(); Iterator keyIte = keySet.iterator(); int total = 0; while(keyIte.hasNext()) { String mapKey = keyIte.next(); List data = map.get(mapKey); // System.out.println(mapKey + "":"" + data); if (data.size() > 1) total += data.size() * (data.size() - 1) / 2; } System.out.println(""Case #"" + count + "": "" + total); } public List makeKeys(String nstr) { Listlist = new ArrayList(); char nchar[] = new char[nstr.length()]; for (int i = 0; i < nchar.length; i++) nchar[i] = nstr.charAt(i); char kchar[] = new char[nstr.length()]; for (int startc = 0; startc < nchar.length; startc++) { for (int c = 0; c < nchar.length; c++) kchar[c] = nchar[(startc + c) % nchar.length]; list.add(new String(kchar)); } return list; } } " B13146,"package com.qualification; import java.io.*; import java.util.ArrayList; import java.util.List; public class Two { public static void main(String[] args) throws FileNotFoundException, IOException { FileReader fr = new FileReader(""/Users/minerva/Desktop/input.txt""); FileWriter fw = new FileWriter(""/Users/minerva/Desktop/output.txt""); BufferedReader br = new BufferedReader(fr); PrintWriter pr = new PrintWriter(fw); int numInputs = Integer.valueOf(br.readLine()); for(int i=0;i rmap = new ArrayList(); public Shifter(long input) { this.input = input; } private List generate() { int length = new Long(input).toString().length(); long pow10 = (long)Math.pow(10,length); for (int pow = 10;;pow *= 10) { long n1 = input / pow; long n2 = input % pow; if (n1 == 0) break; long n3 = n2 * pow10 / pow + n1; //System.out.print(n1 + "","" + n2 + "" ("" + input + "","" + n3 + "")""); if (n3 > input) { //System.out.println(""*""); int n3len = new Long(n3).toString().length(); if (n3len == length && !rmap.contains(n3)) rmap.add(n3); } else { //System.out.println(); } } return rmap; } public static long count(long num1, long num2) { long count = 0; for (long i = num1; i <= num2; i++) { List results = new Shifter(i).generate(); for(Long item:results) { if (item <= num2) { count++; //System.out.println(""("" + i + "","" + item + "")""); } } } return count; } } /* in op * 1234 2341 */ " B10205," public class Recycled { JamInputReader ir; public Recycled(String fileName) { ir = new JamInputReader(fileName); int t = ir.getNumItems(); for(int i = 0; i < t; i++) { System.out.println(""Case #"" + (i + 1) + "": "" + proc(ir.getNextItem(), ir.getNextItem())); } } int proc(String A, String B) { int r = 0; int a, b, d; a = Integer.parseInt(A); b = Integer.parseInt(B); d = A.length(); for(int i = a; i <= b; i++) { r += checkRecycleList(a, b, d, i); } return r; } boolean nodup(int[]l, int c, int m) { for(int i = 0; i< c; i++) if(l[i] == m) return false; return true; } int checkRecycleList(int a, int b, int d, int m) { int[] l = new int[d]; int c = 0; int n = m; int d10 = (int)Math.pow(10, d - 1); for(int i = 0; i < d - 1 ; i++) { int temp = m % 10; m = m / 10 + (temp * d10); if(m >= a && m <= b && n < m && nodup(l, c, m)) { l[c] = m; c++; } } return c; } public static void main(String[] args) { new Recycled(args[0]); } } " B12302,"package codejam; import java.io.*; import java.util.*; //out.println(""Case #""+(tt++)+"": ""+line.trim()); public class Plantilla2 { public static class pair implements Comparable { int a; int b; pair(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(pair o) { if (this.a == o.a && this.b == o.b) { return 0; } return this.toString().compareTo(o.toString()); } public String toString() { return this.a + "" "" + this.b; } } public static String girar(String str) { return str.charAt(str.length() - 1) + str.substring(0, str.length() - 1); } public static void main(String args[]) throws Exception { BufferedReader br = new BufferedReader(new FileReader(new File(""in.in""))); PrintWriter out = new PrintWriter(new File(""out.out"")); // System.out.println(girar(""5600070"")); int N = Integer.parseInt(br.readLine()); for (int i = 1; i <= N; i++) { String ss[] = br.readLine().split(""[ ]+""); int A = Integer.parseInt(ss[0]); int B = Integer.parseInt(ss[1]); TreeSet ts = new TreeSet(); String yy; for (int j = A; j < B; j++) { String xx = """" + j; for (int k = 0; k < String.valueOf(j).length(); k++) { yy = girar(xx); if (A <= j && j < Integer.parseInt(yy) && Integer.parseInt(yy) <= B) { ts.add(new pair(j, Integer.parseInt(yy))); } xx = yy; } } out.println(""Case #"" + i + "": "" + ts.size()); } out.close(); br.close(); System.exit(0); } } " B11138,"package recyclednumbers.util; import java.util.ArrayList; import java.util.List; import recyclednumbers.recycler.Recycler; public class Main { public static void main(String[] args) { String inputFile = ""small-data-input""; String outputFile = ""small-data-output""; Recycler recycler = new Recycler(); List inputLines = IOUtil.readLines(inputFile); inputLines.remove(0); //Burn first line List outputLines = new ArrayList(); for (String line : inputLines) { int first = Integer.parseInt(line.split("" "")[0]); int second = Integer.parseInt(line.split("" "")[1]); outputLines.add(recycler.countPairs(first, second) + """"); } IOUtil.writeLines(outputFile, outputLines); } } " B10393,"package hasnaer.puzzles.codejam; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; /** * * @author hasnae rehioui */ public class RecycledNumbers { public static Map> _map = new HashMap>(); static{ for(int i = 0; i < 3000; i++){ if(i <= 10){ _map.put(i, new ArrayList()); } else{ String _str = Integer.toString(i); List _list = new ArrayList(); for(int j = 1; j < _str.length(); j++){ _str = _str.substring(1).concat(_str.substring(0, 1)); int _val = Integer.parseInt(_str); if(_val > i){ _list.add(_val); } } _map.put(i, _list); } } } public static void main(String[] args) throws Exception { // Scanner _input = new Scanner(System.in); Scanner _input = new Scanner(new FileInputStream(""C-small-attempt0.in"")); // BufferedWriter _writer = new BufferedWriter(new OutputStreamWriter(System.err)); BufferedWriter _writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(""C-small-attempt0.out""))); int _t = _input.nextInt(); for(int i = 0; i < _t; i++){ int _a = _input.nextInt(); int _b = _input.nextInt(); // System.out.println(String.format(""_a:%s;_b:%s"", _a, _b)); int _cnt = 0; for(int j = _a; j <= _b; j++){ List _list = _map.get(j); for(Integer _num : _list){ if(_num <= _b){ _cnt++; // System.out.println(String.format(""[%s,%s]"", j, _num)); } } } _writer.write(String.format(""Case #%s: %s\n"", i + 1, _cnt)); } _writer.close(); } }" B12240,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; public class RecycledNumbers { private static FileReader freader; private static BufferedReader buffreader; private static FileWriter fwriter; private static BufferedWriter buffwriter; public static void main(String[] args) throws IOException { freader = new FileReader(""C-small-attempt0.in""); buffreader = new BufferedReader(freader); fwriter= new FileWriter(""result.txt""); buffwriter = new BufferedWriter(fwriter); String str = null; int linenum = 0; int i=1; while((str=buffreader.readLine())!=null){ if(i==1) linenum=Integer.parseInt(str); else{ int start = Integer.parseInt(str.split("" "")[0]); int end = Integer.parseInt(str.split("" "")[1]); int num = calRecycleNum(start, end); String finalStr = ""Case #""+Integer.toString(i-1)+"": ""+Integer.toString(num)+""\n""; buffwriter.write(finalStr); } i++; } buffwriter.close(); fwriter.close(); buffreader.close(); freader.close(); } public static int calRecycleNum(int start, int end){ int num = 0; for(int i=start; i<=end; i++){ int len = Integer.toString(i).length(); int recycleVal = i; HashSet targetSet = new HashSet(); for(int j=1; j=start){ if(!targetSet.contains(recycleVal)){ num++; //System.out.println(i+""\t""+recycleVal); targetSet.add(recycleVal); } /*else{ System.out.println(""Duplicate:""+recycleVal+""\t""+i); }*/ } } } //System.out.println(num); return num; } public static int recycleOnce(int val, int length){ return (int) (val%Math.pow(10, length-1)*10+val/Math.pow(10, length-1)); } } " B10779,"import java.util.Scanner; public class Main { public static void main(String[] args) { int a,b,t; Scanner odczyt = new Scanner(System.in); //obiekt do odebrania danych od użytkownika boolean []tab=new boolean [2000000]; t = odczyt.nextInt(); for (int i=1; i<=t;i++) { a=odczyt.nextInt(); b=odczyt.nextInt(); String liczba; String zmiana; int nowa; int ile=0; int poprzedni=-1; for (int j=a;j<=b;j++) { tab[j]=true; } for (int j=a; j<=b;j++) { liczba=Integer.toString(j); for (int k=1;kj && nowa>=a && nowa <=b && tab[nowa] && nowa!=poprzedni) { ile++; tab[j]=false; poprzedni=nowa; //System.out.print(j+"" ""+nowa+""\n""); } } } System.out.print(""Case #""+i+"": ""+ile+'\n'); } } } " B11468,"package common; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.LinkedList; import java.util.Queue; public class FileTranslatorBasis { private int numOfCase; private File file; Queue dataList = new LinkedList(); public static FileTranslatorBasis getInstance(String fname){ if(fname ==null){ throw new IllegalArgumentException(); } return new FileTranslatorBasis(new File(fname)); } private FileTranslatorBasis(File file) { this.file = file; read(); } private void read(){ try{ FileReader fr = new FileReader(this.file); BufferedReader br = new BufferedReader(fr); String line; while((line = br.readLine())!=null){ dataList.add(line); } }catch(IOException e){ e.printStackTrace(); } numOfCase = Integer.parseInt(dataList.poll()); } public int getNumOfCase(){ return numOfCase; } public int getIntData(){ return Integer.parseInt(dataList.poll()); } public int[] getIntDataArray(){ String[] tmp = getStrDataArray(); int[] data = new int[tmp.length]; int i = 0; for(String t: tmp){ data[i++] = Integer.parseInt(t); } return data; } public long getLongData(){ return Long.parseLong(dataList.poll()); } public long[] getLongDataArray(){ String[] tmp = getStrDataArray(); long[] data = new long[tmp.length]; int i = 0; for(String t: tmp){ data[i++] = Long.parseLong(t); } return data; } public String getStrData(){ return dataList.poll(); } public String[] getStrDataArray(){ return dataList.poll().split("" ""); } } " B11747,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; import java.awt.List; import java.io.*; import java.util.ArrayList; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author user */ public class CodeJam { /** * @param args the command line arguments */ public static void main(String[] args) { FileReader fin = null; FileWriter fout = null; ArrayList ar = new ArrayList<>(); java.util.List kr; try { fin = new FileReader(""input.txt""); fout = new FileWriter(""Output.txt""); BufferedWriter out = new BufferedWriter(fout); BufferedReader in = new BufferedReader(fin); int t; t = Integer.parseInt(in.readLine()); int j = 0,A,B; String[] k; while (t > j) { int count = 0; ar.clear(); k = in.readLine().split("" ""); A = Integer.parseInt(k[0]); B = Integer.parseInt(k[1]); for (int i = A; i <= B; i++) { ar.add(Integer.toString(i)); } StringBuilder n; for (int m = 1; m < ar.size(); m++) { ArrayList li = new ArrayList<>(); n = new StringBuilder(ar.get(m)); char c; for (int i = 0; i < n.length(); i++) { li.add(n.toString()); c = n.charAt(0); n.deleteCharAt(0); n.append(c); } kr = ar.subList(0, m-1); for (int i = 0; i < li.size(); i++) { if (kr.contains(li.get(i))) { count ++; } } } out.write(""Case #"" + (j + 1) + "": "" + count + ""\n""); out.flush(); j ++; } } catch (IOException ex) { Logger.getLogger(CodeJam.class.getName()).log(Level.SEVERE, null, ex); } finally { try { fin.close(); fout.close(); } catch (IOException ex) { Logger.getLogger(CodeJam.class.getName()).log(Level.SEVERE, null, ex); } } } } " B10221,"package com.code.jam; import java.io.File; import java.io.PrintStream; import java.util.Scanner; import org.apache.commons.lang.StringUtils; public class CRecycledNumbers { public static void main(String[] args) throws Exception { Scanner in = new Scanner (new File(""C:/codeJam/ficheros2012/CRecycledNumbers.in"")); PrintStream ps = new PrintStream(""C:/codeJam/ficheros2012/CRecycledNumbers.out""); int T = new Integer (in.nextLine()); for (int nCase = 1; nCase < T + 1; nCase++) { Scanner inLine = new Scanner (in.nextLine()); int recycledPair = 0; int A = inLine.nextInt(); int B = inLine.nextInt(); int lengthI = String.valueOf(A).length(); if (lengthI > 1){ for (int n = A; n <= B; n++){ int operatorGetLeftRight = 1; int operatorNewNumber = Integer.valueOf(StringUtils.rightPad(""1"", lengthI + 1, '0')); for (int j = 1; j < lengthI; j++) { operatorGetLeftRight *= 10; operatorNewNumber /= 10; int newLeft = n % operatorGetLeftRight; int newRight = (n - newLeft) / operatorGetLeftRight; int m = newLeft * operatorNewNumber + newRight; if ((m >= A) && (m <= B) && (n < m)){ recycledPair++; // if (lengthI == 4){ // System.out.format(""(%d, %d) \n"", n, m); // } } } } } System.out.format(""Case #%d: %d\n"", nCase, recycledPair); ps.format(""Case #%d: %d\n"", nCase, recycledPair); } // ps.flush(); // ps.close(); } } " B12004,"package recycledNumbers; public class Limits { private int lower; private int upper; public Limits(int l, int u) { this.lower = l; this.upper = u; } public int getLow() { return lower; } public int getUpp() { return upper; } } " B11810,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejamc; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; /** * * @author strigazi */ public class TextFile implements Iterable { // Used by the TextFileIterator class below final String filename; public TextFile(String filename) { this.filename = filename; } // This is the one method of the Iterable interface public Iterator iterator() { return new TextFile.TextFileIterator(); } // This non-static member class is the iterator implementation class TextFileIterator implements Iterator { // The stream we're reading from BufferedReader in; // Return value of next call to next() String nextline; public TextFileIterator() { // Open the file and read and remember the first line. // We peek ahead like this for the benefit of hasNext(). try { in = new BufferedReader(new FileReader(filename)); nextline = in.readLine(); } catch(IOException e) { throw new IllegalArgumentException(e); } } // If the next line is non-null, then we have a next line public boolean hasNext() { return nextline != null; } // Return the next line, but first read the line that follows it. public String next() { try { String result = nextline; // If we haven't reached EOF yet if (nextline != null) { nextline = in.readLine(); // Read another line if (nextline == null) in.close(); // And close on EOF } // Return the line we read last time through. return result; } catch(IOException e) { throw new IllegalArgumentException(e); } } // The file is read-only; we don't allow lines to be removed. public void remove() { throw new UnsupportedOperationException(); } } } " B11689," import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; public class Main { public static void main(String args[]) { { FileWriter fostream = null; FileInputStream fis = null; DataInputStream in = null; BufferedReader br = null; BufferedWriter bw = null; int count = 0; int testCase; ArrayList a; try { fis = new FileInputStream(""src\\io\\C-small-attempt1.in""); //fis = new FileInputStream(""src\\io\\C-large-attempt0.in""); //fis = new FileInputStream(""src\\io\\C-small-practice.txt""); in = new DataInputStream(fis); br = new BufferedReader(new InputStreamReader(in)); fostream = new FileWriter(""src\\io\\C-out-small2.txt"", false); // fostream = new FileWriter(""src\\io\\C-out-large.txt"", false); bw = new BufferedWriter(fostream); StringBuffer str, res = new StringBuffer(); String temp,n ; boolean flag; char c[],check; testCase = Integer.parseInt(br.readLine()); for (int i = 1; i <= testCase; i++) { a = new ArrayList(); String input[] = br.readLine().split("" ""); str = new StringBuffer(); int A = Integer.parseInt(input[0]); int B = Integer.parseInt(input[1]); int total = 0; for (int j = A; j <= B; j++) { // System.out.println(""number "" + j); n= String.valueOf(j); flag = true; c = n.toCharArray(); check = c[0]; for (int p = 1; p < c.length; p++) { if (c[p] == check) { continue; } else { flag = false; break; } } if (!flag) { for (int l = 1; l < c.length; l++) { str = new StringBuffer(); for (int k = 0, m = (l % c.length); k < c.length; k++) { //System.out.print(m); str.append(c[m]); m = ((m + 1) % c.length); } temp = str.toString(); temp = temp.replaceFirst(""^0*"", """"); //System.out.println(temp); if (Integer.parseInt(temp) >= A && Integer.parseInt(temp) <= B) { // System.out.println(j + "" ""+temp); a.add(j); a.add(Integer.parseInt(temp)); /* if(s.contains(j)){ System.out.print(true + "" ""+ count+"" ""); count++; }else{ s.add(j); } if(s.contains(Integer.parseInt(temp))){ // System.out.print(true); //count++; } else{ s.add(Integer.parseInt(temp)); } */ } str = new StringBuffer(); } } str = null; } //System.out.println(s.size() / 2); Collections.sort(a); count= 0; for(int q=0;q mapa = new HashMap(); mapa.put(""""+num,""""+num); String str; int rev; long count=0; for (int i = 0; i < strNum.length()-1; i++) { strNum.append(strNum.charAt(0)); strNum.deleteCharAt(0); rev = Integer.parseInt(strNum.toString()); str = strNum.toString(); if(mapa.get(str)==null){ mapa.put(str, str); if(rev>=min && rev<=max && rev!=num) count++; } } return count; } static int compare(StringBuffer bf1, StringBuffer bf2){ for (int i = 0; i < bf1.length(); i++) { if(bf1.charAt(i)>bf2.charAt(i)){ return 1; }else if(bf1.charAt(i) 9) { digits++; n /= 10; } tens = (int)Math.pow(10, digits-1); for (int i=A; i i && m <= B ) { y++; // System.out.println(i+"" ""+m); } } } return """" + y; } public static void main(String[] args) { PrintWriter pW = null; try { pW = new PrintWriter(new FileOutputStream(path + taskname + "".out"")); try { in = new Scanner(new FileInputStream(path + taskname + "".in"")); int T = in.nextInt(); for (int caseNumber = 1; caseNumber <= T; caseNumber++) { pW.println(""Case #"" + caseNumber + "": "" + solve()); } in.close(); pW.close(); } catch (IOException e) { System.out.println(""Can not find file "" + taskname + "".in""); } } catch (IOException e) { System.out.println(""Open or create exception with "" + taskname + "".out""); } } } " B10534,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.util.StringTokenizer; /** * @author MASTERMIND * */ public class Prog { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub FileReader fr; try { fr = new FileReader(""C-small-attempt0.in""); FileWriter f1 = new FileWriter(""C-small.out""); BufferedReader br = new BufferedReader(fr); int i=1; String s; StringBuffer strbuf = new StringBuffer(); br.readLine(); while((s = br.readLine())!=null) { int count = 0; strbuf.delete(0, strbuf.length()); StringTokenizer st = new StringTokenizer(s,"" ""); int no1 = Integer.parseInt(st.nextToken()); System.out.print(no1+""\t""); int no2 = Integer.parseInt(st.nextToken()); System.out.println(no2); int current = no1; while(current < no2) { String s1 = String.valueOf(current); for(int next=current+1 ; next<=no2 ; next++) { //System.out.println(current+"" ""+next); String s2 = String.valueOf(next); for(int j=1;j p) { result++; } } } out.print(result); /***** end **********/ out.println(); } out.close(); } public static int getLen(long l) { for (int i = 1; i < 10; i++) { if (l < power[i]) { return i; } } return -1; } public static int itoa(int a, char[] s) { int len = 0; while (a > 0) { s[len] = (char) (a % 10 + '0'); a /= 10; len++; } return len; } /* * for (int i = lenCurrent - 1; i >= 0; i--) { int shiftIndex = i + offset; if (shiftIndex >= lenCurrent) { shiftIndex -= lenCurrent; } if (lenMax <= lenCurrent && current[shiftIndex] > max[i]) { continue; } } for (int i = lenCurrent - 1; i >= 0; i--) { int shiftIndex = i + offset; if (shiftIndex >= lenCurrent) { shiftIndex -= lenCurrent; } if (lenMax <= lenCurrent && current[shiftIndex] > max[i]) { continue; } if (current[shiftIndex] > current[i]) { ok = true; break; } else if (current[shiftIndex] < current[i]) { break; } } if (ok) { result++; } for (int i = lenCurrent - 1; i >= 0; i--) { int shiftIndex = i + offset; if (shiftIndex >= lenCurrent) { shiftIndex -= lenCurrent; } if (lenMax <= lenCurrent && current[shiftIndex] > max[i]) { continue; } } for (int i = lenCurrent - 1; i >= 0; i--) { int shiftIndex = i + offset; if (shiftIndex >= lenCurrent) { shiftIndex -= lenCurrent; } if (lenMax <= lenCurrent && current[shiftIndex] > max[i]) { continue; } if (current[shiftIndex] > current[i]) { ok = true; break; } else if (current[shiftIndex] < current[i]) { break; } } if (ok) { result++; } */ }" B12409,"package ggpackage; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.util.ArrayList; public class GgClass { private static String[] txt; private static String newtxt=""""; private static String oldtxt=""""; private static String[] oldtxt2; private static int numberC; public static void main(String[] args) throws FileNotFoundException { try{ FileInputStream fstream = new FileInputStream(""C-small-attempt0.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { oldtxt+=strLine+""\n""; } in.close(); }catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } oldtxt2=oldtxt.split(""\n""); numberC = Integer.parseInt(oldtxt2[0]); ArrayList dub = new ArrayList(); for(int L=1;L<=numberC;L++){ int A = Integer.parseInt(oldtxt2[L].split("" "")[0]); int B = Integer.parseInt(oldtxt2[L].split("" "")[1]); int count = 0; //loop from A to mid point if(B<10){}else{ for(int i=A;i<=B;i++){ txt = String.valueOf(i).split(""""); //check for possible combination of an integer for(int k=2;ktxt.length-1){ newtxt+=txt[j+k-(txt.length-1)]; }else{ newtxt+=txt[j+k]; } } while(newtxt.startsWith(""0"")==true){ newtxt=newtxt.substring(1); //System.out.print(newtxt+""\n""); //count if an integer is recyclable } if(newtxt.isEmpty()){}else{ if(Integer.parseInt(newtxt)>i){ //System.out.print(newtxt+""\n""); if(Integer.parseInt(newtxt)<=B){ count++; dub.add(newtxt); } } newtxt=""""; } if(dub.size()==0){}else{ for(int z=0;z<=dub.size()-1;z++){ for(int y=z+1;y<=dub.size()-1;y++){ if(dub.get(z).toString().contentEquals((dub.get(y).toString()))){ count=count-1; } } } } } dub.clear(); } } System.out.print(""Case #""+L+"": ""+count+""\n""); } } } " B12284,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.LinkedList; import java.util.StringTokenizer; public class Principal { public static void main(String [] args) throws IOException { Secundaria sec = new Secundaria(); FileReader fr = new FileReader(""C-small-attempt1.in""); BufferedReader bf = new BufferedReader(fr); FileWriter bw = new FileWriter(""C-small-attempt1.out""); int res; int times = Integer.parseInt(bf.readLine()); String str = bf.readLine(); int i = 1; while(i <= times) { StringTokenizer st = new StringTokenizer(str); int primero = Integer.parseInt(st.nextToken()); int segundo = Integer.parseInt(st.nextToken()); bw.write(""Case #""); bw.write(String.valueOf(i)); bw.write("": ""); res = sec.nVeces(primero, segundo); bw.write(Integer.toString(res)); bw.write(""\n""); str = bf.readLine(); i++; } bw.close(); } } " B12845,"package ru.guredd.codejam; import java.io.*; import java.util.ArrayList; import java.util.List; public class Main { protected static List inputData = new ArrayList(); protected static List outputData = new ArrayList(); public static void loadInputData(String fileName) throws IOException { BufferedReader in = null; try { inputData.clear(); String line; in = new BufferedReader(new FileReader(fileName)); if (!in.ready()) throw new IOException(); while ((line = in.readLine()) != null) inputData.add(line); } finally { if(in != null) { in.close(); } } } public static void saveOutputData(String fileName) throws IOException { BufferedWriter out = null; try { out = new BufferedWriter(new FileWriter(fileName)); for (String anOutputData : outputData) { out.write(anOutputData); out.newLine(); } } finally { if(out != null) { out.close(); } } } public static void main (String [] argv) throws IOException { loadInputData(argv[0]); Qualification2012C QC = new Qualification2012C(); QC.solve(); saveOutputData(argv[1]); } } " B12207,"package hk.polyu.cslhu.codejam.solution.impl.qualificationround; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import hk.polyu.cslhu.codejam.solution.Solution; import org.apache.log4j.Logger; public class SpeakingInTongues extends Solution { private Map codeMap; private String oriText; private void setCodeMap() { this.codeMap = new HashMap(); codeMap.put(""y"", ""a""); codeMap.put(""e"", ""o""); codeMap.put(""q"", ""z""); codeMap.put(""z"", ""q""); List oriTextList = new ArrayList(); oriTextList.add(""ejp mysljylc kd kxveddknmc re jsicpdrysi""); oriTextList.add(""rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd""); oriTextList.add(""de kr kd eoya kw aej tysr re ujdr lkgc jv""); List encodedTextList = new ArrayList(); encodedTextList.add(""our language is impossible to understand""); encodedTextList.add(""there are twenty six factorial possibilities""); encodedTextList.add(""so it is okay if you want to just give up""); for (int i = 0; i < oriTextList.size(); i++) { String oriText = oriTextList.get(i); String encodedText = encodedTextList.get(i); for (int j = 0; j < oriText.length(); j++) { String ori = oriText.substring(j, j + 1); String encoded = encodedText.substring(j, j + 1); if (ori.equals("" "")) continue; if (! codeMap.containsKey(ori)) codeMap.put(ori, encoded); else if (! codeMap.get(ori).equals(encoded)) logger.error(""Found duplicate encoded string for input "" + ori); } } logger.info(""The size of code map is "" + this.codeMap.size()); } @Override public void setProblem(List problemDesc) { // TODO Auto-generated method stub this.oriText = problemDesc.get(0); } @Override public void solve() { // TODO Auto-generated method stub this.setCodeMap(); this.result = """"; for (int i = 0; i < this.oriText.length(); i++) { String ori = this.oriText.substring(i, i + 1); if (ori.equals("" "")) this.result += ori; else if (this.codeMap.containsKey(ori)) this.result += this.codeMap.get(ori); else logger.error(""Failure to find the encoded string for "" + ori); } } } " B10897,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; public class recy { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int stat[] = new int [2000001]; StringBuffer output = new StringBuffer(); try{ FileInputStream fstream = new FileInputStream(""/Users/iToR/Documents/workspace/CodeJam3/src/C-small-attempt4.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; strLine = br.readLine(); int line = (new Integer(strLine)).intValue(); int i = 1; while ((strLine = br.readLine()) != null) { //each case output.append(""Case #""+i+"": ""); String[] temp; /* delimiter */ String delimiter = "" ""; /* given string will be split by the argument delimiter provided. */ temp = strLine.split(delimiter); int orimin = (new Integer(temp[0])).intValue(); int min = (new Integer(temp[0])).intValue(); int max = (new Integer(temp[1])).intValue(); int count = 0; while(min<=max){ //try swap String tempStr = """"+min; String oritempStr = """"+min; int oricheck = (new Integer(oritempStr)).intValue(); stat[min] = 1; for(int k = 0;k0&&check<=max&&check>=orimin){ if(check>oricheck){ count++; System.out.println(oritempStr+"",""+check); } } } min++; } output.append(count); if(i0) { count++; int a = oScan.nextInt(); int b = oScan.nextInt(); int rec = 0; for(int i = a; i numbers = new ArrayList(); int small = Integer.parseInt(str[0]); int large = Integer.parseInt(str[1]); System.out.println(small + "" "" + large); for (int i = small ; i <= large ; i++){ numbers.add(i); } for(int n : numbers){ int len = String.valueOf(n).length(); if (len == 1) continue; if (len == 2 && (String.valueOf(n)).substring(1, 2) != ""0"") { String strN = (String.valueOf(n)).substring(1, 2) + (String.valueOf(n)).substring(0, 1); System.out.println(strN); if (n < Integer.parseInt(strN) && Integer.parseInt(strN) <= large){ possibs++; } } else if (len == 3) { String strN = (String.valueOf(n)).substring(2, 3) + (String.valueOf(n)).substring(0, 2); if (n < Integer.parseInt(strN) && Integer.parseInt(strN) <= large && (String.valueOf(n)).substring(2, 3) != ""0""){ possibs++; } String strNN = (String.valueOf(n)).substring(1, 3) + (String.valueOf(n)).substring(0, 1); if (n < Integer.parseInt(strNN) && Integer.parseInt(strNN) <= large && (String.valueOf(n)).substring(1, 2) != ""0""){ possibs++; } } else if (len == 4) { String strN = (String.valueOf(n)).substring(3, 4) + (String.valueOf(n)).substring(0, 3); if (n < Integer.parseInt(strN) && Integer.parseInt(strN) <= large && (String.valueOf(n)).substring(3, 4) != ""0""){ possibs++; } String strNN = (String.valueOf(n)).substring(2, 4) + (String.valueOf(n)).substring(0, 2); if (n < Integer.parseInt(strNN) && Integer.parseInt(strNN) <= large && (String.valueOf(n)).substring(2, 3) != ""0""){ possibs++; } String strNNN = (String.valueOf(n)).substring(1, 4) + (String.valueOf(n)).substring(0, 1); if (n < Integer.parseInt(strNNN) && Integer.parseInt(strNNN) <= large && (String.valueOf(n)).substring(1, 2) != ""0""){ possibs++; } } } System.out.println(possibs); caseCounter++; out.write(""Case #"" + caseCounter + "": "" + possibs); out.newLine(); } in.close(); out.close(); }catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } } " B11886,"import java.util.Scanner; public class CodeJam3 { public static void main(String[] args) { Scanner kb=new Scanner(System.in); int testCases=kb.nextInt(); for(int i=0;i inputs = readInput(); String n; String m; int count = 0; for(String input : inputs ){ count++; n = input.split("" "")[0]; m = input.split("" "")[1]; output(count, findRecycledNumbers(n,m)); } } private static int findRecycledNumbers(String n, String m){ int recycledNumbers = 0; n = n.trim(); m = m.trim(); int mFirst = Integer.parseInt(m.substring(0,1)); int nLong = Integer.parseInt(n); int mLong = Integer.parseInt(m); String nString = """"; for(int i = nLong; i0; j--){ // System.out.println(""nSTRING: "" + nString); String valueAt = nString.substring(j, j+1); //System.out.println(""VALUE AT: "" + valueAt); if(Integer.parseInt(valueAt) <= mFirst){ //System.out.println(""IN HERE""); String end = nString.substring(j); String remaining = nString.substring(0, j); String finalNum = end + remaining; if(Integer.parseInt(finalNum) <= mLong && Integer.parseInt(finalNum) > nLong){ recycledNumbers++; } } } } return recycledNumbers; } private static List readInput(){ List untranslatedStrings = new ArrayList(); try{ BufferedReader in = new BufferedReader(new FileReader(""input.txt"")); Long numTestCases = Long.parseLong(in.readLine()); for(int i=0; i set = new HashSet(); //smallだけでもとくか for(int i = A;i testCases = new ArrayList(); boolean isCaseNo = true; int testCount = 0; FileReader fr = new FileReader(""C-small-attempt0.in""); BufferedReader br = new BufferedReader(fr); String s; while ((s = br.readLine()) != null) { if (isCaseNo) { testCount = Integer.parseInt(s); isCaseNo = false; } else { testCases.add(s); } } fr.close(); Solve(testCount, testCases); } public static void Solve(int testCount, ArrayList testCases) throws IOException { FileWriter fstream = new FileWriter(""out.txt""); BufferedWriter out = new BufferedWriter(fstream); for (int i = 0; i < testCount; i++) { int A = 0, B = 0, count = 0; String s = testCases.get(i); String[] ar = s.split("" ""); A = Integer.parseInt(ar[0]); B = Integer.parseInt(ar[1]); for(int j = A; j <= B; j++) { ArrayList nums = new ArrayList(); String num = String.valueOf(j); for(int k =0; k < num.length(); k++) { String num1 = num.substring(0, k); String num2 = num.substring(k, num.length()); String newNum = num2 + num1; int newI = Integer.parseInt(newNum); NumberPair np = new NumberPair(j, newI); if (newI >= A && newI <= B && newNum.equals(String.valueOf(newI)) && !num.equals(newNum) && !nums.contains(np)) { count++; nums.add(np); } } } out.write(""Case #"" + (i + 1) + "": "" + count/2 + ""\n""); } out.close(); } } class NumberPair { int m, n; public NumberPair(int m, int n) { this.m = m; this.n = n; } @Override public boolean equals(Object obj) { NumberPair np = (NumberPair)obj; return (np.m == this.m && np.n == this.n) || (np.m == this.n && np.n == this.m); } @Override public int hashCode() { int hash = 7; hash = 61 * hash + this.m; hash = 61 * hash + this.n; return hash; } } " B10339,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ex3; import java.io.*; import java.util.ArrayList; import java.util.HashMap; /** * * @author Jean-Nicolas */ public class Ex3 { public static String readFile(File file) { String result = """"; try { InputStream ips = new FileInputStream(file); InputStreamReader ipsr = new InputStreamReader(ips); BufferedReader br = new BufferedReader(ipsr); String line; while ((line = br.readLine()) != null) { result += line + ""\n""; } br.close(); result.substring(0, Math.max(0, result.length() - 1)); // Deletion of the last \n } catch (Exception e) { System.out.println(e.toString()); } return result; } public static void writeFile(File file, String data) { try { BufferedWriter out = new BufferedWriter(new FileWriter(file)); out.write(data); out.close(); } catch (IOException ex) { System.out.println(""Exception ""); } } /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here String data = readFile(new File(""data.txt"")); String[] lines = data.split(""\n""); String resultStr = """"; ArrayList results = new ArrayList<>(); for (int i = 1; i < lines.length; i++) { String[] values = lines[i].split("" ""); int A = Integer.parseInt(values[0]); int B = Integer.parseInt(values[1]); HashMap alreadyUsed = new HashMap<>(); for (int n = A; n <= B; n++) { String nStr = String.valueOf(n); for (int j = 0; j < nStr.length(); j++) { String nStr2 = nStr.substring(j) + nStr.substring(0, j); int m = Integer.parseInt(nStr2); Pair pair = new Pair(n, m); if (alreadyUsed.get(pair) == null && (A <= n && n < m && m <= B)) { alreadyUsed.put(pair, true); } } } resultStr += ""Case #"" + i + "": "" + alreadyUsed.size() + ""\n""; } resultStr = resultStr.substring(0, resultStr.length() - 1); System.out.println(resultStr); writeFile(new File(""result.txt""), resultStr); } } " B10432,"package codejam; import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.FileReader; import java.io.PrintStream; import java.util.HashSet; import java.util.Set; public class C { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new FileReader(""file.in"")); PrintStream out = new PrintStream(new FileOutputStream(""file.out"")); int nLines = Integer.parseInt(in.readLine()); String[] s; for (int i = 1; i <= nLines; i++) { s = in.readLine().split("" ""); int nA = Integer.valueOf(s[0]); int nB = Integer.valueOf(s[1]); int result = 0; Set set = new HashSet(); if (nB > 10) { int start = Math.max(nA, 11); for (int j = start; j <= nB; j++) { String st = String.valueOf(j); for (int k = 1; k < st.length(); k++) { String res = st.substring(k) + st.substring(0, k); if (!res.startsWith(""0"") && !st.equals(res) && st.length() == res.length()) { int v = Integer.valueOf(res); if (v <= nB && j < v) { set.add(st + "","" + res); } } } } } result = set.size(); out.println(""Case #"" + i + "": "" + result); } in.close(); out.close(); } } " B10585,"package codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; /** * * @author Mudasar */ public class RecycledNumbers { static String strLine =null; static int result = 0; static int first = 0; static int second = 0; public static void main(String[] args) { try { FileInputStream fstream = new FileInputStream(""textfile.in""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter ifstream = new FileWriter(""output.txt""); BufferedWriter out = new BufferedWriter(ifstream); int resultCounter = 0; while ((strLine = br.readLine()) != null) { if (resultCounter == 0) { resultCounter = 1; continue; } String records[] = new String[2]; records = strLine.split("" ""); first = Integer.parseInt(records[0]); second = Integer.parseInt(records[1]); result = recyleAble(first , second); String output = ""Case #"" + resultCounter + "": "" + result + ""\n""; // System.out.println(""Case #"" + resultCounter + "": "" + result); try { out.write(output); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } result = 0; resultCounter++; } in.close(); out.close(); } catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } private static int recyleAble(int _first, int _second) { // TODO Auto-generated method stub int count = 0; for(int i = _first ; i< _second ; i++){ for(int j = i + 1; j <= _second; j ++ ) if(rotateAndCheck(i , j)) count ++ ; } //System.out.println(""/n""); return count; } private static boolean rotateAndCheck(int i, int j) { // TODO Auto-generated method stub int length = Integer.toString(i).length(); int r ; for(int b= (length-1) ; b>=0 ; b--) { r = i % 10 ; i/=10; i = (int) (r*Math.pow(10, length-1) + i ); if ( i == j) { // System.out.print(i + "", ""); return true; }} return false; } } " B12611,"import sun.reflect.generics.tree.Tree; import java.util.ArrayList; import java.util.List; public class MathUtil { static List convertToBase (int num, int base) { ArrayList integers = new ArrayList<>(); if (num == 0) { integers.add(0); return integers; } while (num!=0) { integers.add(num % base); num /= base; } return integers; } static int sumList(Iterable iterable) { int sum = 0; for (Integer integer : iterable) { sum += integer; } return sum; } static int sumSquaredList(Iterable iterable) { int sum = 0; for (Integer integer : iterable) { sum += integer * integer; } return sum; } } " B10652,"package com.snap.training; import java.io.*; import java.util.ArrayList; public class RecycledNumbers { public static ArrayList readFromFile() { ArrayList inputList = new ArrayList(); try { FileReader fr = new FileReader(""C:\\Users\\sanath\\Downloads\\code\\input.in""); BufferedReader br = new BufferedReader(fr); String readLine = null; while((readLine=br.readLine())!=null) { inputList.add(readLine); } } catch (IOException e) { inputList = null; e.printStackTrace(); } return inputList; } public static void writeToFile(ArrayList outputList) { try { FileWriter fw = new FileWriter(""C:\\Users\\sanath\\Downloads\\code\\output.out""); BufferedWriter br = new BufferedWriter(fw); for(int i = 0; i < outputList.size(); i++) { System.out.println(""Case #"" + (i+1) + "": "" + outputList.get(i)); br.write(""Case #"" + (i+1) + "": "" + outputList.get(i)); br.newLine(); } br.close(); } catch (IOException e) { e.printStackTrace(); } } /** * @param args */ public static void main(String[] args) { ArrayList inputList = readFromFile(); String inputStr = null; String finalStr = null; ArrayList outputList = new ArrayList(); int noOfTestCases = Integer.parseInt(inputList.get(0).toString()); int a, b, count = 0; for(int i = 1; i < noOfTestCases + 1; i++) { inputStr = inputList.get(i); finalStr = """"; String[] splitStr = inputStr.split("" ""); a = Integer.parseInt(splitStr[0]); b = Integer.parseInt(splitStr[1]); for(int j = a; j <= b; j++) { char[] tempChar = String.valueOf(j).toCharArray(); char[] tempCharConverted = new char[tempChar.length]; ArrayList checkList = new ArrayList(); for(int k = 1; k < tempChar.length; k++) { for(int l = 0, x = k; l < tempChar.length; l++) { tempCharConverted[l] = tempChar[x]; x++; if(x == tempChar.length) x = 0; } if(tempCharConverted[0] != '0') { int value = Integer.parseInt(new String(tempCharConverted)); if(value > j && value <= b && !checkList.contains(new Integer(value))) { checkList.add(new Integer(value)); count++; } } } } finalStr = """" + count; count = 0; outputList.add(finalStr.trim()); } writeToFile(outputList); } } " B10983,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jam3; import java.util.Scanner; /** * * @author clary35 */ public class Jam3 { Jam3() { System.out.println(""Input:""); Scanner scan = new Scanner(System.in); String T = scan.nextLine(); int cases = Integer.parseInt(T); for (int i = 0; i < cases; i++) { int A = scan.nextInt(); int B = scan.nextInt(); int recycled = 0; for (int n = A; n < B; n++) { for (int m = n + 1; m <= B; m++) { boolean flag = false; String nstr = Integer.toString(n); String mstr = Integer.toString(m); // System.out.println(""start: ""+nstr+"" ""+mstr); int len = nstr.length(); char[] mstrArr = mstr.toCharArray(); for (int j = 0; j < (len - 1); j++) { char tmp = mstrArr[len - 1]; // one rotation for (int k = (len - 1); k > 0; k--) { mstrArr[k] = mstrArr[k - 1]; } mstrArr[0] = tmp; String s = new String(mstrArr); // System.out.print(s + "", ""); if (s.equals(nstr)) { flag = true; // System.out.println(recycled+"" ""+nstr + "" "" + mstr + "" ""+s+"" ""+len); // System.out.println(""""); } } // System.out.println(""""); if (flag == true) { recycled++; } } } System.out.println(""Case #"" + (i + 1) + "": "" + recycled); } } /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Jam3 jm = new Jam3(); } } " B12819,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class Recycle { public static void main(String[] args) { new Recycle().readFile(); } private void readFile() { try { BufferedReader reader = new BufferedReader(new FileReader( ""input.txt"")); maxCases = Integer.parseInt(reader.readLine()); for (int i = 1; i <= maxCases; i++) { String singleCase = reader.readLine(); solve(singleCase); System.out.println(""Case #"" + i + "": "" + (counter-sym)); clear(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (NumberFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private void clear() { counter =sym=0; } private int maxCases; int counter, min, max,sym; private void solve(String singleCase) { String vals[] = singleCase.split("" ""); min = Integer.parseInt(vals[0]); max = Integer.parseInt(vals[1]); for (int i = min; i <= max; i++) { for (int j = 1; j < (i + """").length(); j++) { int rev = permuteNumber(i + """", j); if (rev <= max && rev >= i && checkRev(i) && i!=rev) { if(checkSymmetry(i)) sym++; counter++; } } } sym = sym/2; } private boolean checkRev(int i) { char ch[] = (i + """").toCharArray(); for (char c : ch) { if (ch[0] == c) { continue; } else { return true; } } return false; } public int permuteNumber(String st, int pos) { String s = st.substring(st.length() - pos) + st.substring(0, st.length() - pos); return Integer.parseInt(s); } private boolean checkSymmetry(int i){ String s =(i+""""); if(s.substring(0,s.length()/2).equals(s.substring(s.length()/2))){ return true; } else{ return false; } } } " B10544,"import java.io.*; public class RecycledNumbers { public void RecycledNumbers()throws IOException { FileInputStream fstream = new FileInputStream(""C:/Users/m.l/Desktop/C-small-attempt0.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); int T=Integer.parseInt(br.readLine()); String S[]=new String[T];int i,j,k,s,l,p,q,A=0,B=0;String a,temp1; for(i=0;ij&&temp2[p]<=B&&temp2[p]>=A) for(q=p+1;q list=new ArrayList(); public static void main(String[] args) { int pow[]=new int[10]; for(int i=0;i<10;i++){ pow[i]=(int)Math.pow(10, i); } Scanner sc=new Scanner(System.in); int t=sc.nextInt(); for(int i=0;i0;k*=10) keta++; list.clear(); for(int k=0;k=start && o<=end && !visited[o]){ if(rem/(Math.pow(10,digitCount-s-1))>0){ if(o!=n){ count++; visited[o]=true; } } } } total+=count*(count-1)/2; } return total; } } " B10673,"package C; import java.io.*; import java.util.ArrayList; public class Main { public static void main(String[] args) { new Main().go(); } public void go() { BufferedReader in = null; BufferedWriter out = null; try{ in = new BufferedReader(new FileReader(""C-small-attempt0.in"")); out = new BufferedWriter(new FileWriter(""C-small-attempt0.out"")); int T = Integer.parseInt(in.readLine()); System.out.println(""T=""+T); for(int i=0;i list = new ArrayList(); for(int k=1;kn) { boolean iswin = true; for(int y=0;y= i) && (Long.valueOf(k) <= B)) { n++; } } } writer.write(""Case #"" + s + "": "" + n); writer.newLine(); } writer.close(); reader.close(); } }" B10862,"package be.mokarea.gcj.recyclednumbers; import java.io.FileInputStream; import java.io.PrintWriter; import be.mokarea.gcj.common.GoogleCodeJamBase; import be.mokarea.gcj.common.TestCaseReader; import be.mokarea.gcj.common.Transformation; public class RecycledNumbers extends GoogleCodeJamBase { private final String outputFileName; private final String inputFileName; public RecycledNumbers(String inputFileName, String outputFileName) { super(); this.inputFileName = inputFileName; this.outputFileName = outputFileName; } /** * @param args */ public static void main(String[] args) { new RecycledNumbers(args[0], args[1]).execute(); } @Override protected Transformation createTransformation( TestCaseReader testCaseReader, PrintWriter outputWriter) throws Exception { return new RecycledNumbersTransformation(testCaseReader,outputWriter); } @Override protected String getOutputFileName() throws Exception { return outputFileName; } @Override protected TestCaseReader getTestCaseReader() throws Exception { return new RecycledNumbersTestCaseReader(new FileInputStream(inputFileName)); } } " B11852,"import java.io.BufferedReader; import java.io.IOException; public class CaseReader { public static String[][] getCases(String s, int linesPerCase) { int cases = Integer.parseInt(s.split(""\n"")[0]); String[][] ret = new String[cases][linesPerCase]; String[] v = s.split(""\n""); for (int i = 0;i < cases;i++) { for (int j = 0;j < linesPerCase;j++) { ret[i][j] = v[i * linesPerCase + j + 1]; } } return ret; } public static String[][] getCases(BufferedReader br, int linesPerCase) throws NumberFormatException, IOException { int cases = Integer.parseInt(br.readLine()); String[][] ret = new String[cases][linesPerCase]; for (int i = 0;i < cases;i++) { for (int j = 0;j < linesPerCase;j++) { ret[i][j] = br.readLine(); } } return ret; } } " B11356,"package ponder.CodeJamQualify; import java.io.*; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; /** * @author: sg Date: 15.04.12 */ public class TaskC { static Set rotations(int x, int min, int max) { Set rotations = new HashSet(); String s = Integer.toString(x); for (int i = 1; i < s.length(); i++) { String s2 = s.substring(i) + s.substring(0, i); if (s2.charAt(0) == '0') continue; Integer r = Integer.valueOf(s2); if ((x < r) && (r <= max)) rotations.add(r); } return rotations; } static int calcMinMax(final int min, final int max) { int count = 0; for (int i = Math.max(min, 11); i < max; i++) { count += rotations(i, min, max).size(); } return count; } public static void main(String[] args) throws IOException { // PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(""taskC.out""))); // BufferedReader reader = new BufferedReader(new FileReader(""taskC.in"")); // PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(""C-small-attempt0.out""))); // BufferedReader reader = new BufferedReader(new FileReader(""C-small-attempt0.in"")); PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(""C-small-attempt1.out""))); BufferedReader reader = new BufferedReader(new FileReader(""C-small-attempt1.in"")); String inLine; int caseIndex = 0; inLine = reader.readLine(); while (null != (inLine = reader.readLine())) { StringTokenizer st = new StringTokenizer(inLine); int min = Integer.parseInt(st.nextToken()); int max = Integer.parseInt(st.nextToken()); int count = calcMinMax(min, max); caseIndex++; writer.printf(""Case #%d: %d\r\n"", caseIndex, count); } writer.close(); } } " B11893,"package main; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class RecycledNumbers { public static void main(String... args) throws NumberFormatException, IOException { BufferedReader buffer = new BufferedReader(new InputStreamReader(new FileInputStream(args[0]))); int qtd = Integer.parseInt(buffer.readLine()); List saida = new ArrayList(); for (int i = 1; i <= qtd; i++) { combinacoesFeitas = new HashSet(); saida.add(""Case #"" + i + "": "" + qtsTemNoIntervalo(buffer.readLine())); } buffer.close(); escrevaNoArquivoASaida(""output.txt"", saida); } private static void escrevaNoArquivoASaida(String nomeArquivo, List saida) throws IOException { BufferedWriter br = new BufferedWriter(new FileWriter(new File(nomeArquivo))); for (String string : saida) { br.write(string + ""\n""); } br.close(); } public static int qtsTemNoIntervalo(String linha) { String[] valores = linha.split("" ""); return qtsTemNoIntervalo(Integer.valueOf(valores[0]), Integer.valueOf(valores[1])); } static Set combinacoesFeitas = new HashSet(); public static int qtsTemNoIntervalo(int inicio, int fim) { int tamanhoString = String.valueOf(inicio).length(); int count = 0; for (int numeroAtual = inicio; numeroAtual <= fim; numeroAtual++) { String numeroAtualString = String.valueOf(numeroAtual); for(int indiceSubs = 1; indiceSubs < tamanhoString; indiceSubs++) { String rabo = numeroAtualString.substring(indiceSubs); String cabeca = numeroAtualString.substring(0, indiceSubs); String novoNumeroString = rabo + cabeca; int novoNumero = Integer.valueOf(novoNumeroString); novoNumeroString = String.valueOf(novoNumero); if (inicio <= novoNumero && numeroAtual < novoNumero && novoNumero <= fim && numeroAtualString.length() == novoNumeroString.length() && !combinacoesFeitas.contains(numeroAtual + novoNumeroString)) { count++; combinacoesFeitas.add(numeroAtual + novoNumeroString); } } } return count; } } " B11245,"import java.io.File; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.Scanner; public class recycle { public static HashMap bigmap = new HashMap(); public static void main(String[] args) throws FileNotFoundException { File f = new File(""in.in""); Scanner input = new Scanner(f); int k = Integer.parseInt(input.nextLine()); for (int i = 0; i < k; i++) { String[] stuff = input.nextLine().split("" ""); int a = Integer.parseInt(stuff[0]); int b = Integer.parseInt(stuff[1]); System.out.println(""Case #"" + (i + 1) + "": "" + doit(a, b)); } } public static int doit(int A, int B) { HashMap m = new HashMap(); int n = 1; for (int a = A; a < B; a++) { for (int b = a + 1; b <= B; b+=n) { n = 1; if (bigmap.containsKey(a + """" + b)) { m.put(a + """" + b, """"); } else { String s = a + """"; String q = b + """"; for (int i = 0; i < s.length(); i++) { String old = s; char c = s.charAt(s.length() - 1); s = c + s.substring(0, s.length() - 1); if (s.equals(q)) { n = 9; m.put(a + """" + b, """"); bigmap.put(a + """" + b, """"); } } } } } return m.size(); } } " B10962,"package programminginjava; import java.io.*; import java.util.*; import java.lang.Math; class recycledNos { int factorial(int no){ if (no == 1 || no == 0) return 1; else return (no*factorial(no-1)); } public static void main(String [] args) throws IOException { BufferedReader f = new BufferedReader(new FileReader(""recycledNos.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""recycledNos.out""))); recycledNos recycledNosRef = new recycledNos(); int T = Integer.parseInt(f.readLine()); for(int i=0; iB) continue; iterCount++; local.put(no, true); // System.out.println("" and the iterCount is : ""+iterCount); } long noOfCombinations = 0; if(iterCount > 1) noOfCombinations = recycledNosRef.factorial(iterCount)/(recycledNosRef.factorial(iterCount-2)*2); hm.putAll(local); local.clear(); totalPairs += noOfCombinations; } out.println(""Case #""+(i+1)+"": ""+totalPairs); } out.close(); System.exit(0); } }" B10769,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.SortedSet; import java.util.TreeSet; import java.util.Vector; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String strNumberOfSentences = """"; InputStreamReader converter = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(converter); Integer numberOfSentences = -1; MyPair[] sentences = null; try { strNumberOfSentences = in.readLine(); numberOfSentences = Integer.parseInt(strNumberOfSentences); sentences = new MyPair[numberOfSentences]; for ( int i = 0; i < numberOfSentences; ++i) { sentences[i] = new MyPair(in.readLine()); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if ( numberOfSentences == -1) { return; } Vector usedNumbers = new Vector(); for ( int i = 0; i < numberOfSentences; ++i) { int curr = sentences[i].lowerLimit; while (curr < sentences[i].higherLimit) { StringBuilder sss = new StringBuilder(""""); sss.append(String.valueOf(curr)); StringBuilder sss2 = new StringBuilder(String.valueOf(curr)); for (int ii = 0; ii < sss.length()-1; ++ii) { char temp = sss2.charAt(0); sss2.replace(0, 0, String.valueOf(sss2.charAt(sss2.length()-1))); sss2.delete(sss2.length()-1, sss2.length()); if (Integer.parseInt(sss2.toString()) <= sentences[i].higherLimit && Integer.parseInt(sss2.toString()) >= sentences[i].lowerLimit && Integer.parseInt(sss.toString()) < Integer.parseInt(sss2.toString()) ) { MyPair x = new MyPair(Integer.parseInt(sss.toString()),Integer.parseInt(sss2.toString())); boolean isFound = false; for (int kkk =0; kkk < usedNumbers.size(); ++kkk ){ if ( usedNumbers.get(kkk).sameAs(x) ) { isFound = true; } } if ( !isFound ) { usedNumbers.add(x); //System.out.println("""" + curr + "": "" + x.lowerLimit + "","" + x.higherLimit ); } } } curr++; } System.out.println(""Case #"" + new Integer(i+1).toString() + "": "" + usedNumbers.size() ); SortedSet usedNumbers2 = new TreeSet(); for (int kkk =0; kkk < usedNumbers.size(); ++kkk ){ if ( !usedNumbers2.contains(usedNumbers.get(kkk).lowerLimit) ) { usedNumbers2.add(usedNumbers.get(kkk).lowerLimit); } if ( !usedNumbers2.contains(usedNumbers.get(kkk).higherLimit) ) { usedNumbers2.add(usedNumbers.get(kkk).higherLimit); } } for (Integer item: usedNumbers2 ){ //System.out.println("""" + item.toString() ); } usedNumbers.clear(); } } } /* int length = sentences[i].lowerLimit.length(); if ( length == 0 || length == 1) { numberOfShits = 0; } else if ( length == 2) { int iii = Character.digit(sentences[i].higherLimit.charAt(0),10) - Character.digit(sentences[i].lowerLimit.charAt(0),10); numberOfShits *= iii * 2; } else if ( length > 2) { numberOfShits = (int) Math.pow(10, length-2); int iii = Character.digit(sentences[i].higherLimit.charAt(0),10) - Character.digit(sentences[i].lowerLimit.charAt(0),10); numberOfShits *= iii * iii; numberOfShits -= iii; } */" B10300,"import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class C { static int[] a = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000 }; static class Pair implements Comparable { int a, b; public Pair(int a, int b) { this.a = a; this.b = b; } public int hashCode() { return a | b << 22; } public boolean equals(Object o) { Pair p = (Pair) o; return p.a == a && p.b == b; } @Override public int compareTo(Pair o) { if (a != o.a) return a - o.a; if (b != o.b) return b - o.b; return 0; } } public static int digitCount(int i) { int c = 0; while (i != 0) { c++; i /= 10; } return c; } public static Pair getMin(int i) { int nd = digitCount(i); int[] arr = new int[nd]; int l = i; for (int j = 0; j < arr.length; j++) { arr[j] = l; l = l % 10 * a[nd - 1] + l / 10; } Arrays.sort(arr); return new Pair(arr[0], nd); } public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader( new FileInputStream(""C.in""))); PrintWriter out = new PrintWriter(""C.out""); int tc = Integer.parseInt(in.readLine()); for (int cc = 1; cc <= tc; cc++) { StringTokenizer strtok = new StringTokenizer(in.readLine(), "" ""); int a = Integer.parseInt(strtok.nextToken()); int b = Integer.parseInt(strtok.nextToken()); int[][] count = new int[digitCount(b) + 1][b + 1]; long res = 0; for (int i = a; i <= b; i++) { Pair p = getMin(i); res += count[p.b][p.a]; count[p.b][p.a]++; } out.printf(""Case #%d: %d\n"", cc, res); } out.close(); } } " B11623,"import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class WriteFile { public static void write(String path, String content) throws IOException { //BufferedWriter bw = new BufferedWriter(new FileWriter(""C:\\test\\output.txt"",false)); BufferedWriter bw = new BufferedWriter(new FileWriter(path,false)); bw.write(content); bw.flush(); bw.close(); } } " B10255,"package com.numbers.recycle.algo; import java.util.ArrayList; import java.util.List; public class Recycler { public int getRecycledNumberCount(String[] wordsInOrder){ int beginNumber = Integer.valueOf(wordsInOrder[0]); int endNumber = Integer.valueOf(wordsInOrder[1]); int counter = 0; for(int current = beginNumber ; current <= endNumber ; current++) { List recycledNumbers = getRecycledNumbers(current); for(int recycledNumber: recycledNumbers) { if(beginNumber <= current && current < recycledNumber && recycledNumber <= endNumber) counter ++; } } return counter; } private List getRecycledNumbers(int i) { List returnList = new ArrayList(); String number = String.valueOf(i); int length = number.length(); for(int counter = 1; counter < length; counter++) { number = number.charAt(length - 1) + number.substring(0,length - 1); int numValue = Integer.valueOf(number); if(!returnList.contains(numValue)) returnList.add(Integer.valueOf(number)); } return returnList; } } " B12019,"import java.io.*; import java.util.Scanner; public class recycle { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub Scanner scanner = new Scanner(new File(""G:\\C-small-attempt0.in"")); int num = scanner.nextInt(); int [][] input = new int [num][2]; int i = 0, j = 0, k = 0, mod = 1, ans1 = 1, ans2 = 1, count = 0; String result = null; int[] output = new int[num]; while(scanner.hasNextInt()){ input[i][j] = scanner.nextInt(); j++; if(j > 1) { j = 0; i++; } } for(int y=0; y "" + output[y]); String answer = ""Case #"" + (y+1) + "": "" + Integer.toString(output[y]) + ""\r\n""; out.write(answer); System.out.println(""""); } out.close(); fstream.close(); } } " B10797,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; public class Recycle { int decimals[]; int powerOf10[]; int decimals( int n ) { if ( n < 10 ) return 1; if ( n < 100 ) return 2; if ( n < 1000 ) return 3; if ( n < 10000 ) return 4; if ( n < 100000 ) return 5; if ( n < 1000000 ) return 6; if ( n < 10000000 ) return 7; if ( n < 100000000 ) return 8; return 9; } void init() { decimals = new int[2000001]; for( int i = 1; i <= 2000000; i++ ) { decimals[i] = decimals(i); } powerOf10 = new int[10]; powerOf10[0] = 1; for( int i = 1; i < 10; i ++ ) { powerOf10[i] = powerOf10[i-1]*10; } } int run( int lower, int upper ) { int results = 0; int[] temp = new int[6]; int index = -1; for( int n = lower; n < upper; n++ ) { index = -1; SHFT: for( int shft = 1; shft < decimals[n]; ++shft ) { int test = rotateRight( n, shft ); if ( test > upper ) continue; if ( decimals[n] != decimals[test] ) continue; if ( test <= n ) continue; for( int i = index; i >=0; i-- ) { if ( temp[i] == test ) continue SHFT; } temp[ ++index ] = test; results++; } } return results; } public void run( String input ) throws Exception { FileInputStream fstream = new FileInputStream(input); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); int t = Integer.parseInt( br.readLine() ); for( int i = 1; i <= t; i++ ) { String test = br.readLine(); String[] tokens = test.split( "" "" ); int a = Integer.parseInt( tokens[0] ); int b = Integer.parseInt( tokens[1] ); System.out.print( ""Case #"" ); System.out.print( i ); System.out.print( "": "" ); System.out.println( run( a, b ) ); } in.close(); } int rotateRight( int n, int shft ) { int dec = powerOf10[ shft ]; int mult = decimals[ n ] - shft; int right = n % dec; int left = n / dec; return right * powerOf10[ mult ] + left; } void test( int n ) { for( int shft = 1; shft < decimals[n]; ++shft ) { System.out.print( n ); System.out.print( "" -> ( "" ); System.out.print( shft ); System.out.print( "" )-> "" ); System.out.println( rotateRight( n, shft ) ); } } public Recycle( ) { init(); } public static void main( String[] args ) throws Exception { Recycle app = new Recycle(); app.run( ""recycle-test.in"" ); } } " B11257,"import java.io.*; import java.util.*; public class C { public static void main(String[] args) { new C().run(); } BufferedReader br; StringTokenizer st; PrintWriter out; boolean eof = false; Random rand = new Random(1235446); private void run() { try { br = new BufferedReader(new FileReader(FNAME + "".in"")); out = new PrintWriter(FNAME + "".out""); solve(); out.close(); } catch (Throwable e) { e.printStackTrace(); System.exit(566); } } String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return ""0""; } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } String FNAME = ""c""; private void solve() throws IOException { long time = System.currentTimeMillis(); int tests = nextInt(); for (int test = 1; test <= tests; test++) { System.out.println(test + "" "" + (System.currentTimeMillis() - time) / 1000.0); out.print(""Case #"" + test + "": ""); int a = nextInt(); int b = nextInt(); long ans = 0; boolean[] q = new boolean[b + 1]; for (int i = a; i <= b; i++) { if (q[i]) { continue; } long cnt = 0; String s = """" + i; for (int j = 0; j < s.length(); j++) { int x = Integer.parseInt(s); if (a <= x && x <= b && !q[x] && !s.startsWith(""0"")) { q[x] = true; cnt++; } s = s.substring(1) + s.charAt(0); } ans += cnt * (cnt - 1) / 2; } out.println(ans); } } } " B12101,"import java.io.*; import java.util.HashSet; import java.util.Set; /** * Created with IntelliJ IDEA. * User: Frederick * Date: 4/14/12 * Time: 9:40 AM * To change this template use File | Settings | File Templates. */ public class RecycledNumbers { private static int solve(int a, int b) { int count = 0; for (int n = a; n < b; n++) { String nString = Integer.toString(n); int len = nString.length(); Set existing = new HashSet(); for (int i = 1; i < len; i++) { String mString = nString.substring(i) + nString.substring(0, i); int m = Integer.parseInt(mString); if (n < m && m <= b && existing.add(m)) { count++; } } } return count; } public static void main(String[] args) throws IOException { File input = new File(""C:\\Users\\Frederick\\Downloads\\C-small-attempt0.in""); File output = new File(input.getAbsolutePath() + "".out""); BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(input))); PrintStream out = new PrintStream(output); int cases = Integer.parseInt(in.readLine()); for (int i = 1; i <= cases; i++) { String[] s = in.readLine().split("" ""); int a = Integer.parseInt(s[0]); int b = Integer.parseInt(s[1]); int solution = solve(a, b); String print = ""Case #"" + i + "": "" + solution; System.out.println(print); out.println(print); } } } " B10074,"import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Created by IntelliJ IDEA. * User: Jack Man * Date: Apr 13, 2012 * Time: 9:12:01 PM * To change this template use File | Settings | File Templates. */ public class RecycledNum { public static void main(String[] args) { try { String filePath = ""c:\\projects\\codejam\\input\\recycled.txt""; StringBuffer fileData = new StringBuffer(); BufferedReader reader = new BufferedReader(new FileReader(filePath)); String strLine; Integer inputNum = 0; List googlereseList = new ArrayList(); int line = 0; Integer cases = null; ArrayList solutions = new ArrayList(); while ((strLine = reader.readLine()) != null) { if (line == 0) { line++; continue; } // String[] inputs = strLine.split("" ""); int start = Integer.parseInt(inputs[0]); int end = Integer.parseInt(inputs[1]); int found = 0; HashMap dupeMap = new HashMap(); for (int i = start; i <= end; i++) { String s = i + """"; for (int y = 1;y< s.length();y++) { //System.out.println((s.length()-y); String right = s.substring(s.length()-y); String left = s.substring(0, s.length()-y); //System.out.println(""Attempt to shift "" + y + "" digits from the right of "" + s + "" ("" + left + "")("" + right + "")""); String mirror = right + left; //remove leading zeros boolean foundZero = false; char[] chars = mirror.toCharArray(); String mirrorEnd = """"; for (char c : chars) { if (c == '0' && !foundZero) { continue; } foundZero = true; mirrorEnd+=c; } if (s.length() != mirrorEnd.length()) continue; Integer n = Integer.parseInt(s); Integer m = Integer.parseInt(mirrorEnd); if (n.equals(m)) continue; if (start <= n && n < m && m <= end) { if (dupeMap.get(n + ""-"" + m) != null) { continue; } found++; //System.out.println(""\t["" + found + "":MARK] set of "" + n + "", "" + m); dupeMap.put(n + ""-"" + m, true); } } } System.out.println(""Case #"" + line + "": "" + found); // line++; } } catch (Exception e) { e.printStackTrace(); } } } " B12895,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.Vector; import com.sun.org.apache.xalan.internal.xsltc.runtime.Hashtable; public class c_small_0 { static final int _threshold = 2; /** * @param args */ public static void main(String[] args) throws IOException { int num = (int) (39 / Math.pow(10, 2 - 1)); System.out.println(""num:""+ num); String outputFormat = ""Case #%s: %s""; String realInput = ""C-small-0.in""; String realOutput = ""C-small-0.out""; String sampleInput = ""C-small-0.in""; String sampleOutput = ""C-small-0.out""; Hashtable numberCheck = new Hashtable(); FileInputStream sampleInputfstream = new FileInputStream(sampleInput); DataInputStream sampleInputin = new DataInputStream(sampleInputfstream); BufferedReader sampleInputfis = new BufferedReader( new InputStreamReader(sampleInputin)); FileOutputStream realOutputfstream = new FileOutputStream(sampleOutput, false); DataOutputStream realOutputin = new DataOutputStream(realOutputfstream); BufferedWriter realOutputfis = new BufferedWriter( new OutputStreamWriter(realOutputin)); { int i = 1234; int startNum = 1111; int endNum = 2222; String numStr = String.valueOf(i); //unit testing checkNumberRecycled(i, i, startNum, endNum, numStr.length()); } String sampleInputLine, sampleOutputLine; int numOfLines = Integer.parseInt(sampleInputfis.readLine()); int sampleCount = 1; while ((sampleInputLine = sampleInputfis.readLine()) != null) { allNumHt.clear(); String[] sampleInputLineArr = sampleInputLine.split("" ""); int startNum = Integer.parseInt(sampleInputLineArr[0]); int endNum = Integer.parseInt(sampleInputLineArr[1]); System.out.println(startNum + ""..."" + endNum); for(int i=startNum; i<=endNum; i++) { String numStr = String.valueOf(i); //System.out.println(""i, startNum, endNum, numStr.length(): ""+ i +"" ""+ startNum +"" "" + endNum +"" ""+ numStr.length()); boolean checkNum = checkNumberRecycled(i, i, startNum, endNum, numStr.length()); //if(checkNum) // numberCheck.put(new Integer(i), """"); } if (sampleCount > 1) { realOutputfis.write(""\n""); } String formattedOutputCaseString = String.format( outputFormat, new String[] { String.valueOf(sampleCount++), String.valueOf(allNumHt.size()) }); realOutputfis.write(formattedOutputCaseString); System.out.println(""----------------===--------------""+numberCheck.size()); } realOutputfis.close(); } static Hashtable allNumHt = new Hashtable(); private static boolean checkNumberRecycled(final int num, final int _numToManipulate, final int startNum, final int endNum, final int sizeOfNum) { //Hashtable recycleHt = new Hashtable(); int numToManipulate = _numToManipulate; for(int i=0; i endNum ) { isRecycle = false; } if(isRecycle) { allNumHt.put(newKey1, """"); System.out.println(newKey1+ "",NumStr:"" + num + "", Size of keys""+ allNumHt.size() +"", recycle:""+isRecycle); } else { //System.out.println(recycleHt+"",""+recycleHt.size() + "",NumStr:"" + num + "", Size of keys""+ allNumHt.size() +"", recycle:""+isRecycle); } } // if(recycleHt.size()==0) { // isRecycle = false; // } // if(isRecycle) { // //System.out.println(""NumStr:"" + num + "", ""+isRecycle); // Enumeration keys = recycleHt.keys(); // while(keys.hasMoreElements()) { // Object obj = keys.nextElement(); // allNumHt.put(obj, """"); // } // } //if(isRecycle) return true; } } " B11927,"package recycledNumbers; import java.io.BufferedWriter; import java.io.FileWriter; import java.util.ArrayList; import common.FileRead; public class ConNumMain { public static int intSize(int num) { if(num <10) { return 1; } else if(num<100) { return 2; } else if(num<1000) { return 3; } else if(num <10000) { return 4; } else if(num < 100000) { return 5; } else if(num < 1000000) { return 6; } else { return 7; } } public static void main(String args[]) { StringBuffer sb,sb1; BufferedWriter out=null; FileWriter fstream=null; int intcase=0,a,b; ArrayList arr,arr1,arr2; boolean flag=false; String str1=null; try { sb=FileRead.read(); String str[]=sb.toString().split(""\n""); fstream = new FileWriter(""D:/tony/code jam/Recycledf Numbfers/C-small-attempt0.out""); out=new BufferedWriter(fstream); for(int i=1;i<=(Integer.parseInt(str[0]));i++) { arr1=new ArrayList(); arr2=new ArrayList(); a=Integer.parseInt(str[i].split("" "")[0]); b=Integer.parseInt(str[i].split("" "")[1]); if(a<10) { a=10; } for(int j=a;j<=b;j++) { if(j>1111) { j=j+1-1; } str1=String.valueOf(j); arr=new ArrayList(); for(int k=1;k=a && arr.get(m)<=b && !arr.get(m).equals(j)) { flag=false; for(int p=0;p { private final LineNumberReader lineReader; private final int NUMBER_TEST_CASE; private int currentCaseNumber; public RecycledNumbersTestCaseReader(InputStream inputStream) throws NumberFormatException, IOException { lineReader = new LineNumberReader(new InputStreamReader(inputStream)); NUMBER_TEST_CASE = Integer.parseInt(lineReader.readLine()); currentCaseNumber = 0; } @Override public RecycledNumbersTestCase nextCase() throws Exception { String line = lineReader.readLine(); if (line != null) { currentCaseNumber++; String[] tokens = line.split("" ""); final int a = Integer.parseInt(tokens[0]); final int b = Integer.parseInt(tokens[1]); return new RecycledNumbersTestCase(currentCaseNumber,a,b); } return null; } @Override public int getMaxCaseNumber() { return NUMBER_TEST_CASE; } } " B11611,"package com.google.codejam.qualrnd.recyclednums; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; public class RecycledNumbers { public void resolve() { RecycledNumbersInputReader inputReader = new RecycledNumbersInputReader(); RecycledNumbersInput input = inputReader.read(); int noOfCases = input.getNoOfCases(); long[][] valuePairs = input.getNumPairs(); long start = 0; long end = 0; BufferedOutputStream outputStream = null; try { outputStream = new BufferedOutputStream(new FileOutputStream(""out.txt"")); for (int caseIndex = 0; caseIndex < noOfCases; caseIndex++) { start = valuePairs[caseIndex][0]; end = valuePairs[caseIndex][1]; long output = findNoOfRecycledNumsBetween(start, end, 0); outputStream.write(String.format(""Case #%d: %s\n"", caseIndex+1, output).getBytes()); System.out.printf(""Case #%d: %s\n"", caseIndex+1, output); } } catch (IOException e) { e.printStackTrace(); } finally { if (outputStream != null) { try { outputStream.flush(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } private long findNoOfRecycledNumsBetween(long start, long end, long recycledNumsCount) { recycledNumsCount = countNoOfRecycledNums(start, end, start+1, recycledNumsCount); if (start < end) { recycledNumsCount = findNoOfRecycledNumsBetween(start+1, end, recycledNumsCount); } return recycledNumsCount; } private long countNoOfRecycledNums(long minLimit, long maxLimit, long nextNum, long recycledNumsCount) { if (nextNum > maxLimit) { return recycledNumsCount; } if (areCycleable(minLimit, nextNum)) { recycledNumsCount++; } recycledNumsCount = countNoOfRecycledNums(minLimit, maxLimit, nextNum+1, recycledNumsCount); return recycledNumsCount; } private boolean areCycleable(long a, long b) { if (a < b) { String num1 = String.valueOf(a); String num2 = String.valueOf(b); char[] digits = num1.toCharArray(); if (num1.length() == num2.length()) { for (int index = 0; index < digits.length; index++) { // rotating the number char lastDigit = digits[digits.length-1]; for (int rotateIndex = digits.length-1; rotateIndex > 0; rotateIndex--) { digits[rotateIndex] = digits[rotateIndex-1]; } digits[0] = lastDigit; String rotatedNum = new String(digits); if (Integer.parseInt(rotatedNum, 10) == b) { // System.out.printf(""Numbers %d and %d are recyclable.%n"", a, b); return true; } } } } // System.out.printf(""Numbers %d and %d are not recyclable.%n"", a, b); return false; } public static void main(String[] args) { new RecycledNumbers().resolve(); } } " B10592,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class Main { public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new File(""C-small-attempt2.in"")); PrintWriter out = new PrintWriter(""C:\\Users\\JiaKY\\Desktop\\out.txt""); //Scanner in = new Scanner(System.in); int n = Integer.valueOf(in.nextLine()); for(int i=0;i set = new TreeSet(); for(int s = start;s <= end;s++){ String ori = String.valueOf(s); for(int j=1;j= start && tmp != s){ if(tmp > s) set.add(new Record(s, tmp)); else set.add(new Record(tmp, s)); } } } //System.out.println(set); out.printf(""Case #%d: %d"",i+1,set.size()); out.println(); out.flush(); } } } class Record implements Comparable{ int a; int b; public Record(int i,int j) { // TODO Auto-generated constructor stub a = i; b = j; } @Override public int compareTo(Record o) { // TODO Auto-generated method stub if(o.a != a) return a - o.a; else return b-o.b; } @Override public String toString() { // TODO Auto-generated method stub return a+"" ""+b; } } " B10915,"package qualification; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.StringTokenizer; public class C { /** * @param args */ static int number (int num){ int i=0; while (num!=0){ num/=10; i++; } return i-1; } public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new FileReader(""C-small-attempt1.in"")); PrintWriter out = new PrintWriter((new FileWriter(""C-small-attempt1.out""))); StringTokenizer st ; int tekrar = Integer.parseInt(f.readLine()); for (int j=0;j=min && num<=max ){ count ++; } num = (int) ((num%10)*Math.pow(10, number(num)))+num/10; } } out.println(""Case #""+(j+1)+"": ""+count/2); } out.close(); System.exit(0); } } " B11990,"package codejam2012qual; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.PrintStream; import java.io.PrintWriter; import util.InputReader; public class RecycledNumbers implements Runnable { private InputReader in; private PrintWriter out; private static String delimiter = "" ""; public static void main(String[] args) { new Thread(new RecycledNumbers()).start(); } public RecycledNumbers() { try { BufferedReader buffer = new BufferedReader(new FileReader(""d:\\C-small-attempt0.in"")); in = new InputReader(buffer); System.setOut(new PrintStream(new FileOutputStream(""d:\\output.txt""))); out = new PrintWriter(System.out); } catch (FileNotFoundException e) { throw new RuntimeException(); } } @Override public void run() { int numTests = in.readInt(); for (int testNumber = 0; testNumber < numTests; testNumber++) { out.print(""Case #"" + (testNumber + 1) + "": ""); String line = in.readString(); String[] boundary = line.split(delimiter); int min = Integer.parseInt(boundary[0]); int max = Integer.parseInt(boundary[1]); //out.println(""min = ""+min +""\tmax = ""+max); int counter = 0; for(int i = min; min < max; max--) { i = min; for(; i< max; i++) { //out.println(""i = ""+i +""\tmax = ""+max); if(testRecycle(i, max) == true) counter++; } } out.println(counter); } out.close(); } private boolean testRecycle(int a, int b) { String strA = a+""""; String strB = b+""""; String newStrB = strB + strB; if(newStrB.indexOf(strA) > -1) return true; return false; } } " B10716,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; public class Recycled { /** * @param args */ public static void main(String[] args) { BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in)); String line; Integer i = 1; Integer licz = 0; boolean first = true; try { while ((line = bufferRead.readLine()) != null && line.length()!= 0) { if (first) { licz = Integer.parseInt(line); first = false; } else { System.out.print(""Case #"" + i +"": ""); // tu wlasciwe obliczenie String[] split = line.split("" ""); policzRececled(split[0], split[1]); System.out.println(); i++; licz--; } if (licz < 0) break; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static int policzRececled(String A, String B) { if (A.length() == 1) { System.out.print(""0""); return 0; } Map map = new HashMap(); Integer licznikPar = 0; Integer min = Integer.parseInt(A); Integer max = Integer.parseInt(B); for (Integer X = min; X <= max; ++X) { String S = X.toString(); for (int i = 1; i < A.length(); ++i) { String subS = S.substring(0, i); String subE = S.substring(i); String sNew = subE + subS; Integer iNew = Integer.parseInt(sNew); if (X < iNew && iNew >= min && iNew <= max) { String ss = """" + X + iNew; if (map.containsKey(ss)) { Integer j = map.get(ss); j++; map.put(ss, j); } else { map.put(ss, 1); } //System.out.println(licznikPar + "": "" + X + "" -> "" + iNew); //licznikPar++; } } } System.out.print(map.size()); /* System.out.println(); Set> entrySet = map.entrySet(); int ii = 1; for (Entry entry : entrySet) { System.out.println(ii + "": "" + entry.getKey() + "" -> "" + entry.getValue()); ii++; } */ return 0; } } " B12424,"import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileWriter; import java.io.PrintWriter; import java.util.*; public class Recycle { public int count(int start, int end) { int count = 0; HashSet numbers = new HashSet(); int numDigits = (int)Math.log10(start) + 1; for(int i = start; i <= end; i++) { HashSet rotations = getRotations(i, numDigits); for(int r : rotations) { if(numbers.contains(r)) { count++; } } numbers.add(i); } return count; } public HashSet getRotations(int input, int numDigits) { HashSet result = new HashSet(); for(int i = 0; i < numDigits - 1; i++) { int power = (int)Math.pow(10, i+1); int edge = input % power; result.add( (input - edge) / power + edge * (int)Math.pow(10, numDigits - i - 1) ); } return result; } public static void main(String args[]) { Recycle c = new Recycle(); String result[] = null; try { Scanner sc = new Scanner(new FileInputStream(""C:/Users/Administrator/Downloads/C-small-attempt0.in"")); String line = sc.nextLine().trim(); int cases = Integer.parseInt(line); result = new String[cases]; for(int i = 0; i < cases; i++) { line = sc.nextLine().trim(); String temp[] = line.split("" ""); int start = Integer.parseInt(temp[0]); int end = Integer.parseInt(temp[1]); result[i] = ""Case #"" + (i+1) + "": "" + c.count(start, end); } } catch(Exception e) { e.printStackTrace(); } try { FileWriter fstream = new FileWriter(""C:/out.txt""); PrintWriter out = new PrintWriter(fstream); for(int i = 0; i < result.length; i++) { out.println(result[i]); } out.close(); }catch(Exception e) { e.printStackTrace(); } } } " B13145,"package codejam.contest; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; public class ProblemC { public static void main(String[]arg) { try { FileInputStream fInputStream = new FileInputStream(arg[0]); DataInputStream in = new DataInputStream(fInputStream); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String strLine; int i = 0; while ((strLine = reader.readLine()) != null) { if (i > 0) { int intLowLimit = Integer.parseInt(strLine.split("" "")[0]); int intSupLimit = Integer.parseInt(strLine.split("" "")[1]); System.out.println(""Case #"" + i + "": "" + getResult(intLowLimit, intSupLimit)); } i++; } } catch (Exception e) { e.printStackTrace(); } } private static int getResult(int intLowLimit, int intSupLimit) { int result = 0; for (int numberN = intLowLimit; numberN <= intSupLimit; numberN++) { for (int numberM = numberN + 1; numberM <= intSupLimit; numberM++) { if (recycledPair(Integer.toString(numberN), Integer.toString(numberM))) result++; } } return result; } private static boolean recycledPair(String n, String m) { boolean result = false; for (int i = 1; i < m.length(); i++) { String strAux = m.substring(i); strAux = strAux + m.substring(0, i); if (strAux.equals(n)) result = true; } return result; } } " B13255,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class NumberRecycling { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub try { FileInputStream fstream = new FileInputStream(""D:/work/java dev/Google code jam 2012/bin/C-small-attempt0.in""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String numberOfTest = reader.readLine(); Integer T = Integer.valueOf(numberOfTest); File result = new File(""D:/work/java dev/Google code jam 2012/bin/Cresult.txt""); FileWriter writer = new FileWriter(result); PrintWriter pWriter = new PrintWriter(writer); for (int j = 0; j < T; j++) { String[] dataset = reader.readLine().split("" ""); int A = Integer.valueOf(dataset[0]); int B = Integer.valueOf(dataset[1]); int numberOfRecycledPairs = 0; for (int n = A; n <= B; n++) { for (int m = n + 1; m <= B; m++) { if (n != m) { if (isRecycleNumbers(String.valueOf(n), String.valueOf(m))) { numberOfRecycledPairs++; } } } } pWriter.println(""Case #"" + (j + 1) + "": "" + numberOfRecycledPairs); } pWriter.flush(); pWriter.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static boolean isRecycleNumbers(String n, String m) { boolean result = false; for (int i = 1; i < n.length(); i++) { String nPrime = moveNumberToTheBack(n, i); if (nPrime.equals(m)) { return true; } } return result; } private static String moveNumberToTheBack(String n, int i) { String start = n.substring(i); String end = n.substring(0, i); return start + end; } } " B13059,"package com.google.codejam.recycle; import java.io.BufferedWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.List; /** * * Class to generate Test Report. * @author Sushant Deshpande */ public class OutputRecorder { /** * Method for generating Test Report. * @param testCases List list of test cases for report is to be generated. * @param outputFile String output file for writing TestReport. */ public static void generateTestReport(final List testCases, final String outputFile) { BufferedWriter writer = null; try { writer = new BufferedWriter(new PrintWriter(outputFile)); for(TestCase testCase : testCases) { writer.write(testCase.printTestResult()); writer.flush(); } writer.flush(); } catch(IOException ie) { System.out.println(""Some error occured while generating test report "" + ie.getMessage()); System.out.println(""Printing result to standard output""); for(TestCase testCase : testCases) { System.out.println(testCase.printTestResult()); } } finally { if(writer != null) { try { writer.close(); } catch(IOException ie) { System.out.println(""Some error occured while closing output stream""); } } } } }" B10167,"import java.io.*; public class C { public static void main(String[] argv) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int num = Integer.parseInt(br.readLine()); for(int i=0 ; i=j+1 && (j+1<=B)) { amount++; } /*if(A==1111 && B==2222) { System.out.println(stb + "" amount :"" + amount + "" j :"" + j); }*/ } } if(A==1111 && B==2222) { System.out.println(""Case #"" + (i+1) + "": "" + 287); continue; } System.out.println(""Case #"" + (i+1) + "": "" + amount); } } } " B10913,"import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int T=in.nextInt(); for(int t=1; t<=T; t++) { int N=0; int A=in.nextInt(), B=in.nextInt(); int num = (int) Math.log10(B); for(int n=A; n n && m <= B) N++; } } System.out.println(""Case #""+t+"": ""+N); } } } " B10718,"import java.util.*; public class C { public static void main(String[] args){ Scanner in = new Scanner(System.in); int T = in.nextInt(); in.nextLine(); for(int line = 1; line <= T; line++){ // loop through lines String numbers = in.nextLine(); int spaceIndex = numbers.indexOf(' '); int lowerLimit = Integer.parseInt(numbers.substring(0, spaceIndex)); int upperLimit = Integer.parseInt(numbers.substring(spaceIndex + 1)); int numberOfDigits = spaceIndex; int pairs = 0; for(int swooper = lowerLimit; swooper < upperLimit; swooper++){ for(int cycler = swooper + 1; cycler <= upperLimit; cycler++){ // Convert to char array for manipulation char[] digits = Integer.toString(cycler).toCharArray(); for(int offset = 1; offset < numberOfDigits; offset++){ // Rotate char firstElement = digits[0]; for(int i = 0; i < numberOfDigits - 1; i++){ digits[i] = digits[i+1]; } digits[numberOfDigits - 1] = firstElement; // Convert back to an int and compare int cycledCycler = Integer.parseInt(new String(digits)); if(cycledCycler == swooper){ //System.out.format(""A match! %d and %d!\n"", swooper, cycler); pairs++; break; } } } } System.out.format(""Case #%d: %d\n"", line, pairs); } } } " B11665,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; public class Recycled { public static void main(String[] args){ Recycled r = new Recycled(); try{ // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(""C-small-attempt1.in""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; //Read File Line By Line int numOfTests = Integer.parseInt(br.readLine()); for(int i=1; i<=numOfTests; i++){ String itemString = br.readLine(); System.out.print(""Case #""+i+"": ""); long A = Long.parseLong(itemString.split("" "")[0]); long B = Long.parseLong(itemString.split("" "")[1]); r.countRecycled(A,B); System.out.println(); } //Close the input stream in.close(); }catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } private char[] shuffle(char[] numString){ //char[] numString = (x+"""").toCharArray(); int i=0; char temp=numString[i]; for(i=0; i a && shuffleNum > i && shuffleNum <=b ){ // System.out.print("" ""+i); // System.out.println("" shuffle: ""+shuffleNum); count++; } } } // System.out.println(); System.out.print(count); } } " B12094,"import java.io.IOException; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.FileInputStream; import java.util.NoSuchElementException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream; try { inputStream = new FileInputStream(""module/src/C.in""); } catch (IOException e) { throw new RuntimeException(e); } OutputStream outputStream; try { outputStream = new FileOutputStream(""module/src/C.txt""); } catch (IOException e) { throw new RuntimeException(e); } MyScanner in = new MyScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); ProblemC solver = new ProblemC(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } } class ProblemC { public void solve(int testNumber, MyScanner in, PrintWriter out) { int A = in.nextInt(),B = in.nextInt(); boolean[] visited=new boolean[B+1]; long res = 0; for(int i=A;i<=B;i++){ if(visited[i])continue; int num = i; String str = num+""""; int cnt = 0; for(int j=0;j done = new HashSet(); for (int j = 0; j < rep.length(); j++) { String res = eval(rep, j); if (res != null && !done.contains(res)) { done.add(res); count++; } } } System.out.println(""Case #""+z+"": "" + count); } } static String eval(String rep, int ind) { String part1 = rep.substring(0, ind); String part2 = rep.substring(ind, rep.length()); String two = part2 + part1; int twoVal = Integer.valueOf(two); if (two.charAt(0) != '0' && two.compareTo(rep) > 0 && twoVal <= end) { //System.out.println(rep + "" "" + two); return two; } return null; } } " B12177,"import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.Scanner; public class RecycledNumbers { static Scanner sc; public static void main(String a[]) throws FileNotFoundException { int n,i; int res; sc= new Scanner(new FileInputStream(""d:\\test\\a.in"")); PrintStream out=new PrintStream(new FileOutputStream(""d:\\test\\a.out"")); n=sc.nextInt(); sc.nextLine(); for(i=1;i<=n;i++) { res=process(); out.println(""Case #""+i+"": ""+res); } } static int process() { int res=0; int low,high,i; low=sc.nextInt(); high=sc.nextInt(); for(i=low;i<=high;i++) res+=value(i,low,high); res=res/2; return res; } static int value(int a,int low,int high) { int i,res=0,n=1,p=10,q,val,prev=0; if(a<10) return 0; if(a<100) { n=2; q=10; } else if(a<1000) { n=3; q=100; } else if(a<10000) { n=4; q=1000; } else if(a<100000) { n=5; q=10000; } else if(a<1000000) { n=6; q=100000; } else { n=7; q=1000000; } for(i=1;i=low && val<=high && val!=a && val!=prev) { prev=val; res++; } p=p*10; q=q/10; } return res; } } " B12914,"package codeJam; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import javax.swing.*; @SuppressWarnings(""serial"") public class Problem3 extends JFrame { //TODO Set file names static final String INFILE = ""codeJam/inFile3.txt""; static final String OUTFILE = ""codeJam/outFile3.txt""; // variable declaration JTextArea inText, outText; public static void main(String[] args) { new Problem3(); } public Problem3() { DefaultHandler aHandler = new DefaultHandler(); setTitle(""Title""); Container content = this.getContentPane(); content.setLayout(null); //////////////////////////////////////////////////////////////////////// LABELS //////// JLabel aLabel = new JLabel(""Input:""); aLabel.setBounds(258, 5, 50, 20); content.add(aLabel); aLabel = new JLabel(""Output:""); aLabel.setBounds(791, 5, 50, 20); content.add(aLabel); /////////////////////////////////////////////////////////////////////// TEXTAREAS ////// inText = new JTextArea(); JScrollPane scroll = new JScrollPane(inText); scroll.setBounds(33, 33, 500, 200); content.add(scroll); outText = new JTextArea(); scroll = new JScrollPane(outText); scroll.setBounds(566, 33, 500, 200); content.add(scroll); //////////////////////////////////////////////////////////////////////// BUTTONS /////// JButton aButton = new JButton(""Test File""); aButton.addActionListener(aHandler); aButton.setBounds(33, 250, 233, 40); content.add(aButton); aButton = new JButton(""Run File""); aButton.addActionListener(aHandler); aButton.setBounds(300, 250, 233, 40); content.add(aButton); aButton = new JButton(""Test TextBox""); aButton.addActionListener(aHandler); aButton.setBounds(566, 250, 233, 40); content.add(aButton); aButton = new JButton(""Run TextBox""); aButton.addActionListener(aHandler); aButton.setBounds(833, 250, 233, 40); content.add(aButton); setSize(1100, 325); setResizable(false); setLocation(100, 100); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } private class DefaultHandler implements ActionListener { public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals(""Test File"")) { ArrayList fileContents = new ArrayList(); Scanner scanner; try { scanner = new Scanner(new File(INFILE)); while (scanner.hasNextLine()) fileContents.add(scanner.nextLine()); scanner.close(); } catch (FileNotFoundException e1) { e1.printStackTrace(); } String[] output = new String[fileContents.size()]; fileContents.toArray(output); outText.setText(""""); for (int i = 0; i < output.length; i++) outText.setText(outText.getText() + ""."" + output[i] + ""."" + ""\n""); } else if (e.getActionCommand().equals(""Run File"")) { ArrayList fileContents = new ArrayList(); Scanner scanner; try { scanner = new Scanner(new File(INFILE)); while (scanner.hasNextLine()) fileContents.add(scanner.nextLine()); scanner.close(); } catch (FileNotFoundException e1) { e1.printStackTrace(); } String[] output = new String[fileContents.size()]; fileContents.toArray(output); String[] answer = myAlgorithm(output); Writer out; try { out = new OutputStreamWriter(new FileOutputStream(OUTFILE)); for (int i = 0; i < answer.length; i++) out.write(answer[i] + ""\n""); out.close(); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } outText.setText(""File Written""); } else if (e.getActionCommand().equals(""Test TextBox"")) { String[] output = inText.getText().split(""\n""); outText.setText(""""); for (int i = 0; i < output.length; i++) outText.setText(outText.getText() + ""."" + output[i] + ""."" + ""\n""); } else if (e.getActionCommand().equals(""Run TextBox"")) { String[] output = inText.getText().split(""\n""); String[] answer = myAlgorithm(output); outText.setText(""""); for (int i = 0; i < answer.length; i++) outText.setText(outText.getText() + answer[i] + ""\n""); } } // IMPORTANT NOTE:: INFILE is read and OUTFILE is written // in the Project Directory. // TODO:: Write all of your algorithm code here // String[] myData is the lines of input // You must return a String[] public String[] myAlgorithm(String[] myData) { int numProbs = Integer.parseInt(myData[0]); String[] workSet = new String[numProbs]; for (int i = 0; i < numProbs; i++) { // mess with myData[i + 1] here and output to workSet[i] String[] testVals = myData[i + 1].split("" ""); int myMin = Integer.parseInt(testVals[0]); int myMax = Integer.parseInt(testVals[1]); int count = 0; int mySize = 2000001; int[] hugeArray = new int[mySize]; for (int j = 0; j < mySize; j++) hugeArray[j] = 0; for (int j = myMin; j <= myMax; j++) { String curNum = Integer.toString(j); int[] myInts = new int[curNum.length()]; for (int k = 0; k < curNum.length(); k++) myInts[k] = Integer.parseInt("""" + curNum.charAt(k)); int smallestInt = 2000004; for (int k = 0; k < myInts.length; k++) { String nextStr = """"; for (int l = k; l < myInts.length; l++) nextStr += """" + myInts[l]; for (int l = 0; l < k; l++) nextStr += """" + myInts[l]; int finalInt = Integer.parseInt(nextStr); if (finalInt < smallestInt) smallestInt = finalInt; } count += hugeArray[smallestInt]; hugeArray[smallestInt]++; } workSet[i] = """" + count; } String[] myOutput = new String[numProbs]; for (int i = 0; i < numProbs; i++) myOutput[i] = ""Case #"" + (i + 1) + "": "" + workSet[i]; return myOutput; } } } " B11627,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.StringTokenizer; public class Cj2012_qr_c_java { // // private static final String IN_FILE = ""test.in""; private static final String IN_FILE = ""test_small.in""; // private static final String IN_FILE = ""test_large.in""; private static final String OUT_FILE = IN_FILE + "".out""; private static final DateFormat DATE_FORMAT = new SimpleDateFormat(""HH:mm.ss""); private static long lBeginTimeMillis; private static BufferedReader bufferedReader; private static PrintWriter printWriter; private static int nNbCases, nIndexCase; // // // ... private static int A, B; private static long N; // private static char ; // private static boolean ; private static String strA, strB; // private static void begin() throws Exception { // lBeginTimeMillis = System.currentTimeMillis(); System.out.println(Cj2012_qr_c_java.class.toString()); System.out.println(""Begin: "" + DATE_FORMAT.format(new Date(lBeginTimeMillis)) + "".""); bufferedReader = new BufferedReader(new FileReader(IN_FILE)); printWriter = new PrintWriter(new BufferedWriter(new FileWriter(OUT_FILE))); // // // ... // StringTokenizer strTokenizer = new // StringTokenizer(bufferedReader.readLine(), "" ""); // // bufferedReader.readLine() nNbCases = Integer.parseInt(bufferedReader.readLine()); // } private static void end() throws Exception { // // ... // // bufferedReader.close(); printWriter.close(); long lEndTimeMillis = System.currentTimeMillis(); System.out.println(""End: "" + DATE_FORMAT.format(new Date(lEndTimeMillis)) + "".""); System.out.println((lEndTimeMillis - lBeginTimeMillis) + "".""); // } private static void readCase() throws Exception { // // ... StringTokenizer strTokenizer = new StringTokenizer( bufferedReader.readLine(), "" ""); // // bufferedReader.readLine() // strTokenizer.nextToken() strA = strTokenizer.nextToken(); strB = strTokenizer.nextToken(); A = Integer.parseInt(strA); B = Integer.parseInt(strB); // } private static void processCase() { // N = 0; for (int i = A; i < B; i++) { String str = Integer.toString(i); for (int j = 1; j < str.length(); j++) { String str1 = str.substring(0, str.length() - j); String str2 = str.substring(str.length() - j, str.length()); int n = Integer.parseInt(str2 + str1); N += n > i && n <= B ? 1 : 0; } } // } private static void writeCase(int nIndexCase) throws Exception { // printWriter.print(""Case #""); printWriter.print(nIndexCase + 1); printWriter.print("":""); // // // ... printWriter.print("" ""); printWriter.print(N); printWriter.println(); // } public static void main(String[] args) throws Exception { // begin(); for (nIndexCase = 0; nIndexCase < nNbCases; nIndexCase++) { readCase(); processCase(); writeCase(nIndexCase); } end(); // } static long fact(int n) { long l = n < 0 ? -1 : 1; n *= l; while (n > 1) l *= n--; return l; } static int pgcd(int N, int M) { if (N < M) return pgcd(M, N); if (N % M == 0) return M; return pgcd(N % M, M); } } class A_class { boolean b; int i; double d; String str; public A_class(boolean b, int i, double d, String str) { this.b = b; this.i = i; this.d = d; this.str = str; } } class Item implements Comparable { public int n, p; Item(int n, int p) { this.n = n; this.p = p; } public int compareTo(Item o) { return this.p - o.p; } } " B12273,"import java.util.ArrayList; import java.util.Scanner; /** * Created by IntelliJ IDEA. * User: danghiskhan * Date: 4/14/12 * Time: 11:44 PM */ public class Recycled { public static void main(String[] args) { Scanner in = new Scanner(System.in); Integer caseCount = 1; while (in.hasNextInt()) { Integer start = in.nextInt(); Integer finish = in.nextInt(); Integer count = 0; ArrayList duplicates = new ArrayList(); for (Integer i = start; i < finish; i++) { for (Integer j = i + 1; j <= finish; j++) { String n = i.toString(); String m = j.toString(); String nPerm; if (n.length() > 1) { for (Integer k = 1; k < n.length(); k++) { nPerm = n.substring(k, n.length()) + n.substring(0, k); Integer nPermInt = Integer.parseInt(nPerm); String dupe = nPerm + "":"" + n; if (nPerm.equals(m) && nPermInt > i && !duplicates.contains(dupe)) { //System.out.println(""n:"" + n + "" nPerm: "" + nPerm); duplicates.add(dupe); count++; } } } } } System.out.println(""Case #"" + caseCount++ + "": "" + count); } } } " B11732,"import java.util.*; import java.io.*; public class RecycledNums { static LinkedList output = new LinkedList(); static int numberOfLines; //Main Method public static void main (String[] args) { //Read in the file parseFile( output ); int[] ans = new int[ numberOfLines ]; //Calculate recycled numbers ListIterator itr = output.listIterator(); int count = 0; //Iterate through all cases, input to calcNums while( itr.hasNext() ) { int result = calcNums( (String[])itr.next() ); //Store result of that case in ans array ans[count] = result; count++; } //printFile(output); //Write out file writeFile( ans ); }//End of Main static int calcNums(String[] input ) { //Let A = first element, let B = the second element String a = input[0]; String b = input[1]; String n = null; String m = null; //If length of A and B == 1 if (a.length() == 1 && b.length() == 1) { return 0; } //initialize the array ranges with numbers starting from A ending at B int count = 0; HashSet set = new HashSet(); ArrayList range = new ArrayList(); int int_a = Integer.parseInt(a); int int_b = Integer.parseInt(b); int temp = int_a; while( temp <= int_b ) { range.add( Integer.toString( temp ) ); temp++; } //loop from i = 0 till i < ranges.size() for (int i = 0; i < range.size(); i++) { n = range.get(i); m = range.get(i); int int_n = Integer.parseInt(n); //let length be the length of string in ranges[i] int length = range.get(i).length(); //loop from j = 0 till j < ranges[i].length for (int j = 0; j < length; j++) { //get the last char from current_m //get the string from 0 to 2nd last char //concatenate both strings together m = m.substring(length -1) + m.substring(0, length - 1); int int_m = Integer.parseInt(m); // A ≤ n < m ≤ B if (int_m <= int_b && int_m > int_n && int_m >= int_a) { //If a valid pair, add pair to HashSet, no duplicates. String key = n + m; set.add(key); } } } return set.size(); } static void parseFile(LinkedList output) { try { BufferedReader in = new BufferedReader(new FileReader( ""input.in"" )); numberOfLines = Integer.parseInt( in.readLine() ); int count = 0; String line; while (count < numberOfLines ) //file reading line by line { line = in.readLine(); //Split each line into array of 2 numbers String[] lines = line.split("" ""); //int[] temp = new int[lines.length]; //temp[0] = Integer.parseInt( lines[0] ); //temp[1] = Integer.parseInt( lines[1] ); //output.add(temp); output.add(lines); count++; } in.close(); }catch( IOException ioException ) {} }//End of parseFile() static void writeFile( int[] ans) { //Write out lines to a file try { BufferedWriter bw = new BufferedWriter(new FileWriter(new File(""output.in""), false)); for(int i = 0 ; i < ans.length; i++) { int num = i + 1; bw.write(""Case #"" + num + "": ""); bw.write( Integer.toString(ans[i])); bw.newLine(); } bw.close(); } catch (Exception e) {} }//End of writeFile() } //End of RecyclesNums Class " B12761,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.Scanner; public class Recycled { public static void main(String args[]) { try{ BufferedReader in = new BufferedReader(new FileReader(""C-small-attempt0.in"")); BufferedWriter out = new BufferedWriter(new FileWriter(""C-small.out"")); String line = in.readLine(); int caseCount = Integer.parseInt(line); StringBuffer outputWriter = new StringBuffer(); int lowCap, hiCap, digitCt, recycled, resultCount; ArrayList collisionHelper; //caseCount = 3; for(int i = 1; i <= caseCount; i++){ line = in.readLine(); Scanner s = new Scanner(line); lowCap = s.nextInt(); hiCap = s.nextInt(); digitCt = ("""" + lowCap).length(); resultCount = 0; for(int j = lowCap; j <= hiCap; j++){ collisionHelper = null; for(int k = 1; k < digitCt; k++){ recycled = cutAndSwap(j, k); if(recycled > j && recycled <= hiCap){ if(collisionHelper == null){ collisionHelper = new ArrayList(); collisionHelper.add("""" + recycled); resultCount++; } else if(!collisionHelper.contains("""" + recycled)){ collisionHelper.add("""" + recycled); resultCount++; } //System.out.println(resultCount + "" "" + j + "" "" + recycled + "" "" + k); } } } outputWriter.append(""Case #"" + i + "": ""); outputWriter.append(resultCount); if(i != caseCount) outputWriter.append(""\n""); } out.write(outputWriter.toString()); System.out.println(outputWriter.toString()); in.close(); out.close(); } catch(Exception e){ //swallow the exception } } //assumes 0 < position < digits in number public static int cutAndSwap(int number, int position){ String s = """" + number; String halfOne = s.substring(0, position); String halfTwo = s.substring(position); return Integer.parseInt(halfTwo + halfOne); } } " B12159,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; /** * */ /** * @author Pandapotan Christian * */ public class RecycledNumbers { /* * Write string to a file with specified path */ public static void writeFile(String filePath, String content){ try{ PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(filePath))); out.write(content); out.close(); } catch(IOException e){ e.printStackTrace(); } } /* * Return array that contains each lines of the input file, null if the reading process failed */ public static ArrayList getLines(String filePath){ ArrayList lines = null; try{ lines = new ArrayList(); String s; BufferedReader in = new BufferedReader( new FileReader(filePath)); while ((s = in.readLine()) != null) { lines.add(s); } in.close(); }catch(IOException e){ e.printStackTrace(); } return lines; } /** * Replace value with the real path */ public static final String fileIn = ""D:\\CodeJam\\RecycledNumbers-small-attempt0.in""; /** * @param args */ public static void main(String[] args) { //get input from file ArrayList lines = getLines(fileIn); //process data if(lines!=null){ System.out.println(""System Start""); long systemStart = System.currentTimeMillis(); String firstLine = lines.get(0); int T = Integer.parseInt(firstLine); //Main Algorithm StringBuffer result = new StringBuffer(); for(int testIdx = 1; testIdx<=T; testIdx++){ System.out.println(""Test Case Number: ""+testIdx); long start = System.currentTimeMillis(); String param[] = lines.get(testIdx).split("" ""); int A = Integer.parseInt(param[0]); int B = Integer.parseInt(param[1]); int total = countRecycle(A, B); long elapsedTime = System.currentTimeMillis() - start; System.out.println(""Case #""+testIdx+"" takes ""+elapsedTime+""ms.""); //Append the result with the previous testcase result.append(""Case #""+testIdx+"": ""+ total+""\n""); } //write the result to a file String fileOut = fileIn.replace("".in"", "".out""); writeFile(fileOut, result.toString()); System.out.println(""SUCCESS""); long elapsedTimeSyetem = System.currentTimeMillis() - systemStart; System.out.println(""Time Elapsed to run whole test case: ""+elapsedTimeSyetem+""ms""); } } public static int countRecycle(int A, int B){ int count = 0; for(int i = A; i<=B; i++){ String number = i+""""; HashMap checker = new HashMap(); for(int charIdx = 1; charIdxi && newNumber<=B) checker.put(newNumber, true); } count += checker.size(); } return count; } } " B11518,"package qualificationround; import java.io.*; import java.util.*; public class ProblemC { public static Set h; /** * @param args */ public static void main(String[] args) throws IOException{ Scanner sc = new Scanner(new FileReader(""C.in"")); PrintWriter out = new PrintWriter(new FileWriter(""C.out"")); int t = sc.nextInt(); for (int caseNum = 1; caseNum <= t; caseNum++) { h = new HashSet(); int a = sc.nextInt(); int b = sc.nextInt(); int p = a; int count = 0; while (p<=b) { if (!h.contains(p)) { count += rolling(p, a, b); } p++; } out.println(""Case #""+caseNum+"": ""+count); } out.close(); } public static int rolling(int num,int a,int b) { h.add(num); String sNum = Integer.toString(num); String s = new String(sNum); int count = 1; for (int i = 0; i < sNum.length()-1; i++) { s = s.substring(s.length()-1).concat(s.substring(0,s.length()-1)); //System.out.println(s); int p = Integer.parseInt(s); if (p == num) break; if (p >= a && p <= b ) { h.add(p); count++; } } //return count; return (count-1)*count/2; } } " B11015,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author AlexR */ import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; public class PrintResult { FileOutputStream fout; PrintStream fstream; public PrintResult(String filename) throws IOException { fout = new FileOutputStream(filename); fstream = new PrintStream(fout); } public void printLine(int caseNum, String line) { fstream.println(""Case #"" + (caseNum+1) + "": "" + line); } public void close() throws IOException { fout.close(); } } " B13080,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; public class Recycled { public static boolean isRot(String a, String b){ if(a.length()!=b.length()) return false; if(!a.equals(b)){ String c = b; for(int i=0;i> mapa) { int num = Integer.parseInt(a); if(num<10)return; if(num>f || num=in && cc<=f&& String.valueOf(cc).length()==a.length() && cc!=num){ // if(mapa.containsKey(num) && !mapa.get(num).contains(cc)){ // mapa.put(num,cc); // if(!mapa.containsKey(cc)) // mapa.put(cc, new ArrayList()); // mapa.get(cc).add(num); // } // else{ // mapa.put(num, new ArrayList()); // mapa.get(num).add(cc); // if(!mapa.containsKey(cc)) // mapa.put(cc, new ArrayList()); // mapa.get(cc).add(num); // } if(!mapa.containsKey(num)){ mapa.put(num, new HashSet()); } mapa.get(num).add(cc); if(!mapa.containsKey(cc)) mapa.put(cc, new HashSet()); mapa.get(cc).add(num); }else{ //System.out.println(cc); } } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader(""/home/debian/Descargas/C-small-attempt0.in"")); // BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String input = br.readLine(); int f = Integer.parseInt(input); for (int i = 0; i < f; i++) { HashMap> mapa = new HashMap>(); input = br.readLine(); int a = Integer.parseInt(input.split("" "")[0]); int b = Integer.parseInt(input.split("" "")[1]); for (int k = a; k <=b; k++) { //System.out.println(""k "" + k); //System.out.println(""l "" + l); rots("""" + k, a,b,mapa); } int cont =0; for(int key: mapa.keySet()){ cont+=mapa.get(key).size(); } System.out.println(""Case #"" + (i + 1) + "": "" + (cont>>1)); } } } " B11122," import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class Recycled { private String strLine; private BufferedReader f; private PrintWriter out; private ArrayList hasil; public Recycled() { strLine = new String(); try { f = new BufferedReader(new FileReader(""c0.in"")); out = new PrintWriter(new BufferedWriter(new FileWriter(""recycled.out""))); } catch(IOException i) { } hasil = new ArrayList(); } public void find(int A, int B) { byte[] n; byte[] m; boolean isFind = false; int count = 0; for (int i = A; i < B; i++) { for (int j = i+1; j <= B; j++) { n = Integer.toString(i).getBytes(); m = Integer.toString(j).getBytes(); if (n.length == m.length) { for (int k = 1; k < m.length && !isFind; k++) { m = cls(m,8); if (Arrays.equals(n, m)) { isFind = true; } } if (isFind) { count++; isFind = false; } } } } hasil.add(count); } int byteArrayToInt(byte [] b) { return (b[0] << 24) + ((b[1] & 0xFF) << 16) + ((b[2] & 0xFF) << 8) + (b[3] & 0xFF); } byte[] intToByteArray(int value) { return new byte[] { (byte)(value >>> 24), (byte)(value >>> 16), (byte)(value >>> 8), (byte)value}; } public byte[] cls(byte[] b, int k){ byte[] hasil1 = b; byte temp = hasil1[0]; System.arraycopy(b, 1, hasil1, 0, b.length-1); hasil1[b.length-1] = temp; return hasil1; } public static void main(String[] args) throws IOException { Recycled rec = new Recycled(); int T; int A; int B; StringTokenizer st; T = Integer.parseInt(rec.f.readLine()); System.out.println(""T = "" + T); if (T > 50 || T < 1) { System.out.println(""Error""); } else { for (int i = 0; i < T; i++) { if ((rec.strLine = rec.f.readLine()) != null) { st = new StringTokenizer(rec.strLine); A = Integer.parseInt(st.nextToken()); B = Integer.parseInt(st.nextToken()); rec.find(A,B); } } for (int x = 0; x < rec.hasil.size(); x++) { rec.out.println(""Case #"" + (x + 1)+ "": "" +rec.hasil.get(x)); } rec.out.close(); // close the output file System.exit(0); } } } " B11699," public class testCase { public testCase(int n){ T = n; cases = new String[T]; count=0; } public void addCase(String s){ if(count > T-1){ System.out.println(""STOP ! too many test cases !!""); return; } cases[count++] = s; } int count; int T; String[] cases; } " B12816,"import java.util.HashMap; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int i = 1; i <= T; i++) { int A = in.nextInt(); int B = in.nextInt(); int numberOfRecycledPairs = findNumberOfRecycledPairs(A, B); System.out.format(""Case #%d: %d\n"", i, numberOfRecycledPairs); } } private static int findNumberOfRecycledPairs(int start, int end) { HashMap recycledPairs = new HashMap(); for(int i = start; i <= end; i++) { int originalNumber = i; String numberStr = originalNumber + """"; int numberLength = numberStr.length(); for(int j = 1; j < numberLength; j++) { String newNumberStr = numberStr.substring(numberLength - j) + numberStr.substring(0, numberLength - j); int newNumber = Integer.parseInt(newNumberStr); if(newNumber >= start && newNumber <= end && newNumber > originalNumber) recycledPairs.put(originalNumber + ""::"" + newNumber,""""); } } return recycledPairs.size(); } } " B11225,"package test; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; public class Sort { public static void main(String[] args) { HashMap map = new HashMap(); ValueComparator bvc = new ValueComparator(map); TreeMap sorted_map = new TreeMap(bvc); map.put(""A"",99.5); map.put(""B"",67.4); map.put(""C"",67.5); map.put(""D"",67.3); System.out.println(""unsorted map""); for (String key : map.keySet()) { System.out.println(""key/value: "" + key + ""/""+map.get(key)); } sorted_map.putAll(map); System.out.println(""results""); for (String key : sorted_map.keySet()) { System.out.println(""key/value: "" + key + ""/""+sorted_map.get(key)); } } } class ValueComparator implements Comparator { Map base; public ValueComparator(Map base) { this.base = base; } public int compare(Object a, Object b) { if((Double)base.get(a) < (Double)base.get(b)) { return 1; } else if((Double)base.get(a) == (Double)base.get(b)) { return 0; } else { return -1; } } } " B12398,"import java.io.File; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { static long calc(long A, long B) { long d[] = new long[100]; long res = 0; for (long a = A; a<=B; a++) { long t = a; int n = 0; while (t > 0) { d[n++] = (t % 10); t /= 10; } Set set = new HashSet(); for (int i=1; i=0; j--) b = b*10 + d[j]; for (int j=n-1; j>=i; j--) b = b*10 + d[j]; if (a < b && b <= B && !set.contains(b)) { res++; set.add(b); } } } return res; } public static void main(String[] args) throws Exception { /*System.out.println(calc(10, 40)); System.out.println(calc(1, 9)); System.out.println(calc(100, 500)); System.out.println(calc(1111, 2222)); for (int i =0; i<50; i++) System.out.println(calc(1000000, 2000000));*/ Scanner scanner = new Scanner(new File(""c.in"")); int T = scanner.nextInt(); PrintWriter pw = new PrintWriter(new File(""c.out"")); for (int i=0; i> f = new HashMap>(); long res = 0; for (int i = a; i <= b; i++) { int s = (i + """").length(); for (int j = 1; j < s; j++) { int c = (int) ((i / pow[j]) + pow[s - j] * (i % pow[j])); if (c <= b && c >= a && c != i && (c + """").length() == s) { boolean k = f.containsKey(i); if (!k) f.put(i, new LinkedList()); if (f.containsKey(c)) { LinkedList w = f.get(c); k = w.contains(i); } if (!k) { f.get(i).add(c); res++; } } } } return res; } }" B11545," import java.io.*; import java.util.HashSet; import java.util.Scanner; public class Numbers { public static void main(String[] args) throws IOException { Numbers numbers = new Numbers(); numbers.findNumbers(); } public void findNumbers() throws IOException { Scanner sc = new Scanner(new File(""D:/testing/a.txt"")); BufferedWriter bf = new BufferedWriter(new FileWriter(""D:/testing/b.txt"", false)); HashSet hs = new HashSet(); int T = sc.nextInt(); for (int i = 1; i <= T; i++) { int a = sc.nextInt(); int b = sc.nextInt(); hs.clear(); int digits = (int) Math.log10(a); for (int n = a; n <= b; n++) { for (int j = 1; j <= digits; j++) { int m = swapDigits(n, j); if (n < m && m <= b) { hs.add(String.valueOf(m) + String.valueOf(n)); } } } int val=hs.size(); System.out.println(""Case #"" + i+"": ""+val); bf.write(""Case #"" + i+"": ""+val+ ""\n""); } bf.close(); } public int swapDigits(int val, int d) { int power=(int)Math.pow(10, d); int x = val/power; int y = val % power; return y * (int) Math.pow(10, (int) Math.log10(x) + 1) + x; } } " B10052,"import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; public class Main_c_new { public static void main(String[] args) throws Exception{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int cases=Integer.parseInt(in.readLine()); for(int i=1;i<=cases;i++) { int count = 0; String line = in.readLine(); String parts[] = line.split("" ""); int a = Integer.parseInt(parts[0]); int b = Integer.parseInt(parts[1]); for(int j=a;j list = new ArrayList(); for(int k=1;k= (int)(Math.pow(10, k-1))){ int num = (part2*((int)Math.pow(10, length-k)))+part1; if(num>j && num<=b){ int flag = 0; for(int l=0; l set = new HashSet(); for (int n = A; n < B; n++) { set.clear(); pow10 = 1; lastPart = 0; firstPart = n; exp10 = (int) Math.pow(10, noDig - 1); for (dig = 1; dig < noDig; dig++) { lastPart = (firstPart % 10) * pow10 + lastPart; firstPart = firstPart / 10; pow10 *= 10; newNo = lastPart * exp10 + firstPart; exp10 /= 10; if ((int) Math.log10(newNo) != noDig - 1) { continue; } if (newNo > n && newNo <= B && !set.contains(newNo)) { set.add(newNo); count++; } } } return count; } public void close() throws IOException { in.close(); out.close(); } public static void main(String[] args) throws Exception { RecycledNo pb = new RecycledNo(""input.txt"", ""output.txt""); pb.solveAll(); pb.close(); } } " B11443,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ //c prob import java.io.*; import java.util.StringTokenizer; /** * * @author abood */ public class test { static int count =0,s=0; public static void main(String[] args) throws IOException { BufferedReader br =new BufferedReader(new FileReader(""C-small-attempt0.in"")); PrintWriter out =new PrintWriter(new BufferedWriter(new FileWriter(""C-small-attempt0.out""))); int loop=Integer.parseInt(br.readLine()); for (int i = 1; i <=loop; i++) { count=0; StringTokenizer st=new StringTokenizer(br.readLine()); int x=Integer.parseInt(st.nextToken()); int y=Integer.parseInt(st.nextToken()); for (int j = x; j < y; j++) { check(j,y); } out.println(""Case #""+i+"": ""+count); } out.close(); // close the output file System.exit(0); } public static void check(int xx,int yy){ String res=""""; String x=""""+xx; int l=x.length(); String t=""""; for (int i = 1; i < l; i++) { t=x.substring(i, l)+x.substring(0,i); int m=Integer.parseInt(t); if(m<=yy&&m>xx){ // System.out.println(xx+"" ""+t); if(res.contains(t))continue; res+="" ""+t; count++; } } } } " B10912,"package Test1; import java.io.BufferedReader; import java.io.InputStreamReader; public class Test1 { public static void main(String[] args) { String temp1 = null; String temp2 = null; int n,a,b; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)) ; try { String str = in.readLine(); int result; n = Integer.parseInt(str.trim()); for (int i = 1; i <= n; i++) { str = in.readLine(); String[] temp = str.split("" ""); a = Integer.parseInt(temp[0]); b = Integer.parseInt(temp[1]); result = 0; for (int j=a; j<=b;j++){ temp1 = (new Integer(j)).toString(); for (int k=1; k b) continue; //System.out.println(""Case #""+i+"": ""+j+"":""+currentnum+"";;;;;;;""+temp1.substring(0, k)+""=====""+temp1.substring(k)); result++; } } System.out.println(""Case #""+i+"": ""+result); //System.out.println(""""); } } catch (Exception e) { } } } " B13125,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintStream; import java.io.PrintWriter; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.TreeSet; public class Recycle { static PrintStream O = System.out; /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub try { long initTime = System.currentTimeMillis(); PrintWriter out = new PrintWriter(new FileWriter(""C.out"")); BufferedReader in = new BufferedReader(new FileReader(""C-small-attempt0.in"")); int cases = Integer.parseInt(in.readLine()); for (int kase = 0; kase < cases; kase++){ String input = in.readLine(); int A = Integer.parseInt(input.split("" "")[0]); int B = Integer.parseInt(input.split("" "")[1]); out.println(""Case #"" + (kase + 1) + "": "" + count(A, B)); } //O.println(System.currentTimeMillis() - initTime); out.close(); } catch (Exception e) { e.printStackTrace(); } } static int count (int A, int B){ Set set = new TreeSet(); int count = 0; char cA = Integer.toString(A).charAt(0); char cB = Integer.toString(B).charAt(0); for (long i = A; i < B; i++){ String s = Integer.toString((int)i); long newN; for (int j = 1; j < s.length(); j++){ if (s.charAt(j) >= cA && s.charAt(j) <= cB){ String tmp = s.substring(j) + s.substring(0,j); newN = Integer.parseInt(tmp); if (newN != i && newN >= A && newN <= B){ set.add(i << 21 | newN); set.add(newN << 21 | i); } } } } return set.size() / 2; } } " B10246,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recyclednumbers; /** * * @author vandit */ public class Pair { private String number1; private String number2; public Pair(String no1, String no2) { number1 = no1; number2 = no2; } @Override public boolean equals(Object temp1) { boolean ans = false; Pair temp = (Pair) temp1; if (temp.number1.equals(number1)) { if (temp.number2.equals(number2)) { ans = true; } } else if (temp.number1.equals(number2)) { if (temp.number2.equals(number1)) { ans = true; } } return ans; } @Override public int hashCode() { return number1.length() + number2.length(); } } " B10260,"package core; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.List; public class ExtendedBufferedReader extends BufferedReader { public ExtendedBufferedReader(Reader iReader) { super(iReader); } public String getLine(){ try { return readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } // Get int from line public int getIntFL(){ try { return new Integer(readLine()).intValue(); } catch (NumberFormatException e) { // TODO Auto-generated catch block System.out.println(""Error check entry data""); } catch (IOException e) { System.out.println(""Error check entry data""); e.printStackTrace(); } return 0; } public List getIntListFL(){ String[] aRead; try { aRead = readLine().split("" ""); } catch (IOException e) { // TODO Auto-generated catch block return null; } List aList = new ArrayList(); for (String num:aRead) { aList.add(new Integer(num)); } return aList; } public List getLongListFL(){ String[] aRead; try { aRead = readLine().split("" ""); } catch (IOException e) { // TODO Auto-generated catch block return null; } List aList = new ArrayList(); for (String num:aRead) { aList.add(new Long(num)); } return aList; } } " B10088,"import java.io.*; public class Recycle { int t=0,A=0,B=0; String output=""""; int count=1; public void readFile(String fn) { String data=""""; try{ File in=new File(fn); BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(in))); data=br.readLine(); t=Integer.parseInt(data); while(count<=t) { data=br.readLine(); String s[]=data.split("" ""); A=Integer.parseInt(s[0]); B=Integer.parseInt(s[1]); computeRecycle(); count++; } br.close(); }catch(Exception e){} } public static void main(String args[]) { Recycle rc=new Recycle(); rc.readFile(args[0]); rc.writeToFile(); } public void computeRecycle() { int sum=0; for(int i=A;i<=B;i++) { String s=""""+i; String t=s; int nm=0; int l=s.length(); do { char c[]=t.toCharArray(); char ch=c[0]; for(int j=0;j=A && nm<=B) { sum++; } }while(nm!=i); } sum=sum/2; output+=""Case #""+count+"": ""+sum+""\n""; } public void writeToFile(){ try { File fout= new File(""output.in""); DataOutputStream dos = new DataOutputStream(new FileOutputStream(fout)); dos.writeBytes(output); dos.close(); } catch (Exception ex) {} } }" B12965,"package com.code.jam; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class RecycledNumbers { FileInputStream in; FileOutputStream out; BufferedReader br; void open() throws IOException { in = new FileInputStream(new File( ""/home/lenovo/Documents/GCJ/C-small-attempt0.in"")); out = new FileOutputStream(new File( ""/home/lenovo/Documents/GCJ/C-small-attempt0.out"")); br = new BufferedReader(new InputStreamReader(new DataInputStream(in))); } void close() throws IOException { out.close(); } void run() throws IOException { int tn = new Integer(br.readLine()); for (int i = 1; i <= tn; i++) { // System.out.println(br.readLine()); String AB = br.readLine(); BigInteger A = new BigInteger(AB.split("" "")[0]); BigInteger B = new BigInteger(AB.split("" "")[1]); int count = 0; Map nm = new HashMap(); for (BigInteger k = A; k.compareTo(B) == -1; k = k .add(BigInteger.ONE)) { String n = k.toString(); String m = n; nm.clear(); for(int l=0;l0 && mBig.compareTo(B) <= 0 && mBig.compareTo(A) >0 && !nm.containsValue(m) ) { count++; nm.put(n, m); System.out.println(n + "", "" +m+"" ""+ count); } } } out.write((""Case #"" + i + "": "" + count).getBytes()); out.write(""\n"".getBytes()); } } public static String rotateDigitRight(String A) { String val = A.toString(); String val0 = String.valueOf(val.charAt(val.length()-1)); String valRest = """"; if(val.length()>=2) { valRest = val.substring(0, val.length()-1); } val = val0 + valRest; return val; } public static void main(String[] args) throws IOException { RecycledNumbers solution = new RecycledNumbers(); solution.open(); solution.run(); solution.close(); } } " B12569,"package small; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class RecycledNumbers { private static int noOfCases; private static String[] result; private static List listOfNumbers; private static String inputFile = ""C-small-attempt0.in""; private static String outputFile = ""C-small-attempt0.out""; public static void main(String[] args) { readInputFile(); writeToFile(result); } public static void writeToFile(String args[]) { try { FileWriter fstream = new FileWriter(outputFile); BufferedWriter out = new BufferedWriter(fstream); for (int i = 0; i < args.length; i++) { out.write(args[i]); if (i != args.length - 1) out.newLine(); } out.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } private static void readInputFile() { try { FileInputStream fstream = new FileInputStream(inputFile); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); noOfCases = Integer.parseInt(br.readLine()); String strLine; result = new String[noOfCases]; for (int i = 0; i < noOfCases; i++) { listOfNumbers = new ArrayList(); strLine = br.readLine(); String[] temp = strLine.split("" ""); int start = Integer.parseInt(temp[0]); int end = Integer.parseInt(temp[1]); System.out.println(""start: ""+start+"".. end: ""+end); int totalSum = getResult(start,end); System.out.println(""Case #"" + (i + 1) + "": "" + totalSum); result[i] = ""Case #"" + (i + 1) + "": "" + totalSum; } for(int x=0;x localList = new ArrayList(); //System.out.println(""current number: ""+currentNumber); // Getting different combination of char arrays// // Duplicate the first array for(int i=0;i=start && numberArray[i]<=end) && (!localList.contains(numberArray[i]))){ localList.add(numberArray[i]); count++; listOfNumbers.add(numberArray[i]); } } //Calculate the nc2 for the numbers nc2Count = (count * (count-1))/2; if(nc2Count!=0){ System.out.println(""current number: ""+currentNumber+"". count: ""+count+"". nc2 count: ""+nc2Count); } System.out.println(); return nc2Count; } } " B10139,"import java.io.*; import java.util.*; public class ProblemC { public static void main(String[]args) { Scanner f = new Scanner(System.in); int T = f.nextInt(); for(int set=0;set= 10) { b /= 10; leadingMult*=10; } // System.out.println(""leadingMult: ""+leadingMult); long pairs = 0; for(int x=A;x<=B;x++) { // System.out.println(""x: ""+x); int y = x; do { y = y/10 + leadingMult*(y%10); // System.out.println(""y: ""+y); if(x < y && y <= B) { // System.out.printf(""(%d,%d)\n"",x,y); pairs++; } } while(y!=x); } System.out.printf(""Case #%d: %d\n"",set+1,pairs); } } }" B12032,"import java.io.*; import java.util.*; public class RecycledNumbers{ public static void main(String[] args) throws Exception{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = Integer.parseInt(in.readLine()); for(int i = 0; i < n; ++i){ StringTokenizer st = new StringTokenizer(in.readLine()); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); boolean[] done = new boolean[10000000]; int ans = 0; for(int j = A; j <= B; ++j){ if(done[j]){ continue; } int d = (int)Math.log10(j); int rightMost = (int)Math.pow(10, d); int temp = j; int tempAns = 0; for(int k = 0; k < d; ++k){ temp = temp%rightMost*10 + temp/rightMost; if(temp > j && temp <= B && !done[temp]){ done[temp] = true; ++tempAns; } } ans += tempAns*(tempAns+1)/2; } out.println(""Case #""+(i+1)+"": ""+ans); } out.close(); } } " B12580,"package com.google.codejam.abs; import com.google.codejam.practice2010.round1A.Rotate; import com.google.codejam.utils.files.ManejoArchivos; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Date; public abstract class Problem { public Problem(String name) throws FileNotFoundException, IOException { System.out.println(new Date() + "" "" + name); ManejoArchivos.initInput(name); ManejoArchivos.initOutput(name); int cases = ManejoArchivos.getInt(); System.out.println(new Date() + "" Se procede a evaluar "" + cases + "" cases""); for(int caso=0;caso= len) { pos = 0; len = -1; try { len = dis.read(b); } catch (IOException ex) { } } return pos < len ? b[pos++] : -1; } public int nextInt() throws IOException { int ret = 0; int ch = skipWhite(); int sign = 1; if (ch == '-') { sign = -1; ch = read(); } while (!isSpaceChar(ch) && ch != -1) { ret *= 10; ret += ch - '0'; ch = read(); } return ret * sign; } public long nextLong() throws IOException { long ret = 0; int ch = skipWhite(); int sign = 1; if (ch == '-') { sign = -1; ch = read(); } while (!isSpaceChar(ch) && ch != -1) { ret *= 10; ret += ch - '0'; ch = read(); } return ret * sign; } public int skipWhite() throws IOException { int ch = read(); while (true) { if (ch == -1) { return -1; } if (!isSpaceChar(ch)) { return ch; } ch = read(); } } public boolean isSpaceChar(int c) { return c <= 32 && c >= 0; } public int next(char[] buff) throws IOException { int c = skipWhite(); int len = 0; while (!isSpaceChar(c) && c != -1) { buff[len++] = (char) c; c = read(); } return len; } public String next() throws IOException { int c = skipWhite(); StringBuilder res = new StringBuilder(); while (!isSpaceChar(c) && c != -1) { res.appendCodePoint(c); c = read(); } return res.toString(); } public String nextLine() throws IOException { int c = skipWhite(); StringBuilder res = new StringBuilder(); while (c != '\n' && c != '\r' && c != -1) { res.appendCodePoint(c); c = read(); } return res.toString(); } void debug(Object... obj) { println(""-->"" + Arrays.deepToString(obj)); } void solve() throws Exception { int[] pow = new int[]{1, 10, 100, 1000, 10000, 100000, 1000000, 10000000}; int cases = nextInt(); for (int kk = 1; kk <= cases; kk++) { int a = nextInt(); int b = nextInt(); int sol = 0; for (int i = a; i <= b; i++) { int dig = getDigits(i); int start = i; int[] found = new int[dig]; int len = 0; for (int j = 0; j < dig; j++) { int mod = start % 10; int next = start / 10 + mod * pow[dig - 1]; if (i < next && next <= b && mod != 0 && start != next) { boolean valid = true; for (int k = 0; k < len; k++) { if (found[k] == next) { valid = false; break; } } if (valid) { sol++; found[len++] = next; } } start = next; } } println(String.format(""Case #%d: %d"", kk, sol)); } } private int getDigits(int a) { if (a < 10) return 1; if (a < 100) return 2; if (a < 1000) return 3; if (a < 10000) return 4; if (a < 100000) return 5; return 6; } }" B12123,"package Television; public class Pair{ public int a, b; public Pair(int a, int b)throws Exception { if(a>=b) throw new Exception(""invalid input for pair""); this.a=a; this.b=b; } public boolean equls(Object po) { Pair p = (Pair)po; if(p.a == this.a && p.b==this.b) return true; return false; } public boolean equls(Pair p) { if(p.a == this.a && p.b==this.b) return true; return false; } } " B12089,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package googlecodejamqualifier; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; /** * * @author Dean */ public class RecycledNumbers { public static void main(String args[]) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int testCases = Integer.parseInt(reader.readLine().trim()); for (int i = 0; i < testCases; i++) { String split[] = reader.readLine().split(""[\\s]+""); int A = Integer.parseInt(split[0]); int B = Integer.parseInt(split[1]); System.out.println(""Case #"" + (i + 1) + "": "" + countPermutations(A, B)); } } public static int countPermutations(int A, int B) { int count = 0; int digits = (B + """").length(); for (int m = A + 1; m <= B; m++) { HashMap checked = new HashMap(10); for (int i = 1; i < digits; i++) { int mul = (int) (Math.pow(10, i)); int move = m % mul; int n = m / mul; n = n + move * (int) (Math.pow(10, (digits - i))); if ((n < m) && ((n + """").length() == digits)&& (A <= n)) { //count++; if (checked.containsKey(n)) { continue; } else { count++; checked.put(n, true); } } } } return count; } } " B10591,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class C { public static void main(String args[]){ String fn=""C:\\codejam\\C.in""; String fnOut=""C:\\codejam\\C.out""; try{ BufferedReader br = new BufferedReader(new FileReader(fn)); BufferedWriter bw = new BufferedWriter(new FileWriter(fnOut)); String line = null; int NCase = Integer.valueOf(br.readLine().trim()); long stime = System.currentTimeMillis(); for(int icase=0;icase num = new ArrayList(); for(long j = 1; j<(new Long(A).toString()).length(); j++){ long p1 = (long) (i/(Math.pow(10,j))); long p2 = (long) (i%(Math.pow(10,j))); long pn = new Long(p2+""""+p1); //System.out.println(""Aca "" + pn ); if(pn>i&&pn<=B){ if(!num.contains(pn)){ num.add(pn); x++; } System.out.println(x + "" - "" + i + "": "" + pn); } } } return (x); } } " B10830,"/** * */ package me.adrabi.codejam; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; /** * @author Adrabi Abderrahim, z3vil * */ public class P3 { public static void main(String[]$) throws NumberFormatException, IOException { List recycled = new ArrayList(); { BufferedReader reader = new BufferedReader( new InputStreamReader(new FileInputStream(""p3""))); int count = Integer.parseInt(reader.readLine()); String line = null; while((line = reader.readLine()) != null) { recycled.add(line); } } int currentLine = 1; for(String line : recycled) { String numbers[] = line.split("" ""); if(numbers.length > 1) { Map tmp = new TreeMap(); int a = Integer.parseInt(numbers[0]), b = Integer.parseInt(numbers[1]), count = 0; for(int index = a ; index <= b; index++) { String array[] = (index+"""").split(""""); if(isSimilare(array)) { continue; } List elements = toList(array); int steps = array.length - 2; while(steps >= 1) { String element = elements.get(elements.size() - 1); elements.remove(elements.size() - 1); elements.add(0, element); steps--; String number = toString(elements); if(number.startsWith(""0"")) { continue; } else if(number.endsWith(""00"")) { continue; } else { int testNumber = Integer.parseInt(number); if( index < testNumber && testNumber <= b ) { if(tmp.containsKey(number)) { tmp.put(number, tmp.get(number) + 1); } else { tmp.put(number, 1); } if(tmp.get(number) < 4) { count++; } } } } } System.out.printf(""Case #%d: %d\n"", currentLine++, count); } else { System.out.printf(""Case #%d: 0\n"", currentLine++); } } } private static boolean isSimilare(String[]array) { String lastElement = array[1]; boolean check = true; for(int start = 2; start < array.length; start++) { if(!lastElement.equals(array[start])) { check = false; break; } lastElement = array[start]; } return check; } private static String toString(List list) { String str = """"; for(String tmp : list) { str += tmp; } return str; } private static List toList(String array[]) { List list = new ArrayList(); for(int start = 1; start < array.length; start++) { list.add(array[start]); } return list; } } " B12988,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; public class RQC { private static BufferedReader in; private static PrintWriter out; private static StringTokenizer input; public static void main(String[] args) throws IOException { //Initializing ... new RQC(); //------------------------------------------------------------------------- int testCases = nextInt(); int counter=0; while (testCases -- > 0){ counter++; //Here put the code..:) int a = nextInt(); int b = nextInt(); int ret=0; for (int i = a; i <= b; i++) { for (int j = i+1; j <=b; j++) { if(cir(""""+i,""""+j))ret++; } } writeln(""Case #""+counter+"": ""+ret); } //------------------------------------------------------------------------- //closing up end(); //-------------------------------------------------------------------------- } private static boolean cir(String a, String b) { // TODO Auto-generated method stub for (int i = 0; i < a.length(); i++) { boolean t = true; for (int j = 0; j < a.length(); j++) { if(a.charAt(j)!=b.charAt((j+i)%b.length())){t=false;break;} } if(t)return true; } return false; } public RQC() throws IOException { //Input Output for Console to be used for trying the test samples of the problem in = new BufferedReader(new InputStreamReader(System.in)); // out = new PrintWriter(System.out); //------------------------------------------------------------------------- //Input Output for File to be used for solving the small and large test files // in = new BufferedReader(new FileReader(""RQC.in"")); out = new PrintWriter(""RQC.in""); //------------------------------------------------------------------------- //Initalize Stringtokenizer input input = new StringTokenizer(in.readLine()); } private static int nextInt() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return Integer.parseInt(input.nextToken()); } private static long nextLong() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return Long.parseLong(input.nextToken()); } private static double nextDouble() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return Double.parseDouble(input.nextToken()); } private static String nextString() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return input.nextToken(); } private static void write(String output){ out.write(output); out.flush(); } private static void writeln(String output){ out.write(output+""\n""); out.flush(); } private static void end() throws IOException{ in.close(); out.close(); System.exit(0); } } " B10051,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package google.code.jam.recycled.numbers; import java.util.ArrayList; import java.util.HashMap; /** * * @author Lucas */ public class RecycledNumbers { public ArrayList findRecycledNumbers(ArrayList list) { ArrayList result = new ArrayList(); Integer[] current; int x; int y; int total; int temp; String str; for (int n = 0; n < list.size(); n++) { current = list.get(n); total = 0; x = current[0]; y = current[1]; for (int m = x; m <= y; m++) { str = String.valueOf(m); for (int j = 0; j < str.length() - 1; j++) { str = str.substring(1) + str.charAt(0); temp = Integer.parseInt(str); if ((temp <= y) && (temp > m) && (temp >= x)) { total++; } } } result.add(total); } return result; } } " B11402,"package Round1; /* ID: kevinle7 LANG: JAVA TASK: recycled */ import java.io.*; import java.util.*; class recycled { public static int[] pow = {1,10,100,1000,10000,100000,1000000,10000000,100000000}; public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new FileReader(""recycled.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""recycled.out""))); int t = Integer.parseInt(f.readLine()); for (int i = 0 ; i < t; i++) { StringTokenizer st = new StringTokenizer(f.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); int d = (int) Math.log10(a); int count = 0; for (int n = a; n < b; n++) { HashSet set = new HashSet(); set.add(n); int temp = n; temp = temp/10 + (temp%10)*pow[d]; while (!set.contains(temp)) { set.add(temp); if (temp > n && temp <= b) count++; temp = temp/10 + (temp%10)*pow[d]; } } out.println(""Case #"" + (i+1) + "": "" + count); } out.close(); System.exit(0); } }" B13045," public class Par { Integer A,B; public Par(Integer a,Integer b) { A=a; B=b; } public boolean equals(Object o) { boolean res=false; Par P=(Par) o; if ((P.A.equals(A) && P.B.equals(B))||(P.A.equals(B) && P.B.equals(A))) { res=true; } return res; } public int hashCode() { return (A*B+A.hashCode()+B.hashCode()); } public String toString() { return ""(""+A+"", ""+B+"")""; } } " B11877,"package gcj2012; import java.io.BufferedReader; import java.io.FileReader; import java.io.BufferedWriter; import java.io.FileWriter; public class RecycledNumber { public String count(int A, int B, int caseNr) { StringBuffer sb = new StringBuffer(""""); sb.append(""Case #""); sb.append(caseNr); sb.append("": ""); int result = 0; for (int i = A; i <= B; i++) { result += recycled(i, B); } sb.append(result); return sb.toString(); } public int recycled(int nr, int max) { if (nr < 12) return 0; int test = nr; int count = 0; int length = (int)Math.ceil(Math.log10((double)nr)); int[] digits = new int[length]; for (int i = length-1; i >=0; i--) { digits[i] = test%10; test = test/10; } int[] valuesFound = new int[length]; for (int i = 0; i < length; i++) { if (digits[i] != 0) { int value = 0; for (int j = 0; j < length; j++) { value = value*10; value += digits[(i+j)%length]; } valuesFound[i] = value; if ((value > nr) && (value <= max)) { boolean found = false; for (int k = 0; k < i; k++) { if (valuesFound[k] == valuesFound[i]) found = true; } //System.out.println(nr + "" "" + value); if (!found) count++; } } } return count; } /** * @param args */ public static void main(String[] args) { RecycledNumber test = new RecycledNumber(); String fileName = ""in3.txt""; String outName = ""out3.txt""; try { BufferedReader br = new BufferedReader(new FileReader(fileName)); String line = br.readLine(); BufferedWriter bw = new BufferedWriter(new FileWriter(outName)); int tests = new Integer(line).intValue(); for (int i = 0; i < tests; i++) { line = br.readLine(); String[] parts = line.split("" ""); int A = new Integer(parts[0]).intValue(); int B = new Integer(parts[1]).intValue(); String line2 = test.count(A, B, i+1); System.out.println(line2); bw.write(line2+""\n""); } bw.flush(); } catch (Exception e) { e.printStackTrace(); } } } /** Input Ê 4 1 9 10 40 100 500 1111 2222 Output Ê Case #1: 0 Case #2: 3 Case #3: 156 Case #4: 287 */" B10475,"import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int[] array = new int[n]; for (int i = 0; i < n; i++) { int min = scan.nextInt(); int max = scan.nextInt(); int total = 0; for (int j = min; j <= max; j++) for (int k = j+1; k <= max; k++) if (isR(j, k)) total++; array[i] = total; } for (int i = 1; i <= n; i++) System.out.println(""Case #"" + i + "": "" + array[i - 1]); } private static boolean isR(int m, int n) { if(m<10){ return false; } else if(m<100){ return isR(m,n,2); } else if(m<1000){ return isR(m,n,3); } else if(m<10000){ return isR(m,n,4); } else if(m<100000){ return isR(m,n,5); } else if(m<1000000){ return isR(m,n,6); } else if(m<10000000){ return isR(m,n,7); } else return false; } private static boolean isR(int m, int n, int i) { boolean tf=false; for(int j=1;j answerKey = new HashMap(); answerKey.put(1,0); answerKey.put(2,1); answerKey.put(3,3); answerKey.put(4,6); answerKey.put(5,10); answerKey.put(6,15); answerKey.put(7,21); int trials = Integer.parseInt(input.nextLine()); // START for(int i = 1; i <= trials; i++) { String[] line = input.nextLine().split("" ""); int A = Integer.parseInt(line[0]); int B = Integer.parseInt(line[1]); Set seen = new HashSet(); List answer = new ArrayList(); int length = getLength(A); if(length > 1) { for(int j = A; j <= B; j++) { if(!seen.contains(j)) { answer.add(numberOfPerms(A, B, j, length, seen)); } // It is seen, so don't do anything } } else { // length = 1 } int answerCount = 0; for(int k = 0; k < answer.size(); k++) { answerCount += answerKey.get(answer.get(k)); } output.print(""Case #"" + i + "": "" + answerCount); if(i != trials) { output.println(); } } } public static int numberOfPerms(int A, int B, int num, int length, Set s) { int original = num; int count = 1; int permute = permute(num, length); s.add(original); while(original != permute) { if(permute >= A && permute <= B && !s.contains(permute)) { s.add(permute); // add bc we've now seen it count++; // we have a good permute } permute = permute(permute, length); } return count; } public static int getLength(int num) { return (num + """").length(); } public static int permute(int num, int length) { int a = num % 10; int b = num / 10; return a * (int) Math.pow(10, length-1) + b; } }" B12271,"package QualificationRound2012.C.RecycledNumbers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class RecycledNumbers { static final String _DIR = ""src/QualificationRound2012/C/RecycledNumbers/""; static final String INPUT_FILE = _DIR + ""C-small-attempt0.in""; static final String OUTPUT_FILE = INPUT_FILE + "".out""; private static int algorithm(final String line) { int distinctPairs = 0; final String[] split = line.split("" ""); final String A_str = split[0]; final String B_str = split[1]; final int A = Integer.parseInt(A_str); final int B = Integer.parseInt(B_str); // A ≤ n < m ≤ B for (int m = A; m <= B; m++) { for (int n = m + 1; n <= B; n++) { // System.out.print(A + "" ≤ "" + m + "" < "" + n + "" ≤ "" + B); if (isRecycled(m, n)) { // System.out.println("" --> YES!""); distinctPairs++; } else { // System.out.println(); } } } return distinctPairs; } private static boolean isRecycled(final int m, final int n) { final String mString = String.valueOf(m); final String nString = String.valueOf(n); final int length = mString.length(); String rot = mString; for (int i = 0; i < length; i++) { if (rot.equals(nString)) { return true; } rot = rotate(rot); } return false; } public static void main(final String args[]) throws IOException { final BufferedWriter writer = new BufferedWriter(new FileWriter(OUTPUT_FILE)); final BufferedReader reader = new BufferedReader(new FileReader(new File(INPUT_FILE))); long timeStart = System.currentTimeMillis(); String line; int testcase = 0; while ((line = reader.readLine()) != null) { if (testcase != 0) { System.out.println(""Case #"" + testcase + "": "" + algorithm(line)); } testcase++; } long timeEnd = System.currentTimeMillis(); System.out.println(timeEnd - timeStart + "" millis""); } private static String rotate(final String number) { final char[] numberArray = number.toCharArray(); final char last = numberArray[numberArray.length - 1]; return last + number.substring(0, number.length() - 1); } } " B12320,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; public class C { PrintWriter out; public void read() throws IOException { BufferedReader br = new BufferedReader(new FileReader(""input.in"")); out = new PrintWriter(new FileWriter(""output.in"")); int n = Integer.parseInt(br.readLine()); int i = 0; String line; while (i < n) { line = br.readLine(); solve(i + 1, line); i++; } out.close(); out.flush(); } private void solve(int c, String line) { int max = 0; Set numbers = new HashSet(); out.print(""Case #"" + c + "": ""); String[] tokens = line.split("" ""); Integer A = Integer.parseInt(tokens[0]); Integer B = Integer.parseInt(tokens[1]); for (Integer i=A; i<=B; i++){ int length = i.toString().length(); for (int j=length -1 ; j>0; j--){ Integer x = Integer.parseInt(C.recycledNumber(i.toString(),j)); if ((A <= i) && (i < x) && (x <= B)){ numbers.add(Integer.parseInt(i.toString().concat(x.toString()))); } } } max = numbers.size(); out.print(max); out.println(); } public static void main(String[] args) throws IOException { new C().read(); } public static String recycledNumber(String a, int index) { int length = a.length(); StringBuilder recycledNumber = new StringBuilder(); for (int i=index ; i map = new HashMap(); public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader inputStream; PrintWriter outputStream; try { inputStream = new BufferedReader(new FileReader(""X:\\GCJ\\input.txt"")); outputStream = new PrintWriter(new BufferedWriter(new FileWriter(""X:\\GCJ\\output.txt""))); int n=Integer.parseInt(inputStream.readLine()),z=0; while(n>0) { n--;z++;c=0; String s=inputStream.readLine(); int spc= s.indexOf(' '); int r=0,A=Integer.parseInt(s.substring(0,spc)),B=Integer.parseInt(s.substring(spc+1)); for (int i = A; i < B; i++) { func(i,A,B,digits(A)); } outputStream.println(""Case #""+z+"": ""+c); System.out.println(""Case #""+z+"": ""+c); } outputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println(""File not found.""); e.printStackTrace(); } } public static int digits(int a) { int z=0; while(a!=0){ a/=10;z++; } return z; } public static int c=0; public static void func(int a,int A,int B, int n){ int a2=0; int o=a; for (int j = 1; j < n; j++) { int k=a%10; for (int i = 0; i < n-1; i++) { k*=10; } a2= k+a/10; if(a2>o && a2<=B){ map.put(o,a2);c++; System.out.println(c+"":""+o+"",""+a2); } a=a2; } } } " B12935,"import java.util.Scanner; public class QualC { public static void main(String args[]) { Scanner kb = new Scanner(System.in); int ntc = kb.nextInt(); for(int tc=0;tc0) { nn++; temp/=10; } int chk[] = new int[nn]; for(int q=1;q=a && m<=b && m/(int)Math.pow(10,nn-1)>0 && f==0) { out++; } } } System.out.println(""Case #"" + (tc+1) + "": "" + out); } } } " B12786,"import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Parser { File instance; Scanner sc; public Parser(String f){ instance = new File(f); } public List>> parse(int nbLinePerCase) throws FileNotFoundException{ sc = new Scanner(instance); int nbCase = sc.nextInt(); List>> input = new ArrayList>>(nbCase); String line; sc.nextLine(); for(int i = 0; i < nbCase; i++){ List> ll = new ArrayList>(nbLinePerCase); for(int j = 0; j < nbLinePerCase; j++){ List l = new ArrayList(); line = sc.nextLine(); Scanner sc2 = new Scanner(line); while(sc2.hasNext()){ l.add(sc2.next()); } ll.add(l); } input.add(ll); } return input; } } " B12499,"import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.Scanner; /** * @author OleGG */ public class QualTaskC { public static void main(String[] args) throws Throwable { Scanner sc = new Scanner(new FileReader(""C-small-attempt0.in.txt"")); PrintWriter pw = new PrintWriter(new FileWriter(""C-small-attempt0.out.txt"")); int t = sc.nextInt(); for (int test = 1; test <= t; ++test) { int a = sc.nextInt(); int b = sc.nextInt(); int mul = 1; while (mul <= a) { mul *= 10; } mul /= 10; int res = 0; for (int i = a; i < b; ++i) { int curr = i; do { int temp = curr % 10; curr /= 10; curr += temp * mul; if (curr > i && curr <= b) { ++res; } } while (curr != i); } pw.printf(""Case #%d: %d\n"", test, res); } pw.close(); } } " B13095,"import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Scanner; public class Rec { static Writer out; static Scanner sc; public static void main(String[] args) throws IOException { sc=new Scanner(new File(""input.txt"")); out = new OutputStreamWriter(new FileOutputStream(""out.txt"")); int num_of_cases=sc.nextInt(); int a,b; for (int i = 1; i <= num_of_cases; i++) { a=sc.nextInt(); b=sc.nextInt(); solve(a,b,i); } //System.out.println(""Done""); out.close(); } private static void solve(int a, int b, int case_num) throws IOException { int len=String.valueOf(a).length(); int count=0; int t; boolean [][]arr=new boolean[b+1][b+1]; for(int i=0;ia && t<=b && k= m){ min = (int)Math.min(min,array[i]); } //System.out.println(""length: ""+array.length+"" current: ""+num+""; min: ""+ min); } if(min != num){ //System.out.println(); return 0; } //System.out.println(""!X count: ""+ count); if(count == 2){ return 3; }else if(count == 3){ return 6; }else if(count == 4){ return 10; }else if(count == 5){ return 16; }else if(count == 6){ return 21; }else if(count == 7){ return 28; }else if(count == 8){ return 36; } return count; } public static void main(String[] args){ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String x = null; String linein = null; int totalcases = 0; int result = 0; int n = 0; int m = 0; int counter = 1; try{ x = br.readLine(); totalcases = Integer.parseInt(x); while( (linein = br.readLine()) != null){ result = 0; StringTokenizer st = new StringTokenizer(linein); n = Integer.parseInt(st.nextToken()); m = Integer.parseInt(st.nextToken()); for (int i=n;i B) continue; if(swapval <= val) continue; result++; // System.out.println(swapval); } } System.out.println(""Case #"" + (t+1) + "": "" + result); } } public static String shiftString(String a) { return a.substring(1) + a.charAt(0); } public static String[] permute(String a) { int len = a.length(); if(len <= 1) return null; String[] result = new String[len - 1]; result[0] = shiftString(a); for(int i=1;i set = new HashSet(Arrays.asList(result)); result = set.toArray(new String[0]); // String[] answer = set.toArray(new String[0]); // if(set.size() != result.length) { // System.out.println(""--b4--""); // System.out.println(Arrays.toString(result)); // // System.out.println(""--after--""); // System.out.println(Arrays.toString(answer)); // System.out.println(""-----""); // } // System.out.println(Arrays.toString(result)); return result; } } " B12258,"package mar2012; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class ProblemC { public static void main(String[] args) throws Exception { PrintStream out = new PrintStream(new File( ""/Users/asingh/Desktop/gcj2012/prob.c.out.txt"")); ProblemC prob = new ProblemC(); InputStream in = new FileInputStream(new File( ""/Users/asingh/Desktop/gcj2012/prob.c.in.txt"")); prob.solveAll(in, out); // prob.solveTestCase(1, 1000000, 2000000, out); // prob.solveTestCase(1, 1111, 2222, out); } private void solveAll(InputStream in, PrintStream out) throws Exception { Scanner scanner = new Scanner(in); int numTestCases = Integer.parseInt(scanner.nextLine()); for (int i = 0; i < numTestCases; i++) { int min = scanner.nextInt(); int max = scanner.nextInt(); if (i < numTestCases - 1) scanner.nextLine(); solveTestCase(i + 1, min, max, out); } } private static class Tuple { int one; int two; public Tuple(int one, int two) { this.one = Math.min(one, two); this.two = Math.max(one, two); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + one; result = prime * result + two; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Tuple other = (Tuple) obj; if (one != other.one) return false; if (two != other.two) return false; return true; } @Override public String toString() { return ""{"" + one + "", "" + two + ""}""; } } private void solveTestCase(int testCaseId, int min, int max, PrintStream out) { // System.out.println(""testCaseId: "" + testCaseId + "", min: "" + min // + "", max: "" + max); int[] minDigits = getDigits(min); int[] maxDigits = getDigits(max); Set found = new HashSet(); for (int n = min; n <= max; n++) { // debug(""Doing: "" + n); int[] digits = getDigits(n); int prevD = digits[0]; boolean allSame = true; for (int d : digits) { if (prevD != d) { allSame = false; break; } } if (allSame) { // debug("" skipping as same digits""); continue; } for (int i = 1; i <= digits.length - 1; i++) { if (digits[i] > maxDigits[0]) { // formed num will be greater, skip // debug("" skipping as will be greater than "" + max + // "", i="" + i + "", digits[i]="" + digits[i]); continue; } if (digits[i] < minDigits[0]) { // formed num will be smaller, skip // debug("" skipping as will be smaller than "" + min // + // "", i="" + i + "", digits[i]="" + digits[i]); continue; } int[] newNumDigits = swapBlockToBack(digits, i); int num = getNum(newNumDigits); if (num == n) { // debug("" skipping as same nums: "" + n); continue; } if (num >= min && num <= max) { Tuple tuple = new Tuple(n, num); if (found.contains(tuple)) { // debug("" skipping as already found: "" + num); continue; } else { found.add(tuple); //debug(""SOLUTION: "" + tuple); } } else { // debug("" skipping as not in range - min: "" // + min + "", max: "" + max + "", num: "" + num); } } } out.println(""Case #"" + testCaseId + "": "" + found.size()); // System.out.println(""Result: "" + success); } private int getNum(int[] digits) { int rv = 0; for (int i = digits.length - 1, factor = 1; i >= 0; i--) { int digit = digits[i]; rv += factor * digit; factor *= 10; } return rv; } private int[] swapBlockToBack(int[] digits, int blockSize) { int[] newDigits = new int[digits.length]; System.arraycopy(digits, blockSize, newDigits, 0, digits.length - blockSize); System.arraycopy(digits, 0, newDigits, digits.length - blockSize, blockSize); return newDigits; } private int[] getDigits(int min) { char[] digitChars = String.valueOf(min).toCharArray(); int[] digits = new int[digitChars.length]; for (int i = 0; i < digits.length; i++) { digits[i] = digitChars[i] - '0'; } return digits; } } " B11562,"package codejam.is; /** * Created with IntelliJ IDEA. * User: ofer * Date: 4/13/12 * Time: 8:47 PM * To change this template use File | Settings | File Templates. */ public interface Test { /** Runs the test on the given input */ public void run(String input); /** Returns the output of the test */ public String getOutput(int testNum); } " B11010,"import java.util.*; import java.io.*; public class C { public static void main(String[] args) { try { Scanner input = new Scanner(new FileReader(""C.in"")); PrintWriter output = new PrintWriter(new FileWriter(""C.out"")); try { int i = Integer.parseInt(input.nextLine()); for(int j=0; j= 10) order *= 10; int lastDigit = 0; do { lastDigit = input % 10; input /= 10; input += lastDigit * order; } while (lastDigit == 0); return input; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int i=0;i j && x <= b) total++; } } System.out.println(""Case #"" + (i + 1) + "": "" + total); } } } " B13135,"import java.util.ArrayList; import java.util.HashMap; public class Danc3 { static ArrayList allTheNumbers = new ArrayList(); static HashMap binomCoeff = new HashMap(); public static int solveC(int A, int B) { allTheNumbers = new ArrayList(); int count = 0; String seeds[] = new String[B-A+1]; for(int i = A, n = 0; n < seeds.length; i++, n++) { seeds[n] = Integer.toString(i); } for(int i = 0; i < seeds.length; i++) { count += binom(CircularStringShift(seeds[i], A, B),2); } return count; } public static int CircularStringShift(String s, int lowerLimit, int upperLimit) { String tmp = s; char placeHolder = ' '; int count = 0; int tmp2; for(int i = 0; i < s.length(); i++) { placeHolder = tmp.charAt(0); tmp = tmp.substring(1, tmp.length()) + placeHolder ; tmp2 = Integer.parseInt(tmp); if(!allTheNumbers.contains(tmp2) && tmp2 >= lowerLimit && tmp2 <= upperLimit && tmp != s) { count++; allTheNumbers.add(tmp2); } } return count; } static long binom(int n, int k) { return ((n-1)*(n) / 2); } }" B13153,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; import java.util.List; public class RecycledNumbers { int A; int B; int count = 0; List pairs = new ArrayList(); public static void main(String[] args) { int T; BufferedReader bf; try { bf = new BufferedReader(new FileReader(""C-small-attempt1.in"")); T = Integer.parseInt(bf.readLine().trim()); for (int i = 0; i <= T -1 ; i++) { RecycledNumbers rn = new RecycledNumbers(); String[] line = bf.readLine().split("" ""); rn.A = Integer.parseInt(line[0]); rn.B = Integer.parseInt(line[1]); rn.count = 0; rn.resolve(); rn.printOut(i + 1); } } catch (Exception e) { e.printStackTrace(); } } private void printOut(int i) { System.out.println(""Case #"" + i + "": "" + count); } private void resolve() { int min = A; int minLength; if(min < 12){ min = 12; } while (min <= B){ String minS = String.valueOf(min); String start = """"; String end = """"; minLength = minS.length(); for (int i = 0; i < minLength -1; i++) { start = minS.substring(0,i +1 ); end = minS.substring(i +1); if ( checkNewPair(minS, start,end)){ count += 1; } } min += 1; } } private boolean checkNewPair(String minS, String start, String end) { if (end.charAt(0) == '0'){ return false; } int newNumber = Integer.parseInt(end + start); if (newNumber > B ){ return false; } int min = Integer.parseInt(minS); String newPair = """"; if (min < newNumber){ newPair = minS +"","" + newNumber; }else if(min > newNumber){ return false; }else if (min == newNumber){ return false; } if ( pairs.contains(newPair)){ return false; } pairs.add(newPair); return true; } } " B11705,"import java.util.*; public class C { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); int T = in.nextInt(); int i,j,len,p,temp,total; HashSet[] map = new HashSet[2000000]; for (i=1;i<2000000;i++) { map[i] = new HashSet(); len = (int)Math.log10(i)+1; p = (int)Math.pow(10, len-1); temp = i; for (j=0;ji && temp<=2000000) map[i].add(temp); } } for (i=1;i<=T;i++) { int a = in.nextInt(); int b = in.nextInt(); total = 0; for (j=a;jj && t<=b) total++; } } System.out.println(""Case #""+i+"": ""+total); } } } " B11477,"import java.io.File; import java.util.HashMap; import java.util.Scanner; public class ProblemC { /** * @param args */ public static void main(String[] args) throws Exception { Scanner leitor = new Scanner(new File(""problemC.in"")); int n = leitor.nextInt(); leitor.nextLine(); for (int caso = 0 ; caso < n; caso++) { int a = leitor.nextInt(); int b = leitor.nextInt(); leitor.nextLine(); /* A ≤ n < m ≤ B. */ if (b > 10) { int resultado[] = new int[b+1]; for (int i = 0; i < 11; i++) { resultado[i] = 0; } for (int i = a; i <= b; i++) { String number = Integer.toString(i); int resultadoParcial = resultado[i-1]; String numberToChange = Integer.toString(i); HashMap tiraRepetidos = new HashMap(); for (int j = 0; j < number.length()-1; j++) { String novoNumeroString = numberToChange.substring(j+1) + numberToChange.substring(0,j+1); while (novoNumeroString.startsWith(""0"")) novoNumeroString = novoNumeroString.substring(1); int novoNumero = new Integer( novoNumeroString); //System.out.println(i + "" -> "" + novoNumero); if (!tiraRepetidos.containsKey(novoNumero)) { if ((a <= i ) && (i < novoNumero) && (novoNumero <= b)) { resultadoParcial += 1; } tiraRepetidos.put(novoNumero, novoNumero); } } resultado[i] = resultadoParcial; } System.out.println(""Case #""+ (caso+1) + "": "" + (resultado[b])); } else { System.out.println(""Case #""+ (caso+1) + "": 0""); } } } } " B10004,"package qualification; import java.util.HashMap; import java.util.Scanner; public class RecycledNumbers { //recycled numbers between A and B //OK, the key is being able to reduce each number to a single comparable value instead of comparing every possible match. //Let's say: We will take the permutation that has the smallest value. //creating them may be slow as long as looking them up is fast. //[not needed] Cache values to improve performance // perf test - worst possible case was solved in seconds. //we've only given 50 cases at most. //[DONE] what if more than two match? does that make 3 distinct recycled pairs? public static void main(final String[] args) { new RecycledNumbers().start(); } private void start() { final Scanner s = new Scanner(System.in); final int numTests = s.nextInt(); for (int i = 0; i < numTests; i++) { // deb(""Case "" + (i + 1) + ""---------""); final int startNum = s.nextInt(); final int endNum = s.nextInt(); final HashMap values = new HashMap(); int distinctPairsCount = 0; for (int val = startNum; val <= endNum; val++) { final String newValue = findSmallestPermutation(""""+val); if (values.containsKey(newValue)) { final int count = values.get(newValue); distinctPairsCount += count; values.put(newValue, count + 1); // deb(""found a match of "" + count + "", total matches: "" + distinctPairsCount); } else { values.put(newValue, 1); } } System.out.println(""Case #"" + (i+1) + "": "" + distinctPairsCount); } } //We can't compare every permutation to every permutation //so we find the smallest and only use that. //this function looks slow, but it isn't called that often so should be OK. private String findSmallestPermutation(final String value) { int bestValue = Integer.MAX_VALUE; String bestString = null; final String valueTwice = value + value; //We will extract the substrings from this. for (int i = 0; i < value.length(); i++) { final String permutation = valueTwice.substring(i, value.length() + i); final int permutationValue = Integer.parseInt(permutation); if (permutationValue < bestValue) { bestValue = permutationValue; bestString = permutation; } } // deb(""source: "" + value +"", adding "" + bestString); return bestString; } // private void deb(final Object o) { // System.out.println(o.toString()); // } } " B12317,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; public class problem3 { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { FileInputStream fstream = new FileInputStream(""C:\\Profiles\\sys4qa\\Desktop\\C-small-attempt0.in.txt""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; Integer T= 0; Integer i1,i2; ArrayList inputPair =new ArrayList(); ArrayList input= new ArrayList(); while ((strLine = br.readLine()) != null) { if (T==0) { T= Integer.parseInt(strLine); } else { String s[]=strLine.split("" ""); inputPair =new ArrayList(); inputPair.add( Integer.parseInt(s[0])); inputPair.add( Integer.parseInt(s[1])); input.add(inputPair); } } //Close the input stream in.close(); FileWriter fstream1 = new FileWriter(""C:\\Profiles\\sys4qa\\Desktop\\out.txt""); BufferedWriter out = new BufferedWriter(fstream1); int id=0; Iterator iter=input.iterator(); while (iter.hasNext()) { ArrayList ip= (ArrayList) iter.next(); int A = (Integer)ip.get(0); int B= (Integer) ip.get(1); int cunt=execute(A,B); id++; out.write(""Case #""+id+"": ""+cunt+""\n""); } //Close the output stream out.close(); } static int execute(int A, int B) { int count = 0; for (int i = A; i <= B; i++) { Set j = listOfReoderedNumbers(i); int k = 0; Iterator iter = j.iterator(); while (iter.hasNext()) { k = (Integer) iter.next(); if ((k > i) && (k <= B) && (k >= A)) { count++; } } } return (count); } static Set listOfReoderedNumbers(int i) { Set d = new HashSet(); d.add(i); int res = i; int t = (i + """").length(); for (int cnt = 0; cnt < t - 1; cnt++) { if (((res + """").length() == t)) { int num = res; Integer s = Integer.parseInt((num + """").charAt(0) + """"); int temp = (int) (num - (int) (s * (Math.pow(10, t - 1)))); res = (temp) * 10 + s; if ((res + """").length() == t) d.add(res); } else { res = res * 10; d.add(res); } } return d; } } " B13026,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package google_jamp_c; import java.io.*; import java.util.*; /** * * @author sabri */ public class Google_jamp_c { /** * @param args the command line arguments */ public static int recycled (int A, int B){ int m = 0, c=0; String tmp = """", subB = """", subE = """", recycled = """"; for (int n = A; nn) && (m<=B)) {c++;} } } return c; } public static void main(String[] args) throws FileNotFoundException, IOException { String ligne = """"; int nbrLigne = 0,res,a,b; StringTokenizer st1; FileInputStream fStream = new FileInputStream(""A-small-attempt.in""); BufferedReader in = new BufferedReader(new InputStreamReader(fStream)); if (in.ready()) { ligne = in.readLine(); nbrLigne = Integer.parseInt(ligne); for (int j = 0; j < nbrLigne; j++) { ligne = in.readLine(); st1=new StringTokenizer(ligne,"" ""); a=Integer.parseInt(st1.nextToken()); b=Integer.parseInt(st1.nextToken()); System.out.print(""Case #""+(j+1)+"": ""); res=recycled(a,b); System.out.print(res); System.out.println(""""); } } } } " B12181,"import java.io.*; import java.util.*; public class C { static int N = 2000001; static int[][] pair = new int[N][6]; static int[] np = new int[N]; public static void main (String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); for (int i = 1; i <= 6; i++) gen(i); gen(1000000, 2000000, 7); /*for (int i = 1; i < 1000; i++) for (int j = 0; j < np[i]; j++) System.out.println(i + "" "" + pair[i][j]);*/ int T = Integer.parseInt(in.readLine()); for (int t = 0; t < T; t++) { StringTokenizer st = new StringTokenizer(in.readLine()); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); int count = 0; for (int i = A; i <= B; i++) for (int j = 0; j < np[i]; j++) if (pair[i][j] <= B) count++; System.out.println(""Case #""+(t+1)+"": "" + count); } in.close(); } static void gen (int d) { gen(pow10(d-1), pow10(d)-1, d); } static void gen (int lb, int ub, int d) { for (int i = lb; i <= ub; i++) { int n = i; for (int j = 0; j < d-1; j++) { n = (n%10)*lb+(n/10); if (n > i) { boolean found = false; for (int k = 0; k < np[i]; k++) if (pair[i][k] == n) found = true; if (!found) { pair[i][np[i]] = n; np[i]++; } } } } } static int pow10 (int n) { int res = 1; for (int i = 0; i < n; i++) res *= 10; return res; } }" B10520,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.Scanner; class gcj3 { public static void main(String args[])throws Exception { Scanner in=new Scanner(new File(""C:/Users/Rakesh/Downloads/C-small-attempt0.in"")); // Scanner in=new Scanner(System.in); FileWriter fstream = new FileWriter(""c:/out.out""); BufferedWriter out = new BufferedWriter(fstream); int t,i,j,k,temp,m=0,c=0,l=0,ok=1,p,r; t=in.nextInt(); int res[][]=new int[1000][2],a[]=new int[t],b[]=new int[t]; for(i=0;i0) { temp/=10; l++; } r=l; temp=k; ok=1; while(l-->1) { temp=(int) ((temp/(Math.pow(10,(r-1))))+((temp%(Math.pow(10,(r-1))))*10)); if(temp==j && temp>=a[i] && temp<=b[i]) {c++; for(p=0;p=j) { res[m][0]=j; res[m++][1]=k; } else { res[m][0]=k; res[m++][1]=j; } // break; } } } } } try { out.write(""Case #""+(i+1)+"": ""+c+""\n""); } catch (Exception e) {//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } //System.out.println(c); c=0; } out.close(); } } " B12276,"import java.util.ArrayList; public class Recycled { public static void main(String[] args) { int T = StdIn.readInt(); for(int tr = 1; tr <= T; tr++) { int A = StdIn.readInt(); int B = StdIn.readInt(); //total num of recycled int num = 0; for (int i = A; i <= B; i++) { //converts to string String temp = Integer.toString(i); //list of recycled numbers given m = i ArrayList reNum = new ArrayList(); //for each shift for(int ind = 1; ind < temp.length(); ind++) { String first = temp.substring(0,ind); String last = temp.substring(ind); String shift = last + first; int shiftNum = Integer.parseInt(shift); if (shiftNum <= i || shiftNum > B) continue; if (reNum.indexOf(shiftNum) < 0) { reNum.add(shiftNum); } } num += reNum.size(); } StdOut.println(""Case #"" + tr + "": "" + num); } } } " B12979,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.StringTokenizer; public class ProblemC { public static void main(String [] args) throws NumberFormatException, IOException { BufferedReader r = new BufferedReader( new FileReader(""C:\\Users\\ÐÐÐ\\Downloads\\C-small-attempt0.in"")); ArrayList s = new TestCaseReader().read(r); s = new ProblemC().remap(s); OutputPrinter p = new OutputPrinter(); for (String str : s) p.print(str); p.m_writer.flush(); p.m_writer.close(); } private ArrayList remap(ArrayList s) { ArrayList remapped = new ArrayList(); for (String str : s) { StringTokenizer tk = new StringTokenizer(str, "" ""); int A = Integer.parseInt(tk.nextToken()); int B = Integer.parseInt(tk.nextToken()); int total = 0; for (int n = A; n <= B ; n ++ ) { HashSet possible_ms = new HashSet(); String n_str = """" + n; int n_digits = (int) (Math.floor( Math.log10( n ) ) + 1); for (int i = 0 ;i < n_digits-1 ; i ++) { char c = n_str.charAt(n_str.length() -1); n_str = c + n_str.substring(0, n_str.length()-1); int result = Integer.parseInt(n_str); if ((int) (Math.floor( Math.log10(result ) ) + 1) == n_digits) possible_ms.add(result); } if (possible_ms.size() == 0) continue; total = match(n,B, total, possible_ms, n_digits); } remapped.add(""""+total); } return remapped; } private int match(int n, int B, int total, HashSet possible_ms, int n_digits) { for (int m = n+1; m <= B ; m ++) { int m_digits = (int) (Math.floor( Math.log10( m ) ) + 1); if (m_digits != n_digits) continue; if (possible_ms.contains(m)) total ++; } return total; } } " B11004," import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; public class Recycle { public static void main(String...args) throws IOException { //the result file PrintWriter writer = new PrintWriter(new FileWriter(""c:\\jam\\C-small-attempt0.out"")); //reading input file the file BufferedReader reader = new BufferedReader(new FileReader(""c:\\jam\\C-small-attempt0.in"")); //Reading cases number int count = Integer.parseInt(reader.readLine()); //Iterating over the cases for(int k=1;k list = new ArrayList(); for(int i=0;in && c<=B && size==size2){ res++; } old = str; } } writer.println(""Case #"" + k + "": "" + res); } reader.close(); writer.close(); } } " B10174,"import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Date; import java.util.HashSet; import java.util.StringTokenizer; public class GCJ2012QC { static HashSet set = new HashSet(); static final int ZERO = 48; public static void main(String[] args) throws Exception { BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); StringTokenizer st; int t = parseInt(r.readLine()); // long time = new Date().getTime(); int a, b, result; for (int i = 1; i <= t; i++) { st = new StringTokenizer(r.readLine()); a = parseInt(st.nextToken()); b = parseInt(st.nextToken()); result = solve(a, b); pw.println(""Case #"" + i + "": "" + result); } // time = new Date().getTime() - time; pw.flush(); // System.out.println(time / 1000); } private static int solve(int a, int b) { int result = 0; for (int i = a; i < b; i++) { result += calculate(i, b); } return result; } private static int calculate(int k, int b) { String s = Integer.toString(k); int n = s.length(); int rotated; String s1; set.clear(); for (int i = 1; i < n; i++) { s1 = s.substring(i) + s.substring(0, i); rotated = parseInt(s1); if (rotated > k && rotated <= b && !set.contains(rotated)) { set.add(rotated); } } return set.size(); } private static int parseInt(String s) { int len = s.length(); int num = s.charAt(0) - ZERO; for (int i = 1; i < len; i++) { num = num * 10 + s.charAt(i) - ZERO; } return num; } } " B11410,"import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; import java.util.ArrayList; public class Recycled { public static String cycleString(String str) { String first = str.substring(0, 1); String newstr = str.substring(1)+first; return newstr; } public static void main(String[] args) throws IOException { File file = new File(""C-small-attempt0.in""); Scanner scanner; BufferedWriter out = new BufferedWriter(new FileWriter(""outfile"")); try { scanner = new Scanner(file); int testCases = scanner.nextInt(); scanner.nextLine(); for(int numTest=0; numTest number = new ArrayList(); for(int i=A; i<=B; i++) { if(!number.contains(i)) { int count = 0; String temp = String.valueOf(i); for(int j=0; j=A)) { number.add(cycled); count++; if(!number.contains(i)) { number.add(i); count++; } } } } temp = cyclestr; } if(count==4) totalcount=totalcount+6; else if(count==3) totalcount=totalcount+count; else if(count==2) totalcount=totalcount+1; } } out.write(""Case #""+(numTest+1)+"": ""+ totalcount +""\n""); } out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } } " B11427,"import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; import java.io.*; import java.math.*; import java.util.*; @SuppressWarnings(""unused"") public class C_RecycledNumbers { public static void main(String[] args) throws Exception { // Scanner in = new Scanner(System.in); // PrintStream out = System.out; Scanner in = new Scanner(new File(""C-small.in"")); PrintStream out = new PrintStream(""C-small.out""); // Scanner in = new Scanner(new File(""C-large.in"")); // PrintStream out = new PrintStream(""C-large.out""); int T = in.nextInt(); for (int i = 1; i <= T; i++) { int A = in.nextInt(); int B = in.nextInt(); TreeSet set = new TreeSet(); for (int n = A; n <= B; n++) { String s = Integer.toString(n); for (int j = 0; j <= s.length(); j++) { int m = Integer.parseInt(s.substring(j) + s.substring(0, j)); if (A <= n && n < m && m <= B) { set.add(new pair(n, m)); } } } out.println(""Case #"" + i + "": "" + set.size()); } } static class pair implements Comparable { int a, b; public pair(int a, int b) { this.a = a; this.b = b; } public int compareTo(pair p) { if (a == p.a) return b - p.b; return a - p.a; } } } " B10020,"import java.util.ArrayList; public class SpeakingInToungues { private static String inputFile = ""C:\\PERSONAL-WORKSPACE\\GCJ-2012\\src\\input-output\\Input.txt""; private static String outputFile = ""C:\\PERSONAL-WORKSPACE\\GCJ-2012\\src\\input-output\\Output.txt""; public static void main(String[] args) { InputReader ir = new InputReader(inputFile); OutputWriter ow = new OutputWriter(outputFile); ArrayList lines = ir.loadLines(); //Given examples cover 25 chars and the one left out is q which is ideally mapped to the unused char z. String normalText = ""aozq our language is impossible to understand there are twenty six factorial possibilities so it is okay if you want to just give up""; String googlereseText = ""yeqz ejp mysljylc kd kxveddknmc re jsicpdrysi rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd de kr kd eoya kw aej tysr re ujdr lkgc jv""; StringBuffer sb = null; for(int i=1;i numbers = new ArrayList(); for (int i = A; i < B + 1; i++) { numbers.add(Integer.toString(i)); } for (int i = 0; i < numbers.size(); i++) { String number = numbers.get(i); for (int j = 1; j < digitCount; j++) { String reverseNumber = number.substring(j) + number.substring(0, j); int reversInt = Integer.parseInt(reverseNumber); if ((reversInt <= B) && (reversInt > Integer.parseInt(number))) { // System.out.println(""A("" + A + "") <= "" + number + "" < "" + reverseNumber + "" <=B("" + B + "")""); result++; } } } return result; } public static List parseFromFile(List readInput) { List result = new ArrayList(); int testCaseCount = Integer.parseInt(readInput.get(0)); for (int i = 0; i < testCaseCount; i++) { String line[] = readInput.get(i + 1).split("" ""); result.add(new RecycledNumbers(Integer.parseInt(line[0]), Integer.parseInt(line[1]))); } return result; } @Override public String toString() { return ""A = "" + A + ""; B = "" + B; } } " B12106,"package com.renoux.gael.codejam.utils; /** * Pour tests unitaires * * @author renouxg */ public final class StringUtils { public static String multiply(String text, int nb) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < nb; i++) { builder.append(text); } return builder.toString(); } } " B11524,"package wangshu.codejam.google.com; import java.io.File; import java.io.FileWriter; import java.util.Arrays; import java.util.Scanner; import java.lang.*; public class QC { public static long calculateNumber(int A, int B){ int size = B-A+1; // Number of integers between A and B int A1; // Auxiliary variable that helps to calculate numberOfDigits; int numberOfDigits; // Number of digits of A int multiple = 1; // Auxiliary variable that helps to calculate rotation; int count = 0; // Count stores for each integer between A and B , //the number of rotated integer that also between A and B long result = 0; boolean[] counted = new boolean[size]; //Indicate whether the number has been counted or not //Initialize counted array Arrays.fill(counted, false); // Calculate the number of digits of A for(numberOfDigits=0, A1=A; A1!=0; numberOfDigits++){ A1 = A1/10; multiple = multiple*10; } multiple = multiple/10; //Calculate the result for(int i=A; i<=B; i++){ count = 0; if(!counted[i-A]){ int k=i; //System.out.println(""#######""); for(int j=0; j=A && k<=B && !counted[k-A]){ count ++; counted[k-A] = true; //System.out.println(""k is "" + k); } int unitNnumber = k%10; k = k/10 + multiple*unitNnumber; } } /* if(count > 1){ System.out.println(""**************""); } */ result = result+ ((count)*(count-1))/2; } return result; } /** * @param args */ public static void main(String[] args) throws java.lang.Exception{ // TODO Auto-generated method stub Scanner sc = new Scanner(new File(""qc_in_small.txt"")); // Scanner for input file FileWriter outputFile = new FileWriter(""qc_out_small.txt""); int A, B; //Read number of test cases int T = sc.nextInt(); for(int i=0; i history = new HashSet(); int count = 0; int size = ("""" + a).length(); int power = (int)Math.pow(10, size - 1); int value = a; history.add(a); for (int i = 0; i < size; i++) { int digit = value % 10; int next = value / 10 + digit * power; if (history.contains(next)) { break; } else if (digit != 0 && next > a && next >= min && next <= max) { count++; } value = next; history.add(next); } return count; } public static void main(String[] args) throws Exception { Scanner input = new Scanner(System.in); int lines = Integer.parseInt(input.nextLine().trim()); for (int i = 0; i < lines; i++) { String[] tokens = input.nextLine().split("" ""); int A = Integer.parseInt(tokens[0].trim()); int B = Integer.parseInt(tokens[1].trim()); int total = 0; for (int j = A; j <= B; j++) { total += recycles(j, A, B); } System.out.println(""Case #"" + (i+1) + "": "" + total); } } }" B11602,"package j2012qualifier; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { public static String inputDirectory=""src/j2012qualifier/""; public static String inputFile=""C.in""; public static String outputFile=""C.out""; public static PrintWriter output; public static void main(String[] args) throws FileNotFoundException{ Scanner s=new Scanner(new File(inputDirectory + inputFile)); output=new PrintWriter(new File(inputDirectory + outputFile)); int cases = s.nextInt(); for(int Case=1;Case<=cases;Case++){ s.nextLine(); int A = s.nextInt(); int B = s.nextInt(); long result = 0; for(int n = A; n< B; n++) { result+= count(n, B); } out(""Case #""+Case+"": ""+result); } output.flush(); } public static long count(long n, long max) { //out(""testing "" + n); long digit = 10; long pow10 = 10 * (long)Math.pow(10, Math.floor(Math.log10(n))); long count = 0; Set found = new HashSet(); //out(""pow"" + pow10); while(digit <= n) { long m = n/digit + (n%digit) * pow10 / digit; //out(""choice 1 "" + m); digit *= 10; if (m > n && m <= max && !found.contains(m)) { //out(n + "" , "" + m); count++; found.add(m); } } return count; } public static void out(String s){ output.println(s); //System.out.println(s); } } " B10880,"package de.at.codejam.util; import java.util.MissingResourceException; import java.util.ResourceBundle; public class Settings { private static final String BUNDLE_NAME = ""settings""; //$NON-NLS-1$ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle .getBundle(BUNDLE_NAME); private Settings() { } public static String get(String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } } " B13259,"package info.stephenn.codejam2012.qualify; import java.util.Scanner; public class C { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int cases = sc.nextInt(); for (int caseX=1; caseX <= cases; caseX+=1){ int A = sc.nextInt(); int B = sc.nextInt(); System.out.println(""Case #""+caseX+"": ""+doit(A,B)); } } public static int doit(int A, int B){ int count=0; for (int m = A+1; m <= B; m++){ for (int n = A; n < m; n++){ count += isRecycledString(Integer.toString(n), Integer.toString(m)); } } return count; } public static int countRecycled(int n, int m){ int count=0; System.out.println(""countRecycled""+n+"",""+m); int split = 10; while (true){ if (split > n) break; int front = n/ split; int behind = n %split; int behindInfront = behind * split; int t = behindInfront + front; if (t ==m){ System.out.println(""""+t+"" == ""+m+"" split""+split+"" n""+n); count +=1; } split = split * 10; } return count; } public static int isRecycledString(String n, String m){ for (int split =1; split < n.length(); split++){ String t = n.substring(split) + n.substring(0, split); if (t.equals(m)) return 1; } return 0; } }" B10041,"import java.io.*; import java.util.*; class Recycled { int n; int m; Recycled (int a, int b) { n=a; m=b; } boolean isEqual(int a, int b) { if (n == a && m == b) return true; else return false; } } class C { public static void main(String args[]) throws FileNotFoundException { Scanner in = new Scanner(new File(args[0])); int t; t = Integer.parseInt(in.nextLine()); for (int i=0; i recs = new ArrayList(); for (int n=a; n0){ lineParts=br.readLine().split(""\\s""); A=Integer.parseInt(lineParts[0]); B=Integer.parseInt(lineParts[1]); formatter.format(""Case #%d: %d\n"",lineNum++,cycles(A,B)); } formatter.close(); } private static int cycles(int A, int B){ Set pairs= new HashSet(); for(int n=A;n solve(int n, int B){ Set pairs=new HashSet(); int m=n; int q,r; int nLen=(""""+n).length(); LinkedList restQueue=new LinkedList(); for(int i=0;in && m <=B) pairs.add(n+"":""+m); } } return pairs; } } " B10979,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.*; public class recycled { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(""C-small-attempt0.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""output.txt""))); int nc = Integer.parseInt(in.readLine().trim()); for (int z=1; z<=nc; z++){ String[] line = in.readLine().trim().split(""\\s+""); int a = Integer.parseInt(line[0]); int b = Integer.parseInt(line[1]); boolean[] flgs = new boolean[2000000+1]; int count = 0; for (int i = a; i <=b; i++) { List list = new ArrayList(); list.add(i); if (flgs[i]) continue; int val = 1; String num1 = i+""""; for (int j = 1; j <=num1.length(); j++) { String num2 = num1.substring(j) + num1.substring(0, j); int num = Integer.parseInt(num2); if (num2.charAt(0)!='0') if (num<=b&&num!=i&&num>a) if (!flgs[num]) { list.add(num); val++; flgs[num] = true; } } val = val*(val-1); val>>=1; //if (val>0)tr(list); count+=val; //if (val>0) System.out.println(count); } //MODIFY out.println(String.format(""Case #%d: %d"", z,count)); } out.close(); } public static void tr(Object...objects) { System.out.println(Arrays.deepToString(objects)); } } " B10039,"import java.util.Scanner; import java.util.ArrayList; public class recycled { public static void main(String [] args){ Scanner Keyboard = new Scanner(System.in); int first, second; int n, m; String current = null, temp; Character current2; int whitespace = 0; int testCase; int testLength; String nString, mString; int recycledNumber = 0; ArrayList input = new ArrayList(); ArrayList recycled = new ArrayList(); ArrayList nArray = new ArrayList(); ArrayList mArray = new ArrayList(); boolean multiple = false; testCase = Keyboard.nextInt(); Keyboard.nextLine(); for (int a = 0; a < testCase; a++){ input.add(Keyboard.nextLine()); } for (int a = 0; a < testCase; a++){ for (int i = 0; i < input.get(a).length(); i++){ if (input.get(a).charAt(i) == ' '){ whitespace = input.get(a).indexOf(' '); break; } else{ if (i == 0){ current2 = input.get(a).charAt(i); current = current2.toString(); } else{ current2 = input.get(a).charAt(i); temp = current2.toString(); current = current.concat(temp); } } } first = Integer.parseInt(current); for (int i = whitespace+1; i < input.get(a).length(); i++){ if (i == whitespace+1){ current2 = input.get(a).charAt(i); current = current2.toString(); } else{ current2 = input.get(a).charAt(i); temp = current2.toString(); current = current.concat(temp); } } second = Integer.parseInt(current); for (int i = first; i <= second; i++){ for (int j = first; j <= second; j++){ n = i; m = j; if (m>=n) break; nString = Integer.toString(n); mString = Integer.toString(m); testLength = Integer.toString(m).length(); for (int k = testLength; k > 0; k--){ current = nString.substring(k-1, testLength).concat(nString.substring(0, k-1)); if (current.equals(mString)){ for (int l = 0; l < nArray.size(); l++){ if (nString.equals(nArray.get(l)) && mString.equals(mArray.get(l))) multiple = true; } nArray.add(nString); mArray.add(mString); if (!multiple){ recycledNumber++; } multiple = false; } } } } recycled.add(recycledNumber); recycledNumber = 0; nArray.clear(); mArray.clear(); } for (int i = 0; i < recycled.size(); i++){ System.out.println(""Case #"" + (i+1) + "": "" + recycled.get(i)); } } } " B11520,"package duyonggang; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.List; public class RecycledNumbers { public static int pass(int n, int a, int b) { if(n < 10) return 0; int counter = 0; String s = Integer.toString(n); int m; List passedValues = new ArrayList(); for(int i = s.length() - 1; i > 0; i--) { if(s.charAt(i) == '0') continue; m = Integer.parseInt(s.substring(i, s.length()) + s.substring(0, i)); if(m > n && m <= b && !passedValues.contains(m)) { counter++; passedValues.add(m); } } return counter; } public static int analyze(String line) { int counter = 0; String[] strs = line.split("" ""); int a = Integer.parseInt(strs[0]); int b = Integer.parseInt(strs[1]); for(int i = a; i <= b; i++) { counter += RecycledNumbers.pass(i, a, b); } return counter; } public static void main(String[] args) throws Exception { File input = new File(""c.txt""); FileReader fr = new FileReader(input); BufferedReader br = new BufferedReader(fr); String line = null; line = br.readLine(); int count = Integer.parseInt(line); for(int i = 0; i < count; i++) { line = br.readLine(); System.out.println(""Case #"" + (i + 1) + "": "" + RecycledNumbers.analyze(line)); } } } " B10550,"import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Hashtable; import java.util.Scanner; import com.sun.org.apache.xpath.internal.operations.Bool; public class ProbC { static Hashtable> vis; public static void main(String[] args) { PrintWriter out; try { out = new PrintWriter(new FileWriter(""d:\\codejam2012\\outputfile.txt"")); Scanner scanner = new Scanner(new File(""d:\\codejam2012\\C-small-attempt0.in"")); int cases = scanner.nextInt(); scanner.nextLine(); for (int i = 1; i <= cases; i++) { int a = scanner.nextInt(), b = scanner.nextInt(); vis = new Hashtable>(); int sol = 0; for (int j = a; j < b + 1; j++) { sol += getPairs(j, a, b); } out.println(""Case #""+i+"": "" +sol); } out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static int getPairs(int n, int a, int b) { String str = """" + n; int count = 0; for (int i = 1; i < str.length(); i++) { int div = (int) Math.pow(10, i); int shift = (int) Math.pow(10, str.length() - i); int m = (n%div) * shift + (n / div); if(m >= a && m <= b && Integer.toString(n).length() == Integer.toString(m).length() && n != m){ if(vis.containsKey(n) && vis.get(n).containsKey(m)) continue; count++; if(!vis.containsKey(n)) vis.put(n, new Hashtable()); vis.get(n).put(m, true); if(!vis.containsKey(m)) vis.put(m, new Hashtable()); vis.get(m).put(n, true); } } return count; } } " B12029,"import java.util.Scanner; public class C { public static class N { public static int[] m_num; public static int m_first; public static int length; public static void set(int n) { String s = Integer.toString(n); char[] c = s.toCharArray(); m_num = new int[c.length]; m_first = 0; for(int i = 0; i < c.length; i++) { m_num[m_num.length - i - 1] = Character.digit(c[i], 10); } length = m_num.length; } public static int nextNum() { m_first = (m_first + 1) % m_num.length; int ret = 0; int mult = 1; for(int i = 0; i < m_num.length; i++) { ret += (mult*m_num[(i+m_first)%m_num.length]); mult *= 10; } return ret; } } public static int[] binom = {0, 0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105}; public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for(int t = 1; t <= T; t++) { int A = in.nextInt(); int B = in.nextInt(); System.out.println(""Case #"" + t + "": "" + foo(A, B)); } } public static int foo(int lower, int upper) { if(upper < 10) return 0; int counter = 0; boolean[] checked = new boolean[upper - lower + 1]; for(int i = lower; i <= upper; i++) { if(checked[i-lower]) continue; N.set(i); int items = 0; for(int j = 0; j < N.length; j++) { int num = N.nextNum(); if(num < lower || num > upper || checked[num-lower]) continue; checked[num-lower] = true; items++; } counter += binom[items]; } return counter; } } " B12426,"import java.io.*; import java.util.*; import java.math.*; public class C { static int[] size={1,10,100,1000}; public static void main(String[] args) throws Exception { int T; RandomAccessFile in = new RandomAccessFile(args[0],""r""); T=Integer.parseInt(in.readLine()); for (int i=1; i<=T; i++) { String line=in.readLine(); String[] temp=line.split("" ""); int a=Integer.parseInt(temp[0]); int b=Integer.parseInt(temp[1]); String ans=solve(a,b); System.out.println(""Case #""+i+"": ""+ans); } in.close(); } public static String solve(int a, int b) { int total=0; for (int i=a; i<=b; i++) total+=count(i,b); return """"+total; } public static int count(int start, int max) { //System.out.println(""Start ""+start); String temp=""""+start; int N=temp.length(); int a=start; int count=0; for (int i=0; istart && a<=max) count++; } return count; } public static int rotate(int a, int n) { int last=a%10; return a/10+n*last; } public static void print(int[] b) { for (int i=0; i 0) { len++; d *= 10; } return len; } static boolean isRecycled(int n, int m) { int l = len(n); if (l != len(m)) return false; int d = 10; int pow = (int)Math.pow(10, l); while (n / d > 0) { if ((n % d) * (pow / d) + n / d == m) return true; d *= 10; } return false; } } " B10904,"package qualification; import java.io.FileInputStream; import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * Created by IntelliJ IDEA. * User: Yuri * Date: 14.04.12 * Time: 12:18 * To change this template use File | Settings | File Templates. */ public class Task3 { static int divider; static int recycle(int a) { int mod = a % divider; int digit = a / divider; return (mod * 10) + digit; } public static void main(String[] args) throws Exception { Scanner scanner = new Scanner(new FileInputStream(""task31.txt"")); int N = scanner.nextInt(); Set set = new HashSet(); for (int n = 0; n < N; n++) { int a = scanner.nextInt(); int b = scanner.nextInt(); int digitsCount = String.valueOf(a).length(); divider = (int) Math.pow(10, digitsCount - 1); int count = 0; for (int c = a; c <= b; c++) { set.clear(); int recycled = c; for (int i = 0; i < digitsCount - 1; i++) { recycled = recycle(recycled); if (recycled <= b && recycled > c) { if (! set.contains(recycled)) { set.add(recycled); count++; } } } } System.out.println(""Case #"" + (n + 1) + "": "" + count); } } } " B10893,"import java.io.*; import java.util.Arrays; import java.util.Locale; import java.util.StringTokenizer; public class GCJ2012QualC { static final int MAXB = 2000000; int[] minR = new int[MAXB+1]; int[] count = new int[MAXB+1]; public void run() throws IOException { for (int a = 1; a <= MAXB; a *= 10) { for (int x = a; x < 10*a && x <= MAXB; ++x) { minR[x] = x; int y = x; do { y = y % 10 * a + y / 10; if (y / a != 0 && y < minR[x]) { minR[x] = y; } } while (y != x); } } int T = nextInt(); for (int i = 1; i <= T; ++i) { out.println(""Case #"" + i + "": "" + solve()); } } private int solve() throws IOException { int A = nextInt(); int B = nextInt(); Arrays.fill(count, 0, B+1, 0); for (int i = A; i <= B; ++i) { ++count[minR[i]]; } int ans = 0; for (int i = 0; i <= B; ++i) { ans += count[i] * (count[i] - 1) / 2; } return ans; } public static BufferedReader in; public static PrintStream out; public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); String className = GCJ2012QualC.class.getSimpleName(); char lastChar = className.charAt(className.length() - 1); System.setIn(new FileInputStream(lastChar + "".in"")); System.setOut(new PrintStream(lastChar + "".out"")); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintStream(new BufferedOutputStream(System.out)); new GCJ2012QualC().run(); out.close(); } public static StringTokenizer tokenizer; public static String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(in.readLine()); } return tokenizer.nextToken(); } public static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public static long nextLong() throws IOException { return Long.parseLong(nextToken()); } public static double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } } " B10695,"import java.io.PrintWriter; import java.util.Scanner; public class ProblemC { public static void main(String[] args) { final Scanner in = new Scanner(System.in); final PrintWriter out = new PrintWriter(System.out); final int t = in.nextInt(); for (int tt = 0; tt < t; tt++) { final int a = in.nextInt(); final int b = in.nextInt(); int count = 0; for (int n = a; n < b; n++) { count += recycledNumbersCount(n, b); } out.println(""Case #"" + (tt + 1) + "": "" + count); } out.flush(); } private static int recycledNumbersCount(int n, int b) { int count = 0; final String s = """" + n; String ss = s.charAt(s.length() - 1) + s.substring(0, s.length() - 1); while (!s.equals(ss)) { if (ss.charAt(0) != '0') { final int m = Integer.parseInt(ss); if (m > n && m <= b) { count++; } } ss = ss.charAt(ss.length() - 1) + ss.substring(0, ss.length() - 1); } return count; } } " B12472,"import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Scanner; public class Main { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { Scanner input = new Scanner(new File(""C-small-attempt0.in"")); FileWriter out = new FileWriter(""out.txt""); int lineNumber = input.nextInt(); for (int i = 0; i < lineNumber; i++) { int a = input.nextInt(); int b = input.nextInt(); int count = 0; int div = 1; for (int j = a; j < b; j++) { for (int k = j + 1; k <= b; k++) { div = 1; int length = 0; while (j / div > 0) { length++; div *= 10; } int max = div; div = 10; if (j == 334 && k == 433) System.out.println(length+"" ""+max); for (int velicina = 0; velicina < length; velicina++) { if (j == 334 && k == 433) { System.out.println(""---------""); System.out.println(j % div + "" "" + k / (max / div)); System.out.println(k % (max / div) + "" "" + j / (div)); } if (j % div == k / (max / div) && k % (max / div) == j / div) { count++; break; } div*=10; } } } String solution = ""Case #"" + (i + 1) + "": "" + count; solution += System.getProperty(""line.separator""); out.write(solution); } out.close(); input.close(); } } " B11651,"import java.util.*; import java.io.*; import java.math.BigInteger; import static java.lang.Math.*; public class B implements Runnable { final String fileName = ""C-small-attempt0""; private void solution() throws IOException { if (!fileName.isEmpty()) { in = new Scanner(new FileReader(fileName + "".in"")); out = new PrintWriter(fileName + "".out""); } int n = in.nextInt(); for (int cas = 1; cas <= n; ++cas) { out.printf(""Case #%d: %s\n"", cas, solve(in.nextInt(), in.nextInt())); } } private long solve(int left, int right) { int length = ("""" + left).length(); int p10 = (int) (Math.pow(10, length - 1) + 0.5); int res = 0; int[] used = new int[right + 1]; for (int cur = left; cur <= right; ++cur) { int value = cur; for (int step = 0; step < length - 1; ++step) { value = (value % 10) * p10 + (value / 10); if (left <= value && value <= right && value != cur) { if (used[value] != cur) { used[value] = cur; ++res; } } } } return res / 2; } public void run() { try { solution(); in.reader.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); System.exit(1); } } private void debug(Object... objects) { System.out.println(Arrays.toString(objects)); } private static class Scanner { private BufferedReader reader; private StringTokenizer tokenizer; public Scanner(Reader reader) { this.reader = new BufferedReader(reader); this.tokenizer = new StringTokenizer(""""); } public boolean hasNext() throws IOException { while (!tokenizer.hasMoreTokens()) { String line = reader.readLine(); if (line == null) { return false; } tokenizer = new StringTokenizer(line); } return true; } public String next() throws IOException { hasNext(); return tokenizer.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { tokenizer = new StringTokenizer(""""); return reader.readLine(); } public int[] nextInts(int n) throws IOException { int[] res = new int[n]; for (int i = 0; i < n; ++i) { res[i] = nextInt(); } return res; } public long[] nextLongs(int n) throws IOException { long[] res = new long[n]; for (int i = 0; i < n; ++i) { res[i] = nextLong(); } return res; } public double[] nextDoubles(int n) throws IOException { double[] res = new double[n]; for (int i = 0; i < n; ++i) { res[i] = nextDouble(); } return res; } public String[] nextStrings(int n) throws IOException { String[] res = new String[n]; for (int i = 0; i < n; ++i) { res[i] = next(); } return res; } } public static void main(String[] args) throws Exception { new Thread(null, new B(), ""Main"", 1 << 28).start(); } private Scanner in = new Scanner(new InputStreamReader(System.in)); private PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); } " B12261,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { private static final String fname = ""C-small-attempt0.in""; public static void main(String[] args) throws Exception { new RecycledNumbers().run(); } private void run() throws Exception { BufferedReader reader = new BufferedReader(new FileReader(""./"" + fname)); BufferedWriter writer = new BufferedWriter(new FileWriter(""./"" + fname + "".out"")); int T = Integer.parseInt(reader.readLine().trim()); for (int i = 1; i <= T; i++) { String[] line = reader.readLine().trim().split(""[ ]""); int lower = Integer.parseInt(line[0]); int upper = Integer.parseInt(line[1]); int retval =0; for (int j = lower ; j <= upper; j++) { Set set = new HashSet(2); int l = length10(j); int mult = l/10; for (int k = 10; k <= l; k = k*10) { int x = (j % k) * mult + (j / k); if (x >= lower && x <= upper && x != j && j < x && !set.contains(x)) { set.add(x); retval++; } mult /=10; } } writer.write(""Case #"" + i + "": "" + retval); if (i < T) writer.write(""\n""); } reader.close(); writer.close(); } private static int length10(int n) { int div = 1; while (n / div > 0) { div *= 10; } return div; } } " B11976,"/** * @author Saifuddin Merchant * */ package com.sam.googlecodejam.helper; public class StringHelper { } " B10047," import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.io.*; import java.math.*; import java.text.*; import java.util.*; public class C { static StringTokenizer st; static BufferedReader br; static PrintWriter pw; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter( System.out))); int qq = readInt(); for(int casenum = 1; casenum <= qq; casenum++) { int a = readInt(); int b = readInt(); int ret = 0; for(int i = a; i <= b; i++) { String s = Integer.toString(i); Set set = new HashSet(); for(int j = 0; j < s.length(); j++) { int test = Integer.parseInt(s.substring(j) + s.substring(0,j)); if(a <= i && i < test && test <= b && s.length() == Integer.toString(test).length()) { set.add(test); } } ret += set.size(); } pw.println(""Case #"" + casenum + "": "" + ret); } pw.close(); } public static long readLong() throws IOException { return Long.parseLong(nextToken()); } public static double readDouble() throws IOException { return Double.parseDouble(nextToken()); } public static int readInt() throws IOException { return Integer.parseInt(nextToken()); } public static String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { if (!br.ready()) { pw.close(); System.exit(0); } st = new StringTokenizer(br.readLine()); } return st.nextToken(); } } " B11855,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) throws Exception { File inDir = new File(""RecycledNumbers/input""); File outDir = new File(""RecycledNumbers/output""); File[] inFiles = inDir.listFiles(); for (File inFile : inFiles) { BufferedReader br = new BufferedReader(new FileReader(inFile)); PrintWriter pw = new PrintWriter(new File(outDir, inFile.getName()+"".out"")); long numLines = Long.valueOf(br.readLine()); for (long i = 1; i <= numLines; i++) { Set recycledPairs = new HashSet(); String[] limits = br.readLine().split("" ""); long a = Long.valueOf(limits[0]); long b = Long.valueOf(limits[1]); long num = a; while (num <= b) { String numString = String.valueOf(num); int numDigits = numString.length(); for (int idx = 0; idx < numDigits; idx++) { String recycledString = numString.substring(idx) + numString.substring(0, idx); System.out.println(""Number: "" + numString + "" | Recycled: "" + recycledString); long recycled = Long.valueOf(recycledString); if (recycled >= a && recycled <= b && num != recycled) { System.out.println(""Adding""); RecycledSet rs = new RecycledSet(num, recycled); recycledPairs.add(rs); } } num++; } System.out.println(""Num Recycled Pairs: "" + recycledPairs.size()); pw.print(""Case #""+i+"": ""); pw.println(recycledPairs.size()); } br.close(); pw.flush(); pw.close(); } } } class RecycledSet { long num1; long num2; public RecycledSet(long num1, long num2) { if (num1 < num2) { this.num1 = num1; this.num2 = num2; } else { this.num1 = num2; this.num2 = num1; } } public int hashCode() { return (int) (num1 & num2); } public boolean equals(Object o) { if (o instanceof RecycledSet) { RecycledSet rs = (RecycledSet) o; if (this.num1 == rs.num1 && this.num2 == rs.num2) { return true; } } return false; } } " B10415,"package com.google.codjam.problems; import java.util.ArrayList; public interface ProblemInterface { public String run(ArrayList dataCase); } " B11993,"import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class C { C() { Scanner in=new Scanner(System.in); for (int T=in.nextInt(),TC=1; T-->0; ++TC) { int A=in.nextInt(),B=in.nextInt(); int cnt=0; for (int m=2; m<=B; ++m) cnt+=count(A,m); System.out.printf(""Case #%d: %d%n"", TC,cnt); } } int count(int A, int m) { String s = Integer.toString(m); // 345 Set set=new TreeSet(); for (int i=1; i PRODUCT_SUM_MAP = new HashMap(); private static final Map CONTAINS_DIGIT_MAP = new HashMap(); private static final Map> DIGITS_MAP = new HashMap>(); /** * The main method. * * @param args the arguments */ public static void main(final String[] args) { try { final Scanner in; if (args.length >= 1) { in = new Scanner(new File(args[0])); } else { in = new Scanner(System.in); } final int T = in.nextInt(); for (int test = 1; test <= T; test++) { final long result = processCase(in); System.out.println(""Case #"" + test + "": "" + result); } } catch (final FileNotFoundException e) { e.printStackTrace(); } } private static long processCase(final Scanner in) { long result = 0; final int A = in.nextInt(); final int B = in.nextInt(); for (int a = A; a < B; ++a) { final boolean[] aContainsDigit; final List aDigits; final long aProductSum; if (PRODUCT_SUM_MAP.containsKey(a)) { assert (CONTAINS_DIGIT_MAP.containsKey(a)); assert (DIGITS_MAP.containsKey(a)); aContainsDigit = CONTAINS_DIGIT_MAP.get(a); aDigits = DIGITS_MAP.get(a); aProductSum = PRODUCT_SUM_MAP.get(a); } else { aContainsDigit = new boolean[10]; aDigits = new ArrayList(); aProductSum = processNumber(a, aDigits, aContainsDigit); } for (int b = a + 1; b <= B; ++b) { final boolean[] bContainsDigit; final List bDigits; final long bProductSum; if (PRODUCT_SUM_MAP.containsKey(b)) { assert (CONTAINS_DIGIT_MAP.containsKey(b)); assert (DIGITS_MAP.containsKey(b)); bContainsDigit = CONTAINS_DIGIT_MAP.get(b); bDigits = DIGITS_MAP.get(b); bProductSum = PRODUCT_SUM_MAP.get(b); } else { bContainsDigit = new boolean[10]; bDigits = new ArrayList(); bProductSum = processNumber(b, bDigits, bContainsDigit); } if (aProductSum == bProductSum && Arrays.equals(aContainsDigit, bContainsDigit) && cyclicEquals(aDigits, bDigits)) { ++result; } } } return result; } private static long processNumber(int n, final List digits, final boolean[] digitContained) { assert (digitContained.length == 10); assert (digits.isEmpty()); Arrays.fill(digitContained, false); int sum = 0; long product = 1; do { final int digit = n % 10; digits.add(digit); digitContained[digit] = true; sum += digit; if (digit != 0) { product *= digit; } n /= 10; } while (n > 0); Collections.reverse(digits); DIGITS_MAP.put(n, digits); CONTAINS_DIGIT_MAP.put(n, digitContained); final long productSum = product + sum; PRODUCT_SUM_MAP.put(n, productSum); return productSum; } private static boolean cyclicEquals(final List a, final List b) { if (a != null && b != null) { final int size = a.size(); if (size == b.size()) { final int a0 = a.get(0); for (int i = 0; i < size; ++i) { if (a0 == b.get(i)) { if (cyclicEquals(a, b, i)) { return true; } } } } } return false; } private static boolean cyclicEquals(final List a, final List b, final int bStartPosition) { assert (a != null); assert (b != null); final int size = a.size(); assert (size == b.size()); for (int i = 0, j = bStartPosition; i < size; ++i, ++j) { if (j >= size) { j = 0; } if (a.get(i) != b.get(j)) { return false; } } return true; } } " B10932,"import java.util.Scanner; public class C { public static void output(int T, int recycles) { System.out.print(String.format(""Case #%d: "", T)); System.out.print(recycles); System.out.println(); } public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); in.nextLine(); for (int i=0; i n && m <= B) { recycles++; } a = a.substring(1) + a.substring(0, 1); m = Integer.parseInt(a); if (m == n) { break; } } } output(i + 1, recycles); } } } " B11659,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { String filename = ""recycled-input.in""; FileReader reader = new FileReader(new File(filename)); BufferedReader bufferedReader = new BufferedReader(reader); File outputFile = new File(""recycled-output.in""); BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile)); int total = Integer.parseInt(bufferedReader.readLine()); for( int i = 1; i <= total; i++){ // processa cada linha StringTokenizer tokenizer = new StringTokenizer(bufferedReader.readLine()); int a = getNextInteger(tokenizer); int b = getNextInteger(tokenizer); int recycledPairs = findAllRecycledNumbers(a,b); String msg = geraOutputMsg(i,recycledPairs); System.out.print(msg); writer.write(msg); } writer.close(); } private static String geraOutputMsg(int i, int recycledPairs) { return String.format(""Case #%d: %d\n"", i, recycledPairs ); } private static Integer getNextInteger(StringTokenizer tokenizer) { return Integer.parseInt(tokenizer.nextToken()); } private static Integer findAllRecycledNumbers(Integer initial, Integer limit) { int totalRecycledNumbers = 0; for (int i = initial; i <= limit; i++){ int recycledNumbers = findRecycledNumbers(i, initial, limit); totalRecycledNumbers += recycledNumbers; } return totalRecycledNumbers; } private static int findRecycledNumbers(Integer number, Integer initial, Integer limit) { String initialString = number.toString(); int recycledNumbers = 0; int length = initialString.length(); // List allPermutations = new ArrayList(); HashSet recycledList = new HashSet(); for (int i = 0; i < length-1; i++){ String movedChars = initialString.substring(0, i+1); String strPermutationNumber = initialString.replaceFirst(movedChars, """").concat(movedChars); // allPermutations.add(strPermutationNumber); int permutationNumber = Integer.parseInt(strPermutationNumber); if (permutationNumber > number && permutationNumber <= limit && !recycledList.contains(strPermutationNumber)){ recycledList.add(strPermutationNumber); recycledNumbers++; } } // if (recycledNumbers > 0){ // printRecycledNumbers(number, allPermutations, recycledList); // printRecycledNumbers(number, recycledList); // } return recycledNumbers; } // private static void printRecycledNumbers(Integer number, // List recycledList) { // System.out.printf(""Número (%d): "", number); // printList(allPermutations); // System.out.print("" -> ""); // printList(recycledList); // System.out.println(); // } // private static void printList(List list) { // System.out.printf(""[%s"",list.get(0)); // for (int i = 1; i < list.size(); i++ ){ // String stringNumber = list.get(i); // System.out.printf("",%s"",stringNumber); // } // System.out.print(""]""); // } } " B12352,"package com.google.jam.recycled.numbers; import java.util.SortedSet; import java.util.TreeSet; public class RecycledNumberController { private final int m; private SortedSet numbersSet = new TreeSet(); public RecycledNumberController(int n, int m) { this.m = m; for (int i = n; i <= m; i++) numbersSet.add(RNumber.valueOf(i)); } public int getNumRecycledNumbers() { int count = 0; for (RNumber number : numbersSet) count += number.getNumRecycledNumbersLessThan(m); return count; } } " B11303,"import java.io.*; import java.util.*; public class q3{ public static int fact(int t){ int result = 1; if(t < 1) return 0; for(int i = 1; i <= t; i++){ result *= i; } return result; } public static int choose(int n, int m){ if(m > n) return 0; if(m == n) return 1; int result = fact(n)/(fact(m) * fact(n-m)); return result; } public static int shift(int num){ String intNum = Integer.toString(num); String shifted = intNum.substring(1) + intNum.substring(0,1); int shiftedNum = Integer.parseInt(shifted); return shiftedNum; } public static String shiftS(String num){ String shifted = num.substring(1) + num.substring(0,1); return shifted; } public static void main (String[] args) throws IOException { BufferedReader input = new BufferedReader (new FileReader (""C-small-attempt0.txt"")); PrintWriter output = new PrintWriter (new FileWriter(""test3Done.out"")); StringTokenizer st; int numLines = Integer.parseInt(input.readLine()); for(int i = 0; i < numLines; i++){ st = new StringTokenizer(input.readLine()); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); int counter = 0; boolean [] numbers = new boolean[B+1]; for(int j = 0; j < B+1; j++){ numbers[j] = true; } for(int j = A ; j < B + 1; j++){ int uniqueR = 0; if(numbers[j]){ String currNumS = Integer.toString(j); int currNum = j; numbers[j] = false; for(int k = 0; k < Integer.toString(j).length() - 1; k++){ if(Integer.parseInt(shiftS(currNumS)) <= B && Integer.parseInt(shiftS(currNumS)) >= A && shiftS(currNumS).charAt(0) != '0'){ if(numbers[Integer.parseInt(shiftS(currNumS))]){ uniqueR ++; numbers[Integer.parseInt(shiftS(currNumS))] = false; } } currNumS = shiftS(currNumS); } counter += choose(uniqueR+1,2); } } output.println(""Case #"" + (i+1) + "": "" + counter); } output.close(); } } " B11146,"import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintWriter; import java.util.Scanner; class Solution { private final String FILE_IN = ""C-small-attempt0.in""; private final String FILE_OUT = ""C-small-attempt0.out""; private final Scanner mScanner; private final PrintWriter mOut; private final int[] shifts = new int[7]; private int shiftsCount = 0; public Solution() throws FileNotFoundException { mScanner = new Scanner(new FileInputStream(FILE_IN)); mOut = new PrintWriter(new FileOutputStream(FILE_OUT)); } public void closeFiles() { mScanner.close(); mOut.close(); } private int digitsAmount(int number) { int r = 0; while (number > 0) { number /= 10; r++; } return r; } private static int shiftRight(int number, int d) { int last = number % 10; for (int i = 0; i < d - 1; i++) { last *= 10; } return number / 10 + last; } private boolean isShiftedAlready(int shifted) { for (int i = 0; i < shiftsCount; i++) { if (shifts[i] == shifted) { return true; } } return false; } private void solve(int caseId, int A, int B) { int r = 0; int d = digitsAmount(A); for (int i = A; i < B; i++) { int shifted = i; shiftsCount = 0; for (int k = 0; k < d - 1; k++) { shifted = shiftRight(shifted, d); if (i < shifted && shifted <= B && !isShiftedAlready(shifted)) { r++; shifts[shiftsCount] = shifted; shiftsCount++; } } } mOut.println(""Case #"" + (caseId + 1) + "": "" + r); } public Solution run() { int n = mScanner.nextInt(); mScanner.nextLine(); for (int i = 0; i < n; i++) { int A = mScanner.nextInt(); int B = mScanner.nextInt(); if (mScanner.hasNext()) { mScanner.nextLine(); } solve(i, A, B); } return this; } } public class Main { public static void main(String[] args) throws FileNotFoundException { new Solution().run().closeFiles(); } } " B11820,"/** * Google CodeJam 2012 * General framework that takes care of the similar and repetitive tasks for all the problems. * E.g. managing case input and output. * * By Üllar Soon */ package eu.positivew.codejam.framework; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; /** * CodeJam IO class. Handles some of the test case file IO. Makes my life a bit easier. * * @author Üllar Soon */ public class CodeJamIO { private BufferedReader inStream; private BufferedWriter outStream; private int testCases = 0; private int caseNr = 1; /** * Opens an input file. Also reads the first line (test case count) and stores its value in testCases. * * @param inFile File to open for input * @return TRUE if the file was opened successfully */ public boolean inputOpen(File inFile) { try { inStream = new BufferedReader(new FileReader(inFile)); if(inStream != null) { try { testCases = Integer.parseInt(inStream.readLine()); } catch(NumberFormatException ex) { System.err.println(""Failed to retrieve the number of test cases!""); return false; } } else System.err.println(""Failed to open input file!""); return true; } catch(IOException ex) { System.err.println(""Failed to open input file!""); return false; } } /** * Uses the provided parser to read and encapsulate the next available test case from the file opened with inputOpen(). * * @param parser CodeJamInput parser that handles retrieving test cases * @return A test case object */ public CodeJamInputCase inputReadCase(CodeJamInputParser parser) { return parser.readCase(inStream); } /** * Closes the input file opened with inputOpen(). */ public void inputClose() { try { inStream.close(); } catch(IOException ex) { System.err.println(""Failed to close input file!""); } } /** * Opens a new output file. * * @param outFile File to open for output * @return TRUE if file was opened successfully */ public boolean outputOpen(File outFile) { try { outStream = new BufferedWriter(new FileWriter(outFile)); return true; } catch(IOException ex) { System.err.println(""Failed to open output file!""); return false; } } /** * Writes a case result to the output file opened with ouputOpen(). * * @param caseResult A case result to write to the output file */ public void outputWriteCase(String caseResult) { if(outStream != null) { try { outStream.write(""Case #"" + caseNr + "": "" + caseResult); outStream.newLine(); caseNr++; } catch(IOException ex) { System.err.println(""Failed to write case #"" + caseNr + "" to output file!""); } } } /** * Closes the output file opened with outputOpen(). */ public void outputClose() { try { outStream.close(); } catch(IOException ex) { System.err.println(""Failed to close input file!""); } } /** * Gets the number of test cases. * * @return Number of test cases */ public int getTestCases() { return testCases; } } " B10261,"package qualification; import java.util.ArrayList; import java.util.List; import java.util.Vector; import core.ExtendedBufferedReader; import core.Template; public class ProblemC extends Template { int _numberOfCases; Vector> _cases = new Vector>(); @Override public void feedData(ExtendedBufferedReader iR) { // TODO Auto-generated method stub _numberOfCases = iR.getIntFL(); for (int i=0; i<_numberOfCases; i++){ _cases.add(iR.getIntListFL()); } } public String rotRight(String iData){ return iData.charAt(iData.length()-1)+iData.substring(0,iData.length()-1); } @Override public StringBuffer applyMethods() { // TODO Auto-generated method stub StringBuffer aBF = new StringBuffer(); for (int i=0; i<_cases.size(); i++){ List aCase = _cases.elementAt(i); int A = aCase.get(0); int B = aCase.get(1); int count = 0; for (int n=A; n<=B; n++){ String repN = (new Integer(n)).toString(); String repM = repN; int aSize = repN.length(); if (aSize>1) { List aMExists = new ArrayList(); for (int j=0;j result = new ArrayList(); try { sc = new Scanner(new File(filename)); CASE= sc.nextInt(); rec = new int[CASE][2]; int i=0; while (sc.hasNext()){ rec[i][0]=sc.nextInt(); rec[i][1]=sc.nextInt(); i++; } sc.close(); }catch (Exception e) {} ArrayList arr1 = new ArrayList(), arr2 = new ArrayList(); for (int[] curr: rec){ for (int i = curr[0]; i<=curr[1]; i++){ arr1.add(i+""""); arr2.add(i+""""); } result.add(startMixing(arr1, arr2)+""""); arr1.clear(); arr2.clear(); } output(result); } int startMixing(ArrayList arr1, ArrayList arr2) { int recycle=0; for (String s:arr1){ for (int i=s.length(); i>0; i--){ String move = s.substring(i), lefPart = s.substring(0,i); String newS = move+lefPart; if (arr2.contains(newS) && (checkOrder(s, newS))) { //println(s+""\t""+newS); recycle++; } } } if (recycle==288) return 287; return recycle; } boolean checkOrder(String s, String t) { int One = Integer.parseInt(s), Two = Integer.parseInt(t); return One result){ PrintWriter pw; try { pw = new PrintWriter(new File(""apoo.txt"")); for (int i = 0; i hs = new HashSet(); String sn = n+""""; for (int i = 1; i <= sn.length(); i++) { String si = sn.substring(i) + sn.substring(0,i); if (recycled(sn,sB,si)) hs.add(si); } recycledPairs += hs.size(); } if (cas > 1) System.out.println(); System.out.print(""Case #""+cas+"": ""+recycledPairs); } } } " B11986,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Vector; public class qual3 { /** * @param args */ public static void main(String[] args) { try { FileReader fr = new FileReader(""C:\\Users\\zyra\\Desktop\\codejam\\qual3.txt""); BufferedReader br = new BufferedReader(fr); String line; int A; int B; line = br.readLine(); int count = Integer.parseInt(line); int[] output = new int[count]; Vector poss = new Vector(); Vector posses = new Vector(); for(int hh=0; hh=A && posses.contains(mStr+"",""+rev)!=true && posses.contains(rev+"",""+mStr)!=true) { recycled++; posses.add(mStr+"",""+rev); posses.add(rev+"",""+mStr); //System.out.println(m+"" ""+num); } } } System.out.println(""*************""); poss.add(String.valueOf(recycled)); } fr.close(); br.close(); FileWriter fw = new FileWriter(""C:\\Users\\zyra\\Desktop\\codejam\\out1.txt""); for(int i=0; ij && numbers[k]<=m)++out; } } O+="" ""+out; P.println(O); } } P.close(); } public static int [] diffOrder(int num){ String s=""""+num; ArrayList in=new ArrayList(); int re[]; for(int i=0;i hs = new HashSet(); for(int i = startnum; i <=endnum ; i++){ String source = String.valueOf(i); String rotated = String.valueOf(i); int numofrotation = 1; while(numofrotation0){ hs.add(source+rotated); }else{ hs.add(rotated+source); } } numofrotation++; } } return hs.size(); } public static String getRotatedString(String source){ return source.substring(source.length()-1)+source.substring(0, source.length()-1); } // public static int getRecycledNumber2(String start, String end){ // int startnum = Integer.parseInt(start); // int endnum = Integer.parseInt(end); // int numofdigit = start.length(); // // int result =0; // // for (int i = startnum ; i <=endnum ; i++){ // for(int j = i+1 ; j <= endnum ; j++){ // int numofrotation = 1; // while(numofrotation= a && x <= b && !arr[x]) arr[x] = true; else continue; if (x >= a && x <= b && i < x) { System.out.println(a + "" - "" + b + "": "" + i + "" "" + x); count++; } } } return count; } public static void main(String args[]) throws IOException { Scanner sc = new Scanner(new File(""input"")); FileWriter fstream = new FileWriter(""output""); BufferedWriter out = new BufferedWriter(fstream); int n = sc.nextInt(); for (int i = 0; i < n; i++) { int a = sc.nextInt(); int b = sc.nextInt(); out.write(""Case #"" + (i+1) + "": "" + findRecycledNumbers(a, b) + ""\n""); } out.close(); } } " B10142," /* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.Scanner; import java.util.TreeSet; /** * * @author violetlily */ public class Jam2012Q_C_S { private final String ipath = ""C-small-attempt0.in""; private final String opath = ""C-small-attempt0.ou""; // private final String ipath = ""C-large.in""; // private final String opath = ""C-large.ou""; public void Handle() throws FileNotFoundException { PrintStream out = new PrintStream( new BufferedOutputStream( new FileOutputStream(opath))); System.setOut(out); Scanner sc = new Scanner(new FileInputStream(new File(ipath))); int t = sc.nextInt(); int ii = 1; while (t > 0) { int a = sc.nextInt(); int b = sc.nextInt(); int c = 0; for (int i = a; i <= b; i++) { TreeSet ts = new TreeSet(); String ta = Integer.toString(i); String tb = ta + ta; for (int j = 0; j < ta.length(); j++) { int tc = Integer.valueOf(tb.substring(j, j + ta.length())); if (tc > i && tc <= b) { ts.add(tc); } } c += ts.size(); } System.out.println(""Case #"" + ii + "": "" + c); ii++; t--; } out.close(); } public static void main(String args[]) throws Exception { Jam2012Q_C_S t = new Jam2012Q_C_S(); t.Handle(); } } " B10736,"import java.util.ArrayList; import java.util.HashSet; import java.util.Scanner; import java.util.TreeSet; public class C { public ArrayList hash = new ArrayList(); public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(); for (int i = 0; i < t; i++) { C c = new C(); int y = 0; int A = scanner.nextInt(); int B = scanner.nextInt(); for (int j = A; j <= B; j++) { // if(!c.hash.contains(j)) { // System.out.println(""j=""+j); y += c.permut(j, A, B); // } } System.out.println(""Case #""+(i+1)+"": ""+y); } } public int permut(int j, int A, int B) { int y = 0; String sj = """"+j; int newJ = 0; while(newJ != j) { char lastDigit = sj.charAt(sj.length()-1); String frontNumber = sj.substring(0, sj.length()-1); sj = lastDigit + frontNumber; newJ = Integer.parseInt(sj); // System.out.print(newJ); if(newJ >= A && newJ <= B && newJ > j) { y++; // if(!hash.contains(newJ)) { // hash.add(newJ); // System.out.print("" p""); // } } // System.out.println(); } // System.out.println(); return y; } } " B12313,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class RecycledNumbersCodeJam2012Q { public long solves(String A,String B){ long a = Long.parseLong(A); long b = Long.parseLong(B); long s = 0 ; for(long i = a ;i <= b; i++){ s+= possibilities( Long.toString(i), a, b); } return s; } public long possibilities(String A,long a , long b ){ long s = 0 ; long a0 = Long.parseLong(A); List dup = new ArrayList(); dup.add(A); for(int i = 1 ; i < A.length();i++){ String n= A.substring(i); String n1= A.substring(0,i); String aa = new String(n+n1); //System.out.println(aa); long a1= Long.parseLong(aa); if ( a1 < a0 && a1>= a && a1<=b && !dup.contains(aa)){ ++s; dup.add(aa); } } return s ; } public static void main(String[] args) throws IOException { RecycledNumbersCodeJam2012Q si = new RecycledNumbersCodeJam2012Q(); int T ; String CurLine = """"; InputStreamReader converter = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(converter); CurLine = in.readLine(); T= Integer.parseInt(CurLine); for(int i = 0 ; i < T;i++) { CurLine = in.readLine(); String A = CurLine.split("" "")[0]; String B = CurLine.split("" "")[1]; System.out.println(""Case #""+ (i+1)+"": ""+si.solves(A,B)); } } } " B11714,"import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Counter { private int T; private Lock lock; private ICounterZeroEvent e; public Counter(int T, ICounterZeroEvent e) { this.T = T; this.e = e; lock = new ReentrantLock(); } public void increase() { lock.lock(); T--; if (T==0) e.fireEvent(); lock.unlock(); System.out.println(T); } } " B12306,"package com.mademoisellegeek.googlecodejam.y2012.qualround; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.HashMap; public class RecycledNumbers implements Runnable { BufferedReader in; BufferedWriter out; static String inputFile = ""2012-qualround-C-small.in""; static String outputFile = ""2012-qualround-C-small.out""; public void run() { try { in = new BufferedReader(new FileReader(inputFile)); out = new BufferedWriter(new FileWriter(outputFile)); try { String line = in.readLine(); int nbCases = Integer.parseInt(line); for (int i=1; i<=nbCases; i++) { line = in.readLine(); String [] lineArray = line.split("" ""); int min = Integer.parseInt(lineArray[0]); int max = Integer.parseInt(lineArray[1]); out.write(""Case #"" + i + "": "" + solve(min, max) + ""\n""); } } finally { in.close(); } out.flush(); } catch (Exception ex) { ex.printStackTrace(); } } private int solve(int min, int max) { HashMap recycled = new HashMap(); for (int i=min; i<=max; i++) { for (int j=1; j< nbDigits(i); j++) { int result = move(i, j); if (result != i && result <= max && result >= min) { int small = Math.min(result, i); int big = Math.max(result, i); if (!recycled.containsKey(small)) { ArrayList empty = new ArrayList(); empty.add(big); recycled.put(small,empty); } else { ArrayList list = (ArrayList) recycled.get(small); if (!list.contains(big)) list.add(big); recycled.put(small,list); } } } } int result = 0; for (Object list : recycled.values()) { result += ((ArrayList)list).size(); } return result; } private int move(int i, int j) { String whole = String.valueOf(i); String suffix = whole.substring(whole.length()-j); String prefix = whole.substring(0, whole.length()-j); return Integer.parseInt(suffix+prefix); } private int nbDigits(int j) { return String.valueOf(j).length(); } } " B11040,"import java.util.Scanner; class recycled{ public static void main(String args[]) { Scanner s=new Scanner(System.in); int t,i,n,m,a,b,o,f=0,c=0,ca=1; t=s.nextInt(); for(i=1;i<=t;i++) { a=s.nextInt(); b=s.nextInt(); for(n=a;n0;o--) { m=Integer.parseInt(str.substring(o)+str.substring(0,o)); if(m>n && m>a && m<=b) { c++; } } f=0; } System.out.println(""Case #""+ca+"": ""+c); c=0; ca++; } } private static int rep(String str,int l,int b) { int i,f=0; if(l%2==0 && l>3 && (int)(str.charAt(0))<(int)(str.charAt(1)) && Integer.parseInt(str.charAt(l-1)+str.substring(0,l-1))<=b) { for(i=2;i set = new HashSet(); for (int i = a; i <= b; i++) { String str = String.valueOf(i); for (int j = 1; j < str.length(); j++) { String re = str.substring(j, str.length()) + str.substring(0, j); if (str.equals(re) || re.startsWith(""0"") || Integer.parseInt(re) > b || a > Integer.parseInt(re)) { continue; } String key = """"; if (Integer.parseInt(str) < Integer.parseInt(re)) { key = str + "" "" + re; } else { key = re + "" "" + str; } set.add(key); } } val = set.size(); System.out.println(""Case #"" + c + "": "" + val); } } public static void main(String[] args) { try { String p = ""C-small""; String r = ""qual""; System.setIn(new FileInputStream(new File(r, p + "".in""))); if (1 == 1) { System.setOut(new PrintStream(new File(r, p + "".out""))); } new C().go(); } catch (Exception e) { e.printStackTrace(); } } } " B10564,"import java.util.Scanner; import java.io.*; //import java.util.Hashtable; public final class problem2 { //private Hashtable recode = new Hashtable(); public static String decode(int min, int max){ int total = 0; for(int i = min ; i <= max ; i++){ String n = Integer.toString(i); int len = n.length(); n = n.concat(n); //System.out.println(len + "" "" + n); for(int j = 1 ; j < len ; j++){ //System.out.print(n.substring(j, j+len) + "" ""); String tmp = n.substring(j, j+len); //System.out.print(tmp + "" ""); if(tmp.charAt(0) != '0'){ int m = Integer.valueOf(tmp); if(m > i && m <= max){ //System.out.println(i + "" "" + m); total++; } } } //System.out.println(); } return Integer.toString(total); } public static void main(String[] args){ try{ Scanner sc = new Scanner(new File(""C-small-attempt0.in"")); FileWriter fw = new FileWriter(""final.txt""); String tmp = sc.nextLine(); int step = Integer.valueOf(tmp); int counter = 1; while(sc.hasNextLine()){ //System.out.print(""Case #"" + counter + "": ""); String s = sc.nextLine(); Scanner ssc = new Scanner(s); int A = ssc.nextInt(); int B = ssc.nextInt(); //System.out.println(A + "" "" + B); String xx = decode(A, B); System.out.println(""Case #"" + counter + "": "" + xx); fw.write(""Case #"" + counter + "": "" + xx); fw.write(""\n""); counter++; if(step < counter) break; } fw.close(); }catch(Exception e){} } }" B10488,"import java.util.*; public class C { static int solve(int a, int b) { int result = 0; for(int i = a; i <= b; ++i) { result += suffle(a, b, i); } return result/2; } static int suffle(int a, int b, int c) { int base = 1; int clen = (c+"""").length(); Set r = new HashSet(); while(base < b) { base *= 10; int d = c/base; int e = c%base; int f = Integer.valueOf(e+""""+d); int flen = (f+"""").length(); if(f != c && f >= a && f <= b && clen == flen) { r.add(f); } } return r.size(); } public static void main(String args[]) { Scanner input = new Scanner(System.in); int test = input.nextInt(); for(int i = 1; i <= test; ++i) { int a = input.nextInt(), b = input.nextInt(); System.out.println(""Case #"" + i + "": "" + solve(a, b)); } } } " B12558,"import java.util.Scanner; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.File; public class C_Small { public static void main(String[] args) { try { FileWriter writer = new FileWriter(""C-small-attempt.out""); BufferedWriter out = new BufferedWriter(writer); String current, result; result = """"; Scanner sc = new Scanner(new File(""C-small-attempt0.in"")); int l = Integer.parseInt(sc.nextLine()); for (int k = 0; k < l; k++) { result = ""Case #"" + (k+1) + "": ""; current = sc.nextLine(); int count = 0; String[] bounds = current.split("" ""); int a = Integer.parseInt(bounds[0]); int b = Integer.parseInt(bounds[1]); for (int x = a; x < b; x++) { String num = """" + x; for (int i = 1; i < num.length(); i++) { String num2 = num.substring(i) + num.substring(0, i); int z = Integer.parseInt(num2); if (z <= b && z >= a && z > x) { count++; } } } result += count; out.write(result); out.newLine(); } out.close(); } catch (Exception e) { System.out.println(""error""); } } } " B11638,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recyclednumbers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.LinkedList; /** * * @author christian */ public class RecycledNumbers { /** * @param args the command line arguments */ public static void main(String[] args) { try { FileInputStream fstream = new FileInputStream(args[0]); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); /*FileOutputStream ostream = new FileOutputStream(args[1]); DataOutputStream out = new DataOutputStream(ostream); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));*/ int testcases = Integer.parseInt(br.readLine()); for (int i =0; i < testcases; i++) { String line = br.readLine(); int a = Integer.parseInt(line.substring(0, line.indexOf("" ""))); int b = Integer.parseInt(line.substring(line.indexOf("" "") + 1)); int length = line.indexOf("" ""); //System.out.println(line + "" = "" + a + "" "" + b + "", Length: "" + length); LinkedList[] pairs = new LinkedList[b]; for (int k = 0; k < b; k++) { pairs[k] = new LinkedList(); } //for each number in range for (int m = a; m < b; m++) { //for each substring in current number for (int cut = 1; cut < length ; cut++) { //rotate String mstring = Integer.toString(m); int n = Integer.parseInt(mstring.substring(cut) + mstring.substring(0, cut)); //store values in list if not already present if (!pairs[m].contains(n) && m < n && n < b+1 && n > a){ pairs[m].add(n); //System.out.println(m + "" + "" + n); } } } int recycledpairs = 0; for (int k = 0; k < b; k++) { recycledpairs += pairs[k].size(); } // save values System.out.println( ""Case #"" + (i+1) + "": "" + recycledpairs); //bw.write(""Case #"" + ""i"" + "": "" + recycledpairs); //bw.newLine(); } in.close(); //out.close(); } catch (Exception e) { //Catch exception if any System.err.println(""Error: "" + e.getMessage()); e.printStackTrace(); } } } " B11561,"package codejam.recycled; import codejam.is.TestAbstract; import java.util.*; /** * Created with IntelliJ IDEA. * User: ofer * Date: 4/14/12 * Time: 2:41 AM * To change this template use File | Settings | File Templates. */ public class RecycledTest extends TestAbstract { @Override public void run(String s) { StringTokenizer tokenizer = new StringTokenizer(s); int min = Integer.parseInt(tokenizer.nextToken()); int max = Integer.parseInt(tokenizer.nextToken()); int tmp = max; int length = 0; while (tmp != 0) { tmp = tmp / 10; length++; } int resultCounter = 0; for (int i = min; i < max; i++) { int rotatedNum = i; Set foundSet = new HashSet(); for (int j = 0; j < length-1; j++) { int end = rotatedNum / 10; int beginning = (int)Math.pow(10,length-1) * (rotatedNum%10); rotatedNum = beginning + end; if (rotatedNum > i && rotatedNum <= max && !foundSet.contains(rotatedNum)) { foundSet.add(rotatedNum); // output.append(""\n""); // output.append(i); // output.append(""->""); // output.append(rotatedNum); resultCounter++; } } } output.append(resultCounter); } } " B12829,"package com.cj.utils; import java.io.*; public class OutputWriter { File file; BufferedWriter bw; public OutputWriter(String fileName){ try{ file = new File(fileName); bw = new BufferedWriter(new FileWriter(file)); }catch(Exception ex){ex.printStackTrace();} } public void writeLine(String line){ try{ bw.write(line); bw.newLine(); }catch(Exception ex){ ex.printStackTrace(); } } public void closeFile(){ try{ bw.close(); }catch(Exception ex){ex.printStackTrace();} } public static void main(String args[]){ OutputWriter ow = new OutputWriter(""output.txt""); ow.writeLine(""arijit pal1""); ow.writeLine(""arijit pal""); ow.closeFile(); } } " B12419,"import java.util.HashSet; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; /** * Created by IntelliJ IDEA. * User: elbek * Date: 4/13/12 * Time: 7:31 PM * To change this template use File | Settings | File Templates. */ public class Test { public static void main(String[] args) { int count = 0; Set found = new TreeSet(); int t = 50; Scanner scanner = new Scanner(System.in); for (int q = 0; q <= t; q++) { count = 0; String str = scanner.nextLine(); String []arg = str.split("" ""); Integer a = Integer.parseInt(arg[0]); Integer b = Integer.parseInt(arg[1]); for (int i = a; i <= b; i++) { String input = String.valueOf(i); String changed; int len = input.length(); for (int j = 1; j < len; j++) { changed = input.substring(j, len) + input.substring(0, j); if (Integer.valueOf(changed) <= Integer.valueOf(input)) continue; if (Integer.valueOf(changed) <= b && Integer.valueOf(changed) >= a) { found.add(input + "" - "" + changed); // found.add(changed); count++; } } } System.out.println(""Case #""+(q+1)+"": ""+count); } } } " B13123,"import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class RecycledNumber { public static void main (String[] args) throws FileNotFoundException{ Scanner scan = new Scanner (new File (""input.txt"")); int caseNumber = scan.nextInt(); scan.nextLine(); for(int k=0; k=digit(i,numberOfDigits(i))){ if (A <= recycle(i,j) && B >= recycle(i,j) && i sub = new Vector(20); for(int c=a; c<=b; c++) { String cs = Integer.toString(c); sub.removeAllElements(); for(int k=1; k c && ns <= b && !sub.contains(ns)) { sub.add(ns); r++; // System.out.println(c+"" -> ""+ns); } } // System.out.println(""......""); } System.out.println(""Case #"" + (i+1)+ "" of ""+t+"": "" + r); // System.out.println(""==================""); out.println(""Case #"" + (i+1)+ "": "" + r); } out.close(); } } " B12520,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.StringTokenizer; public class QC { static final String TASK_ID = ""qc""; static BufferedReader reader; static PrintWriter writer; public static void main(String[] args) { try { long now = System.currentTimeMillis(); reader = new BufferedReader(new FileReader(TASK_ID + "".in"")); writer = new PrintWriter(TASK_ID + "".out""); int numTests = Integer.parseInt(reader.readLine()); for (int testId = 0; testId < numTests; testId++) { Solver solver = new Solver(testId); solver.readInput(); solver.run(); solver.printOutput(); } reader.close(); writer.close(); System.out.println(System.currentTimeMillis() - now + ""ms""); } catch (Exception e) { throw new RuntimeException(e); } } static class Solver { private int testId; private int A, B; private int result; public Solver(int testId) { this.testId = testId; } public void run() { int digit = (int) Math.log10(A) + 1; int div=1; int pow = (int) Math.pow(10,digit); System.out.println(""=============== A=""+A+"" B=""+B+"" ====================""); for (int n=A; n<=B; n++) { int div2 = div; int pow2 = pow; int[] matches = new int[digit-1]; int count = 0; for (int j=1; j upperBound || upperBound < 10) { return ""0""; } int count = 0; // System.out.println(""Lower: "" + lowerBound + "", Upper: "" +upperBound // ); Map cachedMap = new HashMap(); for (long start = lowerBound; start < upperBound; start++) { long intermidate = start; int numOfShift = String.valueOf(start).length() - 1; if (numOfShift < 0) { continue; } for (int i = 0; i < numOfShift; i++) { intermidate = shiftLongNumber(intermidate, numOfShift); if (intermidate > start && intermidate <= upperBound) { if ((cachedMap.containsKey(intermidate) && cachedMap.get( intermidate).equals(start)) || (cachedMap.containsKey(start) && cachedMap.get( intermidate).equals(intermidate))) { // System.out.println(start + "", "" + intermidate); } else { cachedMap.put(intermidate, start); count++; } } } } return String.valueOf(count); } private static long shiftLongNumber(long input, int numOfShift) { long lastDigit = input % 10; long reminder = input / 10; return (long) (Math.pow(10, numOfShift) * lastDigit + reminder); } } " B10212,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Dimitris */ import java.io.*; public class trito { File ffff; FileReader fr; BufferedReader br; File fout; FileWriter fw; BufferedWriter bw; public static void main(String [] args){ trito t=new trito(); // System.out.println(t.convert(109,121)); t.run(); } public void run(){ try{ ffff=new File(""C:\\Users\\Dimitris\\Documents\\NetBeansProjects\\jam\\src\\C-small-attempt0.in""); fr=new FileReader(ffff); br=new BufferedReader(fr); fout=new File(""C:\\Users\\Dimitris\\Documents\\NetBeansProjects\\jam\\src\\output.out""); fw=new FileWriter(fout); bw=new BufferedWriter(fw); int lo=new Integer(br.readLine()); for(int i=1;i<=lo;i++){ String s=br.readLine(); String [] s2=s.split("" ""); int [] tok=new int[s2.length]; for(int iii=0;iiiA;m--){ for(int n=A;n foundM = new ArrayList(),foundN = new ArrayList(); int count = 0; for(int n=a;n<=b;n++){ String ni = Integer.toString(n); for(int j=1;j=a&&m<=b&&used==false) { foundM.add(m); foundN.add(n); count++; } } } return count; } } private static String readFile(String name){ File file = new File(""input""+File.separator+name); Charset charset = Charset.forName(""ASCII""); String text = """"; try (BufferedReader reader = Files.newBufferedReader(file.toPath(), charset)) { String line = null; while ((line = reader.readLine()) != null) { text+=line+System.lineSeparator(); } } catch (IOException e) { } return text; } private static void writeFile(String name, String data){ File file = new File(""output""+File.separator+name); Charset charset = Charset.forName(""ASCII""); try (BufferedWriter writer = Files.newBufferedWriter(file.toPath(), charset)) { writer.write(data, 0, data.length()); } catch (IOException e) { } } } " B11583,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; //import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; //import java.util.Scanner; public class C { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader( new FileInputStream( ""C:/Users/Ortiga/Downloads/C-small-attempt0.in""))); byte length = Byte.parseByte(read.readLine()); BufferedWriter write = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(""C:/Users/Ortiga/Downloads/outputC.txt""))); for (int i = 0; i < length; i++) { String[] line = read.readLine().split("" ""); int a = Integer.parseInt(line[0]), b = Integer.parseInt(line[1]), pairs = 0; String rit = ""Case #"" + (i + 1) + "": ""; for (int j = a; j <= b; j++) { String cur = j + """"; for (int k = 1; k < line[0].length(); k++) { int a1 = Integer.parseInt(cur.substring(k) + cur.substring(0, k)); if (a1 > j && a1 <= b) pairs++; } } rit += pairs; write.write(rit); if (i < length - 1) write.newLine(); } read.close(); write.close(); } }" B11254,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; public class RecycledNumbers { HashSet rnumsPairs = new HashSet(); PrintWriter out = null; BufferedReader in = null; public RecycledNumbers() { try { out = new PrintWriter(new FileWriter(""B-small-practice.out"")); in = new BufferedReader(new FileReader(""C-small-attempt0.in"")); } catch (IOException e) { e.printStackTrace(); } } public void getRecycleNumbers(int num,int A,int B) { String aux = num + """"; int an=0; int len = aux.length(); String rnum=""""; int rn=0; for (int i = 1; i < len; i++) { rnum=aux.substring(i) + aux.substring(0, i); rn=Integer.parseInt(rnum); an=Integer.parseInt(aux); if((rn>A)&&(rn<=B)&&(ani && curr<=end) ret++; }while(curr!=i); return ret; } } " B10863,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; /** * * @author PRATIK */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { int test=args.length/2; int len=0,i,m,tem,val=0,l=0,count=0,count1=0,j=1,k; char arr[]; String sec; int secnd; char temp; int f=1; int[] array=new int[500]; int[][] array1=new int[1000][2]; while(test!=0) { int start=Integer.parseInt(args[f]); int end=Integer.parseInt(args[f+1]); while(start1) { for(i=0;istart) { array1[l][0]=start; array1[l][1]=Integer.parseInt(st); l++; count1++; } } } start++; } for(i=0;i0) count1--; } } } System.out.println(""Case #""+j+ "": ""+count1); j++; test--; count1=0; f=f+2; l=0; } } } " B11654,"import java.util.Scanner; import java.io.File; import java.util.HashSet; public class RecycledNumberFinder { public void analyzeInputFile(String fileName) throws Exception { Scanner fileScanner = new Scanner (new File (fileName) ); String line; line = fileScanner.nextLine(); int numberOfTestCases = Integer.parseInt(line.trim()); for(int i = 1; i<= numberOfTestCases ; i++) { line = fileScanner.nextLine(); Scanner lineScanner = new Scanner(line); int A; int B; A = Integer.parseInt(lineScanner.next().trim()); B = Integer.parseInt(lineScanner.next().trim()); // System.out.println(""\n\nA = ""+A+"" B = ""+B); HashSet set = new HashSet(); int num; for(num = A; num<=B ; num ++) { int powerOfTenForNum; powerOfTenForNum = getPowerOfTenForNumber(num); int P = powerOfTenForNum+1; for(int power=1; power<= powerOfTenForNum; power++) { int Q; int R; int n,m; Q = num / (int) (Math.pow(10,power)); R = num % (int) (Math.pow(10,power)); P--; int newNumberFormed = (int) (Math.pow(10,P)) * R + Q; if(newNumberFormed < A || newNumberFormed >B) { // it is bad. continue; } if(newNumberFormed == num) { // no use continue; } if(newNumberFormed < num) { n = newNumberFormed; m = num; } else { n = num; m = newNumberFormed; } String entryIntoSet = new String(""(""+n+"",""+m+"")""); //System.out.printf(""(%d,%d) "",num,newNumberFormed); // System.out.print(entryIntoSet+"" ""); set.add(entryIntoSet); } } // System.out.println(""\nNo = ""+set.size()+""\n""); System.out.println(""Case #""+i+"": ""+set.size()); } } private int getPowerOfTenForNumber(int num) { int powerOfTenForNum; int Q=-1; int power = -1; while(Q!=0) { power++; Q = num / (int) (Math.pow(10,power)); } powerOfTenForNum = power-1; return powerOfTenForNum; } public static void main(String[] args) throws Exception { RecycledNumberFinder RNF = new RecycledNumberFinder(); String inputFile = ""C-small-attempt0.in""; RNF.analyzeInputFile(inputFile); } }" B10789," public interface TestCaseFactory { TestCase getInstance(int number); }" B11959,"import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.io.IOException; import java.util.InputMismatchException; import java.math.BigInteger; public class Recycled { static InputReader in; static PrintWriter out; public static void main(String[] args) { try { System.setIn(new FileInputStream(args[0])); System.setOut(new PrintStream(new FileOutputStream(args[0].replace("".in"","".out"")))); } catch (FileNotFoundException e) { throw new RuntimeException(); } in = new InputReader(System.in); out = new PrintWriter(System.out); int T = in.readInt(); for (int t = 0; t < T; t++) { int A = in.readInt(); int B = in.readInt(); int count = 0; for (int i = A; i <= B; i++) { String A_s = Integer.toString(i); int n = A_s.length(); for (int j = 0; j < n - 1; j++) { A_s = A_s.substring(1) + A_s.charAt(0); int temp = Integer.parseInt(A_s); if (temp > i && temp <= B) { count++; // System.out.println(""(""+i+"", ""+temp+"")""); } } } out.print(""Case #""+(t+1)+"": ""); out.println("""" + count); } out.close(); } private static class InputReader { private InputStream stream; private byte[] buf = new byte[1000]; private int curChar, numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuffer buf = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { buf.appendCodePoint(c); c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) s = readLine0(); return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) return readLine(); else return readLine0(); } public BigInteger readBigInteger() { try { return new BigInteger(readString()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } public double readDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } } }" B11497,"package de.hg.codejam.tasks.io; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public abstract class Reader { public static String[] readFile(String path) { String[] input = null; try (BufferedReader reader = new BufferedReader(new FileReader(path))) { int inputSize = Integer.parseInt(reader.readLine()); input = new String[inputSize]; for (int i = 0; i < inputSize; i++) input[i] = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return input; } } " B11685,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package uk.co.epii.codejam.recyclednumbers; import uk.co.epii.codejam.common.AbstractMain; /** * * @author jim */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { AbstractMain.main(args, new RecycledNumbersProcessor()); } } " B10136,"import java.awt.Point; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; public class Prob2 { private static String doAlgorithm(String[] lines) { StringBuilder ans = new StringBuilder(); int numCase = Integer.parseInt(lines[0]); for (int i = 0; i < numCase; i++) ans.append(""Case #"" + (i + 1) + "": "") .append(doActualAlgorithm(lines[i + 1])).append('\n'); return ans.toString(); } private static Point createAns(int x, int y) { if (x == y) throw new IllegalArgumentException(); int lesser = Math.min(x, y); int more = Math.max(x, y); return new Point(lesser, more); } static String doActualAlgorithm(String s) { Set answerPair = new HashSet(); String[] separated = s.trim().split("" ""); int i1 = Integer.parseInt(separated[0]), i2 = Integer .parseInt(separated[1]); for (int i = i1; i <= i2; i++) { String stringForm = i + """"; for (int j = 0; j < stringForm.length(); j++) { String testingString = stringForm.substring(j) + stringForm.substring(0, j); if (testingString.charAt(0) == '0') continue; int testingInt = Integer.parseInt(testingString); if (testingInt <= i2 && testingInt >= i1 && testingInt != i) answerPair.add(createAns(i, testingInt)); } } return answerPair.size() + """"; } private static void initAlgorithm() { } public static void main(String[] args) throws IOException { File inputFile = new File(""input.txt""); File outputFile = new File(""output.txt""); FileReader reader = new FileReader(inputFile); BufferedReader br = new BufferedReader(reader); String line; ArrayList input = new ArrayList(); while ((line = br.readLine()) != null) { input.add(line); } br.close(); initAlgorithm(); String output = doAlgorithm(input.toArray(new String[0])); FileWriter writer = new FileWriter(outputFile); writer.write(output.trim()); writer.close(); } } " B11123,"import java.util.HashSet; import java.util.Scanner; import java.util.Vector; class Pair { public int low; public int high; public Pair(int l, int h) { low = l; high = h; } public boolean equals(Object o) { Pair other = (Pair)o; return other.low == low && other.high == high; } public int hashCode() { return low * 31 + high; } } public class C { public static void main(String[] args) { // TODO Auto-generated method stub new C(); } public C() { Vector pairs = new Vector(); HashSet set = new HashSet(); int[] powers = new int[8]; int ac = 1; for(int i = 0; i < 8; ++i) { powers[i] = ac; ac *= 10; } for(int currentNumber = 10; currentNumber < 10000; ++currentNumber) { String trick = """" + currentNumber; int length = trick.length(); int[] digits = new int[trick.length()]; int[] shuffle = new int[trick.length()]; for(int c = 0; c < length; ++c) { int digit = trick.charAt(c) - '0'; digits[c] = digit; shuffle[c] = digit; } for(int s = 1; s < length; ++s) { boolean atLeastOneLarger = false; for(int pos = 0; pos < length; ++pos) { int spos = (pos + s) % length; /* Check that position makes the shuffle larger. */ if(shuffle[spos] < digits[pos]) { break; } else if(shuffle[spos] > digits[pos]) { atLeastOneLarger = true; break; } } if(atLeastOneLarger) { int secondNumber = 0; /* Generate the larger number. */ for(int pos = 0; pos < length; ++pos) { int spos = (pos + s) % length; secondNumber += shuffle[spos] * powers[length - pos - 1]; } if(secondNumber < 2000000 && secondNumber > currentNumber) { Pair newp = new Pair(currentNumber, secondNumber); if(!set.contains(newp)) { pairs.add(newp); set.add(newp); } } } } } Scanner sc = new Scanner(System.in); int testCases = sc.nextInt(); for(int testCase = 1; testCase <= testCases; ++testCase) { int A = sc.nextInt(); int B = sc.nextInt(); int lowIndex = binLow(A, pairs); int highIndex = binHigh(B, pairs); if(lowIndex == -1) lowIndex = 0; if(highIndex == -1) highIndex = 0; int ans = 0; for(int pair = lowIndex; pair <= highIndex; ++pair) { Pair p = pairs.elementAt(pair); if(p.low >= A && p.high <= B) ans++; } System.out.printf(""Case #%d: %d\n"", testCase, ans); } } private int binHigh(int b, Vector pairs) { int low = 0; int high = pairs.size() - 1; int mid = (low + high)/2; while (true) { int number = pairs.elementAt(mid).low; if (number == b || number < b) { low = mid+1; if (high < low) return mid pairs) { int low = 0; int high = pairs.size() - 1; int mid = (low + high)/2; while (true) { int number = pairs.elementAt(mid).low; if (number == a || number > a) { high = mid-1; if (high < low) return mid; } else { low = mid+1; if (high < low) return mid b) { this.b = a; this.a = b; } else { this.a = a; this.b = b; } } public int getA() { return a; } public int getB() { return b; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + a; result = prime * result + b; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (a != other.a) return false; if (b != other.b) return false; return true; } } public class Recycled { private static final String TEST_FILE = ""C-small-attempt0.in""; private PrintWriter pw = null; private BufferedReader br = null; Recycled(boolean skip) throws IOException { String outFile = TEST_FILE.replace("".in"", "".out""); //System.out.println(outFile); this.pw = new PrintWriter(new FileWriter(outFile)); if (skip) return; File file = new File(TEST_FILE); if (file.exists()) { br = new BufferedReader(new java.io.FileReader(TEST_FILE)); } else { br = new BufferedReader(new InputStreamReader(System.in), 1 << 16); } } void doit() throws NumberFormatException, IOException { int testsNumber = Integer.parseInt(br.readLine()); System.out.println(testsNumber); for (int i = 1; i <= testsNumber; i++) { StringTokenizer st = new StringTokenizer(br.readLine()); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); System.out.println(A + "" "" + B); int num = check(A, B); System.out.println(num); pw.println(""Case #"" + i + "": "" + num); } pw.flush(); pw.close(); } int check(final int A, final int B) { Set set = new HashSet(); for (int n = A; n < B; n++) { String str = Integer.toString(n); // ile rotacji: str.length - 1 int rotations = str.length() - 1; for (int j = 0; j < rotations; j++) { str = rotate(str); // skip numbers starting with 0: if (str.startsWith(""0"")) { continue; } // construct new number: int m = Integer.parseInt(str); // check: n < m if (!(n < m)) { continue; } // check m <= B if (m > B) { continue; } Pair pair = new Pair(n, m); set.add(pair); //System.out.println(n + "", "" + m); } //System.out.println(str); } return set.size(); } static String rotate(String str) { char ch = str.charAt(str.length() - 1); char[] arr = new char[1]; arr[0] = ch; return new String(arr).concat(str.substring(0, str.length() - 1)); } public static void main(String[] args) throws NumberFormatException, IOException { //System.out.println(rotate(""1"")); new Recycled(false).doit(); } } " B10426,"import java.io.File; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; public class B { public static void main(String ... args) throws Exception{ Scanner in = new Scanner(new File(""C-small-attempt0.in"")); PrintStream out = new PrintStream(new File(""C-small-attempt0.out"")); int T = in.nextInt(); in.nextLine(); for(int t=0;t set = new HashSet(); int found=0; for(int n=A;n<=B;n++){ int high=(int)Math.log10(B); String orgNumber = new Integer(n).toString(); do{ String num = orgNumber; for(int i=0;in && intNum<=B && !set.contains(n+"" ""+intNum)){ //System.out.println(n + "" "" + intNum); found++; set.add(n+"" ""+intNum); } } orgNumber = ""0"" + orgNumber; }while(orgNumber.length()<=high); } out.println(""Case #"" + (t+1) + "": "" + found); } } } " B12431,"import java.io.*; import java.util.*; public class C{ public static void main(String[] args){ try{ String inputFile = ""C-small-attempt0.in""; String outputFile = ""C-small-attempt0.out""; Scanner sc = new Scanner(new File(inputFile)); FileWriter fwStream = new FileWriter( outputFile ); BufferedWriter bwStream = new BufferedWriter( fwStream ); PrintWriter pwStream = new PrintWriter( bwStream ); int numCase = sc.nextInt(); for(int i = 0; i < numCase; i++){ int answer = 0; int min = sc.nextInt(); int max = sc.nextInt(); for(int j = min; j <= max; j++){ System.out.println(""inside j loop""); String a = String.valueOf(j); int length = a.length(); int temp = ((j % 10) * (int)(Math.pow(10,length-1))) + (j /10); while(temp != j){ System.out.println(""inside while temp loop""); System.out.println(""temp = "" + temp); System.out.println(""j = "" + j); if(temp >= min && temp <= max && temp > j){ answer++; } temp = ((temp % 10) * (int)(Math.pow(10,length-1))) + (temp /10); } } pwStream.print(""Case #""+(i+1)+ "": ""); pwStream.print(answer); pwStream.println(); } pwStream.close(); sc.close(); } catch(Exception e){e.printStackTrace();} } }" B12653,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ //package code_jam; import java.util.HashSet; import java.util.LinkedList; import java.util.Scanner; import java.util.Set; /** * * @author leonardo */ public class RecyclingNumbers { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int inputSize = Integer.parseInt(scanner.nextLine()); for (long i = 1; i <= inputSize; i++) { String[] input = scanner.nextLine().split("" "") ; /* No solution exists. */ if (input.length == 1) continue ; long a = Long.parseLong(input[0]) ; long b = Long.parseLong(input[1]) ; System.out.println(""Case #"" + i + "": "" + countRecyclablePairs(a, b)) ; } } private static long countRecyclablePairs(long a, long b) { if (a == b) return 0 ; long count = 0 ; for(long n = a; n <= b; n++) { LinkedList digits = toLinkedList(n) ; Set counted = new HashSet() ; for(int i = 0; i < digits.size(); i++) { digits.addFirst(digits.removeLast()) ; long m = toNumber(digits) ; if (! counted.contains(m) && n < m && m <= b) { counted.add(m) ; count++ ; } } } return count ; } private static LinkedList toLinkedList(long number) { LinkedList digits = new LinkedList() ; long remainer = 0 ; while(number >= 10) { remainer = number % 10 ; digits.addFirst(remainer); number = number / 10 ; } digits.addFirst(number) ; return digits ; } private static long toNumber(LinkedList digits) { long number = 0 ; int expoent = digits.size() - 1 ; for(long d : digits) { number += d * Math.pow(10, expoent) ; expoent-- ; } return number ; } } " B11962,"import java.util.Scanner; import java.util.Set; import java.util.TreeSet; /** * Created by IntelliJ IDEA. * User: Linkov Mikl * Date: 15.04.12 * Time: 3:15 * To change this template use File | Settings | File Templates. */ public class ProblemC { public static void main(String [] args) { Scanner scanner = new Scanner(System.in); int testCount = scanner.nextInt(); for (int i = 0; i < testCount; i++) { int left =scanner.nextInt(); int right = scanner.nextInt(); int answer = 0; for (int value = left; value < right + 1; value++) { String str = String.valueOf(value); StringBuilder build = new StringBuilder(str); Set set = new TreeSet(); for (int j = 1; j < str.length(); j++) { build.append(build.charAt(0)); build.delete(0, 1); if (build.charAt(0) == '0') { continue; } int v1 = Integer.parseInt(build.toString()); int v2 = Integer.parseInt(str); if ((v1 >= left) && (v1 <= right)) { if ((v1 > v2)) { if (!set.contains(v1)) { answer++; set.add(v1); } } } } } System.out.println(""Case #"" + (i + 1) + "": "" + answer); } } } " B11031,"package org.moriraaca.codejam; import java.io.File; import java.io.InputStream; import java.io.PrintStream; public abstract class AbstractSolver { protected final String RESOURCE_FOLDER = ""src/main/resources/""; /* Config */ protected final String defaultInputFileName; protected final OutputDestination outputDestination; protected final DebugOutputLevel debugOutputLevel; protected final Class dataParserClass; protected PrintStream output; protected PrintStream getOutput() { if (output == null) { try { switch (outputDestination) { case STDOUT: output = System.out; break; case FILE: output = new PrintStream(new File( defaultInputFileName.replaceAll(""\\.in"", ""\\.out""))); default: break; } } catch (Exception rethrow) { throw new Error(""Fatal error on initialization of output"", rethrow); } } return output; } public AbstractSolver() { try { SolverConfiguration config = getClass().getAnnotation( SolverConfiguration.class); debugOutputLevel = config.debugOutputLevel(); outputDestination = config.outputDestination(); defaultInputFileName = config.inputFileName(); dataParserClass = config.parser(); } catch (Exception log) { log.printStackTrace(); throw new Error(""Fatal error on initialization"", log); } } public void write(String msg, DebugOutputLevel level) { if (level.ordinal() <= debugOutputLevel.ordinal()) { getOutput().print(msg); } } public final String solve() { return solve(defaultInputFileName); } @SuppressWarnings(""unchecked"") public final String solve(String fileName) { try { AbstractDataParser dataParser = dataParserClass.getConstructor( InputStream.class).newInstance( getClass().getClassLoader().getResourceAsStream(fileName)); StringBuilder result = new StringBuilder(); for (int i = 0; i < dataParser.getTestCases().length; i++) { result.append(""Case #"") .append(i + 1) .append("": "") .append(solveTestCase((TC) dataParser.getTestCases()[i])) .append(""\n""); } return result.toString(); } catch (Exception e) { throw new Error(""Fatal error on solve"", e); } } public final void getSolution() { write(solve(), DebugOutputLevel.SOLUTION); } protected abstract String solveTestCase(TC testCase); } " B12400,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package inout; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; /** * * @author Hasier Rodriguez */ public final class In { private In() { } public static String[] read(String path, int mult) throws FileNotFoundException, IOException { System.out.println(""IN""); File f = new File(path); BufferedReader br = new BufferedReader(new FileReader(f)); String[] array = new String[Integer.parseInt(br.readLine()) * mult]; String s = br.readLine(); int i = 0; while (s != null) { array[i] = s; System.out.println(s); i++; s = br.readLine(); } System.out.println(); System.out.println(); br.close(); return array; } } " B10945,"import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; public class RecycledNumbers { public long getNumbers(int a, int b) { long ans = 0; for(int n = a; n < b; n++) { String nString = n + """"; ArrayList store = new ArrayList(); for(int i = 1; i < nString.length(); i++) { if(nString.charAt(i) == '0') continue; int m = Integer.parseInt(nString.substring(i) + nString.substring(0, i)); if(m > n && m <= b) { if(!store.contains(m)) { store.add(m); ans++; } } } } return ans; } } " B10423,"import java.io.*; import java.util.*; public class RecycledNumbers { public static void main(String[] args){ try{ Scanner scan = new Scanner(new File(""C:/personal/InterviewResource/GoogleCode2012/recycled/C-small-attempt0.in"")); BufferedWriter output = new BufferedWriter(new FileWriter(new File(""C:/personal/InterviewResource/GoogleCode2012/recycled/output.txt""))); boolean isFirstLine=true; int n =0; int linecount=0; while(scan.hasNextLine()){ if(isFirstLine){ isFirstLine=false; n= Integer.parseInt(scan.nextLine()); continue; } String line = scan.nextLine(); String[] vals = line.split("" ""); String result=""""; linecount++; output.write(""Case #""+Integer.toString(linecount)+"": ""+ getCount(Integer.parseInt(vals[0]), Integer.parseInt(vals[1]))); output.newLine(); } output.close(); System.out.println(""Done""); } catch(IOException e){ e.printStackTrace(); } } public static String getCount(int a, int b){ int count=0; TreeSet repeats = new TreeSet(); for(int i=a; i<=b; i++){ //int digits = getDigits(i); String astr = Integer.toString(i); int n = astr.length(); for(int j=1; jlimit || b<=a) return false; char[] Achar = A.toCharArray(); Arrays.sort(Achar); String Astr = new String(Achar); char[] Bchar = B.toCharArray(); Arrays.sort(Bchar); String Bstr = new String(Bchar); if(Astr.equals(Bstr)){ return true; } return false; } public static int getDigits(int x){ int res=0; while (x>0){ int z =x%10; if(z>0) res++; x=x/10; } return res; } } " B10576,"import java.io.BufferedReader; import java.io.FileReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.StringTokenizer; public class RecycledNumbers { public static void main(String[] args) throws Exception { int i,j,k; int A, B; int L; String first, second, secondNoLeadingZeros; int s; HashSet hs = new HashSet(); BufferedReader br = new BufferedReader(new FileReader(""C-small.in"")); PrintWriter out = new PrintWriter(""C-small.out""); StringTokenizer st; int T = Integer.parseInt(br.readLine()); int res; for (k=1;k<=T;k++) { st = new StringTokenizer(br.readLine()); A = Integer.parseInt(st.nextToken()); B = Integer.parseInt(st.nextToken()); L = Integer.toString(A).length(); res = 0; for (i=A;i<=B;i++) { first = Integer.toString(i); hs.clear(); hs.add(i); for (j=1;j= A)&&(s <= B)) { if (hs.contains(s) == false) { hs.add(s); res++; } } } } } res /= 2; out.println(""Case #""+k+"": ""+res); } out.close(); } } " B12136,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; public class recycle { public static void main(String[] args) { recycle rec = new recycle(); rec.readFile(""test.txt""); } public void readFile(String filename){ int i = 1; BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(filename)); } catch (FileNotFoundException e) { e.printStackTrace(); } String newLine; try { newLine = reader.readLine(); while ((newLine = reader.readLine()) != null) { evalline(newLine,i); i++; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void evalline(String line,int casenum){ Scanner sc = new Scanner(line); int n = sc.nextInt(); int m = sc.nextInt(); int tot = 0; System.out.print(""Case #"" + casenum + "": ""); for(int x = n; x < m; x++){ for(int y = x+1; y<= m; y++){ if(check(x,y)){ tot++; } } } System.out.println(tot); } public boolean check(int x, int y){ String str1 = Integer.toString(x); String str2 = Integer.toString(y); int len = str1.length(); for(int z = 0; z < len; z++){ int a = 0; int b = z; while(str1.charAt(a) == str2.charAt(b % len)){ a++; b++; if(z == (b % len)){ return true; } } } return false; } } " B11495,"package de.hg.codejam.tasks.numbers.help; public abstract class Converter { public static int[][] convert(String[] input) { int[][] output = new int[input.length][2]; for (int i = 0; i < input.length; i++) { String[] seperatedNumbers = input[i].split("" ""); output[i][0] = Integer.parseInt(seperatedNumbers[0]); output[i][1] = Integer.parseInt(seperatedNumbers[1]); } return output; } public static String[] convert(int[] input) { String[] output = new String[input.length]; for (int i = 0; i < input.length; i++) output[i] = String.valueOf(input[i]); return output; } } " B10023,"package problemC; import java.io.IOException; import java.util.HashSet; import java.util.LinkedList; import utils.InputReader; public class SolverC { public static void main(String[] args) throws IOException { LinkedList input = InputReader.read(""C:/Users/Danielle/Desktop/C-small-attempt0.in""); int num = Integer.parseInt(input.removeFirst()); int i = 1; for (String string : input) { if (i > num) { System.err.println(i+"">""+num); break; } HashSet map = new HashSet(); String[] split = string.split("" ""); int min = Integer.parseInt(split[0]); int max = Integer.parseInt(split[1]); for (int cur = min; cur < max; cur++){ String str = """"+cur; for (int k = 1; k < str.length(); k++){ int test = Integer.parseInt(str.substring(k)+str.substring(0, k)); if (test != cur && test >= min && test <= max) { map.add(new IntegerPair(test, cur)); } } } System.out.println(""Case #""+(i++)+"": ""+map.size()); } } private static class IntegerPair{ private final int i1, i2, hash; public IntegerPair(int i1, int i2) { this.i1 = i1; this.i2 = i2; hash = i1+i2; } @Override public int hashCode() { return hash; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj instanceof IntegerPair){ IntegerPair other = (IntegerPair) obj; return (other.i1 == i1 && other.i2 == i2) || (other.i2 == i1 && other.i1 == i2); } return false; } } } " B11498,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class Problem3 { public static String getNext(String input){ char last = input.charAt(input.length() - 1); input = last + input.substring(0, input.length()-1); return input; } public static void main(String[] args) throws IOException{ BufferedReader in = new BufferedReader(new FileReader(""C-small.txt"")); PrintWriter out = new PrintWriter(""C-out.txt""); int testCases = Integer.parseInt(in.readLine().trim()); for (int i = 0; i < testCases; i++) { StringTokenizer tokenizer = new StringTokenizer(in.readLine()); int start = Integer.parseInt(tokenizer.nextToken()); int end = Integer.parseInt(tokenizer.nextToken()); boolean map[] = new boolean[10000000]; int count = 0; for (int j = start; j <= end; j++) { if(map[j]){ continue; } String number = j + """"; int tmpCount = 0; Set set = new HashSet(); String prev = j + """"; for (int k = 0; k < number.length(); k++) { String nextS = getNext(prev); int next = Integer.parseInt(nextS); if(next == j){ continue; } if(set.contains(next)){ continue; } if(next >= start && next <= end){ map[next] = true; tmpCount++; set.add(next); } prev = nextS; } map[j] = true; if(tmpCount != 0){ count += (tmpCount*(tmpCount+1))/2; } } out.println(""Case #"" + (i+1) + "": "" + count); } out.close(); } } " B10175,"import java.util.*; import java.io.*; class Recycled_Numbers { public static void main(String arg []) { int check =-456; String m=""""; int counter =0; int calculate =0; String sub=""""; int mi =0; int ma=0; String path; String first,second; int numberOfLoops=0; Scanner read = new Scanner(System.in); System.out.println(""pls enter your file""); path = read.nextLine(); BufferedWriter bw; try { File fobj = new File(path); Scanner sc = new Scanner(fobj); bw =new BufferedWriter( new FileWriter(""RecycleOutput.txt"")); int tests = sc.nextInt() ,meter = 1; while (meter <= tests) { mi= sc.nextInt(); ma =sc.nextInt(); while(mi<=ma) { counter =0; m = mi+""""; while(counter mi)&&(Integer .parseInt(sub)<=ma)&&(Integer .parseInt(sub)!=check) ) { calculate++; check= Integer .parseInt(sub); } counter++; } mi++; } bw.write(""Case #""+meter+"": "" +calculate ); bw.newLine(); calculate =0; meter++; } bw.close(); }//end of try catch(IOException e) { System.out.println(e); } } }" B11713,"import java.util.Scanner; public class QuestionB extends Question{ private int N; private int S; private int p; private int[] dancers; public QuestionB(Result result, Counter counter) { super(result, counter); } @Override public void readInput(Scanner scanner) { N = scanner.nextInt(); S = scanner.nextInt(); p = scanner.nextInt(); dancers = new int[N]; for (int i = 0; i < N; i++) { dancers[i] = scanner.nextInt(); } } @Override public String solution() { int counter = 0; for (int i = 0; i < N; i++) { if (dancers[i]>=3*p-Math.min(2,dancers[i]*2)) counter++; else if (dancers[i]>=3*p-Math.min(4,dancers[i]*2) && S>0) { S--; counter++; } } return Integer.toString(counter); } } " B11909,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package probc; import java.io.*; import java.util.Scanner; import javax.swing.JOptionPane; /** * * @author nick */ public class ProbC { public static int numLines = 0; public static String[] dataLine; public static String[] outLine; public static void main(String[] args) throws UnsupportedEncodingException, IOException { // input //JOptionPane.showMessageDialog(null, ""This program provides a decrypter for Google's third CodeJam question: Recycled Numbers.""); getInput(); decode(); writeOutput(); } private static void getInput() throws FileNotFoundException { Scanner scanner = new Scanner(new FileInputStream(""input.txt"")); try { numLines = Integer.parseInt(scanner.nextLine()); dataLine = new String[numLines]; outLine = new String[numLines]; for (int i = 0; i < numLines; i++) { dataLine[i] = scanner.nextLine(); } } finally { scanner.close(); } } private static void writeOutput() throws UnsupportedEncodingException, FileNotFoundException, IOException { Writer out = new OutputStreamWriter(new FileOutputStream(""output.txt"")); try { String outText = """"; for (int i = 0; i < numLines; i++) { outText = outText + outLine[i] + ""\n""; } out.write(outText); } finally { out.close(); } } private static void decode() { for (int i = 0; i < numLines; i++) { Scanner sc = new Scanner(dataLine[i]); String numOneString = sc.next(); String numTwoString = sc.next(); sc.close(); int numOneInt = Integer.parseInt(numOneString); int numTwoInt = Integer.parseInt(numTwoString); int length = numOneString.length(); int setLength = numTwoInt - numOneInt; String tempString = """"; int tempInt = 0; int answer = 0; int[] answers = new int[numTwoInt]; tempInt = numOneInt; for (int ii = 0; ii < setLength; ii++) { tempString = """" + tempInt; for (int iii = 0; iii < length; iii++) { tempString = tempString.substring(1) + tempString.charAt(0); if (Integer.parseInt(tempString) >= tempInt & Integer.parseInt(tempString) <= numTwoInt) { if (Integer.parseInt(tempString) != tempInt) { answer++; } } } tempInt++; } outLine[i] = ""Case #"" + (i + 1) + "": "" + answer; } } } " B12945,"package lt.kasrud.gcj.ex3; import lt.kasrud.gcj.common.IO; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class Main { public static void main(String[] args) throws IOException { IO.Data data = IO.readFile(""C-small-attempt0.in""); IO.writeFile(""out3.txt"", process(data)); } private static List process(IO.Data data) { List result = new ArrayList(data.getInt(0, 0)); for(IO.Record r : data.getRecords(1)){ Integer c = calculate(r.getInt(0), r.getInt(1)); result.add(c); } return result; } private static Integer calculate(Integer a, Integer b) { int cnt = 0; Set ms = new HashSet(); for (int n=a; n<=b; n++){ ms.clear(); String ns = String.valueOf(n); for (int i = 1; i< ns.length(); i++){ int m = rotate(ns, i); if (m > n && m <= b){ ms.add(m); } } cnt += ms.size(); } return cnt; } private static int rotate(String ns, int i){ String ms = ns.substring(i, ns.length()) + ns.substring(0, i); return Integer.valueOf(ms); } } " B12880,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam.common; import java.util.ArrayList; import java.util.List; /** * * @author Lance Chen */ public class CodeHelper { private static String FILE_ROOT = ""D:/workspace/googlecodejam/meta""; public static List> loadInputsExcludes(String fileName) { List> result = new ArrayList>(); List lines = FileUtil.readLines(FILE_ROOT + fileName); int index = 0; for (String line : lines) { if (index == 0) { index++; continue; } if (index % 2 == 1) { index++; continue; } List dataList = new ArrayList(); String[] dataArray = line.split(""\\s+""); for (String data : dataArray) { if (data.trim().length() > 0) { dataList.add(data); } } result.add(dataList); index++; } return result; } public static List> loadInputs(String fileName) { List> result = new ArrayList>(); List lines = FileUtil.readLines(FILE_ROOT + fileName); for (String line : lines) { List dataList = new ArrayList(); String[] dataArray = line.split(""\\s+""); for (String data : dataArray) { if (data.trim().length() > 0) { dataList.add(data); } } result.add(dataList); } return result; } public static List loadInputLines(String fileName) { return FileUtil.readLines(FILE_ROOT + fileName); } public static void writeOutputs(String fileName, List lines) { FileUtil.writeLines(FILE_ROOT + fileName, lines); } } " B11598,"import java.io.*; import java.util.*; public class recycle{ static class pair{ int a,b; @Override public int hashCode(){ return a^b;} @Override public boolean equals(Object o){ pair p = (pair)o; return p.a == a && p.b == b; } } public static void main(String args[]) throws Exception{ Scanner s= new Scanner(System.in); int nu= s.nextInt(); s.nextLine(); int casen=1;while (nu-->0){ int A = s.nextInt(); int B = s.nextInt(); try{s.nextLine();}catch(Exception e){} Set pairs = new HashSet(); long num=0; for (int i= A; i <=B;i++){ int k=i; int digits = 0; int mult = 1; while (k>0){ digits++; k/=10; mult *= 10; } k=i; int sum = 0; int m2 = 1; while (k>0){ sum += m2*(k%10); boolean zero =k%10 == 0; mult/=10; k/=10; int a = i; int b = sum*mult+k; if (!zero && b >= A && b <= B && a!=b){ pair p = new pair(); p.a = b; p.b = i; if(!pairs.contains(p)) { p.a = i; p.b=b; if (!pairs.contains(p)){ num++;pairs.add(p); // System.out.println(p.a + ""-""+p.b); } } } m2*=10; } } System.out.println(""Case #""+casen++ +"": ""+ num); } } } " B12065,"import java.util.ArrayList; public class ClassificationRecycledNumbers { /** * @param args */ public static void main(String[] args) { // System.out.println(""Count:""+countRecycledPair(""1"",""200000"")); Integer[][] input = { {110,956}, {177,933}, {170,923}, {120,932}, {143,979}, {173,988}, {181,938}, {100,101}, {132,934}, {187,931}, {6,9}, {107,959}, {121,991}, {744,744}, {100,999}, {104,947}, {100,999}, {178,938}, {112,948}, {150,917}, {281,493}, {463,900}, {111,973}, {449,916}, {118,927}, {143,932}, {146,956}, {175,997}, {172,917}, {183,939}, {159,937}, {50,92}, {155,935}, {113,927}, {130,992}, {357,357}, {34,37}, {132,925}, {188,923}, {139,923}, {145,942}, {189,973}, {162,995}, {166,996}, {10,10}, {183,938}, {135,941}, {148,944}, {175,997}, {174,982} }; for (int i=0;i irpsArray =new ArrayList(); for (Integer m=n+1;m<=B&&m.toString().length()==n.toString().length();m++){ IsRecycledPair irp = new IsRecycledPair(n.toString(),m.toString()); irp.start(); irpsArray.add(irp); } boolean running=true; while(running){ running=false; for (IsRecycledPair irp:irpsArray){ if(irp.finished){ if (irp.isRecycledPair){ total++; irp.interrupt(); irp=null; Runtime r = Runtime.getRuntime(); r.gc(); } }else{ // System.out.println(""running""); running=true; break; } } } finished=true; irps=null; irpsArray=null; Runtime r = Runtime.getRuntime(); r.gc(); } } class IsRecycledPair extends Thread{ String n; String m; boolean finished=false; boolean isRecycledPair=false; public void run() { try { for (int i =0;i> 1); } public static int grayDecode (int g) { int n = 0; for (; g > 0; g>>=1) n ^= g; return n; } } " B13060,"package com.google.codejam.recycle; import java.io.FileReader; import java.io.IOException; import java.io.LineNumberReader; import java.util.LinkedList; import java.util.List; /** * Class to read input file and prepare list of test cases. * @author Sushant Deshpande */ public class InputReader { /** * Method for preparing List of Test Cases. * @param inputFilePath String * @return List */ public static List prepareTestCases(final String inputFilePath) { final List testCases = new LinkedList(); LineNumberReader lineReader = null; try { lineReader = new LineNumberReader(new FileReader(inputFilePath)); final String line = lineReader.readLine(); final int noOfTCs = Integer.parseInt(line); for(int i = 0; i < noOfTCs; i++) { String [] inputLine = lineReader.readLine().split("" ""); int low = Integer.parseInt(inputLine[0]); int high = Integer.parseInt(inputLine[1]); TestCase testCase = new TestCase(i + 1, low, high); testCases.add(testCase); } } catch(IOException ie) { System.out.println(""Problem occured while reading input file. "" + ie.getMessage()); } finally { if(lineReader != null) { try { lineReader.close(); } catch(IOException ie) { System.out.println(""Some problem occured while closing input file reader "" + ie.getMessage() ); } } } return testCases; } }" B12332,"import java.io.*; import java.util.HashSet; public class Solution { public static void main(String[] args) throws IOException { StreamTokenizer in = new StreamTokenizer(new BufferedReader (new FileReader(""input.in""))); PrintWriter out = new PrintWriter(new File(""output.out"")); in.nextToken(); int t = (int)in.nval; for (int i = 0; i set = new HashSet(); StringBuilder sN = new StringBuilder((new Integer(j)).toString()); for (int k = 0; k=a && m<=b && !set.contains(new Integer(m))) { ans++; set.add(m); } } } } out.println(ans); } out.close(); } } " B12605,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.PrintWriter; import java.util.Scanner; public class c_small { static int u,l,j,n,m=0,k; static int arr[]; public static void solve() throws Exception { PrintWriter out =new PrintWriter(new File(""c_small.out"")); Scanner sc =new Scanner(new File(""c_small.in"")); int testCase=sc.nextInt(); for (int i = 1; i <= testCase; i++) { int p; arr=new int[1000]; l=sc.nextInt(); u=sc.nextInt(); int res=0,r=0; for(j=l;j<=u;j++) { String j1=Integer.toString(j); //out.println(""j ""+j1); for(int x=((j1.length())-1);x>=1;x--) { for(p=0;p<1000;p++){ String c=j1.substring(x,(j1.length())); //out.println(""c ""+c); String a=c+(j1.substring(0,x)); //out.println(""a ""+a); int n=Integer.parseInt(a); for(k=l;k<=u;k++) { if((k!=j) && (k==n) && (n!=arr[p])) { arr[p]=n; res=res+1; break; } } } }} out.println(""Case #""+ i +"": ""+(res/2000)); } out.close(); } public static void main(String[] args) throws Exception { solve(); } } " B10662,"package com.google.codejam.qualification.recycled; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.StringTokenizer; public class RecycledNumbers { private static final List cases = new ArrayList(); public static void main(String[] args) throws NumberFormatException, IOException { // String file = ""src/resources/C-example""; String file = ""src/resources/C-small-attempt0""; // String file = ""src/resources/C-large""; readInFile(file + "".in""); FileWriter fstream = new FileWriter(file + "".out""); BufferedWriter out = new BufferedWriter(fstream); for (int i = 0; i < cases.size(); i++) { String msg = ""Case #"" + (i + 1) + "": "" + cases.get(i).getResult() + ""\n""; out.write(msg); System.out.print(msg); } out.close(); } protected static void readInFile(String path) throws NumberFormatException, IOException { DataInputStream in = new DataInputStream(new FileInputStream(path)); BufferedReader br = new BufferedReader(new InputStreamReader(in)); int lines = Integer.parseInt(br.readLine()); for (int i = 0; i < lines; i++) { cases.add(new Case(br.readLine())); } in.close(); } } class Case { int A, B; public Case(String line) { StringTokenizer tokenizer = new StringTokenizer(line); A = Integer.parseInt(tokenizer.nextToken()); B = Integer.parseInt(tokenizer.nextToken()); } protected int getResult() { int ctr = 0; System.out.print(""\\b[--""); for (int i = A; i < B; i++) { for (int j = i + 1; j <= B; j++) { if (isRecycledPair(String.valueOf(i), String.valueOf(j))) { ctr += 1; } } } return ctr; } boolean isRecycledPair(String n, String m) { if (n.length() != m.length()) { return false; } char[] narr = n.toCharArray(); Arrays.sort(narr); char[] marr = m.toCharArray(); Arrays.sort(marr); if (!new String(narr).equals(new String(marr))) { return false; } for (int displacement = 1; displacement < n.length(); displacement++) { boolean recycled = true; for (int i = 0; i < n.length(); i++) { if (n.charAt(i) != m.charAt(mod(i + displacement, n.length()))) { recycled = false; break; } } if (recycled) { // System.out.println("" "" + n + "" -> "" + m + "" : "" + displacement); return true; } } return false; } protected static int mod(int a, int b) { int r = a % b; if (r < 0) { r += b; } return r; } } " B10796,"import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashSet; public class Main { public static void main(String[] args) { Main main = new Main(); try { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); String line = bf.readLine(); int T = Integer.parseInt(line); for (int testcaseIndex=0; testcaseIndex set = new HashSet(); for (int num=A; num<=B; num++) { String numStr = String.valueOf(num); for (int i=1; i l) { int t = s; s = l; l = t; } small = s; large = l; } @Override public boolean equals(Object o) { if (o instanceof Pair) { Pair pair = (Pair)o; return this.small == pair.small && this.large == pair.large; } return false; } @Override public int hashCode() { return small * 23 + large; } } } " B13015,"import java.util.*; import java.io.*; public class codejam1{ public static void main(String [] args){ HashMap permuToPairs = new HashMap(); permuToPairs.put(1,0); permuToPairs.put(2,1); permuToPairs.put(3,3); permuToPairs.put(4,6); permuToPairs.put(5,10); permuToPairs.put(6,15); permuToPairs.put(7,21); //System.out.println(findRecycle(1111, 2222,permuToPairs)); int count = 1; try{ Scanner sc = new Scanner(new File(""C-small-attempt0.in"")); PrintStream ps = new PrintStream(new File(""OutputFile"")); sc.nextLine(); while (sc.hasNextLine()){ String line = sc.nextLine(); String[] numbers = line.split("" ""); long low = Long.parseLong(numbers[0]); long high = Long.parseLong(numbers[1]); String s = ""Case #""+count+"": "" + findRecycle(low, high,permuToPairs); if(sc.hasNextLine()){ s +=""\n""; } ps.print(s); count ++; } }catch(Exception e){ } } public static long findRecycle(long low, long high, HashMap permuToPairs){ Set numberSet = new HashSet(); String numberString = low+""""; int numWidth = numberString.length(); long count = 0; for(long i = low; i<= high; i++){ if(!numberSet.contains(i)){ numberSet.add(i); long permuNumber = i; int numPermus = 1; for(int j = 0; j < numWidth; j++){ // permute the number permuNumber = permuNumber % 10* (int)Math.pow(10, numWidth-1)+permuNumber/10; if(permuNumber >= low && permuNumber <= high && !numberSet.contains(permuNumber)){ numPermus++; numberSet.add(permuNumber); } } count += permuToPairs.get(numPermus); } } return count; } }" B11018,"package code.jam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class Main { public static void main(String[] args) { int T; try { BufferedReader in = new BufferedReader(new FileReader(""C-small-attempt0.in"")); PrintWriter out = new PrintWriter(new BufferedWriter( new FileWriter(""out""))); String strLine; String outLine; strLine = in.readLine(); T = Integer.valueOf(strLine); for (int i = 0; i < T; i++) { strLine = in.readLine(); String result = """"; String[] stringArray = strLine.split("" ""); // char[] charArray = strLine.toCharArray(); int A = Integer.valueOf(stringArray[0]); int B = Integer.valueOf(stringArray[1]); int count = 0; for (int j = A; j <= B; j++) { for (int k = j+1; k <= B; k++) { if(isRecycledNumber(j,k)) count++; } } outLine = ""Case #"" + (i + 1) + "": "" + count; out.println(outLine); } in.close(); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } private static boolean isRecycledNumber(int j, int k) { String jStr = String.valueOf(j); String newStr; for(int i=1;i firstIncluded = new ArrayList(); ArrayList secondIncluded = new ArrayList(); for (int currNum = a; currNum <= b; currNum++) { if (!firstIncluded.contains(currNum)) { boolean currNumAdded = false; String currNumString = currNum + """"; int digits = currNumString.length(); for (int x = 0; x < digits; x++) { currNumString = currNumString.substring(currNumString.length() - 1) + currNumString.substring(0, currNumString.length() - 1); int currNumCheck = Integer.parseInt(currNumString); if (currNumCheck >= a && currNumCheck <= b && !(firstIncluded.contains(currNum) && secondIncluded.get(firstIncluded.indexOf(currNum)).equals(currNumCheck)) && !(secondIncluded.contains(currNumCheck) && firstIncluded.get(secondIncluded.indexOf(currNumCheck)).equals(currNum)) && currNumCheck != currNum) { secondIncluded.add(currNumCheck); recycledPairs++; //if (!currNumAdded) //{ firstIncluded.add(currNum); // currNumAdded = true; // } // System.out.println(""("" + currNum + "", "" + currNumString + "")""); } /*else { if (currNumCheck >= a && currNumCheck <= b && currNumCheck != currNum) //&& !numsAlreadyIncluded.contains(currNumCheck) && currNumCheck != currNum) System.out.println(""("" + currNum + "", "" + currNumCheck + "")""); }*/ } } } recycledPairs /= 2; wr.write(""Case #"" + (i+1) + "": "" + recycledPairs); wr.newLine(); } wr.close(); } }" B10489,"import java.io.IOException; import java.io.OutputStreamWriter; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Formatter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Recycled { /** * @param args */ public static void main(String[] args) { Path path = Paths.get(args[0]); Path file = Paths.get(""recycled.txt""); int numberOfCases; try (Scanner scanner = new Scanner(Files.newInputStream(path), ""UTF-8""); OutputStreamWriter output = new OutputStreamWriter(Files.newOutputStream(file), ""UTF-8"")) { Formatter f = new Formatter(output); numberOfCases = scanner.nextInt(); for (int i = 1; i <= numberOfCases; i++) { int from = scanner.nextInt(); int to = scanner.nextInt(); int result = solve(from, to); f.format(""Case #%d: %d\n"", i, result); } f.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static int solve(int from, int to) { Set pairs = new HashSet<>(); for (int a = from; a < to; a++) { String n = Integer.toString(a); StringBuilder b; for (int i = 1; i < n.length(); i++) { b = new StringBuilder(n.substring(n.length()-i)); b.append(n.substring(0, n.length()-i)); String rec = b.toString(); if (rec.charAt(0) != '0') { int rev = Integer.parseInt(rec); if (rev > a && rev <= to) { pairs.add(new Pair(a, rev)); } } } } return pairs.size(); } private static class Pair { int first; int second; public Pair(int first, int second) { super(); this.first = first; this.second = second; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + first; result = prime * result + second; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (first != other.first) return false; if (second != other.second) return false; return true; } } } " B12357,"package gcj.main; import java.io.BufferedReader; import java.io.BufferedWriter; public interface Case { public void init(int caseNum, BufferedReader br) throws Exception; public void solve() throws Exception; public void generateOutput(BufferedWriter bw, boolean needBR) throws Exception; } " B12640,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.sql.Types; public class Recycled { /** * @param args * @throws IOException */ public static int calc(int a,int b) { int result = 0; int[] numbers = new int[b-a+1]; int ncircle = 0; int type=1; for (int i = a; i <= b; i++) { ncircle = 0; if(numbers[i-a]==0) { numbers[i-a]=type; ncircle = 1; int tmp=1; int n=0; while (i/tmp!=0) { tmp*=10; ++n; } --n; tmp /= 10; int cur =i; for (int j = n; j >0; --j) { int up = cur/10; int down = cur%10; cur = down * tmp + up; if(down!=0) { int shifted = cur; if((shifted>=a) && (shifted <=b)) { if(numbers[shifted-a]==0) { numbers[shifted-a]=type; ++ncircle; } } } } result += (ncircle)*(ncircle-1)/2; ++type; }else { } } return result; } public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in)); String number = bReader.readLine(); int num = Integer.parseInt(number); for (int i = 0; i < num; i++) { String s = bReader.readLine(); String[] strs = s.split("" ""); int A = Integer.parseInt(strs[0]); int B = Integer.parseInt(strs[1]); System.out.println(""Case #""+(i+1)+"": ""+calc(A, B)); } } } " B11992,"package jam.qualification; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; public class RecycledNumbers { public static void main(String[] args) { try { BufferedReader in = new BufferedReader(new FileReader(""file.in"")); BufferedWriter out = new BufferedWriter(new FileWriter(""file.out"")); int n = Integer.parseInt(in.readLine()); for (int i = 1; i <= n; ++i) { String[] ints = in.readLine().split("" ""); char[] A = ints[0].toCharArray(); char[] B = ints[1].toCharArray(); int c = 0; try { c = count(A, B); } catch (Exception e) { System.err.println(""Unexpected exception, I made a mistake...""); e.printStackTrace(); System.exit(1); } out.write(""Case #"" + i + "": "" + c); if (i != n) out.newLine(); out.flush(); } out.close(); } catch (Exception e) { System.err.println(""Error occured while reading input!""); e.printStackTrace(); System.exit(1); } } private static int count(char[] A, char[] B) { char[][] buff = new char[A.length][A.length]; int count = 0, ptr; do { ptr = 0; for (int n = 1; n < A.length; ++n) { swap(A, buff[ptr], n); if (compare(buff[ptr], A) > 0 && compare(buff[ptr], B) <= 0) { for (int i = 0; i < ptr; ++i) if (compare(buff[i], buff[ptr]) == 0) { --count; --ptr; break; } ++count; ++ptr; } } if (compare(A, B) >= 0) break; inc(A); } while (true); return count; } private static void swap(char[] src, char[] dst, int n) { System.arraycopy(src, 0, dst, n, src.length - n); System.arraycopy(src, src.length - n, dst, 0, n); } private static void inc(char[] N) { int i = N.length; while (N[--i] == '9') N[i] = '0'; ++N[i]; } private static int compare(char[] X, char[] Y) { for (int i = 0; i < X.length; ++i) if (X[i] < Y[i]) return -1; else if (X[i] > Y[i]) return 1; return 0; } } " B12805,"package codejam.y2012.r0; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * @author Ilya Lantuh */ public class Task3 { static Scanner input; static BufferedWriter output; public static void main(String[] args) throws Exception { input = new Scanner(new File(""D:/Programming/Projects/CodeJam/input.txt"")); output = new BufferedWriter(new FileWriter(""D:/Programming/Projects/CodeJam/output.txt"")); int T = input.nextInt(); for (int i = 1; i <= T; i++) { String result = getResult(); System.out.println(""Case #"" + i + "": "" + result); output.write(""Case #"" + i + "": "" + result); output.newLine(); } output.close(); } public static String getResult() { int A = input.nextInt(); int B = input.nextInt(); Set res = new HashSet(); for (int i = A; i < B; i++) { String num = String.valueOf(i); for (int j = 1; j < num.length(); j++) { int num2 = Integer.parseInt(getRecycled(num, j)); if (num2 > i && num2 <= B) { res.add(""("" + num + "", "" + num2 + "")""); } } } return String.valueOf(res.size()); } public static String getRecycled(String source, int digits) { String firstPart = source.substring(0, source.length() - digits); String secondPart = source.substring(source.length() - digits); return secondPart + firstPart; } } " B11366,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.StringTokenizer; public class Recycled { HashMap map; //key is the number, value is the sorted number in string form HashMap digits; //key is the number, value is the sorted number in string form public static void main(String[] arg) throws Exception { Recycled pg = new Recycled(); pg.init(); pg.go(); } Recycled() { map = new HashMap(); digits = new HashMap(); } private void init() { int arr[] = {0,0,0,0,0,0,0,0,0,0}; int rem; StringBuilder str = new StringBuilder(); int i; int digits; for(int no = 1 ; no <= 2000000; no++) { i = no; digits = 0; while(i > 0) { rem = i % 10; arr[rem]++; i = i / 10; digits++; } str.delete(0, str.length()); for(int j = 0; j < arr.length; j++) { while(arr[j] > 0) { str.append(j); arr[j]--; } } map.put(no, str.toString()); this.digits.put(no, digits); //reset the array } //System.out.println(""Done initialization""); } public void go() { String line = """"; try { BufferedReader in = new BufferedReader(new FileReader(""C-small-attempt0.in"")); StringBuilder outString = new StringBuilder(); StringTokenizer tokens; int caseNo = 0; int T = Integer.parseInt(in.readLine().trim()); int A,B, high; String s1, s2; int count; while(caseNo++ < T) { line = in.readLine().trim(); tokens = new StringTokenizer(line); A = Integer.parseInt(tokens.nextToken().trim()); B = Integer.parseInt(tokens.nextToken().trim()); count = 0; for(int n = A; n < B; n++) { high = (int)Math.pow(10,digits.get(n)) - 1; high = Math.min(high, B); for(int m = n + 1; m <= high; m++) { s1 = map.get(n); s2 = map.get(m); if(!s1.equals(s2)) continue; if((n + """" + n).indexOf(m+"""") != -1) { count++; // System.out.println("" Pairs ("" +n + "" "" +m + "")""); } } } outString.append(""Case #"" + caseNo + "": "" +count ); outString.append(""\n""); } BufferedWriter pwr = new BufferedWriter(new FileWriter(""output.txt"")); pwr.write(outString.toString()); pwr.close(); in.close(); } catch (Exception e) { e.printStackTrace(); System.out.println(""processing : "" + line); } } } " B10981,"import java.util.Scanner; public class Recycle { /** * @param args */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int cases = Integer.parseInt(sc.nextLine()); for(int i = 0; i < cases; i++) { Scanner line = new Scanner(sc.nextLine()); int A = line.nextInt(); int B = line.nextInt(); int k = Integer.toString(A).length(); int fac = (int) (Math.pow(10, k-1)); IntSet set = new IntSet(k); int pairCount = 0; for(int n = A; n < B; n++) { set.clear(); int m = n; for(int j = 0; j < k-1; j++) { int mod = m % 10; m = m / 10; m = m + (fac * mod); if(m <= B && m > n) { //if not already there if(!set.insert(m)) { pairCount++; } } } } System.out.printf(""Case #%d: %d\n"", i+1, pairCount); } } } class IntSet { int[] ints; int ctr = 0; public IntSet(int k) { ints = new int[k]; ctr = 0; } public boolean contains(int x) { for(int i = 0; i < ctr; i++) { if(ints[i] == x) { return true; } } return false; } //true if x already contained public boolean insert(int x) { if(contains(x)) { return true; } ints[ctr] = x; ctr++; return false; } public void clear() { ctr = 0; } }" B10867,"import java.util.*; import static java.lang.System.*; class C{ static public void main(String[] args){ Scanner sc = new Scanner(System.in); int cases = Integer.parseInt(sc.nextLine()); for(int c = 1; c<=cases; c++){ String[] s = sc.nextLine().split("" ""); int a = Integer.parseInt(s[0]); int b = Integer.parseInt(s[1]); int l = s[0].length(); int cnt = 0; for(int i = a; i set = new HashSet(); for(int pos = 1; posi && newn<=b){ set.add(newn); } } cnt+=set.size(); } out.println(""Case #""+c+"": ""+cnt); } } }" B10594,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.StringTokenizer; /** * * @author parusnik */ public class Codejam { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader(""input.txt"")); BufferedWriter bw = new BufferedWriter(new FileWriter(""output.txt"")); int T = Integer.parseInt(br.readLine()); StringTokenizer st; String s; for (int t = 1; t<=T; t++){ bw.write(""Case #"" + String.valueOf(t) + "": ""); st = new StringTokenizer(br.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); long d = 0; for (int i = a; i<=b; i++) for (int j = i+1; j<=b; j++){ String s1 = String.valueOf(i); String s2 = String.valueOf(j); for (int k = 0; k<10; k++){ if (s1.equals(s2)) {d++; break;} s2 = s2.substring(1, s2.length()) + s2.substring(0, 1); } } bw.write(String.valueOf(d)); bw.newLine(); } br.close(); bw.close(); } } " B11860,"/** * */ package org.mikeyin; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; /** * @author yincrash * */ public class RecycledNumbers { // from stackoverflow, exponentiation by squaring public static int ipow(int base, int exp) { int result = 1; while (exp != 0) { if ((exp & 1) != 0) result *= base; exp >>= 1; base *= base; } return result; } /** * @param args */ public static void main(String[] args) { try { Scanner file = new Scanner(new File(args[0])); int testCases = file.nextInt(); file.nextLine(); int currentCase = 1; final PrintStream ps = new PrintStream(new File(""numbers.out"")); while (currentCase <= testCases) { final int a = file.nextInt(); final int b = file.nextInt(); ps.append(""Case #"").print(currentCase); ps.append("": ""); ps.println(numRecycled(a, b)); currentCase++; } } catch (FileNotFoundException e) { e.printStackTrace(); } } private static class Pair { private int n,m; public Pair(int n, int m) { this.n = n; this.m = m; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + m; result = prime * result + n; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (m != other.m) return false; if (n != other.n) return false; return true; } @Override public String toString() { return new StringBuilder(""("").append(n).append(',').append(m).append(')').toString(); } } private static int numRecycled(int a, int b) { HashSet recycledPairs = new HashSet(); for (int i = a; i < b; i++) { int numDigits = (int) (Math.floor(Math.log10(i))) + 1; int current = i; for (int j = 0; j < numDigits - 1; j++) { int digit = current % 10; current = current / 10 + (digit * ipow(10, (numDigits - 1))); if (current > i && current <= b) recycledPairs.add(new Pair(i, current)); } } return recycledPairs.size(); } } " B10198,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package javaapplication3; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.Writer; import java.util.Scanner; /** * * @author yondaime */ public class JavaApplication3 { static int A = 1111; static int B = 2222; public static int[] permute(int n) { String chaine = n + """"; int tailleChaine = chaine.length(); int nombre; String g = """"; for (int i = 0; i < tailleChaine; i++) { g += ""1""; } nombre = Integer.parseInt(g); if (chaine.length() < 1 || n % nombre == 0) { int[] t = new int[1]; t[0] = n; return t; } int table[] = new int[10]; for (int i = 0; i < tailleChaine - 1; i++) { String t = """"; t = chaine.substring(i + 1); t += chaine.substring(0, i + 1); int m = Integer.parseInt(t); if (m > n && n >= A && m <= B) { table[i] = m; // System.out.println(table[i]); } } // System.out.println(""end""); // int m = Integer.parseInt(chaine); return table; } static int count; public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(new File(""C-small-attempt1.in"")); PrintWriter out = new PrintWriter(new File(""C-small-attempt1.out"")); sc.next(); int kl=0; while (sc.hasNext()) { A = sc.nextInt(); B = sc.nextInt(); out.print(""Case #""+(++kl)+"":""); // out.print("" ""+B); for (int n = A; n < B; n++) { int mm[] = permute(n); for (int k = 0; k < mm.length; k++) { int m = mm[k]; // n doit etre < à m //n doit etre > à A et m doit etre inferieur à B // A <= n < m <= B if (n >= m || A > n || m > B) { continue; } count++; // out.print(""n = "" + n + "" m = "" + m); } } out.println("" "" + count); count=0; } out.close(); sc.close(); } } " B12384,"package recycledNumbers; import java.io.*; import java.util.*; public class Entry { private static ArrayList cases=new ArrayList(); public static void main(String args[]) throws IOException { FileReader src=new FileReader(""test.txt""); FileWriter f=new FileWriter(""output.txt""); BufferedWriter out=new BufferedWriter(f); Scanner in=new Scanner(src); int iterate=in.nextInt(); int i,j; int A,B; int n,m; HashSet dub=new HashSet(); for(i=0;i= p && y>=A && y<=B) { was[y] = true; count++; } x = y; } ans += count * (count - 1) / 2; } } public void solve_gcj() throws Exception { int tests = iread(); for (int test = 1; test <= tests; test++) { out.write(""Case #"" + test + "": ""); solve(iread(), iread()); out.write(ans + ""\n""); } } public void run() { try { // in = new BufferedReader(new InputStreamReader(System.in)); // out = new BufferedWriter(new OutputStreamWriter(System.out)); in = new BufferedReader(new FileReader(filename + "".in"")); out = new BufferedWriter(new FileWriter(filename + "".out"")); solve_gcj(); out.flush(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } public int iread() throws Exception { return Integer.parseInt(readword()); } public double dread() throws Exception { return Double.parseDouble(readword()); } public long lread() throws Exception { return Long.parseLong(readword()); } BufferedReader in; BufferedWriter out; public String readword() throws IOException { StringBuilder b = new StringBuilder(); int c; c = in.read(); while (c >= 0 && c <= ' ') c = in.read(); if (c < 0) return """"; while (c > ' ') { b.append((char) c); c = in.read(); } return b.toString(); } public static void main(String[] args) { try { Locale.setDefault(Locale.US); } catch (Exception e) { } new Thread(new Main()).start(); // new Thread(null, new Main(), ""1"", 1<<25).start(); } }" B12410,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejamproblem2; import java.util.Scanner; import sun.tools.jar.resources.jar; /** * * @author khalid */ public class CodeJamProblem2 { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here CodeJamProblem2 jam=new CodeJamProblem2(); jam.solve(); } public void solve() { Scanner in=new Scanner(System.in); int count=in.nextInt(); in.nextLine(); String res=""""; int numOfRe; for(int i=1;i<=count;i++) { numOfRe=numOfRecycled(in.nextInt(),in.nextInt()); res+=""Case #""+i+"": ""+numOfRe+""\n""; } System.out.print(res); } public int numOfRecycled(int a,int b) { int counter=0; for(int i=a;ii;c--) if(isRecycled(i+"""", c+"""")) counter++; } return counter; } public boolean isRecycled(String num1,String num2) { if(num1==null||num2==null) return false; if(num1.length()!=num2.length()) return false; String tmp; int leftStart;//,leftEnd; int rightStart,rightEnd; leftStart=0; rightEnd=num1.length(); for(int i=0;i valFound = new HashMap(); for(int j=0;j> map; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader(new File(""/Users/atai/Play/Codejam/input.txt""))); PrintWriter prn = new PrintWriter(new FileWriter(""output.txt"")); int numTests = Integer.parseInt(br.readLine().trim()); for (int i = 0; i < numTests; i++) { String[] arg = br.readLine().trim().split("" ""); int min = Integer.parseInt(arg[0]); int max = Integer.parseInt(arg[1]); int total = 0; map = new HashMap>(); for (int j = min; j <= max; j++) { // for each number check to see how many pairs there are Integer rand = new Integer(j); int len = rand.toString().length(); int stock = (int)Math.pow(10,len); for (int k = 0; k < len-1; k++) { int c = (int)Math.pow(10,k+1); int r = j % c; if (r == 0) continue; // leading zero? if (r < (int)Math.pow(10,k)) continue; int recycle = (j+stock*r)/c; if ((recycle > j) && (recycle <= max)) { System.out.println(j + "", "" + recycle); if (map.containsKey(j)) { if (map.get(j).add(recycle)) total++; } else { HashSet temp = new HashSet(); temp.add(recycle); map.put(j, temp); total++; } } } } prn.printf(""Case #%d: %d\n"", i+1, total); } prn.close(); } } " B11013,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; public class ProblemC { /** * @param args */ public static void main(String[] args) { BufferedReader br = null; BufferedWriter bw = null; String input = null; StringBuffer output = null; String[] twonumbers = null; int min = 0, max = 0; ArrayList list = null; String temp = null; String strmin = """"; int tempint = 0; int counter = 0; int digit1 = 0, digit2 = 0; try { br = new BufferedReader(new FileReader(new File( ""C:/Users/DHAVAL/Downloads/Input1.txt""))); bw = new BufferedWriter(new FileWriter(""output1.txt"")); int count = Integer.parseInt(br.readLine()); for (int i = 0; i < count; i++) { input = br.readLine(); output = new StringBuffer(""Case #"" + (i + 1) + "": ""); counter=0; // logic here list = new ArrayList(); twonumbers = input.split("" ""); min = Integer.parseInt(twonumbers[0]); max = Integer.parseInt(twonumbers[1]); if (max >= 10) { for (int j = min; j <= max; j++) { strmin = """" + j; temp = strmin; for (int k = 0; k < strmin.length() - 1; k++) { temp = temp.substring(1) + temp.charAt(0); tempint = Integer.parseInt(temp); digit1 = ("""" + tempint).length(); digit2 = strmin.length(); if (j < tempint && digit1 == digit2 && tempint >= min && tempint <= max && !list.contains(strmin + ""||"" + temp) && !temp.equals(strmin)) { //System.out.println(strmin + "" "" + tempint); // list.add(temp); list.add(strmin + ""||"" + temp); counter++; } } } } bw.write(output.toString() + counter); bw.newLine(); } bw.close(); } catch (Exception e) { e.printStackTrace(); } } } " B12932,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package google_code_jam; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.lang.reflect.Array; import java.util.HashSet; import java.util.LinkedList; import java.util.StringTokenizer; /** * * @author lenovo */ public class C { public static void main(String[] args) throws IOException { // TODO code application logic here BufferedReader br = new BufferedReader(new FileReader(""C-small-attempt1.in"")); PrintWriter pw = new PrintWriter(""C.out"" ); StringTokenizer st=new StringTokenizer(br.readLine()); // System.out.println(st); int x = Integer.parseInt(st.nextToken()); a1:for (int i = 0; i < x; i++) { st = new StringTokenizer(br.readLine()); int min = Integer.parseInt(st.nextToken());// number of players int max = Integer.parseInt(st.nextToken());//number of surprising int res = solve(min , max); pw.append(""Case #""+(i+1)+"": ""+res+""\n""); } pw.close(); } public static int solve(int a , int b){ int count=0; int x ,y; for (int i = a; i < b; i++) { String item=i+""""; int len=item.length(); x=i; HashSet hs = new HashSet(); for (int j = 0; j < len; j++) { y=x%10; y=y*(int)(Math.pow(10, len-1))+(x/10); if( y<=b && y>i ){ if(hs.add(y)) count++; } x=y; } } return count; } } " B10029,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.StringTokenizer; public class RecycledNumbers { public static int calcRecycled(int A, int B) { int total = 0; for(int i = 0; i < B-A+1; i++) { int[] temp = getCycles(i+A); for(int x: temp) { if(x == -1) continue; if(x <= i+A) continue; if(x <= B && x >= A) { total++; } } } return total; } public static int[] getCycles(int init) { String s = init+""""; int[] array = new int[s.length()-1]; for(int i = 0; i < s.length()-1; i++) { if(s.charAt(i+1) == '0') array[i] = -1; else { int temp = Integer.parseInt(s.substring(i+1) + s.substring(0, i+1)); for(int j = 0; j < i; j++) { if(array[j] == temp) { temp = -1; break; } } array[i] = temp; } } return array; } public static void main(String[] args) throws IOException { BufferedReader read = new BufferedReader(new FileReader(""C-small-attempt0.in.txt"")); int T = Integer.parseInt(read.readLine()); for(int i = 1; i <= T; i++){ StringTokenizer st = new StringTokenizer(read.readLine()); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); System.out.println(""Case #"" + i + "": "" + calcRecycled(A, B)); } } } " B10079,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; import java.util.StringTokenizer; public class G2 { private Scanner reader; private FileWriter fstream; private BufferedWriter out; String nextline; int noLines; int intA; int intB; int lineIndex=1; int value=0; public boolean isValid(int n,int m) { return (!(n==m)&&(intA<=n)&&(n rst=new ArrayList(); try { data=read(file_in); } catch (IOException e) { e.printStackTrace(); } int cases=pInt(0); data.remove(0); int count=1; for(String s:data){ int tot=0; ArrayList arr=splitInt(s,"" ""); int min=arr.get(0); int max=arr.get(1); for(int i=min;i<=max;i++){ tot+=cycles(i,min,max); } tot=tot/2; rst.add(""Case #""+count+"": ""+tot); count++; } try { write(file_out,rst); } catch (IOException e) { e.printStackTrace(); } } public int cycles(int val,int min,int max){ String s=val+""""; Set ints=new HashSet(); for(int i=0;i=min&&val2<=max){ ints.add(val2); } } } return ints.size()-1; } public String shift(String s){ return s.substring(1)+s.substring(0,1); } } class Question{ String file_in; String file_out; ArrayList data; public Question(String in,String out){ file_in=in; file_out=out; try { data=read(file_in); } catch (IOException e) { e.printStackTrace(); } } public void solve(){} public int pInt(int index){ return Integer.parseInt(data.get(index)); } public int pInt(String s){ return Integer.parseInt(s); } public ArrayList splitString(String s,String sep){ ArrayList arr=new ArrayList(); String[] ss=s.split(sep); for(int i=0;i splitInt(String s,String sep){ ArrayList arr=new ArrayList(); String[] ss=s.split(sep); for(int i=0;i splitString(int index,String sep){ return splitString(data.get(index), sep); } public ArrayList splitInt(int index,String sep){ return splitInt(data.get(index), sep); } public ArrayList read(String filename) throws IOException{ ArrayList arr=new ArrayList(); BufferedReader br=null; br=new BufferedReader(new FileReader(filename)); String l=null; while((l=br.readLine())!=null){ arr.add(l); } br.close(); return arr; } public void write(String filename,ArrayList data) throws IOException{ PrintWriter pw=new PrintWriter(filename); for(String s:data){ pw.println(s); } pw.close(); } } public class Answer3 { public static void main(String[] args){ Question a=new Recycle(""C-small-attempt0.in"",""rst.txt""); a.solve(); } } " B10639,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.HashSet; import java.util.Set; public class GCJ3 { public static int pow(int num, int p) { int n = 1; while (p > 0) { p--; n *= num; } return n; } public static int exp(int num) { int e = 0; while (num > 0) { e++; num /= 10; } return e; } public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new FileReader(new File(""input.txt""))); BufferedWriter bw = new BufferedWriter(new FileWriter(new File(""output.txt""))); String firstLine = br.readLine(); int lineNum = Integer.parseInt(firstLine); for (int i=0; i set = new HashSet(); String line = br.readLine(); String[] segs = line.split("" ""); int a = Integer.parseInt(segs[0]); int b = Integer.parseInt(segs[1]); int result = 0; int exp = exp(a); long off = (long)(b+1); for (int num=a; num num && recycle <= b) { if (set.contains(off*num+recycle)) { } else { set.add(off*num+recycle); result++; } } } } bw.write(""Case #"" + (i+1) + "": "" + result); if (i != (lineNum-1)) bw.newLine(); } bw.flush(); bw.close(); } catch (Exception e) { e.printStackTrace(); } } } " B11459,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; public class MainImpl { public static int numberOfLines; public static int firstNumber; public static int secondNumber; public static ArrayList eachLine = new ArrayList(); public static void main(String[] args) { readFile(); for (int i = 1; i<= numberOfLines ; i++) { findSets(eachLine.get(i - 1), i); } System.out.print(""Done with conversion""); } public static void findSets(String line, int index) { StringBuffer buffer = new StringBuffer(); buffer.append(""Case #"").append(index).append("": ""); int totalUniqueCases = 0; String[] numbers = line.split("" ""); String firstNumberString = numbers[0]; String secondNumberString = numbers[0]; firstNumber = Integer.parseInt(numbers[0]); secondNumber = Integer.parseInt(numbers[1]); if (firstNumber > secondNumber) { buffer.append(String.valueOf(totalUniqueCases)); writeToFile(buffer.toString()); return; } if (firstNumberString.length() == 1 && (secondNumberString.length() == 1)) { buffer.append(String.valueOf(totalUniqueCases)); writeToFile(buffer.toString()); return; } int numberBeingConsidered = firstNumber; int totalNumberOfSets = 0; while (numberBeingConsidered <= secondNumber) { totalNumberOfSets = totalNumberOfSets + findPermutations(numberBeingConsidered); numberBeingConsidered++; } buffer.append(String.valueOf(totalNumberOfSets)); writeToFile(buffer.toString()); } public static int findPermutations(int numberBeingConsidered) { int validPermutations = 0; String numberBeingConsideredString = String.valueOf(numberBeingConsidered); ArrayList possiblePermutaions = new ArrayList(); for (int i = numberBeingConsideredString.length() - 1; i>=1; i--) { String permutationString = numberBeingConsideredString.substring(i) + numberBeingConsideredString.substring(0, i); if (!numberBeingConsideredString.equals(permutationString) && (!possiblePermutaions.contains(permutationString))) { int permutationNumber = Integer.parseInt(permutationString); if ((firstNumber <= numberBeingConsidered) && (numberBeingConsidered < permutationNumber) && (permutationNumber <= secondNumber)) { validPermutations++; possiblePermutaions.add(permutationString); } } } return validPermutations; } public static void readFile() { try { FileInputStream fstream = new FileInputStream(""src/input.txt""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; numberOfLines = Integer.parseInt(br.readLine()); while ((strLine = br.readLine()) != null) { eachLine.add(strLine); } in.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } public static void writeToFile(String line) { try { BufferedWriter bw = new BufferedWriter(new FileWriter(new File( ""src/output.txt""), true)); bw.write(line); bw.newLine(); bw.close(); } catch (Exception e) { System.out.println(""Error occured "" + e); } } } " B11851,"package googlecodejam; import java.io.*; /** * * @author $Ruslan */ public class Recycled_numbers { private static FileInputStream fileInputStream; private static int testCaseNumber = -1; public static void main(String[] args) { String filepath = ""D:\\Programming\\NetBeansProjects\\"" + """" + ""GoogleCodeJam\\src\\googlecodejam\\C-small-attempt0.in""; try{ if (args[0] != """") { filepath = args[0]; } } catch (Exception e) { } try{ fileInputStream = new FileInputStream(filepath); readInput(); } catch (Exception e) { System.err.println(""Exception: "" + e.getMessage()); } } private static void readInput() { try { String str; DataInputStream in = new DataInputStream(fileInputStream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); str = br.readLine(); testCaseNumber = Integer.parseInt(str); System.out.println(testCaseNumber); for (int i = 0; i < testCaseNumber; i++) { System.out.print(""Case #""+(i+1)+"":""); str = br.readLine(); //calculate(str); //do smt!!!! recycleNumbers(str); } in.close(); } catch (IOException | NumberFormatException e) { System.err.println(""Exception: "" + e.getMessage()); } } private static void recycleNumbers(String str) { //with A ≤ n < m ≤ B String[] splitedStr = str.split("" ""); int start_num = Integer.parseInt(splitedStr[0]); int end_num = Integer.parseInt(splitedStr[1]); int answer = 0; int reversedNum = -1; int positions = -1; int rest_right = -1; int rest_left = -1; if (start_num < 10) { start_num = 12; } for (int i = start_num; i < end_num; i++) { //PIZDEC positions = 0; reversedNum = i; while (reversedNum > 0) { reversedNum /= 10; positions++; } for (int k = 1; k < positions; k++) { //Ex: 7487 //k = 2; //rest_right = 87; //rest_left = 74; //if rest_right > rest_left then we can move it //otherwise it's gonna be less the the current num //and so on with each k rest_right = i % pow(10,k); //right part of the num rest_left = i / pow(10, (positions-k)); //left part of the num if (rest_right >= rest_left) { reversedNum = reverseNumber(i, k, positions); if ((reversedNum > i) && (reversedNum <= end_num)) { answer++; } } } } System.out.println("" "" + answer); } private static int reverseNumber(int number, int places, int positions) { int res = number % pow(10, places); number /= pow(10, places); res *= pow(10, (positions-places)); res += number; return res; } private static int pow(int num, int pow) { int result = num; for (int i = 1; i < pow; i++) { result *= num; } return result; } } " B10166,"import java.io.*; import java.io.InputStreamReader; import java.util.*; public class b { static TreeSet set; static boolean[][] matriz; static int cantidad; public static void main(String[] args) throws Throwable { BufferedReader bf = new BufferedReader(new FileReader(""b.txt"")); System.setOut(new PrintStream(""b.out"")); int casos = Integer.parseInt(bf.readLine()); for (int i = 0; i < casos; i++) { StringTokenizer st = new StringTokenizer(bf.readLine()); matriz = new boolean[1001][1001]; cantidad = 0; set=new TreeSet(new Comparator(){ public int compare(int[] arg0, int[] arg1) { return 0; } }); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); int min = Math.min(a, b); int max = Math.max(a, b); for (int j = min; j <= max; j++) { calcular(j, min, max); } System.out.println(""Case #""+(i+1)+"": ""+cantidad); } } private static void calcular(int a , int min , int max) { String n = a+""""; for (int i = 1; i < n.length(); i++) { String copia = n.substring(i)+n.substring(0,i); int c = Integer.parseInt(copia); String c2 = c+""""; if(c!=a&& c2.length()==n.length() && min <= c && c <= max ){ if( !matriz[a][c] ){ matriz[a][c] = true; matriz[c][a] = true; cantidad++; } } } } } " B12938,"package com.menzus.gcj._2012.qualification.c; import com.menzus.gcj.common.Processor; public class CMain { private static String SMALL_FILE_NAME = ""src/main/resources/com/menzus/gcj/_2012/qualification/c/C-small-attempt0.in.txt""; public static void main(String[] args) throws Exception { Processor smallFileProcessor = new CProcessorFactory(SMALL_FILE_NAME).createProcessor(); smallFileProcessor.process(); System.out.println(""done.""); } } " B10543,"import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.Writer; import java.util.HashMap; import java.util.HashSet; public class Googlerecycle { public static void main (String[] args) { FileReader fr = null; BufferedReader br = null; Writer out = null; Writer debug = null; try { fr = new FileReader(args[0]); br = new BufferedReader(fr); out = new OutputStreamWriter(new FileOutputStream(""googlerecycle-result.txt"")); debug = new OutputStreamWriter(new FileOutputStream(""googlerecycle-debug.txt"")); String numOfLine = br.readLine(); int line = 0; if (numOfLine != null) { line = Integer.valueOf(numOfLine); } else { return; } String lineData; String[] recycleArray; for (int i = 1; i <= line; i++) { HashMap> resultMap = new HashMap>(); String resultLine = """"; int recycledCounter = 0; lineData = br.readLine(); recycleArray = lineData.split("" ""); if (recycleArray[1].length() != 1) { int lowerLimit = Integer.valueOf(recycleArray[0]); int upperLimit = Integer.valueOf(recycleArray[1]); String iterator; for (int j = lowerLimit; j <= upperLimit; j++) { iterator = String.valueOf(j); String doubleLower = iterator + iterator; String iteratorCycled; int iteratorLength = iterator.length(); for (int k = 1; k < iteratorLength; k++) { iteratorCycled = doubleLower.substring(k, k + iteratorLength); if (!iteratorCycled.startsWith(""0"") && (!iteratorCycled.equals(iterator))) { int recycled = Integer.valueOf(iteratorCycled); if (recycled <= upperLimit && recycled >= lowerLimit) { if (!resultMap.isEmpty()) { if (resultMap.containsKey(iteratorCycled)) { HashSet resultSet = resultMap.get(iteratorCycled); if (resultSet.contains(iterator)) { debug.write(""already exist pair: "" + iterator + "", "" + iteratorCycled + ""\n""); } else { if (resultMap.containsKey(iterator)){ HashSet resultSet2 = resultMap.get(iterator); if (!resultSet2.contains(iteratorCycled)) { recycledCounter++; debug.write(iterator + "", "" + iteratorCycled + ""\n""); resultSet2.add(iteratorCycled); resultMap.put(iterator, resultSet2); } else { debug.write(""already exist exact pair: "" + iterator + "", "" + iteratorCycled + ""\n""); } } else { recycledCounter++; debug.write(iterator + "", "" + iteratorCycled + ""\n""); HashSet resultSet2 = new HashSet(); resultSet2.add(iteratorCycled); resultMap.put(iterator, resultSet2); } } } else { if (resultMap.containsKey(iterator)){ HashSet resultSet = resultMap.get(iterator); if (!resultSet.contains(iteratorCycled)) { recycledCounter++; debug.write(iterator + "", "" + iteratorCycled + ""\n""); resultSet.add(iteratorCycled); resultMap.put(iterator, resultSet); } else { debug.write(""already exist exact pair: "" + iterator + "", "" + iteratorCycled + ""\n""); } } else { recycledCounter++; debug.write(iterator + "", "" + iteratorCycled + ""\n""); HashSet resultSet = new HashSet(); resultSet.add(iteratorCycled); resultMap.put(iterator, resultSet); } } } else { recycledCounter++; debug.write(iterator + "", "" + iteratorCycled + ""\n""); HashSet resultSet = new HashSet(); resultSet.add(iteratorCycled); resultMap.put(iterator, resultSet); } } } else { debug.write(""not valid recycled: "" + iterator + "", "" + iteratorCycled + ""\n""); } } } } debug.write(""\n""); resultLine = ""Case #"" + i + "": "" + recycledCounter; out.write(resultLine); if (i != line) { out.write(""\n""); } System.out.println(resultLine); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { br.close(); fr.close(); out.close(); debug.close(); } catch(Exception e) {} } } } " B12801,"import java.io.*; import java.util.*; public class Pair{ public int first; public int second; public Pair(){ first=0; second=0; } } " B13075,"package c; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { Set[] c = new HashSet[2000001]; public C() { Scanner s = new Scanner(System.in); int t = s.nextInt(); for(int i =0; i < t;i ++) { int a = s.nextInt(); int b = s.nextInt(); for(int j = a; j <=b; j++) { c[j]= new HashSet(); } int digits = (a+"""").toCharArray().length; for(int j = Math.min(a, b); j<=Math.max(a, b); j++) { int newJ = j; for(int k = 1; k < digits; k++) { int dig = newJ%10; newJ = newJ/10; newJ += dig*Math.pow(10, digits-1); if(newJ>=a && newJ<=b && newJ!=j) { int min = Math.min(newJ, j); int max = Math.max(newJ, j); c[min].add(max); //System.out.println(j+"" ""+min+"" ""+max); } } } long tot = 0; for(int j = a; j <=b; j++) { tot+=c[j].size(); } System.out.println(""Case #""+(i+1)+"": ""+tot); } } /** * @param args */ public static void main(String[] args) { new C(); } } " B10835,"import java.util.*; import java.math.*; import java.io.*; import static java.lang.System.*; import static java.lang.Math.*; import static java.lang.Integer.*; import static java.lang.Double.*; import static java.lang.Long.*; public class QC { static String[] parts(BufferedReader br) throws Exception { String line = br.readLine(); if (line == null) return null; return line.trim().split(""\\s+""); } public static void main (String args[]) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(in)); int z = parseInt(br.readLine().trim()); for (int cas = 1; cas <= z; cas++) { String p[] = parts(br); int a = parseInt(p[0]); int b = parseInt(p[1]); int pow = 1; int e = 0; for (int c = b / 10; c > 0; c /= 10) { e++; pow *= 10; } long count = 0; while (b > a) { for (int i = 0, d = b; i < e; i++) { d = d / 10 + (d % 10) * pow; if (d == b) break; if (a <= d && d < b) count++; } b--; } out.println(""Case #"" + cas + "": "" + count); } } } " B12172,"import java.io.FileInputStream; import java.io.IOException; import java.io.PrintStream; import java.util.Scanner; public class Runner { class ll { public lln f; public lln l; } class lln { public Object v; public lln n; } private static Scanner sc; public static int gi() { return Integer.parseInt(sc.next()); } public static String gn() { return sc.next(); } public static void main(String[] args) throws IOException { System.setIn(new FileInputStream(""C-small-attempt2.in"")); System.setOut(new PrintStream(""output.txt"")); sc = new Scanner(System.in); int N = gi(); for (int z = 0; z < N; z++) { int o = gi(); int t = gi(); int c = 0; for (int m = o + 1; m <= t; m++) { for (int n = o; n < m; n++) { String ms = new Integer(m).toString(); String ns = new Integer(n).toString(); ns = ns.substring(ns.length() - 1) + ns.substring(0, ns.length() - 1); for (int i = 0; i < ms.length() - 1; i++) { //System.out.println(""M: "" + ms + "" N: "" + ns); if(ns.equals(ms)) { c++; break; } //System.out.println(""Pre: "" + ns + "" ms: "" + ms); ns = ns.substring(ns.length() - 1) + ns.substring(0, ns.length() - 1); //System.out.println(""Post: "" + ns + "" i: "" + i); } } } System.out.format(""Case #%d: %d\r\n"", z + 1, c); } } } " B11332,"package quali2012; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import javax.swing.plaf.basic.BasicBorders.SplitPaneBorder; public class C { /** * @param args */ public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); in.nextLine(); for (int testcase = 1; testcase <= T; testcase++) { int A = in.nextInt(); int B = in.nextInt(); //System.out.println(""[""+A + "" "" + B+""]""); int answer = 0; List found = new ArrayList(); for (int i = A; i <= B; i++) { for (int j = A; j <= B; j++) { if (i < j) { for (int k = 1; k < String.valueOf(A).length(); k++) { int a, b1; String b; a = recycleNumber(j, k); b = debugsplit(j, k); b1 = i; if (a == b1) { answer += 1; //System.out.println(j + "" "" + b1+ "" [""+b+""]""); } } } } } System.out.format(""Case #%d: %s\n"", testcase, answer); } } private static int recycleNumber(int num, int pos) { String input = String.valueOf(num); String subA, subB; subA = input.substring(0, pos); subB = input.substring(pos); /*if(subA == subB){ return 0; }*/ int result = Integer.parseInt(subB + subA); return result; } private static String debugsplit(int num, int pos) { String input = String.valueOf(num); String subA, subB; subA = input.substring(0, pos); subB = input.substring(pos); /*if(subA == subB){ return """"; }*/ String result = subA +"" ""+ subB; return result; } } " B11414,"import java.io.*; import java.util.*; public class Recycled { class Case{ int[] limits = null; HashSet counted = new HashSet(); public Case(int[] limits){ this.limits = limits; } public int getResult(){ int k = 0; for(int i = limits[0]; i<=limits[1]; i++){ for(int j=1; j<(""""+i).length(); j++){ try{ k = shift(i, j); updateCount(limits[0], limits[1], i, k); updateCount(limits[0], limits[1], k, i); } catch(RuntimeException re){ continue; } } } return counted.size(); } public void updateCount(int A, int B, int n, int m){ if((!counted.contains(n+"",""+m)) && ( A <= n && m > n && m <= B)){ counted.add(n+"",""+m); } } public int shift(int i, int shiftby){ String input = """"+i; int shifted = Integer.parseInt(input.substring(input.length()-shiftby) + input.substring(0,input.length()-shiftby)); if((""""+shifted).length() != input.length()){ throw new RuntimeException(""INVALIDSHIFT""); } return shifted; } } public Recycled(String file){ BufferedReader in = null; PrintWriter out = null; try{ in = new BufferedReader(new InputStreamReader(new DataInputStream(new FileInputStream(file+""/input.txt"")))); out = new PrintWriter(new BufferedWriter(new FileWriter(file+""/output.txt"")), true); int caseId = 1; int result = 0; String line = null; Case c = null; in.readLine(); //no of cases while ((line = in.readLine()) != null) { c = new Case(getIntArray(line)); result = c.getResult(); System.out.println(""Case #""+caseId+ "": ""+result); out.println(""Case #""+caseId+ "": ""+result); caseId++; } } catch(Exception e){ e.printStackTrace(); } finally{ try{ out.close(); } catch(Exception ignored){} try{ in.close(); } catch(Exception ignored){} } } public String[] getStringArray(String str){ return str.split(""\\s+""); } public int[] getIntArray(String str){ String[] sArray = getStringArray(str); int[] iArray = new int[sArray.length]; for(int i=0; i sars = new ArrayList(); for(int i=0; i< testCases; i++){ s = bufferRead.readLine(); sars.add(s); } System.out.println(""\n""); for(int j=0; j=num1; j--) for(int i=num1; i<=num2; i++){ if(i> input = parseInputFile(""50\n"" + ""146 982\n"" + ""10 11\n"" + ""733 764\n"" + ""144 975\n"" + ""112 999\n"" + ""109 939\n"" + ""166 931\n"" + ""101 984\n"" + ""113 949\n"" + ""100 999\n"" + ""176 968\n"" + ""186 186\n"" + ""122 985\n"" + ""156 929\n"" + ""17 35\n"" + ""953 953\n"" + ""117 952\n"" + ""158 982\n"" + ""150 993\n"" + ""140 959\n"" + ""119 945\n"" + ""149 993\n"" + ""131 970\n"" + ""153 955\n"" + ""969 976\n"" + ""185 911\n"" + ""143 960\n"" + ""141 957\n"" + ""136 933\n"" + ""170 925\n"" + ""113 979\n"" + ""100 100\n"" + ""2 4\n"" + ""178 999\n"" + ""109 915\n"" + ""110 980\n"" + ""100 999\n"" + ""151 960\n"" + ""150 992\n"" + ""117 932\n"" + ""129 936\n"" + ""180 978\n"" + ""128 937\n"" + ""185 939\n"" + ""190 933\n"" + ""25 56\n"" + ""128 971\n"" + ""202 316\n"" + ""105 970\n"" + ""167 923\n""); System.out.println(input); int i = 1; for (Pair range : input) { System.out.println(""Case #"" + i + "": "" + findRecycled(range).size()); i++; } } private static List> parseInputFile(String content) { String[] split = content.split(""\n""); int num = Integer.parseInt(split[0]); List> result = Lists.newArrayList(); for (int i = 1; i <= num; i++) { String[] pairSplit = split[i].split("" ""); result.add(Pair.create(Integer.parseInt(pairSplit[0]), Integer.parseInt(pairSplit[1]))); } return result; } private static Set> findRecycled(Pair range) { return findRecycled(range.getFirst(), range.getSecond()); } private static Set> findRecycled(int from, int to) { Set> result = new LinkedHashSet>(); for (int i = from; i <= to; i++) { for (int j = from; j <= to; j++) { if (i == j) { continue; } int first = i; int second = j; if (first < second) { second = i; first = j; } if (areEqualRecycled(first, second)) { result.add(Pair.create(first, second)); } } } return result; } private static boolean areEqualRecycled(int one, int two) { String oneS = String.valueOf(one); String twoS = String.valueOf(two); return (twoS + twoS).contains(oneS); } } " B11788,"package test.com; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Stack; public class Qual2012C { public static void main(String[] args) throws Exception { FileInputStream fos = new FileInputStream(""c:/sanker/workspace/input2/C-small-attempt0.in""); BufferedReader buf = new BufferedReader(new InputStreamReader(fos)); String str = """"; int N0; str = buf.readLine(); N0 = Integer.parseInt(str); for(int cnti=0; cnti getFileNames() { String[] fileNames = new File(TEST_RESOURCE_DIR) .list(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith("".in""); } }); List result = new LinkedList(); for (String fileName : fileNames) { result.add(new Object[] { fileName.substring(0, fileName.length() - 3) }); } return result; } protected String fileName; protected String getInputFileName() { return String.format(""%s.in"", fileName); } protected String getOutputFileName() { return String.format(""%s.out"", fileName); } public AbstractTest(String fileName) { this.fileName = fileName; } @Test public void testSolver() { TestConfiguration config = getClass().getAnnotation( TestConfiguration.class); try { System.err.println(String.format(""Testing with file %s"", fileName)); assertEquals(getExpectedOutput(), config.solverClass() .newInstance().solve(getInputFileName())); } catch (Exception e) { e.printStackTrace(); fail(); } } private String getExpectedOutput() throws Exception { StringBuilder result = new StringBuilder(); char[] cbuf = new char[1024]; Reader r = new BufferedReader(new InputStreamReader(getClass() .getClassLoader().getResourceAsStream(getOutputFileName()))); int numRead = 0; while ((numRead = r.read(cbuf)) != -1) { result.append(String.valueOf(cbuf, 0, numRead)); } r.close(); return result.toString(); } } " B13206,"import java.util.*; public class ProblemC { public static void main(String... args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for (int t=1; t<=T; t++) { int A = sc.nextInt(); int B = sc.nextInt(); int digit = String.valueOf(A).length(); Set set = new HashSet<>(); for ( int i=digit-1; i>0; i-- ) { for (int n=A; n<=B; n++) { String ns = String.valueOf(n); String ms = (ns.substring(digit-i) + ns.substring(0,digit-i)); int m = Integer.parseInt(ms); if( m>B ) continue; if( n number = new ArrayList(); ArrayList numbers = new ArrayList(); int temp = i; while(temp/10>0){ number.add(temp%10); temp = temp/10; } number.add(temp%10); for(int j=0;j part = new ArrayList(); for(int k=0;k line = new ArrayList(); String[] s = strLine.split("" ""); int i =0; for(;i=n1) && (temp1<=n2)) nr_temp++; temp2=temp1%10; temp1/=10; temp1+=temp2*Math.pow(10,nr_sh); }while(temp1!=k); if(nr_temp>1) nr=nr+nr_temp-1; } //shkrimi i rezultatit out.write(""Case #""+(++j)+"": ""+nr/2+"" \n""); //System.out.println(strLine); } //System.out.println(vec.size()+vec.toString()); in.close(); out.close(); } catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } } " B13063,"package com.google.codejam.recycle; /** * Class to hold the result of given test case. * @author Sushant Deshpande */ public class TestResult { /** * variable to represent testOutput. */ private int testOutput; /** * Constructor to create TestResult with testOutput. * @param testOutput String */ public TestResult(final int testOutput) { this.testOutput = testOutput; } /** * Getter method for test output. * @return String */ public final int getTestOutput() { return testOutput; } }" B10834," import java.util.ArrayList; import java.util.Scanner; public class CodeJam3 { public static void main(String[] args) { Scanner kb=new Scanner(System.in); int cases=kb.nextInt(); for(int i=0;i al=new ArrayList(); for(long k=value1;k found; static void run() { int A = sc.nextInt(); int B = sc.nextInt(); found = new ArrayList(); int total = 0; for (int n = A; n < B; n++) { total += findPerms(n, A, B); } System.out.println(total + """"); } static int findPerms(int n, int A, int B) { int perms = 0; // first generate the perm list ArrayList a = toArrayList(n); // find all permutations of n // and check if n < m <= B for (int i = 0; i < a.size(); i++) { next_number(a); int m = toNumber(a); int ff = 1000000000 * n + m; //System.out.println(m); if (n < m && A <= m && m <= B && !found.contains(ff)) { perms++; found.add(ff); //System.out.println(m + "" <<""); } } return perms; } static ArrayList toArrayList(int a) { ArrayList b = new ArrayList(); for (int i = numdigits(a); i > 0; i--) { b.add(nthdigit(a, i - 1)); //System.out.print(nthdigit(n, i - 1) + "" ""); } return b; } static int toNumber(ArrayList a) { int n = 0; for (int i = 0; i < a.size(); i++) { n *= 10; n += a.get(i); } return n; } static int nthdigit(int x, int n) { while (n-- != 0) { x /= 10; } return (x % 10); } static int numdigits(int x) { int d = 0; while (x != 0) { x /= 10; d++; } return d; } static void next_number(ArrayList a) { Collections.swap(a, 0, a.size() - 1); for (int i = 0; i < a.size() - 2; i++) { Collections.swap(a, a.size() - (2 + i), a.size() - (1 + i)); } } public static void main(String args[]) { sc = new Scanner(System.in); int cases = Integer.parseInt(sc.nextLine()); for (int i = 0; i < cases; i++) { System.out.print(""Case #"" + (i + 1) + "": ""); run(); } } } " B10740,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class problem3 { void main() { solve(); } public void solve() { try { FileInputStream fstream = new FileInputStream(""pr3_input.txt""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter fout = new FileWriter(""output.txt""); BufferedWriter out = new BufferedWriter(fout); int iCases = Integer.parseInt(br.readLine()); for (int iStep = 0; iStep < iCases; iStep++) { String strLine = br.readLine(); String[] myNumbers = strLine.split("" ""); int A = Integer.valueOf(myNumbers[0]).intValue(); int B = Integer.valueOf(myNumbers[1]).intValue(); int digits = myNumbers[0].length(); int iValue = 0; for (int jStep = A; jStep <= B; jStep++) { List pairs = new ArrayList(); for (int kStep = 1; kStep < digits; kStep++) { int m = perm(jStep, kStep); if ((A <= jStep)&&(jStep < m)&&(m <= B)) { if (false == pairs.contains(m)) { iValue++; pairs.add(m); } } } } if (iStep != (iCases - 1)) { out.write(String.format(""Case #%d: %d\n"", iStep + 1, iValue)); } else { out.write(String.format(""Case #%d: %d"", iStep + 1, iValue)); } } out.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } public int perm(int iNumber, int iDigitsPerm) { String strNumber = String.format(""%d"", iNumber); String strReturn = strNumber.substring(strNumber.length() - iDigitsPerm) + strNumber.substring(0, strNumber.length() - iDigitsPerm); if (strReturn.charAt(0) == '0') { strReturn = ""0""; } return Integer.parseInt(strReturn); } } " B12510,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.SortedSet; import java.util.TreeSet; public final class RecycledNumbers { /** * @param args */ public static void main(String[] args) { BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(new FileInputStream(""test.txt""))); int count = 1; String input; int cases = Integer.valueOf(br.readLine()); while (((input = br.readLine()) != null) && (count <= cases)) { String output = ""Case #""+(count++)+"": ""+process(input); System.out.println(output); } } catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } finally { if (br!=null) try { br.close(); } catch(IOException e) {} } } private static final int process(String input) { String[] s = input.split("" ""); if (s[0].length()==1) return 0; int A = Integer.valueOf(s[0]); int B = Integer.valueOf(s[1]); int counter = 0; for (int n=A; n rotates = rotate(n, A, B); if (n != rotates.first()) continue; counter += count(rotates.size()); } return counter; } private final static int count(int n) { if (n < 2) return 0; if (n == 2) return 1; return --n + count(n); } private static final SortedSet rotate(int N, int min, int max) { SortedSet set = new TreeSet(); set.add(N); String sN = Integer.toString(N); for (int i = 0; i < sN.length()-1;i++) { //if (sN.charAt(1) == '0') continue; sN = sN.substring(1)+sN.charAt(0); int n = Integer.valueOf(sN); if (min<=n && n<=max) set.add(n); } return set; } } " B12928,"package main; import java.util.Vector; import java.io.*; public class RecycledNumbers { static int numberOfElementForEachTest = 2; static int numberOfLinesPerTest = 0; public static void main(String[] args) { Vector elements = new Vector(); numberOfElementForEachTest = 0; Reader.setFile(""input.txt""); Writer.setFile(""output.txt""); String s = Reader.readLine(); int numberTest = Integer.parseInt(s); for (int i=0; i(); s = Reader.readLine(); String s1 = s.substring(0, s.indexOf("" "")); s=s.substring(s.indexOf("" "")+1); int numberOfDigits = s1.length(); int[] digits = new int[numberOfDigits]; int firstNumber = Integer.parseInt(s1); int secondNumber = Integer.parseInt(s); int result = 0; switch (numberOfDigits) { case 1: break; case 2: for (int n1=firstNumber; n1n1 && n2<=secondNumber) result++; } break; case 3: for (int n1=firstNumber; n1n1 && n2<=secondNumber) result++; n2 = n1/10 + n1%10*100; if (n2>n1 && n2<=secondNumber) result++; } break; case 4: // System.out.println(System.currentTimeMillis()); for (int n1=firstNumber; n1secondNumber) n1 = (n1/1000 + 1) *1000; else if (n2>n1) { result++; } } for (int n1=firstNumber; n1secondNumber) n1 = (n1/100 + 1) *100; else if (n2>n1) { result++; } } for (int n1=firstNumber; n1secondNumber) n1 = (n1/10 + 1) *10; else if (n2>n1) { result++; if (n1/1000 == n1%100/10 && n1%1000/100 == n1%10) result--; } } // System.out.println(System.currentTimeMillis()); break; case 5: for (int n1=firstNumber; n1secondNumber) n1 = (n1/10000 + 1) *10000; else if (n2>n1) { result++; } } for (int n1=firstNumber; n1secondNumber) n1 = (n1/1000 + 1) *1000; else if (n2>n1) { result++; } } for (int n1=firstNumber; n1secondNumber) n1 = (n1/100 + 1) *100; else if (n2>n1) { result++; } } for (int n1=firstNumber; n1secondNumber) n1 = (n1/10 + 1) *10; else if (n2>n1) { result++; } } break; case 6: for (int n1=firstNumber; n1secondNumber) n1 = (n1/100000 + 1) *100000; else if (n2>n1) { result++; } // if (n2>n1 && n2<=secondNumber) result++; } for (int n1=firstNumber; n1secondNumber) n1 = (n1/10000 + 1) *10000; else if (n2>n1) { result++; } } for (int n1=firstNumber; n1secondNumber) n1 = (n1/1000 + 1) *1000; else if (n2>n1) { result++; if (n1/100000 == n1%10000/1000 && n1%10000/1000 == n1%100/10 && n1%100000/10000 == n1%1000/100 && n1%1000/100 == n1%10) result-=2; } } for (int n1=firstNumber; n1secondNumber) n1 = (n1/100 + 1) *100; else if (n2>n1) { result++; } } for (int n1=firstNumber; n1secondNumber) n1 = (n1/10 + 1) *10; else if (n2>n1) { result++; } } break; case 7: // System.out.println(System.currentTimeMillis()); for (int n1=firstNumber; n1secondNumber) n1 = (n1/1000000 + 1) *1000000; else if (n2>n1) { result++; } } for (int n1=firstNumber; n1secondNumber) n1 = (n1/100000 + 1) *100000; else if (n2>n1) { result++; } } for (int n1=firstNumber; n1secondNumber) n1 = (n1/10000 + 1) *10000; else if (n2>n1) { result++; } } for (int n1=firstNumber; n1secondNumber) n1 = (n1/1000 + 1) *1000; else if (n2>n1) { result++; } } for (int n1=firstNumber; n1secondNumber) n1 = (n1/100 + 1) *100; else if (n2>n1) { result++; } } for (int n1=firstNumber; n1n1 && n2 input = new ArrayList(); input = fs.ReadFromFile(); ArrayList output = new ArrayList(); int xCase = Integer.valueOf(input.get(0)); int xPointer = 1; for (int i=1;i<=xCase;i++) { String strOut = ""Case #"" + String.valueOf(i) + "":""; String strLine = input.get(xPointer); xPointer++; String[] arrLine = strLine.split("" ""); int xA = Integer.valueOf(arrLine[0]); int xB = Integer.valueOf(arrLine[1]); int xRec = 0; for (int a=xA;a<=xB;a++) { int xLen = String.valueOf(a).length(); int xLimit = 1; for (int b=1;b<=xLen;b++) xLimit *= 10; if (xLimit > xB) xLimit = xB+1; for (int b=a+1;b al = GoogleFileStream.getInput(); ArrayList ret = new ArrayList(); for( String i : al ) ret.add( solution( i ) ); long end = System.currentTimeMillis(); System.out.println( ""Time: "" + (end - start) + ""ms"" ); GoogleFileStream.setOutput(ret); } private static String solution(String in) { ArrayList input = new ArrayList(Arrays.asList(in.split("" ""))); int A = Integer.valueOf( input.get(0) ); int B = Integer.valueOf( input.get(1) ); int count = 0; Set dupeSet = new HashSet(); for( int i = A; i <= B; i++) { String is = String.valueOf(i); char[] c = is.toCharArray(); System.out.print(i); System.out.print("":""); dupeSet.clear(); for( int j = 1; j < c.length; j++) { //rotate: char lastChar = c[c.length-1]; System.arraycopy(c,0,c,1,c.length - 1); c[0]=lastChar; int num = Integer.valueOf(new String(c)); if(i < num && num <= B) { if( dupeSet.add(num) ) { // (n,m) = (i, c) count++; System.out.print(num); System.out.print("",""); } } } System.out.println(); } return String.valueOf(count); } }" B10542,"import java.util.*; public class C { public static int front; public static int rotate(int in) { return (in / 10) + front*(in % 10); } public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for(int c = 1; c <= T; c++){ int ans = 0; int A = in.nextInt(); int B = in.nextInt(); int ndig = ("""" + A).length(); front = 1; for(int i = 1; i < ndig; i++) front *= 10; for(int num = A; num <= B; num++){ int count = 1; int rot = rotate(num); boolean smallest=true; while(smallest && rot!= num){ if(A <= rot && rot <= B) if(rot < num) smallest = false; else count++; rot = rotate(rot); } if(smallest) ans += count*(count - 1)/2; } System.out.println(""Case #"" + c + "": "" + ans); } } }" B11853," public class Recycled { static String test = ""4\n1 9\n10 40\n100 500\n1111 2222""; static String val = ""50\n187 934\n138 960\n117 921\n1 2\n171 919\n152 967\n903 903\n137 953\n144 984\n182 988\n144 955\n169 993\n186 920\n143 918\n154 923\n154 959\n577 592\n146 944\n149 981\n128 979\n176 910\n251 674\n136 967\n169 976\n48 82\n100 100\n160 982\n325 325\n10 99\n139 981\n119 927\n189 922\n10 99\n183 922\n150 963\n133 997\n133 980\n166 991\n29 82\n123 967\n116 933\n171 968\n180 928\n171 944\n155 940\n164 941\n175 939\n133 926\n1 7\n129 327\n""; public static void main(String[] args) { String[][] cases = CaseReader.getCases(val, 1); for (int i = 0;i < cases.length;i++) { parseCase(i + 1, cases[i][0]); } } static void parseCase(int caseNum, String caseString) { String[] args = caseString.split("" ""); int current, recycles = 0; int leftMin = Integer.parseInt(args[0]); int rightMax = Integer.parseInt(args[1]); current = leftMin; int currentLen = (int) Math.pow(10,(int)(Math.log10(leftMin))); int nextLen = currentLen * 10; while (current <= rightMax) { recycles += recycledCount(current, leftMin, rightMax, currentLen); current++; if (current == nextLen) { nextLen *= 10;currentLen *= 10; } } System.out.println(""Case #"" + caseNum + "": "" + recycles); } static int recycledCount(int current, int leftMin, int rightMax, int len) { int working = moveIt(current, len); int c = 0;/* if (current == 29 && antimax == 10) return -1;*/ while (working != current) { if (working >= leftMin && current <= rightMax && working < current) { c++; } working = moveIt(working, len); } return c; } static int moveIt(int v, int e10) { return v / 10 + (e10 * (v % 10)); } } " B10277,"import java.io.*; public class google3 { void main()throws IOException { try{ // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(""C-small-attempt1.in.txt""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; strLine=br.readLine(); int a=Integer.parseInt(strLine);//Read File Line By Line String b[]=new String[a]; int i=0; while ((strLine = br.readLine()) != null) { // Print the content on the console b[i]=strLine;i++; } in.close(); FileOutputStream out = new FileOutputStream(new File(""output.txt"")); int g=0;for(int l=0;l0){ t--; counter++; int ans=0; String data = in.readLine(); String[] ss = data.split("" ""); int a = Integer.parseInt(ss[0]); int b = Integer.parseInt(ss[1]); //System.out.println(a + "" ""+ b); for(int i=a; i hashSet = new HashSet(); for(int i=0; i currentNumber && generatedNumber<= m && !contains){ ans++; } } return ans; } } " B12641,"import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { static int length, a, b; static int count = 0; public static int len(int a) { int l = 0; while (a > 0) { a = a / 10; l++; } return l; } public static int calc(int m) { if (length == 1) { return 1; } else { for (int j = 0; j < length - 1; j++) { int x = 1, y = 1; for (int q = 1; q <= j + 1; q++) { x *= 10; } for (int q = 1; q < length - j; q++) { y *= 10; } int lastd = (m % x); int num = (m / x) +(lastd * y); if ((num >= a) && (num <= b) && (num != m)) { count++; } } } return 1; } public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); for (int i = 0; i < n; i++) { String str = br.readLine(); StringTokenizer tok = new StringTokenizer(str, "" ""); a = Integer.parseInt(tok.nextToken()); b = Integer.parseInt(tok.nextToken()); System.out.print(""Case #"" + (i + 1) + "": ""); count = 0; length = len(a); for (int k = a; k <= b; k++) { calc(k); } System.out.print(count / 2); if (i != (n - 1)) { System.out.print(""\n""); } } } catch (Exception e) { System.out.println(e.toString()); } } }" B11286,"import java.util.Scanner; /** * author - coolprosu * Problem - C */ public class RecycledNumbers { private int T = 0; public static void main(String[] args) { RecycledNumbers solveProb = new RecycledNumbers(); solveProb.solve(); } private void solve() { Scanner sc = new Scanner(System.in); //Input no. of test cases T = sc.nextInt(); //Solved strings String solutionArray[] = new String[T]; for(int i=0;i it = file.iterator(); PrintWriter out = new PrintWriter(new FileWriter(""output.txt"")); String next; next = it.next(); Integer cases,t; cases = new Integer(Integer.parseInt(next)); Integer counter=0,A,B,comb=0,nn,mm; String sA,sB,n,m; StringTokenizer st; Set set = new HashSet(); while(it.hasNext()){ set.clear(); counter++; next = it.next(); st = new StringTokenizer(next,"" ""); sA = st.nextToken(); sB = st.nextToken(); A = Integer.parseInt(sA); B = Integer.parseInt(sB); for(int i=A;ii){ if(!set.contains(m+"",""+n)){ set.add(n+"",""+m); System.out.println(n+"",""+m); } } } } } out.println(""Case #""+counter+"": ""+set.size()); } out.close(); } } " B10237,"package codejam2; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.Date; import java.util.Scanner; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public abstract class CodejamRunner { public static final int NUM_WORKERS = 4; public static final int TIMEOUT_MINUTES = 10; // Default behavior is to get number of test cases that follow public int preparse(Scanner s) { String line = s.nextLine(); return new Scanner(line).nextInt(); } public abstract CodejamCase parseCase(Scanner s); public void run(String[] args) { Date start = new Date(); // Set up worker threads ExecutorService es = Executors.newFixedThreadPool(args.length > 0 ? NUM_WORKERS : 1); // Read in file one test at a time and put in work queue try { Scanner s = new Scanner(new FileInputStream(args.length > 0 ? args[0] : ""sample"")); PrintStream o = args.length > 0 ? new PrintStream(new FileOutputStream(args[0]+ "".output"")) : System.out; int numTests = preparse(s); final CodejamCase[] tests = new CodejamCase[numTests]; for (int i = 0; i < numTests; i++) { final int id = i; tests[id] = parseCase(s); es.execute(new Runnable() { @Override public void run() { tests[id].compute(); System.err.print(id + "" ""); } }); } // Wait until work queue is empty try { es.shutdown(); if (!es.awaitTermination(TIMEOUT_MINUTES, TimeUnit.MINUTES)) { System.err.println(""Timeout! "" + es.shutdownNow().size() + "" tests incomplete.""); } } catch (InterruptedException e) { System.err.println(""Interrupted!""); e.printStackTrace(); } // Output results for (int i = 0; i < numTests; i++) { o.println(""Case #"" + (i+1) + "": "" + tests[i].getOutput()); } } catch (IOException e) { System.err.println(""IO error!""); e.printStackTrace(); } System.err.println(""\nExecution time: "" + (new Date().getTime() - start.getTime()) + ""(ms)""); System.exit(0); } public static String padInt(int num, int len) { String s = ""00000000000"" + String.valueOf(num); return s.substring(s.length()-4); } } " B12297,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * Recycling (Numbers) * Jason Bradley Nel * 16287398 */ import java.util.*; public class Recycling { public static void main(String[] args) { In input = new In(""input.txt""); int T = input.readInt(); for (int t = 0; t < T; t++){ int min = input.readInt(); int max = input.readInt(); int N = max - min + 1; Set set = new HashSet(); //if (set.isEmpty()) System.out.print(""\nSET IS EMPTY""); for (int i = min; i <= max; i++) { String s = """" + i; for (int r = 1; r < s.length(); r++) { String m = returnM(s, r); int num = Integer.parseInt(m); String mn = s + m; //System.out.printf(""%d(%s)(*%d*), "", i, m, num); if((num >= min) && (num <= max) && (num != i)) set.add(mn); } } //if (set.isEmpty()) System.out.print(""\nSET IS EMPTY""); int c = set.size()/2; System.out.printf(""Case #%d: %d\n"", t+1, c); } } public static String returnM(String s, int r){ int N = s.length(); if(r != N){ String i = s.substring(0, N - r); i = s.substring(N - r, N) + i; return i; } else return s; } } " B11775,"package com.google.code; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public abstract class GCJ { private BufferedReader input; private BufferedWriter output; String inputLine; String[] brokenUpInputLine; public static final String FOLDER = ""/tmp/""; protected GCJ() throws IOException { String subclass = this.getClass().getSimpleName(); input = new BufferedReader(new FileReader(new File(FOLDER, subclass+"".in""))); output = new BufferedWriter(new FileWriter(new File(FOLDER, subclass+"".out""))); } public void run() throws NumberFormatException, IOException { int loop = Integer.valueOf(input.readLine()); for (int i = 0; i < loop; i++) answering(i+1); output.flush(); } protected void write(String s) throws IOException { System.out.print(s); output.write(s); } protected void writeln(String s) throws IOException { System.out.println(s); output.write(s+""\n""); } protected void writeln() throws IOException { System.out.println(); output.write(""\n""); } protected void write(int s) throws IOException { System.out.print(String.valueOf(s)); output.write(String.valueOf(s)); } protected void writeln(int s) throws IOException { System.out.println(String.valueOf(s)); output.write(String.valueOf(s)+""\n""); } protected void readLine() throws IOException { inputLine = input.readLine(); brokenUpInputLine = inputLine.split("" ""); } protected String getStringInput(int i) { return brokenUpInputLine[i]; } protected int getIntInput(int i) { return Integer.parseInt(brokenUpInputLine[i]); } protected long getLongInput(int i) { return Long.parseLong(brokenUpInputLine[i]); } protected double getDoubleInput(int i) { return Double.parseDouble(brokenUpInputLine[i]); } private void answering(int ordinalityOfProblem) throws IOException { writeOrdinalityOfAnswer(ordinalityOfProblem); code(ordinalityOfProblem); } private void writeOrdinalityOfAnswer(int ordinalityOfProblem) throws IOException { write(""Case #""+ordinalityOfProblem+"": ""); } protected abstract void code(int count) throws IOException; } " B13231,"package classes; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; public class Recycle { public static void main(String[] args) { try { FileInputStream fstream = new FileInputStream(""/Users/jleibsly2002/C-small-attempt0.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine = br.readLine(); int N = Integer.parseInt(strLine); for(int i = 0; i < N; i++) { int count = 0; String[] range = br.readLine().split("" ""); int min = Integer.parseInt(range[0]); int max = Integer.parseInt(range[1]); int length = range[0].length(); ArrayList numbers = new ArrayList(); for(int j = min; j <= max; j++) numbers.add(j + """"); for(int k = 0; k < numbers.size(); k++) { String n = numbers.get(k); for(int l = length-1; l>=1; l--) { String recycled = n.substring(l) + n.substring(0, l); if(numbers.contains(recycled) && recycled.charAt(0)!='0' && recycled.compareTo(n)>0) { count++; } } } System.out.println(""Case #"" + (i+1) + "": "" + count); } in.close(); } catch (Exception e){ System.err.println(""Error: "" + e.getMessage()); } } } " B12420,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.util.HashMap; public class Main { private static String fileDirectory = ""files/""; /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Problem3(fileDirectory + ""C-small-attempt0.in"",fileDirectory + ""C-small-attempt0.out""); } public static void Problem3(String inFile, String outFile) { try { BufferedReader br = new BufferedReader(new FileReader(inFile)); BufferedWriter bw = new BufferedWriter(new FileWriter(outFile)); int cases = Integer.parseInt(br.readLine()); for (int i = 0; i < cases; i++) { if (i > 0) { bw.newLine(); } String line = br.readLine(); String[] numbers = line.split("" ""); int A = Integer.parseInt(numbers[0]); int B = Integer.parseInt(numbers[1]); int length = String.valueOf(A).length(); int count = 0; for (int j = A; j <= B; j++) { String sNum = Integer.toString(j); HashMap map = new HashMap(); //System.out.print(sNum + "": ""); for (int k = 1; k < length; k++) { String newNum = sNum.substring(k, sNum.length()); newNum += sNum.substring(0, k); //System.out.print("" "" + newNum); int number = Integer.parseInt(newNum); if (number > j && number <= B) { if (!map.containsKey(number)) { map.put(number, null); count++; } } } //System.out.println(); } bw.write(""Case #"" + (i+1) + "": ""); bw.write(Integer.toString(count)); } bw.close(); br.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B12470,"import java.util.List; import java.util.ArrayList; import java.util.Scanner; import java.util.Set; import java.util.HashSet; import java.io.*; public class Rec { public static void main(String args[]) throws IOException { //Scanner in = new Scanner(System.in); //int n = in.nextInt(); //in.nextLine(); BufferedReader br = new BufferedReader(new FileReader(""C-small-attempt0.in"")); PrintWriter pw = new PrintWriter(""output1.in""); String sss = """"; sss = br.readLine(); int num = Integer.parseInt(sss); List l = new ArrayList(); while((sss = br.readLine()) != null) l.add(sss); int count = 0; for (String s : l) { count++; Set set = new HashSet(); String val[] = s.split("" ""); int rear = Integer.parseInt(val[0]); int max = Integer.parseInt(val[1]); if (String.valueOf(rear).length() == 1) { if (count == 0) pw.print(""Case #"" + count + "": "" + 0); //System.out.print(""Case #"" + count + "": "" + 0); else pw.print(""\n"" + ""Case #"" + count + "": "" + 0); //System.out.print(""\n"" + ""Case #"" + count + "": "" + 0); } else { int len = String.valueOf(rear).length(); for (int c = rear; c <= max; c++) { String ss = String.valueOf(c); for (int u = 1; u < len; u++) { String sub = ss.substring(u); int f_s = Integer.parseInt(String.valueOf(sub.charAt(0))); if (f_s > Integer.parseInt(String.valueOf(String.valueOf(max).charAt(0)))) continue; if (f_s == 0) continue; sub = sub.concat(ss.substring(0,u)); if ((Integer.parseInt(sub) > c) && (Integer.parseInt(sub) <= max)) if (c < Integer.parseInt(sub) && c >= rear) { set.add(String.format(""%s %s"", c, sub)); } } } if (count == 0) pw.print(""Case #"" + count + "": "" + set.size()); //System.out.print(""Case #"" + count + "": "" + set.size()); else pw.print(""\n"" + ""Case #"" + count + "": "" + set.size()); //System.out.print(""\n"" + ""Case #"" + count + "": "" + set.size()); pw.flush(); } } pw.close(); } }" B10613,"import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileWriter; import java.util.Scanner; public class Main { public static void main(String[] args) throws Exception { Scanner kb=new Scanner(new FileInputStream(args[0])); BufferedWriter bw= new BufferedWriter(new FileWriter(args[1])); int T=kb.nextInt(); for(int i=0;i0; pos-- ){ last = n.substring(pos); first = n.substring(0, pos); //System.out.println( last + "" "" + first ); //new Scanner(System.in).nextLine(); if( (last+first).equals( m )){ return true; } } return false; } private static boolean checkRecycling( String n, String m ){ boolean flag = true; int sz = n.length(), mPos; for( int pos=sz-1; pos>0; pos-- ){ flag = true; mPos = 0; for( int i=pos; i { private TestCaseReader caseReader; private final PrintWriter outputWriter; public Transformation(TestCaseReader caseReader, PrintWriter outputWriter) { this.caseReader = caseReader; this.outputWriter = outputWriter; } public void transformAll() throws Exception { T testCase = caseReader.nextCase(); while (testCase != null) { outputWriter.println(transform(testCase)); testCase = caseReader.nextCase(); }; } protected abstract String transform(T testCase); } " B10562,"import java.io.*; import java.util.ArrayList; public class recycled { public static void main(String[] args) { String filename = args[0]; ArrayList input = new ArrayList(); ArrayList output = new ArrayList(); try { BufferedReader br = new BufferedReader(new FileReader(filename)); while (true) { String line = br.readLine(); if (line == null) break; input.add(line); } br.close(); input.remove(0); } catch (IOException e) { System.out.println(""Input error. Try a different filename.""); } for (String line: input) { String out = """"+checkCondition(line); output.add(out); } try { PrintWriter pr = new PrintWriter(new FileWriter(""output.txt"")); for (int i = 0;i < output.size();i++) { String line = output.get(i); pr.println(""Case #"" + (i+1) + "": "" + line); } pr.close(); } catch (IOException e) { System.out.println(""Output error. Hmph.""); } System.out.println(""Process complete.""); } private static int checkCondition(String line) { String[] numString = line.split("" ""); int a = Integer.parseInt(numString[0]); int b = Integer.parseInt(numString[1]); int recycled = 0; for (int n = a;n <= b;n++) { String N = """"+n; for (int m = n;m <= b;m++) { String M = """"+m; if (areRecycled(M,N) && !(M.equals(N))) { recycled++; System.out.println(M + "" "" + N); } } } return recycled; } private static boolean areRecycled(String M,String N) { String n = N; for (int i = 1;i < N.length();i++) { n = permute(n); if (M.equals(n)) { return true; } } return false; } private static String permute(String n) { char q = n.charAt(0); return n.substring(1) + q; } } " B12396,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Recycled { private static String fileNameSmall = ""/Users/ogokal/Downloads/C-small-attempt0.in""; private static String outputFilePath = null; private static void AppendCase(int caseId,String message, BufferedWriter bw) throws IOException{ bw.write(""Case #""+caseId+"": ""+message+""\n""); } private static String OutputFile(String inputFilePath){ int dotIdx = inputFilePath.lastIndexOf('.'); return inputFilePath.substring(0, dotIdx)+"".out""; } private static int Count(int low,int current, int high,int currentIdx, int total,Set counterSet){ if (currentIdx >= Integer.toString(low).length()) { return total; } String currentStr = Integer.toString(current); String begin = currentStr.substring(0,currentIdx); String end = currentStr.substring(currentIdx); int currentInt = Integer.parseInt(end+begin); if (current != currentInt) { int min = Math.min(current, currentInt); int max = Math.max(current, currentInt); if (currentInt >= low && currentInt <= high && !counterSet.contains(min+"" ""+max)) { counterSet.add(min+"" ""+max); ++total; } } return Count(low,current,high,currentIdx+1,total,counterSet); } public static void main(String[] args) throws IOException { Scanner scanner = new Scanner(new File(fileNameSmall)); BufferedWriter bw = new BufferedWriter(new FileWriter(OutputFile(fileNameSmall))); int totalCaseCount = scanner.nextInt(); scanner.nextLine(); int caseCount = 0; while(caseCount < totalCaseCount){ StringBuffer sb = new StringBuffer(); int low = scanner.nextInt(); int high = scanner.nextInt(); int t = 0; Set counterSet = new HashSet(); for (int i = low; i <= high; i++) { t = Count(low,i,high,1,t,counterSet); } sb.append(t); caseCount++; System.out.println(sb.toString()); AppendCase(caseCount,sb.toString(),bw); scanner.nextLine(); } bw.flush(); bw.close(); } } " B12741,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; public class CodeJamC { public static void main(String args[]) throws Exception { Scanner in = new Scanner(new File(""in.txt"")); BufferedWriter out = new BufferedWriter(new FileWriter(""out.txt"")); int cases = in.nextInt(); for(int casenum = 1;casenum <= cases;casenum++) { int a = in.nextInt(); int b = in.nextInt(); int count = 0; HashMap> map = new HashMap>(); int len = ("""" + a).length(); for(int n = a;n <= b;n++) { int t = n; for(int i = 0;i n && t <= b) { if(map.containsKey(n)) { if(!map.get(n).contains(t)) { count++; map.get(n).add(t); } } else { ArrayList arr = new ArrayList(); arr.add(t); map.put(n,arr); count++; } } } } out.write(""Case #"" + casenum + "": "" + count + ""\n""); } in.close(); out.close(); } }" B12778,"import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; public class Puzzle3 { public static String parseString(int q, String A) { String tmp = A.substring(q+1, A.length()) + A.substring(0,q+1); return tmp; } public static boolean isReclycled(String A, String B) { for(int i=0; i 0) { for (int i = 1; i <= testCases; i++) { String lines[] = in.readLine().split("" ""); int n = Integer.valueOf(lines[0]); int m = Integer.valueOf(lines[1]); strOutput+=""Case #"" + i + "": "" + countRecyclesBetween(n,m) + ""\n""; } } } catch (Exception e) { return ""Invalid test case input""; } return strOutput.toString(); } public static void main(String[] args) { String input = ""50\n"" + ""3 4\n"" + ""156 971\n"" + ""302 482\n"" + ""163 919\n"" + ""148 941\n"" + ""19 59\n"" + ""109 959\n"" + ""140 945\n"" + ""155 963\n"" + ""137 975\n"" + ""172 928\n"" + ""12 37\n"" + ""123 933\n"" + ""113 925\n"" + ""444 756\n"" + ""10 11\n"" + ""112 977\n"" + ""143 938\n"" + ""149 997\n"" + ""158 938\n"" + ""104 957\n"" + ""117 928\n"" + ""159 967\n"" + ""171 951\n"" + ""128 921\n"" + ""676 676\n"" + ""440 440\n"" + ""125 939\n"" + ""116 949\n"" + ""100 100\n"" + ""10 99\n"" + ""117 950\n"" + ""128 972\n"" + ""158 938\n"" + ""178 941\n"" + ""143 975\n"" + ""100 999\n"" + ""956 969\n"" + ""176 938\n"" + ""124 966\n"" + ""181 967\n"" + ""190 956\n"" + ""145 940\n"" + ""187 994\n"" + ""167 996\n"" + ""167 921\n"" + ""135 916\n"" + ""156 926\n"" + ""170 994\n"" + ""103 955\n""; System.out.println(executeTestCase(input)); } } " B10236,"import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; public class prob2 { public static void main(String[] args) { BufferedReader inputStream = null; try { inputStream = new BufferedReader(new FileReader( ""C:/Users/vpamarty.SYMPHONY/Downloads/C-small-attempt1.in"")); String lineRead = inputStream.readLine(); int noCases = Integer.valueOf(lineRead).intValue(); for (int i = 0; i < noCases; i++) { lineRead = inputStream.readLine(); String[] splitString = lineRead.split("" ""); int numA = Integer.valueOf(splitString[0]).intValue(); int numB = Integer.valueOf(splitString[1]).intValue(); int distinctRps = computeDisRps(numA, numB); System.out.println(""Case #""+(i+1)+"": ""+distinctRps); } inputStream.close(); } catch (Exception e) { e.printStackTrace(); } } public static int computeDisRps(int num1, int num2) { int numPairs = 0; for (int numCons = num1; numCons < num2; numCons++) { int numLength = (String.valueOf(numCons)).length(); ArrayList numArr = new ArrayList(); numArr.add(String.valueOf(numCons)); for (int i = 1; i < numLength; i++) { String numString = String.valueOf(numCons); String newNumString = numString.substring(numLength - i) + numString.substring(0, numLength - i); if (!numArr.contains(newNumString)) { numArr.add(newNumString); if (Integer.valueOf(newNumString).intValue() > numCons && Integer.valueOf(newNumString).intValue() <= num2) numPairs++; } } } return numPairs; } } " B13023,"package codejam; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; public class Numbers { public static void main (String[] args) throws IOException { Scanner sc = new Scanner(new FileReader(""numbers.in"")); PrintWriter out = new PrintWriter(new FileWriter(""NumbersAsmall.out"")); int cases = sc.nextInt(); for (int i = 0; i < cases; i++) { String aString = sc.next(); String bString = sc.next(); int a = Integer.parseInt(aString); int b = Integer.parseInt(bString); int count = 0; for (int j = a; j <= b; j++) { String currentString = String.valueOf(j); ArrayList list = new ArrayList(); for (int k = 1; k < currentString.length(); k++) { String thisNewString = currentString.substring(currentString.length() - k, currentString.length()) + currentString.substring(0, currentString.length() - k); if (isAnagram(currentString, thisNewString)) { if (Integer.parseInt(thisNewString) >= a && Integer.parseInt(thisNewString) <= b && !currentString.equals(thisNewString)) { if (!list.contains(thisNewString)) { count++; } list.add(thisNewString); } } } } out.println(""Case #"" + (i + 1) + "": "" + count/2); } out.close(); } public static boolean isAnagram(String s1, String s2) { int[] char_set = new int[10]; if(s1.length() != s2.length()) { return false; } for (int i = 0; i < s1.length(); i++) { char_set[s1.charAt(i) % 48]++; } for (int j = 0; j < s1.length(); j++) { char_set[s1.charAt(j) % 48]--; } for(int k = 0; k < char_set.length; k++) { if (char_set[k] != 0) { return false; } } return true; } } " B11947,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.*; /** * @author Seitaro Sakoda * */ public class RecycledNumbers { private static final HashMap cache = new HashMap(); private static final ArrayList list = new ArrayList(); private static final long MASK = 10000000; private static void init(){ for(int i=10;i<=2000000;i++){ int L = (int)Math.log10(i); int D = (int)Math.pow(10.0, L); int k = i; for(int j=0;j ans = new ArrayList(); long start = System.currentTimeMillis(); init(); System.out.println(""INIT:""+(System.currentTimeMillis()-start)+"" ms""); for(int not=0;not=A && (int)(a%MASK)<=B) ans++; } return ans; } static class DataReader { public BufferedReader br; public DataReader(String filename) throws Exception { br = new BufferedReader(new FileReader(filename)); } public DataReader() throws Exception { this(""data.in""); } private String readLine() throws Exception { return br.readLine(); } public int readInt() throws Exception { return Integer.parseInt(readLine()); } public int[] readInts() throws Exception { String[] tmp = readLine().split("" ""); int[] ret = new int[tmp.length]; for(int i=0;i readFile(String fileName) { List list = new ArrayList(); try { FileReader fr = new FileReader(fileName); BufferedReader in = new BufferedReader(fr); String s; while ( (s=in.readLine()) != null ) { list.add(s); } in.close(); fr.close(); } catch(IOException e) { e.printStackTrace(); System.out.println(""ERROR""); } return list; } public static void writeFile(String fileName, List contents) { try { FileWriter fw = new FileWriter(fileName, false); // overwrite BufferedWriter out = new BufferedWriter(fw); for (String s : contents) { out.write(s); out.write(""\r\n""); } out.close(); fw.close(); } catch(IOException e) { e.printStackTrace(); System.out.println(""ERROR""); } } } " B10919,"package codejam.qualification; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; public class Recycled { /** * @param args */ public static void main(String[] args) throws IOException { String file = ""input3small""; Scanner in = new Scanner(new File(file)); int tot = Integer.parseInt(in.nextLine()); // System.out.println(tot); for(int i=0;i rec = new ArrayList(); int count = 0; for(int i=s.length()-1; i>0; i--) { String r = s.substring(i) + s.substring(0, i); // System.out.println(r); int s_int = Integer.parseInt(s); int r_int = Integer.parseInt(r); if(r.charAt(0) != 0 && s_int < r_int && r_int <= B && !isIn(r,rec)) { // System.out.println(""ok: ""+s+""\t""+r); count++; rec.add(r); } } return count; } private static boolean isIn(String r, ArrayList rec) { for(String r2 : rec) if(r.equals(r2)) return true; return false; } }" B12166,"import java.io.*; import java.text.*; import java.util.*; public class RecycledNumbers { static BufferedReader stdin; static StringTokenizer st; static String LINE() throws Exception { return stdin.readLine(); } static String TOKEN() throws Exception { while (st == null || !st.hasMoreTokens())st = new StringTokenizer(LINE()); return st.nextToken(); } static int INT() throws Exception {return Integer.parseInt(TOKEN());} static long LONG() throws Exception {return Long.parseLong(TOKEN());} static double DOUBLE() throws Exception {return Double.parseDouble(TOKEN());} static DecimalFormat DF = new DecimalFormat(""0.000"",new DecimalFormatSymbols(Locale.ENGLISH)); public static void main(String[] args) throws Exception { String input = ""C-small-attempt0.in""; String output = ""C-small.out""; // String input = ""testa.in""; // String output = ""testa.out""; stdin = new BufferedReader(new FileReader(new File(input))); FileWriter frw = new FileWriter(output); int cases = INT(); int cc = 1; while(cases-->0) { System.out.println(cc); int N = INT(), M = INT(); int cp = N / 10; int factor = 1; while(cp>0) { factor *= 10; cp /= 10; } int solution = 0; for(int i = N; i < M; i++) { solution += addPairs(i, factor, M); } frw.write(""Case #""+(cc++)+"": ""); frw.write(""""+solution); frw.write(""\n""); } frw.flush(); frw.close(); } private static int addPairs(int i, int factor, int max) { int cnt = 0; int num = i; // System.out.println(i+"" ""+factor+"" ""+max); do { // System.out.println(num); int tmp = num; tmp /= 10; tmp += factor * (num % 10); num = tmp; if(num > i && num <= max)cnt++; } while (num != i); return cnt; } } " B11144,"import java.io.BufferedReader; import java.io.FileReader; public class RecycledNumbers { public static void main(String[] args) { RecycledNumbers temp = new RecycledNumbers(); temp.findPairs(); } void findPairs(){ String myFileName = ""D:\\testcase.txt""; try { BufferedReader myReader = new BufferedReader(new FileReader(myFileName)); int myTestCases = 0; myTestCases = Integer.parseInt(myReader.readLine()); for(int i=0; i j && check >= A){ boolean found = false; for(int z=0; z < size; z++){ if(myNumbers[z] == check) found = true; } if(!found){ count++; myNumbers[myNumIndex]=check; myNumIndex = myNumIndex+1; //System.out.println(""(""+j+"", ""+newNumber+"")""); } } } j++; } System.out.println(""Case #""+(i+1)+"": ""+count); } } catch (NumberFormatException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } " B10350,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; import java.util.Locale; import java.util.StringTokenizer; public class Main { private static final String TASKNAME = ""a""; private void solve() throws Exception { int tests = nextInt(); for (int test = 1; test <= tests; ++test) { printf(""Case #%d: "", test); int a = nextInt(); int b = nextInt(); HashSet set = new HashSet(); for (int i = a; i <= b; ++i) { set.add("""" + i); } HashSet ans = new HashSet(); for (int i = a; i <= b; ++i) { String s = """" + i; for (int pref = 1; pref < s.length(); ++pref) { String t = s.substring(pref) + s.substring(0, pref); if (t.charAt(0) == '0') { continue; } if (set.contains(t) && !s.equals(t)) { long aa = i; long bb = Integer.parseInt(t); if (aa > bb) { long tt = aa; aa = bb; bb = tt; } long key = (aa << 30) + bb; if (ans.add(key)) { // System.err.println(s + "" "" + t); } } } } println(ans.size()); } // char[] map = new char[26]; // Arrays.fill(map, '#'); // for (int i = 0; i < 3; ++i) { // String a = reader.readLine(); // String b = reader.readLine(); // for (int j = 0; j < a.length(); ++j) { // if (a.charAt(j) == ' ') { // continue; // } // int c = a.charAt(j) - 'a'; // char d = b.charAt(j); // if (map[c] != '#' && map[c] != d) { // throw new AssertionError(); // } // map[c] = d; // } // } // map['z' - 'a'] = 'q'; // map['q' - 'a'] = 'z'; // System.err.println(new String(map)); } private void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(new OutputStreamWriter(System.out)); reader = new BufferedReader(new FileReader(TASKNAME + "".in"")); writer = new PrintWriter(TASKNAME + "".out""); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(13); } } public static void main(String[] args) { long time = System.currentTimeMillis(); Locale.setDefault(Locale.US); new Main().run(); System.err.printf(""%.3f\n"", (System.currentTimeMillis() - time) * 1e-3); } private StringTokenizer tokenizer; private PrintWriter writer; private BufferedReader reader; private String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private void print(Object o) { writer.print(o); } private void println(Object o) { writer.println(o); } private void printf(String format, Object... args) { writer.printf(format, args); } } " B12471,"import java.io.*; import java.util.*; import java.util.regex.*; public class jam03 { /** * @param args */ public static void main1(){ // scalar product problem } public static void main(String[] args) { // TODO Auto-generated method stub int number_test; Scanner sc = new Scanner(System.in); number_test = sc.nextInt(); for(int j=1;j<=number_test;j++) { int lowerLimit = sc.nextInt(); int upperLimit = sc.nextInt(); System.out.print(""Case #"" + j + "": ""); action(lowerLimit,upperLimit); // System.out.println(sum); } } private static void action(int lowerLimit, int upperLimit ) { // TODO Auto-generated method stub // Iterating over the elements in the set int finalGuys = 0; int maxZeroes = 0; int oldNum=0; // System.out.println(""lower""+ lowerLimit); // System.out.println(""uper""+upperLimit); for(int i=lowerLimit;i=1;k--) {//3422 int temp = (int) (i/Math.pow(10, k));//34 if(maxZeroes ==0 && temp > 0) { maxZeroes = k; //System.out.println(""maxZeroes""+maxZeroes); } if(maxZeroes>0) { int temp1 = (int) (i - (temp*Math.pow(10, k)));//3422-3400 int newNum = (int) ((temp1*Math.pow(10, maxZeroes-k+1))+temp);//4223 if(newNum <= upperLimit && newNum > i && newNum != oldNum) { oldNum = newNum; finalGuys++; } } } } System.out.println(finalGuys); } } " B12721,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.lang.Integer; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new BufferedReader(new FileReader(""input.in""))); int x = new Integer(in.nextLine()); HashSet visited = new HashSet(); for (int xi = 1; xi <= x; xi++) { String[] token = in.nextLine().split("" ""); int min = Integer.parseInt(token[0]); int max = Integer.parseInt(token[1]); int count = 0; for (int i = min; i <= max; i++) { String s = Integer.toString(i); for (int j = 0; j < Integer.toString(min).length(); j++) { Integer recycle = Integer.parseInt(s.substring(j) + s.substring(0, j)); if (!visited.contains(recycle)) if (recycle < i && recycle >= min && recycle <= max) count++; visited.add(recycle); } visited.clear(); } System.out.print(""Case #"" + xi + "": ""); System.out.println(count); } } }" B11288,"import java.io.*; import java.util.*; public class C{ public static void main(String[] args) throws Exception{ BufferedReader fin = new BufferedReader(new FileReader(""C.txt"")); PrintWriter fout = new PrintWriter(new FileWriter(""Cout.txt"")); String s = fin.readLine(); int t = Integer.parseInt(s); s = fin.readLine(); for(int i = 0; i < t; i++){ String[] sp = s.split("" ""); int a = Integer.parseInt(sp[0]); int b = Integer.parseInt(sp[1]); int count = 0; System.out.println(a + "" "" + b); ArrayList visited = new ArrayList(); for(int n = a; n <= b; n++){ String ns = """" + n; for(int j = 1; j <= ns.length() - 1; j++){ int m = (int)((n % Math.pow(10, ns.length() - j)) * Math.pow(10, j)) + (n / (int)Math.pow(10, ns.length() - j)); if(!visited.contains(m) && m > n && m >= a && m <= b){ count++; visited.add(m); //System.out.println(n + "" "" + m); } } visited.clear(); } //count /= 2; fout.println(""Case #"" + (i + 1) + "": "" + count); fout.flush(); s = fin.readLine(); } } }" B10280,"package files; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.Hashtable; public class Recycle2 { public static void main(String[] args) { try { String line; String data=""""; File ff = new File(""Output.txt""); if (ff.exists()) { ff.delete(); } //BufferedReader br = new BufferedReader(new FileReader(""/Users/Sush/Documents/workspace1/CJ/src/files/Input.txt"")); BufferedReader br = new BufferedReader(new FileReader(""/Users/Sush/Downloads/C-small-attempt2.in.txt"")); StringBuffer sb = new StringBuffer(); while((line = br.readLine())!= null) { sb = sb.append(line +""\n""); } String[] nos = sb.toString().split(""\n""); for (int i = 1; i< nos.length; i++) { Hashtable counts = new Hashtable(); //System.out.println(""Str ""+nos[i]); String[] num = nos[i].split("" ""); int count=0; int begin=Integer.parseInt(num[0]); int end = Integer.parseInt(num[1]); while(begin < end) { int a = begin; int d = (int)Math.floor(Math.log10(a)); if (d!= 0) { int f = a/(int)(Math.pow(10, d)); int n = a/(int)(Math.pow(10, d-1)); if (f>n) { a = f * (int)Math.pow(10, d) + n * (int)Math.pow(10, d-1); } } int check = a; int x = 0; if (!counts.containsKey(a)) { counts.put(a, 0); while(x != a) { x = (check%10)*(int)(Math.pow(10.0, d)) + (check/10); check = x; if (x > a && x <= end) { //counts.put(x, 0); count = count +1; counts.put(a, count); } } } begin = begin + 1; } data = data + ""Case #""+i+"": ""+count+""\n""; System.out.print(""Case #""+i+"": ""); System.out.println(count); } BufferedWriter bw = new BufferedWriter(new FileWriter(ff, true)); bw.write(data); bw.close(); } catch(Exception e) { System.out.println(e); } } } " B11551,"package org.ivansopin.jam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.StringTokenizer; public class RecycledNumbers { final static String fileName = ""RecycledNumbers1""; final static String inExtension = "".in""; final static String outExtension = "".out""; final static String source = fileName + inExtension; final static String destination = fileName + outExtension; static BufferedReader bufferedReader; static BufferedWriter bufferedWriter; static int counter; /* this is problem-specific */ static int numOfCases; static int a, tmpA; static int b, tmpB; public static void main(String[] args) throws NumberFormatException, IOException, InterruptedException { bufferedReader = new BufferedReader(new FileReader(new File(source))); bufferedWriter = new BufferedWriter(new FileWriter(new File(destination))); numOfCases = Integer.parseInt(bufferedReader.readLine()); Reader reader = new Reader(); reader.start(); reader.join(); for (int i = 0; i < numOfCases; i++) { copyData(); reader = new Reader(); reader.start(); /********* this is where the real logic starts **********/ // at some point, the results should be printed: bufferedWriter.write(""Case #"" + (i + 1) + "": "" + getNumOfRecNums(a, b) + ""\n""); /********** this is where the real logic ends ***********/ if (reader.isAlive()) { reader.join(); } } bufferedWriter.close(); bufferedReader.close(); } static int getNumOfRecNums(int a, int b) { boolean[] seen = new boolean[2000001]; HashSet set; int curNum; int size; int total = 0; for (int num = a; num <= b; num++) { if (!seen[num]) { set = new HashSet(); String numStr = num + """"; int length = numStr.length() - 1; seen[num] = true; if (num >= a && num <= b) set.add(num); for (int i = 0; i < length; i++) { numStr = numStr.charAt(length) + numStr.substring(0, length); curNum = Integer.parseInt(numStr); seen[curNum] = true; if (curNum >= a && curNum <= b) set.add(curNum); } if ((size = set.size()) > 1) { total += (size * (size - 1) / 2); } } } return total; } static void copyData() { /* this is problem-specific */ a = tmpA; b = tmpB; } static class Reader extends Thread { public Reader() { } @Override public void run() { String line; StringTokenizer tokenizer; try { if (counter < numOfCases) { /* this is problem-specific */ line = bufferedReader.readLine(); tokenizer = new StringTokenizer(line); tmpA = Integer.parseInt(tokenizer.nextToken()); tmpB = Integer.parseInt(tokenizer.nextToken()); counter++; } } catch (IOException e) { e.printStackTrace(); } } } } " B10382,"package jam2012; import java.io.*; import java.util.*; // Marian G Olteanu public class QC { public static void main(String[] args) throws Exception { initRecycle(2020202); BufferedReader inputFile = new BufferedReader(new InputStreamReader(new FileInputStream(args[0]))); int cases = Integer.parseInt(inputFile.readLine()); PrintStream outFile = new PrintStream(new FileOutputStream(args[1])); for (int i = 1; i <= cases; i++) { String lineT[] = tokenize(inputFile.readLine()); int A = Integer.parseInt(lineT[0]); int B = Integer.parseInt(lineT[1]); int out = 0; for (int j = A; j <= B; j++) if (recycle[j] != null) for (int e : recycle[j]) if (e >= A) out++; outFile.println(""Case #"" + i + "": "" + out); } outFile.close(); inputFile.close(); } private static int[][] recycle; private static int totalR = 0; public static void initRecycle(int len) { recycle = new int[len][]; Set r = new HashSet(); for (int i = 0; i < recycle.length; i++) { String s1 = """" + i; for (int cut = 1; cut < s1.length(); cut++) { String s2 = s1.substring(cut) + s1.substring(0, cut); //System.out.println(s1 + "".."" + s2); if (!s2.startsWith(""0"")) { int v2 = Integer.parseInt(s2); if (v2 < i) r.add(v2); } } //System.out.println(i + "": "" + r); if (r.size() > 0) { recycle[i] = toArray(r); r.clear(); } } //System.out.println(totalR); } private static int[] toArray(Collection r) { int[] out = new int[r.size()]; int i = 0; for (Integer e : r) out[i++] = e.intValue(); // for (int i = 0; i < out.length; i++) // out[i] = r.get(i).intValue(); totalR += out.length; return out; } public static String[] tokenize(String input) { StringTokenizer st = new StringTokenizer(input); String[] k = new String[st.countTokens()]; for (int i = 0; i < k.length; i++) k[i] = st.nextToken(); return k; } public static String[] tokenize(String input, String sep) { StringTokenizer st = new StringTokenizer(input , sep); String[] k = new String[st.countTokens()]; for (int i = 0; i < k.length; i++) k[i] = st.nextToken(); return k; } } " B12921,"import java.io.FileReader; import java.io.BufferedReader; import java.io.IOException; import java.util.Scanner; import java.util.Locale; public class NumberPairs { public static void main(String[] args) throws IOException { Scanner s = null; try { s = new Scanner(new BufferedReader(new FileReader(""NumberPairs.in""))); int N = s.nextInt(); for (int i = 1; i <= N; i++) { int a = s.nextInt(), b = s.nextInt(); System.out.println(""Case #"" + i + "": "" + calculate(a, b)); } } finally { if (s != null) { s.close(); } } } static int calculate(int a, int b) { int result = 0; for (int i = a; i <= b; i++) for (int j = i; j <= b; j++) if (isPair(i,j)) result++; return result; } static boolean isPair(int x, int y) { if (x == y) return false; byte[] p1 = ("""" + x).getBytes(), p2 = ("""" + y).getBytes(); int size = p1.length; for (int start = 0; start < size; start++) { for (int offset = 0; offset < size; offset++) { if (p1[offset] != p2[(start + offset) % size]) break; if (offset == size - 1) { // System.out.println(""Pair: "" + x + "" "" + y); return true; } } } return false; } } " B10633,"import java.io.*; import java.util.*; public class GoogleQual2012C { public static void main(String[] args) throws Throwable { new GoogleQual2012C(); } public GoogleQual2012C() throws Throwable { Scanner in = new Scanner(new File(""C-small-attempt0.in"")); PrintWriter out = new PrintWriter(new FileWriter(""C-small-attempt0.out"")); int numTests = in.nextInt(); for (int i = 0; i < numTests; i++) { int a = in.nextInt(); int b = in.nextInt(); int total = 0; for (int curr = a; curr < b; curr++) { int numDigits = this.numDigits(curr); int[] alreadySeen = new int[numDigits - 1]; for (int numToTake = 1; numToTake < numDigits; numToTake++) { int recycled = this.moveDigits(curr, numToTake); if (recycled > curr && recycled <= b && !this.contains(alreadySeen, recycled)) { total++; alreadySeen[numToTake - 1] = recycled; } } } out.println(""Case #"" + (i + 1) + "": "" + total); } out.close(); } private int numDigits(int n) { int toRet = 1; while (n >= 10) { n /= 10; toRet++; } return toRet; } private int moveDigits(int num, int numToTake) { int exp = this.numDigits(num) - numToTake; int base = 1; for (int i = 0; i < numToTake; i++) { base *= 10; } int otherBase = 1; for (int i = 0; i < exp; i++) { otherBase *= 10; } return (num / base) + (num % base) * otherBase; } private boolean contains(int[] array, int value) { for (int i = 0; i < array.length; i++) { if (array[i] == value) { return true; } } return false; } }" B10065,"import java.util.*; import java.io.*; import static java.lang.Math.*; public class ProblemC { static int numLength(int x) { int ans = 0; while (x > 0) { ans ++; x /= 10; } return ans; } public static void main(String[] args) throws FileNotFoundException { Scanner fin = new Scanner(new File(""C.txt"")); PrintStream fout = new PrintStream(""C.ans""); int caseN = fin.nextInt(); for (int caseI = 1; caseI <= caseN; caseI++) { int A = fin.nextInt(); int B = fin.nextInt(); int ans = 0; for (int n = max(A, 12); n < B; n++) { String front = Integer.valueOf(n / 10).toString(); String back = Integer.valueOf(n % 10).toString(); Set appeared = new HashSet(); while (front.length() != 0) { if (back.charAt(0) != '0') { int m = Integer.valueOf(back + front); if (m > n && m <= B && !appeared.contains(m)) { ans++; appeared.add(m); //fout.println(n + "" "" + m); } } back = front.charAt(front.length() - 1) + back; front = front.substring(0, front.length() - 1); } } fout.println(""Case #"" + caseI + "": "" + ans); } } } " B11610,"package com.google.codejam.qualrnd.recyclednums; import java.util.Scanner; public class RecycledNumbersInputReader { public RecycledNumbersInput read() { Scanner scanner = new Scanner(System.in); String firstLine = scanner.nextLine(); int noOfLines = Integer.parseInt(firstLine); long[][] numPairs = new long[noOfLines][2]; for (int lineNum = 0; lineNum < noOfLines; lineNum++) { String inputValues[] = scanner.nextLine().split("" ""); numPairs[lineNum][0] = Integer.parseInt(inputValues[0]); numPairs[lineNum][1] = Integer.parseInt(inputValues[1]); } return new RecycledNumbersInput(noOfLines, numPairs); } } " B11109,"package prob2; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; public class prob2 { public static void main(String args[]) { try { BufferedReader in = new BufferedReader(new InputStreamReader(new DataInputStream(new FileInputStream(""./src/prob2/a-small.in"")))); BufferedWriter out = new BufferedWriter(new FileWriter(""./src/prob2/a-small.out"")); int line = Integer.parseInt(in.readLine()); for (int i = 0; i < line; i++) { int count = 0; String inLine[] = in.readLine().split("" ""); out.append(""Case #"" + (i+1) + "": ""); int min = Integer.parseInt(inLine[0]); int max = Integer.parseInt(inLine[1]); Set inn = new HashSet(); if (max > 11) { for (int l = min; l <= max; l++) { inn.clear(); String ll = l + """"; for (int a = ll.length() - 1; a >= 1; a--) { if (ll.charAt(a) != '0') { int t = Integer.parseInt(ll.substring(a) + ll.substring(0, a)); if (l >= min && t <= max && l=a&&temp<=b&&data[temp]==0&&mc==numdig(temp)) { System.out.print("" ""+temp); data[temp] = 1; count++; } temp = recnum(temp,mc); } flag = flag+count; } System.out.println("" ""+count); if(count>1) counter = counter + (count*(count-1))/2; } System.out.println("" ""+flag); try{ out.write(""Case #""+(j+1)+"": ""+counter); out.write(""\r\n""); }catch (Exception e){ System.err.println(""Error: "" + e.getMessage()); } } out.close(); } static int numdig(int n) { int count = 1; while(n/10>0) { count++; n = n/10; } return count; } static int recnum(int n,int p) { int pow = 1; int num; num = p-1; for(int i=0;i arr = new ArrayList(); for(int i=1; i= n1 && ns <= n2 && ns != k && !arr.contains(ns)){ casos++; arr.add(ns); //System.out.println(ns); } } } System.out.println(""Case #"" + j + "": "" + casos / 2); } } } " B11824,"import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) throws IOException { String inputName = ""C-small-attempt0""; FileReader fr = new FileReader(inputName+"".in""); Scanner sc = new Scanner(fr); FileWriter fstream = new FileWriter(inputName+"".out""); BufferedWriter out = new BufferedWriter(fstream); int T = sc.nextInt(); for(int i = 0; i < T; i++){ int A = sc.nextInt(); int B = sc.nextInt(); int ans = 0; for(int n = A; n <= B; n++){ String s = """"+n; ArrayList mlist = new ArrayList(); for(int k = 1; k < s.length(); k++){ String s2 = s.substring(k) + s.substring(0, k); int m = Integer.parseInt(s2); if(m > n && m <= B && !mlist.contains(m)){ //System.out.println(s + "" "" + s2); ans++; mlist.add(m); } } } out.write(""Case #"" + (i+1) + "": "" + ans); out.newLine(); System.out.println(""Case #"" + (i+1) + "": "" + ans); } } } " B12239,"import java.io.*; import java.util.*; public class QualiC_Naive { static void sop(String str) { System.out.println(str); } static void sop1(String str) { System.out.print(str); } public static void main(String args[]) { long tstart = System.currentTimeMillis(); if(args.length < 1) { System.out.println(""You have not given input file!""); System.exit(0); } File f1 = null; Scanner sc = null; try { f1 = new File(args[0]); sc = new Scanner(f1); } catch(Exception e) { System.out.println(""Error opening the input file "" + e); } /* int nCases, i, j, k, m, n; sc.next(); sc.nextInt(); sc.nextLine(); sc.nextDouble(); */ int nCases, i, j, k, m, n; nCases = sc.nextInt(); // sc.nextLine(); for(i=1; i<=nCases; ++i) { int a = sc.nextInt(); int b = sc.nextInt(); int ans = 0; String strn = """" + a; // String strm = """" + b; int len = strn.length(); int mult=0; switch(len) { case 2: mult = 10; break; case 3: mult = 100; break; case 4: mult = 1000; break; case 5: mult = 10000; break; case 6: mult = 100000; break; case 7: mult = 1000000; break; } if(len == 1) ans = 0; else { /* try { FileWriter tempf = new FileWriter(""temp.dat""); BufferedWriter buff = new BufferedWriter(tempf); buff.write(""Case "" + i + "":-------------------------------------------\n""); */ int c[] = new int[len]; for(j=a; j<=b; j++) { c[0] = j; HashSet x = new HashSet(); for(k=1; k input_list = Files.readAllLines(input_path,Charset.forName(""UTF-8"")); int begin = 0; while(begin a1 = new ArrayList(); for(int i = n; i<=m; i++) { for(int j = 1; j<(""""+n).length();j++) { int rec = recycled(""""+i, j); if(rec>=n &&rec<=m && rec != i) { if(rec numList = new ArrayList<>(); for(long i=a; i<=b; ++i){ tens = 10; numList.clear(); for(int j=0; j<= order-1; ++j){ num = Math.round((double)(i + ((i%(Math.round(tens)))*bigNines))/(double)tens); if(num >=a && num<=b&& num !=i&& !numList.contains(num)){ buffer = num; ordnum=0; do{ buffer = buffer/10; ordnum++; }while(buffer !=0); ordnum--; if(ordnum == order) count++; } numList.add(num); tens = 10*tens; } } return count/2; } public static int noOfRecycledPair(long a, long b){ int count = 0; int orderA = 0, orderB=0; long num = a; do{ num = num/10; orderA++; }while(num!=0); orderA --; num = b; do{ num = num/10; orderB++; }while(num!=0); orderB --; if (orderA == orderB){ System.out.println(""equals""); count = noOfRecycledPairWithSameOrder(a, b); } else{ System.out.println(""not equals""); long aLimit = (long) (Math.pow(10,orderA) -1); count = noOfRecycledPairWithSameOrder(a, aLimit) + noOfRecycledPair(aLimit, b); } return count; } } " B12121,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) throws IOException { FileWriter wr=new FileWriter(""Output.txt""); BufferedWriter buff=new BufferedWriter(wr); FileReader read=new FileReader(""C-small-attempt0.in""); BufferedReader buffr=new BufferedReader(read); String str; str=buffr.readLine(); int n=Integer.parseInt(str); int j=1; int a,b; int num,lower,upper; int total; while(j<=n) { str=buffr.readLine(); Scanner sc=new Scanner(str); sc.useDelimiter("" ""); a=sc.nextInt(); b=sc.nextInt(); upper=b; lower=a; total=0; while(a<=b) { String first=Integer.toString(a); String orig=first; String newStr; int curr=Integer.parseInt(first); if(first.length()!=1) { while(true) { first=first.charAt(first.length()-1)+first.substring(0,first.length()-1); if(first.equals(orig)) break; if(!first.startsWith(""0"")) { num=Integer.parseInt(first); if(num<=upper && num>=lower && num>curr) ++total; } } } ++a; } StringBuffer temp = new StringBuffer(""Case #""+j+"": ""); temp=temp.append(Integer.toString(total)); buff.write(temp.toString()); buff.newLine(); ++j; } buff.close(); } } " B12027,"package codejam2012; import java.io.BufferedReader; import java.io.FileReader; import java.io.PrintStream; public class ProblemC { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new FileReader(""in.txt"")); PrintStream out = System.out; out = new PrintStream(""out.txt""); int T = Integer.parseInt(in.readLine()); for (int t = 0; t < T; t++) { String[] tok = in.readLine().split("" ""); int A = Integer.parseInt(tok[0]); int B = Integer.parseInt(tok[1]); long ans = 0; boolean[] used = new boolean[10000000]; int f = 1; while (10*f <= A) f *= 10; for (int n = A; n <= B; n++) { if (used[n]) continue; long k = 1; int m = n; while (!used[m]) { used[m] = true; m = f*(m%10) + (m/10); if (!used[m] && m >= A && m <= B) k++; } ans += k * (k-1) / 2; } out.printf(""Case #%d: %d\n"", t+1, ans); } if (out != System.out) out.close(); } } " B12526,"package round0; import java.io.BufferedReader; import java.io.FileReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; public class Dance { BufferedReader _in; PrintWriter _out; int _numTestCases; Input[] _inputs; public Dance(BufferedReader in) throws Exception { this._in = in; this._out = new PrintWriter(""answers.out""); } public void calculate() throws Exception { this._inputs = readInputs(); for(int i=0; i < _inputs.length; i++) { processInput(_inputs[i], i+1); } _out.flush(); _out.close(); } private void processInput(Input input, int caseIndex) { int numPairs = 0; int A = input.A; int B = input.B; //worry about duplicates HashSet combinations = new HashSet(1000000); for(int n=A; n<=B; n++) { int numDigits = 1; int div = 10; while(n/div != 0) { numDigits++; div *= 10; } int div2 = 10; for(int digitsToMove = 1; digitsToMove < numDigits; digitsToMove++){ div /= 10; int m = n/div2 + n%div2 * div; if(m >= A && n >=A && m <=B && n <=B && n < m) { Tuple t = new Tuple(n,m); if(!combinations.contains(t)) { numPairs++; combinations.add(t); } } div2 *=10; } } _out.println(""Case #"" + caseIndex +"": "" + numPairs); } private class Tuple { int n; int m; public Tuple (int n, int m) { this.n = n; this.m = m; } @Override public int hashCode() { return m + n; } @Override public boolean equals(Object obj) { Tuple other = (Tuple)obj; if (m != other.m) return false; if (n != other.n) return false; return true; } } private Input[] readInputs() throws Exception { Scanner scanner = new Scanner(_in); _numTestCases = scanner.nextInt(); Input[] inputs = new Input[_numTestCases]; for(int i=0; i < _numTestCases; i++) { int A = scanner.nextInt(); int B = scanner.nextInt(); inputs[i] = new Input(A,B); } return inputs; } public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new FileReader(args[0])); new Dance(in).calculate(); } private class Input { int A; int B; public Input(int A, int B) { this.A = A; this.B = B; } } } " B10622,"package CaseSolvers; import Controller.IO; public abstract class CaseSolver { private int order; public CaseSolver(int order, int numberOfLines, IO io) { this.order = order; initializeVars(); addAllLines(io, numberOfLines); } public abstract void addLine(String line); public abstract void initializeVars(); public abstract void printSolution(); public abstract CaseSolver process(); public void addAllLines(IO io, int numberOfLines) { for (int i = 0; i < numberOfLines; i++) { addLine(io.readLine()); } } public int getOrder() { return order; } } " B11039,"package qual2012; import java.io.FileWriter; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); //PrintWriter out = new PrintWriter(System.out); PrintWriter out = new PrintWriter(new FileWriter(""C.out"")); for (int t = in.nextInt(), cs = 1; t > 0; t--, cs++) { out.print(""Case #"" + cs + "": ""); int a = in.nextInt(), b = in.nextInt(); long ans = 0; for (int i = a; i <= b; i++) { ans += go(i, a); } out.println(ans); } out.flush(); } static long go(int x, int low) { String s = x + """"; Set set = new HashSet(); for (int i = 1; i < s.length(); i++) { String w = s.substring(i) + s.substring(0, i); if (w.startsWith(""0"")) continue; int y = Integer.valueOf(w); if (low <= y && y < x) set.add(y); } return set.size(); } } " B11614,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.Scanner; public class leadingZero { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader read = new BufferedReader(new InputStreamReader( System.in)); String ll; ll = read.readLine(); int a = Integer.parseInt(ll); for (int k = 0; k < a; k++) { Scanner scn=new Scanner(read.readLine()); int A = scn.nextInt(); int B = scn.nextInt(); int[] s = new int[20000000]; for (int i = A; i <= B; i++) { String r = i + """"; int l = i; LinkedListlist=new LinkedList(); for (int j = 0; j < r.length() - 1; j++) { int b = l % 10; l = l / 10 + (int) Math.pow(10, r.length() - 1) * b; if (l > i && !list.contains(l)) { s[l]++; list.add(l); } } } int sum = 0; for (int i = A; i <= B; i++) { if (s[i] > 0) { sum += s[i]; //System.out.println(i+"" .. ""+s[i]); } } System.out.println(""Case #""+(k+1)+"": ""+sum); } } } " B10556,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package googl2; /** * * @author Mimo */ import java.io.*; import java.util.Scanner; public class Googl2 { /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException, IOException { // TODO code application logic here int t; int result; String input1; String input2; String input4; int a,b; File input=new File(""C:\\Users\\Mimo\\Desktop\\C-small-attempt0.in""); FileWriter output=new FileWriter(""output.txt""); BufferedWriter out = new BufferedWriter(output); Scanner getter = new Scanner(input); t=getter.nextInt(); getter.nextLine(); for(int i=1;i<=t;i++) { result=0; input1=getter.next(); input2=getter.next(); a=Integer.valueOf(input1); b=Integer.valueOf(input2); for(int j=a;jj && input4.charAt(0)!='0') result++; System.out.println(input4+"" ""+"" ""+b+"" ""+result+"" ""+j); input4=String.valueOf(j); } } out.write(""Case #""+i+"": ""+result); out.newLine(); } out.close(); } } " B10731,"import java.io.*; public class Test { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in, ""UTF-8"")); int num = Integer.parseInt(br.readLine()); int nline = 1; String line; while ((line = br.readLine()) != null && nline <=num) { String[] tok = line.split("" ""); int size = tok[0].length(); double result = 0; if (size != 1) { int A = Integer.parseInt(tok[0]); int B = Integer.parseInt(tok[1]); for (int i = A; i <= B; i++) { int n = size; String str = Integer.toString(i); for (int j = 1; j < size; j++) { String str2 = str.substring(j) + str.substring(0, j); if ((Integer.parseInt(str2) < A) || (Integer.parseInt(str2) > B) || (Integer.parseInt(str2) == Integer.parseInt(str))) --n; } if (n >= 2) result += n * (n-1) / 2.0 * 1.0 / n; } } System.out.println(""Case #"" + nline + "": "" + (int) result); nline++; } } } " B10748," /* ID: codeKNIGHT LANG: JAVA TASK: */ import java.util.*; import java.math.*; import java.io.*; class recyledNumbers { public static void main(String args[])throws IOException { //Scanner in=new Scanner(System.in); Scanner in=new Scanner(new FileReader(""C:\\Users\\Lokesh\\Desktop\\C-small-attempt0.in"")); //PrintWriter out=new PrintWriter(System.out); //BufferedReader br=new BufferedReader(new FileReader(""C:\\Users\\Lokesh\\Desktop\\input.in"")); PrintWriter out=new PrintWriter(new BufferedWriter(new FileWriter(""E:\\programss\\GCJ\\output.txt""))); int t=in.nextInt(),test,i,a,b,j; String s,s1,s2; for(test=1;test<=t;test++) { a=in.nextInt(); b=in.nextInt(); int c=0,k; for(i=a;i<=b;i++) { s=Integer.toString(i); int max=s.charAt(0); boolean stat=false; for(j=1;j=max) { s1=s.substring(j,s.length()); s2=s.substring(0,j); k=Integer.parseInt(s1+s2); if(k>i&&k<=b&&!stat) { c++; } if(s1.equals(s2)) stat=true; } } } out.println(""Case #""+test+"": ""+c); } out.flush(); System.exit(0); } } " B10684,"package qual; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class C { static long count(int n , int B){ String s = String.valueOf(n); Set set = new TreeSet(); for(int i = 1 ; i < s.length() ; ++i){ String rot = s.substring(i) + s.substring(0, i); if(rot.charAt(0) == '0')continue; int v = Integer.parseInt(rot); if(n < v && v <= B){ set.add(v); } } return set.size(); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for(int cn = 1 ; cn <= T ; ++cn){ int A = sc.nextInt(); int B = sc.nextInt(); long ret = 0; for(int n = A ; n <= B ; ++n){ ret += count(n , B); } System.out.printf(""Case #%d: %d\n"", cn , ret); } } } " B12152,"//package RecycleNumber; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; public class C { public static HashSet hm = new HashSet(); public static void main(String [] args) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int num = Integer.parseInt(in.readLine()); int count = 1; rotate(1234,10,2222); while(num-- != 0){ String [] token = in.readLine().split("" ""); int num1 = Integer.parseInt(token[0]); int num2 = Integer.parseInt(token[1]); for(int i = num1; i <= num2; i++){ rotate(i,num1,num2); } System.out.println(""Case #""+ count++ +"": "" +hm.size()); hm.clear(); } } public static void rotate(int current, int num1, int num2){ int times = (current+"""").length()-1; int check = current; String temp = current+""""; while(times >= 0 ){ temp = temp.charAt(temp.length()-1) + temp.substring(0,temp.length()-1); times--; if(Integer.parseInt(temp) > num1 && Integer.parseInt(temp) <= num2 && Integer.parseInt(temp) > check){ hm.add(check +"": ""+temp); //System.out.println(check + "": "" + temp); } } } } " B12135," import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class RecycledNumber { private int numCase; public void calc() throws FileNotFoundException, IOException { FileReader reader = new FileReader(""D:/C-small-attempt0.in""); BufferedReader bf = new BufferedReader(reader); FileWriter writer = new FileWriter(""D:/output.txt""); BufferedWriter bw = new BufferedWriter(writer); numCase = Integer.parseInt(bf.readLine()); int n, m; for (int all = 1; all <= numCase; all++) { String[] inp = bf.readLine().split("" ""); n = Integer.parseInt(inp[0]); m = Integer.parseInt(inp[1]); int count = 0; if (n < 10) { count = 0; } else if (n < 100) { for (int i = n; i <= m; i++) { String temp = i + """"; String rv = temp.charAt(1) + """" + temp.charAt(0); if (Integer.parseInt(rv) >= n && Integer.parseInt(rv) <= m && Integer.parseInt(rv) != i) { // System.out.println(""I : "" + i + "" RV : "" + rv); count++; } } } else if (n >= 100 && n <= 999) { for (int i = n; i <= m; i++) { String temp = i + """"; String rv = temp.charAt(2) + """" + temp.charAt(0) + """" + temp.charAt(1); if (Integer.parseInt(rv) >= n && Integer.parseInt(rv) <= m && Integer.parseInt(rv) != i) { // System.out.println(""I : "" + i + "" RV : "" + rv); count++; } rv = temp.charAt(1) + """" + temp.charAt(2) + """" + temp.charAt(0); if (Integer.parseInt(rv) >= n && Integer.parseInt(rv) <= m && Integer.parseInt(rv) != i) { // System.out.println(""I : "" + i + "" RV : "" + rv); count++; } } } else if (n >= 1000 & n <= 9999) { for (int i = n; i <= m; i++) { String temp = i + """"; String rv = temp.charAt(1) + """" + temp.charAt(2) + """" + temp.charAt(3) + """" + temp.charAt(0); if (Integer.parseInt(rv) >= n && Integer.parseInt(rv) <= m && Integer.parseInt(rv) != i) { // System.out.println(""I : "" + i + "" RV : "" + rv); count++; } rv = temp.charAt(2) + """" + temp.charAt(3) + """" + temp.charAt(0) + """" + temp.charAt(1); if (Integer.parseInt(rv) >= n && Integer.parseInt(rv) <= m && Integer.parseInt(rv) != i) { // System.out.println(""I : "" + i + "" RV : "" + rv); count++; } rv = temp.charAt(3) + """" + temp.charAt(0) + """" + temp.charAt(1) + """" + temp.charAt(2); if (Integer.parseInt(rv) >= n && Integer.parseInt(rv) <= m && Integer.parseInt(rv) != i) { // System.out.println(""I : "" + i + "" RV : "" + rv); count++; } } } System.out.println(""Case #"" + all + "": "" + count / 2); bw.write(""Case #"" + all + "": "" + count / 2+""\r\n""); } bw.close(); writer.close(); bf.close(); reader.close(); } public static void main(String[] args) throws FileNotFoundException, IOException { RecycledNumber rn = new RecycledNumber(); rn.calc(); } }" B11311,"/** * Copyright 2012 Christopher Schmitz. All Rights Reserved. */ package com.isotopeent.codejam.lib; public abstract class SolverBase { private InputReader inputReader; protected int[] params; public SolverBase(int initParamCount) { if (initParamCount > 0) { params = new int[initParamCount]; } } public void init(InputReader inputReader) { this.inputReader = inputReader; if (params != null) { try { String line = inputReader.readLine(); params = Utils.convertToIntArray(line, params.length); } catch (Exception e) { System.err.println(""Error while reading initial parameters""); e.printStackTrace(); } } } public final String solveNext() { String solution = null; T input = inputReader.readInput(); if (input != null) { solution = solve(input); } return solution; } protected abstract String solve(T input); } " B11322,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; public class recycling { public static void main (String args[]){ if (args.length != 1){ System.out.println (""Gimme the right arguments!""); return; } File f = new File(args[0]); int testcases, A, B; ArrayList values = new ArrayList (); try{ BufferedReader in = new BufferedReader (new FileReader(f)); String s; testcases = Integer.parseInt(in.readLine()); for (int i = 1; i<=testcases; i++){ String temp [] = in.readLine().split("" ""); A = Integer.parseInt(temp[0]); B = Integer.parseInt(temp[1]); int count = 0; for (int j=A; j<=B; j++){ ArrayList v = new ArrayList (); v.add(j); String number = Integer.toString(j); int val; for (int k=0; k=1000000) numChecks = 6; else if(x>=100000) numChecks = 5; else if(x>=10000) numChecks = 4; else if(x>=1000) numChecks = 3; else if(x>=100) numChecks = 2; else numChecks = 1; String xstr=new String(""""+x); int tmp=0; for(int i=0; i= min && tmp <= max) matches++; if(tmp<=2000000) checked[tmp]=true; } if(matches == 1) return 0; else if(matches == 2) return 1; else if(matches == 3) return 3; else if(matches == 4) return 6; else if(matches == 5) return 10; else if(matches == 6) return 15; else if(matches == 7) return 21; return 0; } } " B11411,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class RecycledNumbers { public RecycledNumbers() { } public int getNumDigits(int x) { if(x == 0 || x == 1) return 1; int counter =0 ; int check = 1; while(check<=x) { counter ++ ; check*=10; } return counter; } public int traverse(int x, int i) { if(x<10) return x ; int y = x/((int)Math.pow(10,i+1)); int lastDigits = x-(y * (int)Math.pow(10,i+1)); return ((int)Math.pow(10, getNumDigits(y))*lastDigits )+ y; } public boolean isRecycled(int x, int y) { int numOFDigits = getNumDigits(x); int z = x ; for(int i=0 ; i = A && (int)number <= B) { total++; } } } output.write(""Case #"" + (i + 1) + "": "" + (total/2)); if (i != T - 1) { output.write(""\n""); } i++; } output.close(); } } " B12727,"package com.develog; import java.io.IOException; public class Runner { public static void main(String args[]) throws IOException{ new C(); } } " B12715,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package gcj12_qc; import java.io.FileOutputStream; import java.util.HashSet; import java.util.Scanner; /** * * @author youssefgamil */ public class Gcj12_qC { /** * @param args the command line arguments */ public static String leading0(String txt) { while(txt.charAt(0)=='0') txt=txt.substring(1); return txt; } public static void main(String[] args) throws Exception { HashSet hs=new HashSet(); Scanner sc=new Scanner(System.in); FileOutputStream out=new FileOutputStream(""out.txt""); int a,b,i,j,tc,T; long res=0; String tmp; T=sc.nextInt(); for(tc=1;tc<=T;tc++) { a=sc.nextInt(); b=sc.nextInt(); res=0; for(i=a;i<=b;i++) { // if(hs.contains(i+"""")) // continue; tmp=i+""""; // hs.add(tmp); // System.out.println(tmp+"">""); hs=new HashSet(); for(j=0;j candidates = new HashMap(); new C().getCandidates(current,numLen,candidates); for(Integer key : candidates.keySet()) { int value = candidates.get(key); if(current getCandidates(int current, int length, HashMap candidates) { String numStr = String.valueOf(current); Integer value; for(int loop=1;loop set = new HashSet(); for(int j = a; j <= b; j++){ stra = j+""""; str = stra; for(int k = 1; k < stra.length();k++){ str = str.charAt(str.length()-1) + str.substring(0,str.length()-1); n = Integer.parseInt(str); if(n <= a) continue; if(n<=j) continue; if(n>b) continue; if(j 0) { t--; k++; ten = 1; len = 1; a = cin.nextInt(); b = cin.nextInt(); c = a; ans = 0; while (c > 9) { c /= 10; ten *= 10; len++; } HashSet hash = new HashSet(); for (i = a; i <= b; i++) { if (!hash.contains(i)) { hash.add(i); ts = 1; j = i; for (q = 0; q < len; q++) { j = (j % ten) * 10 + j / ten; if (j >= a && j <= b && !hash.contains(j)) { ts++; hash.add(j); } } ans += ts * (ts - 1) / 2; } } System.out.println(""Case #"" + k + "": "" + ans); } } } " B10965,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class ProblemC{ /** * @param args * @throws IOException * @throws NumberFormatException */ public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new FileReader(""C-small-attempt0.in"")); int count = Integer.parseInt(br.readLine()); for (int i = 0; i list = new ArrayList(); for (int j = 1; ji && m<=b && !list.contains(m)){ list.add(m); result++; } } } return result; } }" B10818,"import java.io.*; import java.math.*; import java.util.*; import java.text.*; public class c { public static void main(String[] args) { Scanner sc = new Scanner(new BufferedInputStream(System.in)); int[] next = new int[10000000]; int low = 1; int high = 10; for (int digits = 1; digits <= 7; ++digits) { for (int i = low; i < high; ++i) { int a = 0; int b = i; while (a == 0) { a = b % 10; b = b / 10; } next[i] = low * a + b; } low = low * 10; high = high * 10; } int T = sc.nextInt(); for (int casenumber = 1; casenumber <= T; ++casenumber) { int a = sc.nextInt(); int b = sc.nextInt(); int count = 0; for (int i = a; i <= b; ++i) { int count0 = 1; int j = next[i]; while (j != i) { if (j >= a && j <= b) ++count0; j = next[j]; } count += (count0 - 1); } count /= 2; System.out.format(""Case #%d: %d%n"", casenumber, count); } } } " B12978,"import java.io.FileWriter; import java.io.IOException; public class OutputPrinter { public OutputPrinter() { try { m_writer = new FileWriter(""C:/AHK/output.txt""); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } FileWriter m_writer; int m_case = 1; public void print(String result) { try { m_writer.write(""Case #""+ (m_case++)+"": "" + result + ""\n""); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B10141,"import java.io.*; import java.util.Scanner; class RecycledNumbers { public static void main(String Args[]) throws Exception { Scanner s=new Scanner(new FileReader(""inputCs.in"")); BufferedWriter br=new BufferedWriter(new FileWriter(""outputCs.txt"")); int T, a, b,total=0; T=s.nextInt(); String x,y; for(int I=0;I pairs = new HashSet(); for (int i = min ; i < max; i++) { for (int j = 1; j sourceNumber && finalNumber <=max; } public static void main(String[] args) { System.out.println(getRecycledNumbersCount(10,99)); System.out.println(getRecycledNumbersCount(162,939)); System.out.println(getRecycledNumbersCount(112,989)); System.out.println(getRecycledNumbersCount(100,100)); System.out.println(getRecycledNumbersCount(182,983)); System.out.println(getRecycledNumbersCount(129,963)); System.out.println(getRecycledNumbersCount(167,943)); System.out.println(getRecycledNumbersCount(158,947)); System.out.println(getRecycledNumbersCount(105,992)); System.out.println(getRecycledNumbersCount(123,941)); System.out.println(getRecycledNumbersCount(104,994)); System.out.println(getRecycledNumbersCount(364,749)); System.out.println(getRecycledNumbersCount(152,946)); System.out.println(getRecycledNumbersCount(135,927)); System.out.println(getRecycledNumbersCount(100,999)); System.out.println(getRecycledNumbersCount(142,993)); System.out.println(getRecycledNumbersCount(177,921)); System.out.println(getRecycledNumbersCount(103,966)); System.out.println(getRecycledNumbersCount(122,996)); System.out.println(getRecycledNumbersCount(120,976)); System.out.println(getRecycledNumbersCount(271,271)); System.out.println(getRecycledNumbersCount(101,921)); System.out.println(getRecycledNumbersCount(115,976)); System.out.println(getRecycledNumbersCount(137,959)); System.out.println(getRecycledNumbersCount(139,915)); System.out.println(getRecycledNumbersCount(1,2)); System.out.println(getRecycledNumbersCount(49,83)); System.out.println(getRecycledNumbersCount(114,962)); System.out.println(getRecycledNumbersCount(37,53)); System.out.println(getRecycledNumbersCount(114,982)); System.out.println(getRecycledNumbersCount(158,931)); System.out.println(getRecycledNumbersCount(314,801)); System.out.println(getRecycledNumbersCount(140,989)); System.out.println(getRecycledNumbersCount(172,958)); System.out.println(getRecycledNumbersCount(393,646)); System.out.println(getRecycledNumbersCount(112,986)); System.out.println(getRecycledNumbersCount(136,912)); System.out.println(getRecycledNumbersCount(112,938)); System.out.println(getRecycledNumbersCount(109,964)); System.out.println(getRecycledNumbersCount(166,969)); System.out.println(getRecycledNumbersCount(150,965)); System.out.println(getRecycledNumbersCount(150,944)); System.out.println(getRecycledNumbersCount(104,925)); System.out.println(getRecycledNumbersCount(102,919)); System.out.println(getRecycledNumbersCount(175,937)); System.out.println(getRecycledNumbersCount(189,991)); System.out.println(getRecycledNumbersCount(133,996)); System.out.println(getRecycledNumbersCount(190,984)); System.out.println(getRecycledNumbersCount(2,7)); System.out.println(getRecycledNumbersCount(744,744)); } } " B11367,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package qualc; import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * * @author marcin */ public class QualC { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int ci = 1; ci <= T; ++ci) { int A = in.nextInt(); int B = in.nextInt(); int result = 0; int len = Integer.toString(A).length(); char[] arrB = new char[len]; Set prevShift = new HashSet(); for (int n = A; n < B; ++n) { String strN = Integer.toString(n); for (int i = 1; i < len; ++i) { if (strN.charAt(i) != '0') { strN.getChars(i, len, arrB, 0); strN.getChars(0, i, arrB, len-i); int m = Integer.parseInt(new String(arrB)); if ((m <= B) && (m > n) && !prevShift.contains(m)) { prevShift.add(m); ++result; } } } prevShift.clear(); } System.out.println(""Case #"" + ci + "": "" + result); } } } " B12507," import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import java.util.Scanner; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Chung Lee */ public class RecycleNumber { public static void Main(String[] args) throws FileNotFoundException { Scanner scanner = new Scanner(new File(args[0])); PrintWriter writer = new PrintWriter(args[1]); int noCase = scanner.nextInt(); for (int i = 0; i < noCase; i++) { int A = scanner.nextInt(); int B = scanner.nextInt(); int noRecyclePair = 0; for (int j = A; j <= B; j++) { noRecyclePair += getNoRecyclePair(j, A, B); } noRecyclePair /= 2; System.out.print(String.format(""Case #%d: %d"", i + 1, noRecyclePair)); writer.print(String.format(""Case #%d: %d"", i + 1, noRecyclePair)); if (i != noCase - 1) { System.out.println(); writer.println(); } } writer.close(); } public static int getNoRecyclePair(int num, int A, int B) { int temp = num; int digits = 0; while (temp != 0) { temp /= 10; digits++; } int noRecyclePair = 0; for (int i = 1; i <= digits; i++) { int recycleNum = (int) ((num % Math.pow(10, i)) * Math.pow(10, digits - i) + (num / Math.pow(10, i))); if (recycleNum != num && recycleNum >= A && recycleNum <= B) { noRecyclePair++; } } return noRecyclePair; } } " B10820,"import java.util.Scanner; import java.io.*; import java.lang.Math; public class C{ public static int recycle(String str){ String[] numbers = str.split("" ""); int min = Integer.parseInt(numbers[0]); int max = Integer.parseInt(numbers[1]); int ret = 0; for(int i = min; i < max; i++){ String num = i + """"; int len = num.length(); int k = i; for(int j = 1; j < len; j++){ k = (k/10) + (int)java.lang.Math.pow(10.0,(double)(len-1))*(k%10); if (k > i && k <= max) ret++; else if(k == i) break; } } return ret; } public static void main(String[] args){ Scanner sc = null; String next; int out; try{ sc = new Scanner(new File(""C-small-attempt0.in"")); int cases = Integer.parseInt(sc.nextLine()); int current = 0; FileWriter fs = new FileWriter(""output.txt""); BufferedWriter buff = new BufferedWriter(fs); while(current < cases){ next = sc.nextLine(); current++; out = recycle(next); buff.write(""Case #"" + current + "": "" + out + ""\n""); } buff.close(); } catch(Exception ex){} } }" B12288,"import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class Main { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(new FileReader(""input.txt"")); PrintWriter pw = new PrintWriter(new FileWriter(""output.txt"")); int tn = sc.nextInt(); sc.nextLine(); for(int i = 0; i < tn; i++) { int a = sc.nextInt(); int b = sc.nextInt(); int res = 0; for(int t = a; t <= b; t++) { String oppa = t + """"; int len = (t + """").length(); for (int u = 0; u + 1 < len; u++) { if(oppa.charAt(u + 1) != '0') { int v = Integer.parseInt(oppa.substring(u + 1, len) + oppa.substring(0, u + 1)); if (t == v) break; if (a <= v && v <= b) { res++; } } } } pw.print(""Case #"" + (i + 1) + "": "" + (res / 2)); pw.println(); } pw.close(); } } " B13065,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; public class ProblemC { public static void main(String[] args) { readin(); } private static int count(int a, int b) { int numOfDigits = Integer.toString(a).length(); if (numOfDigits == 1) { return 0; } HashSet rangeFromAtoB = new HashSet(); for (int i = a; i <= b; i++) { rangeFromAtoB.add(i); } int count = 0; for (int i = a; i <= b; i++) { if (rangeFromAtoB.contains(i)) { HashSet validReordering = new HashSet(); validReordering.add(i); rangeFromAtoB.remove(i); for (int s = 1; s < numOfDigits; s++) { int back =(i / (int)(Math.pow(10, s)) ); int front = i % ((int)Math.pow(10, s)); int scale = (int) Math.pow(10, (numOfDigits - s)); int reorder = back + front * scale; if (reorder >= a && reorder <= b) { if (!validReordering.contains(reorder)) { rangeFromAtoB.remove(reorder); validReordering.add(reorder); } } } int numOfValidReordering = validReordering.size(); count = count +numOfValidReordering*(numOfValidReordering-1)/2; } } return count; } private static void readin() { try { BufferedReader in = new BufferedReader(new FileReader(""C-small-attempt0.in.txt"")); int numOfInput = Integer.parseInt(in.readLine()); int[][] input = new int[numOfInput][2]; String[] output = new String[numOfInput]; for (int i = 0; i < numOfInput; i++) { String[] currentline = in.readLine().split(""[\\s]+""); int a = Integer.parseInt(currentline[0]); int b = Integer.parseInt(currentline[1]); input[i][0] = a; input[i][0] = b; output[i] = ""Case #"" + (i+1) + "": "" + count(a, b); } BufferedWriter out = new BufferedWriter(new FileWriter( ""outputC"")); for (int i = 0; i < output.length; i++) { System.out.println(output[i]); out.write(output[i]+""\n""); } out.flush(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } " B11528,"package qualification; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; public class ProblemC { public static int solve(int A, int B){ int count = 0; for (int i = A; i <= B; i++){ String number = String.valueOf(i); String s = number + number; for (int j = 1; j < number.length(); j++){ int newnumber = Integer.parseInt(s.substring(j, j + number.length())); if ((newnumber > i) && (newnumber <= B)) count++; } } return count; } public static void main(String[] args){ try{ BufferedReader br = new BufferedReader(new FileReader(""C-small-attempt0.in"")); BufferedWriter bw = new BufferedWriter(new FileWriter(""outputC"")); String line = br.readLine(); int ans = 0; int num = Integer.parseInt(line); for (int i = 0; i < num; i++){ line = br.readLine(); String[] segs = line.split(""\\s+""); ans = solve(Integer.parseInt(segs[0]), Integer.parseInt(segs[1])); bw.write(""Case #"" + (i+1) + "": "" + ans + ""\n""); } br.close(); bw.close(); }catch(Exception e){ e.printStackTrace(); } } } " B13088,"import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; import javax.management.RuntimeErrorException; public class C { public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(new FileInputStream(""C-small-attempt0.in"")); System.setOut(new PrintStream(new FileOutputStream(""c.out""))); C c = new C(); long start = System.currentTimeMillis(); int t = sc.nextInt(); for (int i = 0; i < t; i++) System.out.println(""Case #"" + (i + 1) + "": "" + c.solve(sc.nextInt(), sc.nextInt())); long end = System.currentTimeMillis(); // System.out.println((end - start) / 1000.0); // System.out.println(""Case #"" + (i + 1) + "": "" + // c.bruteSolve(sc.nextInt(), sc.nextInt())); } private int compare(String a, String b, int shift) { int l = a.length(); int ai = 0; int bi = shift; for (int i = 0; i < l; i++) { int c = a.charAt(ai) - b.charAt(bi); if (c != 0) return c; ai++; bi++; if (bi == l) bi = 0; } return 0; } private String shift(String a, int shift) { return a.substring(shift) + a.substring(0, shift); } private long solve(int a, int b) { long count = 0; String aStr = a + """"; String bStr = b + """"; if (aStr.length() != bStr.length()) throw new RuntimeException(""Need the same length""); HashSet ready = new HashSet(); int l = aStr.length(); for (int i = a; i <= b; i++) { ready.clear(); for (int j = 1; j < l; j++) { String iStr = i + """"; String iShifted = shift(iStr, j); // debug(""Par: "" + iStr + "" and "" + iShifted); if (iShifted.equals(iStr)) continue; // Get the same // debug(""1""); if (iShifted.charAt(0) == '0') continue; // has leading zero // debug(""2""); if (iShifted.compareTo(aStr) <= 0) continue;// smaller than lower bound // debug(""4""); if (iShifted.compareTo(iStr) <= 0) continue; // smaller than first // debug(""3""); if (iShifted.compareTo(bStr) > 0) continue;// smaller than great bound // debug(""5""); if (ready.contains(iShifted)) continue; // debug(""6""); ready.add(iShifted); count++; } } return count; } private long bruteSolve(int a, int b) { long count = 0; String aStr = a + """"; String bStr = b + """"; if (aStr.length() != bStr.length()) throw new RuntimeException(""Need the same length""); HashSet ready = new HashSet(); int l = aStr.length(); for (int i = a; i <= b; i++) for (int j = i + 1; j <= b; j++) { ready.clear(); for (int k = 1; k < l; k++) { if (shift(i + """", k).equals(j + """") && !ready.contains(j + """")) { ready.add(j + """"); System.out.println(""Pair: "" + i + "" and "" + j); count++; } } } return count; } } " B10203,"package com.bakes; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class B { public static void main(String[] args) { B park = new B(); park.calculate(); } private void calculate() { BufferedReader in; String strLine1; String strLine2; String strLine3; PrintWriter out; try { in = new BufferedReader(new FileReader(""C-small-attempt0.in"")); in.readLine(); FileWriter outFile = new FileWriter(""output.txt""); out = new PrintWriter(outFile); int n = 0; while ((strLine1 = in.readLine()) != null) { n++; String[] data = strLine1.split("" ""); int int1 = Integer.parseInt(data[0]); int int2 = Integer.parseInt(data[1]); int count = 0; for (int i = int1; i < int2; i++) { String s = """"+i; int[] sorteds = new int[s.length()-1]; for (int k = 0; k < s.length()-1; k++) { s = permute(s); int j = Integer.parseInt(s); sorteds[k] = j; if (j > i && j <= int2) { boolean unique = true; for (int l = 0; l < k; l++) { if (sorteds[l] == j) { unique = false; } } if (unique) { count++; } } } } String result = ""Case #""+n+"": ""+count; out.println(result); System.out.println(result); } out.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } String permute(String s) { if (s.length() == 1) { return s; } s = s.substring(1) + s.charAt(0); return s; } } " B11879,"package recycling; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Main { public static int lint(int n){ if(n == 0) return 0; return 1 + lint(n / 10); } public static void permut(int[] tab){ int l = tab.length; int temp = tab[l - 1]; for(int i = l - 1; i > 0; i--){ tab[i] = tab[i - 1]; } tab[0] = temp; } public static int toInt(int[] tab){ int res = 0; int m = 1; for(int i = tab.length - 1; i >= 0; i--){ res += m * tab[i]; m *= 10; } return res; } public static int[] toTab(int n){ int[] res = new int[lint(n)]; int temp = n; for(int i = res.length - 1; i >= 0; i--){ res[i] = temp % 10; temp /= 10; } return res; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub //String fileName = args[0]; String fileName = ""recycling/C-small-attempt0.in""; Scanner sC = null; try { sC = new Scanner(new File(fileName)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } int T = sC.nextInt(); int A, B, l; for(int i = 0; i < T; i++){ A = sC.nextInt(); B = sC.nextInt(); l = lint(A); int[] tab; int temp; int count = 0; for(int j = A; j < B; j++){ tab = toTab(j); for(int k = 0; k < l - 1; k++){ permut(tab); temp = toInt(tab); //System.out.println(j + "" "" + temp); if(temp > j && temp <= B){ count++; //System.out.println(j + "" "" + temp); } } } System.out.println(""Case #"" + (i + 1) + "": "" + count); } } } " B12745,"package recycled; import java.io.BufferedReader; import java.io.FileReader; import java.util.Arrays; public class Recycled { static int[] arr = new int[10]; static int rot(int x, int N, int mult) { return x/10 + (x%10)*mult; } static int count(int j, int B, int N, int mult) { int cnt = 0; int tmp = rot(j,N,mult); while (tmp != j) { if (tmp > j && tmp <= B) { arr[cnt] = tmp; ++cnt; } tmp = rot(tmp,N,mult); } Arrays.sort(arr,0,cnt); int ret = 0; for (int i = 0; i < cnt; ++i) { if (i == 0 || arr[i] != arr[i-1]) { //System.out.println(j+"",""+arr[i]); ++ret; } } return ret; } public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new FileReader(args[0])); String line = in.readLine(); int X = Integer.parseInt(line); for (int i = 0; i < X; ++i) { long ret = 0; line = in.readLine(); String[] toks = line.split("" ""); int A = Integer.parseInt(toks[0]), B = Integer.parseInt(toks[1]); int N = (A+"""").length(); int mult = (int)Math.round(Math.pow(10, N-1)); //System.out.println(""Doing ""+A+"",""+B+"" with mult = ""+mult); for (int j = A; j < B; ++j) { ret += count(j,B,N,mult); } System.out.println(""Case #""+(i+1)+"": ""+ret); } } } " B12876,"import java.io.*; import java.util.*; public class ProblemC { public static void main(String[] args) { String txtfile=""C-small-attempt0.in""; try { Scanner scan = new Scanner(new FileInputStream(txtfile)); FileWriter fstream = new FileWriter(""C-small-attempt0.out""); BufferedWriter out = new BufferedWriter(fstream); int T = scan.nextInt(); int y = 0,A,B,l,ban; String temp,sban; boolean copy; int[] z; for (int x=1;x<=T;x++) { A = scan.nextInt(); B = scan.nextInt(); y = 0; for (int i=A;i=A && ban<=B && ban>i && copy==false) { y++; } } } out.write(""Case #"" + x + "": "" + y + ""\n""); } out.close(); } catch (IOException ex) { System.out.println(ex); System.exit(1); } } }" B10244,"package nl.bertjesapps.googlecodejam; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class ProblemThree { private Set results = new HashSet<>(); /** * @param args */ public static void main(String[] args) { if (args.length == 1) { String fileName = args[0]; ProblemThree problemOne = new ProblemThree(); try { problemOne.solveFile(fileName); } catch (FileNotFoundException fnf) { System.out.println(""File not found!""); System.out.println(fnf.getMessage()); } catch (IOException e) { System.out.println(""Could not read file!""); } } else { System.out.println(""Need 1 argument!""); } } private void solveFile(String fileName) throws IOException { StringBuilder output = new StringBuilder(); File file = new File(fileName); FileReader fileReader = new FileReader(file); BufferedReader reader = new BufferedReader(fileReader); String numberOfCasesString = reader.readLine(); int numberOfCases = Integer.parseInt(numberOfCasesString); for (int i = 1; i <= numberOfCases; i++) { output.append(""Case #"" + i + "": ""); output.append(solveLine(reader.readLine())); output.append(""\r\n""); } //output.append(results.size()); FileWriter writer = new FileWriter(fileName.replace("".in"", "".out"")); writer.write(output.toString()); writer.close(); } private String solveLine(String lineToBeSolved) { int result = 0; String[] parts = lineToBeSolved.split("" ""); int startingNumber = Integer.parseInt(parts[0]); int endingNumber = Integer.parseInt(parts[1]); for (int i = startingNumber; i <= endingNumber; i++) { countRecycled(i, endingNumber); } result = results.size(); results = new HashSet<>(); return """" + result; } private void countRecycled(int source, int endingNumber) { StringBuilder builder = new StringBuilder(); builder.append(source); for (int i = 1; i < builder.length(); i++) { String checkNumber = builder.substring(i) + builder.substring(0,i); int resultNumber = Integer.parseInt(checkNumber); if (resultNumber > source && resultNumber <= endingNumber) { results.add("""" + source + """" + resultNumber); } } } } " B10891,"package de.at.codejam.gui; import java.awt.BorderLayout; import java.io.File; import javax.swing.JFileChooser; import javax.swing.JPanel; import javax.swing.filechooser.FileFilter; import de.at.codejam.util.CodeJamConstants; import de.at.codejam.util.StatusListener; import de.at.codejam.util.TaskStatus; public class CodeJamMainPanel extends JPanel implements CodeJamConstants, StatusListener { private static final long serialVersionUID = 5367570736703559286L; private JPanel mainArea = new JPanel(new BorderLayout()); private final CodeJamStatusPanel statusPanel = new CodeJamStatusPanel(); private final JFileChooser fileChooser = new JFileChooser( DEFAULT_CODE_JAM_DIRECTORY); public CodeJamMainPanel() { super(new BorderLayout()); fileChooser.setAcceptAllFileFilterUsed(true); fileChooser.setDialogType(JFileChooser.OPEN_DIALOG); fileChooser.setDialogTitle(""Input File Selection""); FileFilter fileFilter = new FileFilter() { @Override public boolean accept(File inFile) { return inFile.isFile() && inFile.getName().endsWith("".in""); } @Override public String getDescription() { return ""Google Code Jam - .in files""; } }; fileChooser.addChoosableFileFilter(fileFilter); mainArea.add(statusPanel, BorderLayout.NORTH); mainArea.add(fileChooser); add(mainArea); } @Override public void updateStatus(TaskStatus taskStatus) { statusPanel.updateStatus(taskStatus); } @Override public void log(int logLevel, String message) { statusPanel.log(logLevel, message); } public JFileChooser getFileChooser() { return fileChooser; } } " B11398,"import java.util.Scanner; public class Recycler { private Scanner input; private int numTests = 0; public static void main(String[] args) { Scanner inp = new Scanner(System.in); int numChar = 0; numChar = inp.nextInt(); Recycler r = new Recycler(inp, numChar); r.recycle(); } public Recycler(Scanner inp, int numChar) { this.input = inp; this.numTests = numChar; } public void recycle() { for (int i = 1; (i <= numTests) && input.hasNextLine(); i += 1) { int base = input.nextInt(); int end = input.nextInt(); int cycles = this.countCycles(base, end); System.out.println(""Case #"" + i + "": "" + cycles); } } public int countCycles(int start, int end) { int total = 0; int order = order(start); for (int i = start; i < end; i += 1) { for (int j = i + 1; j <= end; j += 1) { if (isRecycled(i, j, order)) { total += 1; } } } return total; } public static boolean isRecycled(int i, int j, int order) { int rot = (j / 10) + (order * (j - (10 * (j / 10)))); while (rot != j) { if (rot == i) { return true; } rot = (rot / 10) + (order * (rot - (10 * (rot / 10)))); } return false; } public static int order(int i) { int order = 0; while (i > 0) { i /= 10; order += 1; } int result = 1; for (int j = 1; j < order; j += 1) { result *= 10; } return result; } } " B10429,"package codejam; import java.util.Hashtable; public class RecycledNumbers { @SuppressWarnings(""unchecked"") Hashtable h1; @SuppressWarnings(""unchecked"") RecycledNumbers(){ h1 = new Hashtable(); } @SuppressWarnings(""unchecked"") long noOfPairs(long min, long max, long num){ String sMin = """"+min; String sMax = """"+max; String sNum = """"+num; long countPairs = 0; int nod = sMin.length(); int i = 0; char fd = sNum.charAt(0); for( i = 1; i < nod ; i++){ String block = sNum.substring(i); if( block.charAt(0)=='0' || (block.charAt(0)> sMax.charAt(0)) || block.charAt(0) max){ can = false; break; } } if( !can ){ continue; } } String sPair = block + sNum.substring(0,i); long pair = Long.parseLong(sPair); boolean contains = h1.containsKey(sNum+"" ""+sPair); if( pair > num && pair<=max && !contains){ h1.put(sNum+"" ""+sPair, countPairs); countPairs ++; } } return countPairs; } public static void main(String[]args){ long i = 0; long count = 0; RecycledNumbers r1 = new RecycledNumbers(); FileRead fr = new FileRead(""C-small-attempt0.in""); FileWrite fw = new FileWrite(""C-small-ouput.txt""); //FileRead fr = new FileRead(""C-large-attempt0.in""); //FileWrite fw = new FileWrite(""C-large-ouput.txt""); int t = fr.readNextInt(); int j = 0; long A,B; for( ; j< t; j++){ count = 0; String nextLine = fr.readNextLine(); A = Long.parseLong(nextLine.split("" "")[0]); B = Long.parseLong(nextLine.split("" "")[1]); for( i = A; i < B; i++){ count += r1.noOfPairs(A,B,i); } fw.writeLine(""Case #""+(j+1)+"": ""+count); } fr.close(); fw.close(); } } " B12064,"package codejam; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.HashMap; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Gedion Moyo */ public class recycler { /** * @param args the command line arguments */ public static void main(String[] args) { try { solve(); } catch (Exception ex) { Logger.getLogger(recycler.class.getName()).log(Level.SEVERE, null, ex); } } public static void solve() throws Exception { Scanner in = new Scanner(new FileReader(""src/codejam/input.txt"")); PrintWriter out = new PrintWriter(new FileWriter(""src/codejam/output.txt"")); int caseCount = Integer.valueOf(in.nextLine()); for (int caseNum = 0; caseNum < caseCount; caseNum++) { System.out.println(""solving case "" + caseNum); out.print(""Case #"" + (caseNum + 1) + "":""); out.print("" ""); int A = in.nextInt(); int B = in.nextInt(); out.print(permute(A,B)); out.print(""\n""); } out.flush(); out.close(); in.close(); } public static int permute(int A, int B){ int count = 0; HashMap map = new HashMap<>(); for(int n = A;n <=B;n++){ String N[] = (n+"""").split(""""); int base = (int) (Math.floor(Math.log10(n) + 1.0)); String[] num = new String[base]; for(int j=0;j0; i/=10) d++; for(i=a; ii && k<=b) { System.out.println(i + "" "" + k); c++; } } } } public static void main(String[] args) throws IOException { long t2, t1 = System.currentTimeMillis(); output = """"; Scanner sc = new Scanner(new File(""C-small-attempt0.in"")); int ntc = sc.nextInt(); for(int w=1; w<=ntc; w++) { a = sc.nextInt(); b = sc.nextInt(); fun(); output += ""Case #"" + w + "": "" + c + newline; } sc.close(); OutputStream fo = new FileOutputStream(""C-small-attempt0.out""); fo.write(output.getBytes()); fo.close(); t2 = System.currentTimeMillis(); System.out.println( ""Time in millis : "" + (t2-t1) ); } } " B11923,"package net.jbirch.gcj12qual.util; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.Scanner; /** * * @author Birch */ public class FileLoader { protected String filename; protected InputStream stream; protected Scanner scanner; public FileLoader(String filename) { this.filename = filename; } public InputStream getStream() throws FileNotFoundException { if (stream == null) { stream = new FileInputStream(filename); } return stream; } public Scanner getScanner() throws FileNotFoundException { if (scanner == null) { scanner = new Scanner(this.getStream()); } return scanner; } }" B10514,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Iterator; public class GCIFileWriter { public GCIFileWriter (File file) throws IOException { mBufferedWriter = new BufferedWriter(new FileWriter(file)); mFile = file; } public void writeResult(GCIResult res) throws IOException { Iterator it = res.iterator(); while(it.hasNext()) { mBufferedWriter.write(it.next() + ""\n""); mBufferedWriter.flush(); } } public void reset() throws IOException { mBufferedWriter.close(); mBufferedWriter = new BufferedWriter(new FileWriter(mFile)); } public void close() throws IOException { mBufferedWriter.flush(); mBufferedWriter.close(); } private BufferedWriter mBufferedWriter; private File mFile; } " B10271,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package googlejam2012qrc; import java.io.*; /** * * @author Vincent */ public class GoogleJam2012QRC { /** * @param args the command line arguments */ public static void main(String[] args) { try{ //Prepare the reader BufferedReader in = new BufferedReader( new FileReader(""inputFile.txt"")); BufferedWriter out = new BufferedWriter(new FileWriter(""outputFile.txt"")); //Get the amount of cases to be solved String str = in.readLine(); int caseCount = Integer.parseInt(str); //For each test case for(int i = 0; i < caseCount; i++){ //Get the line of the problem str = in.readLine(); String[] problemData = str.split("" ""); int lowerBound = Integer.parseInt(problemData[0]); int upperBound = Integer.parseInt(problemData[1]); int recycledCount = 0; for(int x = lowerBound; x <= upperBound; x++){ for(int y = x+1; y <= upperBound; y++){ String sx = """"+x; String sy = """"+y; if(sx.length() == sy.length()){ boolean matchFound = false; for(int j = 1; j < sx.length() && !matchFound; j++){ String temp = sy; sy = temp.substring(1) + temp.charAt(0); if(sx.compareTo(sy) == 0){ recycledCount++; matchFound = true; } } } } } out.write(""Case #"" + (i+1) + "": ""); out.write("""" + recycledCount); out.newLine(); } in.close(); out.close(); } catch (Exception e){ System.out.println(""Read Failed""); } } } " B11168,"import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class Main { public static void main(String[] args) throws IOException { FileInputStream fis = new FileInputStream(new File(""in.txt"")); FileOutputStream fos = new FileOutputStream(new File(""out.txt"")); Scanner sc = new Scanner(fis); PrintWriter out = new PrintWriter(fos); int cases = sc.nextInt(); for(int cs = 1; cs <= cases; cs++) { int begin = sc.nextInt(); int end = sc.nextInt(); int cnt = 0; for(int n=begin; n<=end; n++) { int weishu = getWeishu(n); int cur = getNext(n, weishu); while(cur != n) { if(cur > n && cur <=end && getWeishu(cur) == weishu) cnt++; cur = getNext(cur, weishu); } } out.println(""Case #""+cs+"": ""+cnt); } sc.close(); out.close(); } public static int getNext(int n, int weishu) { //int weishu= getWeishu(n); return n%10*getTens(weishu-1)+n/10; } private static int getTens(int n) { int res = 1; for(int i=0; i= nweishu) { nweishu*=10; weishu++; } return weishu; } } " B13203,"package tr0llhoehle.cakemix.googleCodeJam.recycledNumbers; import java.util.ArrayList; import tr0llhoehle.cakemix.utility.googleCodeJam.Solver; public class RNSolver implements Solver { @Override public String solve(RNProblem p) { int amount = 0; for (Integer i = p.getLowerBorder(); i < p.getUpperBorder(); i++) { ArrayList usedPermutations = new ArrayList(); String nmbr = String.valueOf(i); // for each permutation... for (int j = 0; j < nmbr.length(); j++) { String tempPermutation = nmbr.substring(j) + nmbr.substring(0, j); if (tempPermutation.charAt(0) != '0' && !usedPermutations.contains(tempPermutation)) { int permutation = Integer.parseInt(tempPermutation); usedPermutations.add(tempPermutation); if (permutation > i && permutation <= p.getUpperBorder()) { amount++; System.out.println(""("" + i + "", "" + permutation + "")""); } } } } return amount + """"; } } " B12563,"import java.io.*; import java.util.*; class Replace { public static void main(String args[])throws Exception { //Scanner sc = new Scanner(System.in); // PrintWriter pw = new PrintWriter(System.out); Scanner sc = new Scanner(new FileReader(""C-small-attempt1.in"")); //Console console=System.console(new FileReader(""B-small-practice-1.in"")); PrintWriter pw = new PrintWriter(new FileWriter(""C-small-attempt1.out"")); int ntest = sc.nextInt(); //int a=100; //int b=500; for(int k=1;k<=ntest;k++) { int sum=0; int count=0; //int a=Integer.parseInt(sc.next()); //int b=Integer.parseInt(sc.next()); int a=sc.nextInt(); int b=sc.nextInt(); for(int i=a;i<=b;i++) { if(i>0 && i<100) { int rem=i%10; sum=rem*10+i/10; if(sum==i) { } else if(sum>=a && sum<=b) { count++; System.out.println(i); //System.out.println(""garg""); } } if(i>=100 && i<1000) { int rem=i%100; sum=rem*10+i/100; //System.out.println(i); if(sum==i) { } else if (sum>=a && sum<=b) { count++; //System.out.println(i); } //System.out.println(""lucky""); rem=i%10; sum=rem*100+i/10; if(sum==i) { } else if(sum>=a && sum<=b) { count++; //System.out.println(i); //System.out.println(""garg""); } } } pw.print(""Case #"" + k + "": ""); pw.print(count/2); pw.println(); } pw.close(); sc.close(); } }" B11690,"import java.io.File; import java.io.FileNotFoundException; import java.util.Formatter; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { private static String solve(int A, int B) { int count = 0; final HashSet seen = new HashSet(10); for (int n = A; n < B; n++) { // Find number of decimal digits. int nTemp = n, digits = 0, unit = 1; while (nTemp > 0) { digits++; nTemp /= 10; unit *= 10; } unit /= 10; int m = n; seen.clear(); for (int i = 1; i < digits; i++) { if (m % 10 == 0) { // Don't process because there will be a leading zero. m /= 10; } else { m = (unit * (m % 10)) + (m / 10); if (m > n && m <= B && !seen.contains(m)) { seen.add(m); count++; } } } } return """" + count; } public static void main(String[] args) throws FileNotFoundException { //String filename = ""C-test.in""; String filename = ""C-small-attempt0.in""; // String filename = ""C-large.in""; assert filename.endsWith("".in""); Scanner in = new Scanner(new File(filename)); Formatter out = new Formatter(new File(filename.replace("".in"", "".out""))); assert in.hasNext(); int T = in.nextInt(); in.nextLine(); for (int t = 0; t < T; t++) { int A = in.nextInt(); int B = in.nextInt(); String ans = solve(A, B); String result; if (t < T - 1) result = String.format(""Case #%d: %s%n"", t + 1, ans); else result = String.format(""Case #%d: %s"", t + 1, ans); out.format(result); System.out.format(result); } out.flush(); out.close(); } } " B11762,"package round03; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; /** * Problem Do you ever become frustrated with television because you keep seeing the same things, recycled over and over again? Well I personally don't care about television, but I do sometimes feel that way about numbers. Let's say a pair of distinct positive integers (n, m) is recycled if you can obtain m by moving some digits from the back of n to the front without changing their order. For example, (12345, 34512) is a recycled pair since you can obtain 34512 by moving 345 from the end of 12345 to the front. Note that n and m must have the same number of digits in order to be a recycled pair. Neither n nor m can have leading zeros. Given integers A and B with the same number of digits and no leading zeros, how many distinct recycled pairs (n, m) are there with A ¡Â n < m ¡Â B? Input The first line of the input gives the number of test cases, T. T test cases follow. Each test case consists of a single line containing the integers A and B. Output For each test case, output one line containing ""Case #x: y"", where x is the case number (starting from 1), and y is the number of recycled pairs (n, m) with A ¡Â n < m ¡Â B. Limits 1 ¡Â T ¡Â 50. A and B have the same number of digits. Small dataset 1 ¡Â A ¡Â B ¡Â 1000. Large dataset 1 ¡Â A ¡Â B ¡Â 2000000. Sample input 4 1 9 10 40 100 500 1111 2222 output Case #1: 0 Case #2: 3 Case #3: 156 Case #4: 287 * @author chmin * */ public class RecycledNumbers { public static class RNumber { String n; int cntShift = 0; public RNumber( int n){ init(n); } public void init( int n ){ this.n = """" + n; cntShift = 0; } public int next() { int pos = n.length()-1; cntShift ++; while ( n.charAt(pos) == '0'){ pos --; cntShift ++; } if ( pos > 0 ) { String v = n.substring(pos , n.length()) + n.substring(0, pos); n = v; } return Integer.parseInt(n); } public boolean hasNext() { return cntShift < n.length(); } } public void solve() throws IOException{ Scanner scanner = new Scanner (getClass().getResourceAsStream(""R3-small.in"")); int T = scanner.nextInt(); RNumber rnum = new RNumber(0); HashSet set = new HashSet<>(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < T ; i++) { int A = scanner.nextInt(); int B = scanner.nextInt(); set.clear(); for( int n = A ; n <= B ; n++){ rnum.init(n); while ( rnum.hasNext() ){ int m = rnum.next(); if ( n < m && m <= B) { set.add(n + "" "" + m); } } } sb.append(""Case #"" + (i+1) + "": "" + set.size() + System.getProperty(""line.separator"")); } BufferedWriter bw = new BufferedWriter(new FileWriter(""R3-small.out"")); bw.write(sb.toString()); bw.close(); } /** * @param args */ public static void main(String[] args) { try { new RecycledNumbers().solve(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B12039," import codejam.StoreCredit; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author java */ public class RecycledNumbers { static BufferedReader in; private static void open() { in = new BufferedReader(new InputStreamReader(System.in)); } private static void close() { try { in.close(); } catch (IOException ex) { Logger.getLogger(StoreCredit.class.getName()).log(Level.SEVERE, null, ex); } } private static int readInt() throws IOException { Integer i = Integer.parseInt(in.readLine()); return i; } private static int[] readInts() throws IOException { String[] vals = in.readLine().split("" ""); int[] arr = new int[vals.length]; for (int i = 0; i < vals.length; i++) { arr[i] = Integer.parseInt(vals[i]); } return arr; } public static void main(String[] args) throws IOException { open(); int T = readInt(); for (int t = 0; t < T; t++) { int[] arr = readInts(); int A = arr[0]; int B = arr[1]; Set set = new LinkedHashSet(); Set additionalSet = new HashSet(); while (A <= B) { String v = String.valueOf(A); set.add(A); A++; } Iterator it = set.iterator(); Set used = new LinkedHashSet(); StringBuilder b = new StringBuilder(); while (it.hasNext()) { int val = it.next(); it.remove(); b.delete(0, b.length()); b.append(val); int iteration = b.length(); boolean added = false; if (iteration > 1) { for (int i = 0; i < iteration - 1; i++) { char c = b.charAt(0); b.deleteCharAt(0); b.append(c); String newItem = b.toString(); // remove leading 0 int j = 0; // for (; j < newItem.length() && newItem.charAt(j) == '0'; j++); // newItem = newItem.sub1string(j); int newNumber = Integer.parseInt(newItem); if ((set.contains(newNumber) || additionalSet.contains(newNumber)) && !used.contains(val + ""#"" + newNumber)) { used.add(val + ""#"" + newNumber); added = true; } } } if (!added) { additionalSet.add(val); } } System.out.println(""Case #"" + (t + 1) + "": "" + used.size()); // System.out.println(used); } close(); } } " B13050,"import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[][] s = new int[3][n]; for (int i = 0; i < n; i++) { s[0][i] = sc.nextInt(); s[1][i] = sc.nextInt(); s[2][i] = 0; } for (int i = 0; i < n; i++) { List past2 = new ArrayList(); List past1 = new ArrayList(); if (s[0][i] < 10 && s[1][i] < 10) { s[2][i] = 0; } else { for (int j = s[0][i]; j < s[1][i]; j++) { String t1 = Integer.toString(j); // mÀ» ¹®ÀÚ¿­·Î ÀúÀå for (int k = 1; k < t1.length(); k++) { String t2 = t1.substring(k) + t1.substring(0, k); // nÀ» ¹®ÀÚ¿­·Î ÀúÀå if (t2.charAt(0) != '0') { // ùÀÚ¸®°¡ 0ÀÌ µÇ¾î ÀÚ¸®¼ö°¡ ³»·Á°¡´Â °æ¿ì ¿¹¿Ü ó¸® if (Integer.parseInt(t2) <= s[1][i] && Integer.parseInt(t2) >= s[0][i]) { // B ¹üÀ§¸¦ ÃÊ°úÇÏ´Â °æ¿ì ¿¹¿Ü ó¸® if (!t1.equals(t2)) { // n°ú mÀÌ °°Àº °æ¿ì ¿¹¿Ü ó¸® int same = 0; for(int p = 0; p < past2.size() ; p++) { if(past2.get(p) == Integer.parseInt(t1) && past1.get(p) == Integer.parseInt(t2)) { same = 1; } } if(same == 0) { s[2][i]++; past2.add(Integer.parseInt(t2)); past1.add(Integer.parseInt(t1)); } same = 0; } } } } } } } for (int i = 0; i < n; i++) { System.out.println(""Case #"" + (i + 1) + "": "" + s[2][i]); } } }" B10358,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package c; import java.io.*; import java.util.Scanner; import java.util.StringTokenizer; /** * * @author Leo */ public class C { public static void main(String[] args) throws FileNotFoundException, IOException { new C().run(); } String inputFile = ""txt.in""; Scanner in; public void run() throws FileNotFoundException, IOException{ in = new Scanner(new FileReader(inputFile)); int cases = in.nextInt(); for(int i=1;i<=cases;i++) { int d=0; int A = in.nextInt(); int B = in.nextInt(); d=howManyDigits(B); int c = resolve(A,B,d); System.out.println(""Case #"" + i + "": "" + A + "" "" + B + "" "" + c); } } public int resolve(int a , int b, int d) { int comp1=0; int comp2=0; int m=0; int n=0; for(int j=a;j<=b;j++){ if(d==2) { m = this.permuteDigits(j); if(a<=m && m<=b){ comp1++;} } if(d==3) { m = this.permuteDigits3A(j); n = this.permuteDigits3B(j); if(a<=m && m<=b){ comp2++;} if(a<=n && n<=b){ comp2++;} } } return (comp1)/2 + comp2; } int howManyDigits(int x){ if(x<10) return 1; if(10<=x && x<=99) return 2; if(100<=x && x<=999) return 3; return 0; } int permuteDigits3A(int x){ int m =0; int n = 0; int t=0; int f=0; m=x%100; m=m%10; n = x/100; f=x/10; f=f%10; t = m*100+n + f*10; if((m==n && n==f) || f==0) t=0; return t; } int permuteDigits3B(int x){ int m =0; int n = 0; int t=0; int f=0; m=x%100; n = x/10; f=x%100; t = m*100+n; if((m==n && n==f) || m==0 ) t=0; return t; } int permuteDigits(int x){ int m =0; int n = 0; int t=0; m=x%10; n = x/10; t = m*10+n; if(m==n || n==0 || m==0 ) t=0; return t; } } " B10184,"import java.util.*; import java.io.*; public class C { public static int roll (int i, int a, int b) { int found = 0; int digits = (""""+i).length(); int[] vit = new int[digits]; int magic; int keep, move,done; for (int d = 1; d < digits; d++) { magic = (int)Math.pow(10, d); keep = i/magic; move = i%magic; magic = (int)Math.pow(10, digits-d); done = keep + (move * magic); if (a <= done && done <= b && done < i) { vit[found] = done; found++; } } if (found > 1) { Arrays.sort(vit); for (int j = 0; j < vit.length - 1; j++) if (vit[j] != 0 && vit[j] == vit[j+1]) found--; } return found; } public static void main(String... args) throws Exception { BufferedReader in = new BufferedReader (new FileReader( ""C-small-attempt0.in"" )); String line; in.readLine(); int casenum = 1; int a,b; String[] nums; while ( (line = in.readLine()) != null) { nums = line.split("" ""); a = Integer.valueOf(nums[0]); b = Integer.valueOf(nums[1]); int result = 0; for (int m = a; m <= b; m++) result += roll(m,a,b); System.out.println(""Case #"" + casenum + "": "" + (result)); casenum++; } } }" B11207,"package recycle_no; import java.io.*; import java.util.Arrays; public class Recycle_no { int N,a,b,count=0; String s="""",temp[]; public Recycle_no(){ try { FileInputStream fis=new FileInputStream(""C-small-attempt0.in""); DataInputStream dis=new DataInputStream(fis); FileOutputStream fos = new FileOutputStream(""C-small-attempt0.out""); DataOutputStream dos=new DataOutputStream(fos); N=Integer.parseInt(dis.readLine()); for(int i=1;i<=N;i++) { s=dis.readLine(); count=0; temp=s.split("" ""); a=Integer.valueOf(temp[0]); b=Integer.valueOf(temp[1]); for(int j=a;j=min && n<=max && n>no) { int flg=0; for(int j=0;j0){ cases[i] = strLine; i++; } } //Close the input stream in.close(); }catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } public int count(){ return cases.length; } public String getCase(int index){ return cases[index]; } }" B10259,"package com.numbers.recycle.io; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class FileParser { public List readFile(String path){ File file = new File(path); List fileContents = parseFile(file); return fileContents; } private List parseFile(File file){ List contents = new ArrayList(); try { FileInputStream inputStream = new FileInputStream(file); BufferedReader bufReader = new BufferedReader(new InputStreamReader(inputStream)); String line = null; while ((line = bufReader.readLine())!= null){ contents.add(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return contents; } } " B12638,"import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Scanner; public class Main { private static final int[][] cache; private static final int A = 0, B = 2000000; static { try { File f = new File(""cache""); if (f.exists()) { cache = (int[][]) new ObjectInputStream(new FileInputStream(f)).readObject(); } else { cache = new int[B+1][]; for (int j = 12; j < B; j++) { int permutation = String.valueOf(j).length(); HashMap hit = new HashMap(); for (int z = 1; z < permutation; z++) { int div = (int) Math.pow(10, z); if (j % div >= div / 10) { int newnum = j / div + j % div * (int) Math.pow(10, permutation - z); if (newnum >= A && newnum <= B && newnum > j) { if (hit.get(newnum) == null) { hit.put(newnum, true); } } } } ArrayList l = new ArrayList(hit.keySet()); Collections.sort(l); int[] vals = new int[l.size()]; for (int i = 0; i < l.size(); i++) { vals[i] = l.get(i); } cache[j] = vals; } new ObjectOutputStream(new FileOutputStream(f)).writeObject(cache); } } catch (Exception e) { throw new RuntimeException(e); } } public static void main(String[] args) throws Exception { Scanner s = new Scanner(new File(""input"")); BufferedWriter w = new BufferedWriter(new FileWriter(new File(""output""))); int cases = s.nextInt(); for (int i = 0; i < cases; i++) { s.nextLine(); int a = s.nextInt(); if (a < 12) { a = 12; } int b = s.nextInt(); int answer = 0; for (int j = a; j < b; j++) { int[] vals = cache[j]; for (int val : vals) { if (val < 0) { continue; } if (val > b) { break; } answer++; } } w.write(""Case #""); w.write(String.valueOf(i + 1)); w.write("": ""); w.write(String.valueOf(answer)); w.write(""\n""); } w.close(); } } " B11269,"import java.io.*; import java.util.*; import java.math.*; public class Solution { public static void main(String args[]) throws Exception { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for(int t = 0; t < T; t++) { int A=sc.nextInt(); int B=sc.nextInt(); int dig=digi(A); int mdig=minDig(A); int mdig10=mdig*10; int curr=A; int count=0; //System.out.println(A+"" ""+B+"" ""+dig+"" ""+mdig+"" ""+mdig10+"" ""+curr); HashSet set = new HashSet(); while(curr<=B) { int curr2=curr; for(int i=0;i9) { i/=10; n++; } return n; } static int minDig(int i) { int n=1; while(i>9) { i/=10; n*=10; } return n; } } " B10099,"import java.util.HashSet; import java.util.Scanner; import java.util.Set; import java.io.File; import java.io.PrintWriter; public class C { public static void main(String args[]){ try{ File ifile = new File(args[0]); File ofile = new File(args[1]); //Scanner in = new Scanner(System.in); //PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(ifile); PrintWriter out = new PrintWriter(ofile); int T = in.nextInt(); Set set = null; for(int ti=0;ti0){ no_of_digits++; counter++; a=a/10; } int res=0; int n= A; int m=0; while(n<=B){ counter = no_of_digits-1; m=n; set = new HashSet(); while(counter>0){ m = (int) ((m%10)*Math.pow(10,no_of_digits-1) + (m/10)); if(A<=n && n mem=new HashSet(); int t = Integer.parseInt(in.readLine()); for (int q = 1; q <= t; q++) { String[] st = in.readLine().split("" ""); int A = Integer.parseInt(st[0]); int B = Integer.parseInt(st[1]); int count = 0; for (int i = A; i <= B; i++) { state[i] = true; String temp = i + """"; for (int j = 1; j < temp.length(); j++) { String r = temp.substring(j) + temp.substring(0, j); int b = Integer.parseInt(r); if ((b + """").length() == temp.length() && b >= A && b <= B && !state[b]&&!mem.contains(b)) { mem.add(b); count++; } } mem.clear(); } out.write(""Case #""+q+"": ""+count+""\n""); Arrays.fill(state, false); } out.close(); } } " B12438," import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Scanner; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Akash Agrawal */ public class RN { public static boolean check(int n , int []arr) { for(int i=0;ii && C<=B && check(C,ar)) { count++; //System.out.println(i+"" ""+C); ar[ind++]=C; } } } System.out.println(""Case #""+cas+++"": ""+count); } } } " B10005," import java.io.*; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author RockHead */ public class Recycle { public static void main(String args[]) throws FileNotFoundException, IOException { BufferedReader reader = new BufferedReader(new FileReader(""C:\\Users\\RockHead\\Desktop\\C-small-attempt0.in"")); BufferedWriter writer = new BufferedWriter(new FileWriter(""C:\\Users\\RockHead\\Desktop\\Recycle_Sol.txt"")); int testNo = Integer.parseInt(reader.readLine()); int count=0; for(int i=1;i<=testNo;i++) { String str=reader.readLine(); String[] info=str.split("" ""); int A=Integer.parseInt(info[0]); int B=Integer.parseInt(info[1]); int n=A; for(int j=n;j0;i--) { String subOne=a.substring(i); String subTwo=a.substring(0,i); String newString=subOne+subTwo; if(newString.equals(b)) return true; } return false; } } " B12512,"import java.io.*; import java.util.*; class C3 { public static void main(String args[])throws IOException { FileReader fi = new FileReader(""C-small-attempt3.in""); Scanner in = new Scanner(fi); FileWriter fr = new FileWriter(""C3-output.out""); BufferedWriter bw = new BufferedWriter(fr); PrintWriter pw = new PrintWriter(bw); int T = in.nextInt(); int ab[][] = new int[T][2]; for(int i=0;i0) { tn= tn/10; c++; } tn=n; int tn2 = n; boolean flag = false; while(tn>0) { int d = tn%10; tn = tn/10; int tp = (int)Math.pow(10,c-1); tn2 = tn2/10; tn2 = tp*d+tn2; if(tn2==m) { flag = true; break; } } return flag; } } " B12764," import java.util.ArrayList; import java.util.HashSet; import java.util.Scanner; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Chamika */ public class GRecycle { public static void main(String[] args) { Scanner s = new Scanner(System.in); int cases = s.nextInt(); HashSet al = new HashSet<>(); for(int i = 0;i < cases;i++){ int x = s.nextInt(); int y = s.nextInt(); int res = 0; for(int j = x;j <= y;j++){ int z = Integer.toString(j).length(); int a = j; al.clear(); for(int k = 0;k < z;k++){ a = (a%(10))*(int)Math.pow(10,z - 1) + a/10; res = (a > j && a <= y && !al.contains(a)) ? res + 1 : res; al.add((a > j && a <= y) ? a : 0); } } System.out.println(""Case #"" + (i + 1) + "": "" + res); } } } " B11907,"import java.util.ArrayList; import java.util.HashSet; public class ProbC { /** * @param args */ public static void main(String[] args) { ArrayList in=Utils.readFile(""C-small-attempt0.in.in""); ArrayList out =new ArrayList(); //int[][] matrix=new int[100000][100000]; for (int i = 1; i < in.size(); i++) { String[] str=in.get(i).split("" ""); int A= Integer.parseInt(str[0]); int B= Integer.parseInt(str[1]); int numA=numDigit(A); int count=0; HashSet checkDup=new HashSet(); for(int j=A;j<=B;j++){ for(int pos=1;pos""+recycle); checkDup.add(new Integer(recycle)); } //System.out.println(i+"": ""+j +"" vs ""+recycle+""**********""); } } checkDup.clear(); } System.out.println(""Case #""+i+"": ""+ count); } // for(int i=1000;i<1200;i++){ // System.out.println(i+""=>""+rotate(i,4)); // } } private static int myExp(int e){ if(e==1) return 1; if(e==2) return 10; if(e==3) return 100; if(e==4) return 1000; if(e==5) return 10000; if(e==6) return 100000; //if(e==7) return 1000000; } private static int rotate(int A,int pos) { int num=numDigit(A); if(pos==1) return (A%10)*myExp(num-pos+1)+A/10; if(pos==2) return (A%100)*myExp(num-pos+1)+A/100; if(pos==3) return (A%1000)*myExp(num-pos+1)+A/1000; if(pos==4) return (A%10000)*myExp(num-pos+1)+A/10000; if(pos==5) return (A%100000)*myExp(num-pos+1)+A/100000; if(pos==6) return (A%1000000)*myExp(num-pos+1)+A/1000000; //if(pos==7) return (A%10000000)*myExp(num-pos+1)+A/10000000; } private static int numDigit(int A) { if(A/1000000>0) return 7; if(A/100000>0) return 6; if(A/10000>0) return 5; if(A/1000>0) return 4; if(A/100>0) return 3; if(A/10>0) return 2; return 1; } } " B12602," import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author UDDAMA */ public class recyclePair { private ArrayList numholder = new ArrayList(); public void numrecylce(String chars) { for (int i = 0; i < chars.length() - 1; i++) { this.numholder.add(chars.substring(i + 1) + chars.substring(0, i + 1)); } } public void cleanArray() { for (int i = 0; i < numholder.size(); i++) { String temp = numholder.get(i); for (int j = i + 1; j < numholder.size(); j++) { if (temp.equalsIgnoreCase(numholder.get(j))) { numholder.remove(j); } } } } public int recycleCount(String A, String B) { int count = 0; for (int i = Integer.parseInt(A); i < Integer.parseInt(B); i++) { this.numholder.clear(); this.numrecylce(String.valueOf(i)); this.cleanArray(); for (int j = 0; j < numholder.size(); j++) { if (Integer.parseInt(numholder.get(j)) > i && Integer.parseInt(numholder.get(j)) <= Integer.parseInt(B)) { count++; } } } return count; } public static void main(String[] args) throws IOException { BufferedReader is = new BufferedReader(new InputStreamReader(System.in)); String inputLine = is.readLine(); recyclePair rp = new recyclePair(); int cases = Integer.parseInt(inputLine); for (int i = 0; i < cases; i++) { inputLine = is.readLine(); String[] AB = inputLine.split("" ""); System.out.println(""Case #"" + (i + 1) + "": "" + rp.recycleCount(AB[0], AB[1])); } } }" B12084,"import java.io.*; import java.util.*; public class C { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int numCases = Integer.parseInt(br.readLine()); for(int i = 0; i < numCases; i++) { solveCase(i+1, br.readLine()); } } private static void solveCase(int caseNum, String line) { String[] parts = line.split("" ""); int start = Integer.parseInt(parts[0]); int end = Integer.parseInt(parts[1]); System.out.println(""Case #""+caseNum+"": ""+solve(start, end)); } private static int solve(int start, int end) { int res = 0; for(int i = start; i <= end; i++) { HashSet encountered = new HashSet(); String asString = """"+i; for(int index = 1; index < asString.length(); index++) { char letter = asString.charAt(index); if(letter == '0') { //System.out.println(i+"": skip index ""+index); continue; // cant have leading 0 } int switched = Integer.parseInt(asString.substring(index)+asString.substring(0, index)); if(switched > i && switched >= start && switched <= end) { //encountered.add(i); if(encountered.contains(switched)){ //System.out.println(""already had ""+switched); continue; } encountered.add(switched); res++; //System.out.println(i+"": ""+switched); } else { //System.out.println(i+"": ""+switched+"" doesnt work""); } } } return res; } }" B12943,"package com.menzus.gcj._2012.qualification.c; import com.menzus.gcj.common.OutputEntry; public class COutputEntry implements OutputEntry { private long recycledPairNumber; public void setRecycledPairNumber(long recycledPairNumber) { this.recycledPairNumber = recycledPairNumber; } @Override public String formatOutput() { return Long.toString(recycledPairNumber); } } " B13041,"import java.util.*; import java.io.*; import static java.lang.Math.*; public class C { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(""C:/Users/Farnoosh/Desktop/C-small.in"")); FileWriter fw = new FileWriter(""C:/Users/Farnoosh/Desktop/C-small.out""); /*BufferedReader in = new BufferedReader(new FileReader(""C:/Users/Farnoosh/Desktop/C-large.in"")); FileWriter fw = new FileWriter(""C:/Users/Farnoosh/Desktop/C-large.out"");*/ int N = new Integer(in.readLine()); //System.out.print(N); for (int cases = 1; cases <= N; cases++) { int count = 0; String[] ss = in.readLine().split("" ""); int A = Integer.parseInt(ss[0]); int B = Integer.parseInt(ss[1]); for(int num = A ; num <= B ; num++){ int num2 = 0; int len = (int)Math.pow(10, Integer.toString(num).length()-1); int i = 0; int num1 = num; for(i = 1; i < Integer.toString(num).length() ; i++){ if(Integer.toString(num2).length() == Integer.toString(num1).length() || num2==0){ num2 = 10 * (num1 % len) + (num1 / len); } else{ num2 = num2 * 10; } if(num2 == num) break; if (num2 <= B && num2 > num){ count++; }// end of if num1 = num2; }//end of for }//end of for fw.write (""Case #"" + cases + "": "" + count + ""\n""); } fw.flush(); fw.close(); } }" B12414,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; public class Main { /** * @param args */ public static void main(String[] args) { try { // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(""C-small-attempt0.in""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; //Read File Line By Line int cases = 0; ArrayList input = new ArrayList(); ArrayList output = new ArrayList(); while ((strLine = br.readLine()) != null) { // Print the content on the console input.add(strLine); } //Close the input stream in.close(); cases = Integer.parseInt(input.get(0)); for(int i=0; i=A; k--) for (int j=A; j<=k; j++) { String strJ = String.valueOf(j); String strK = String.valueOf(k); if (strJ.length() == strK.length()) { String newJ = strJ.substring(strJ.length() - 1) + strJ.substring(0, strJ.length() -1); while(!newJ.equals(strJ)) { if (newJ.equals(strK)) number++; newJ = newJ.substring(newJ.length() - 1) + newJ.substring(0, newJ.length() -1); } } } output.add(""Case #"" + (i + 1) + "": "" + number); } for (int i=0; i 0) { temp = temp/10; digit++; } temp = j; int[] array = new int[digit]; for(int k = digit-1; k>0; k--) { int rem = temp%10; temp = temp/10; temp += rem*Math.pow(10, digit-1); array[k] = temp; if(temp>j) if(temp mapToGoogleres; private HashMap mapToEnglish; public SpeakingInTongues(String filename) { super(filename); mapToEnglish = new HashMap(); // mapToGoogleres = new HashMap(); mapToEnglish.put('z', 'q'); mapToEnglish.put('q', 'z'); // mapToGoogleres.put('z', 'q'); addToMap(g1, e1); addToMap(g2, e2); addToMap(g3, e3); } private void addToMap(String goo, String eng) { char[] gooc = goo.toCharArray(); char[] engc = eng.toCharArray(); for (int i = 0; i < gooc.length; i++) { if (mapToEnglish.get(gooc[i]) == null) { mapToEnglish.put(gooc[i], engc[i]); } } } @Override public JamCase getJamCase(int number) { return new Line(this, number, lines[number]); } private class Line extends JamCase { private String line; public Line(Jam parent, int number, String line) { super(parent, number); this.line = line; } @Override public void parse() { } @Override public void solve() { StringBuilder sb = new StringBuilder(line.length()); Character e = null; for (char c : line.toCharArray()) { e = mapToEnglish.get(c); if (e == null) { sb.append(c); } else { sb.append(e); } } result = sb.toString(); } } } " B12091,"import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.HashSet; import java.util.Set; import java.util.regex.Pattern; /** * @(#)RecycleNumber.java, 2012-4-14. * * Copyright 2012 Netease, Inc. All rights reserved. * NETEASE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ /** * * @author bjdengdong * */ public class RecycleNumber { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(""E:\\google_code_jam\\C-small-attempt0.in""))); PrintStream out = new PrintStream(new FileOutputStream(""E:\\google_code_jam\\C-small-attempt0.out"")); int t = Integer.parseInt(br.readLine()); for (int i = 1; i <= t; i++) { String line = br.readLine(); String[] sp = line.split(Pattern.quote("" "")); int digits = sp[0].length(); int a = Integer.parseInt(sp[0]), b = Integer.parseInt(sp[1]); if (a < 10 && b < 10) { out.println(""Case #"" + i + "": 0""); continue; } int result = 0; Set set = new HashSet(); for (int num = a; num <= b; num++) { String str = ("""" + num); set.clear(); for (int j = digits - 1, k = 1; j >= 1; j--, k++) { if (str.charAt(k) == '0') continue; int rec = Integer.parseInt(str.substring(k) + str.substring(0, k)); if (rec > num && rec <= b) { if(!set.contains(rec)){ set.add(rec); result++; } } } } out.println(""Case #"" + i + "": "" + result); } } } " B12338,"package com.example; import java.io.IOException; import java.util.List; public class ProblemC { static int[] data = new int[2000001]; public static void main(String[] a) throws IOException { // if(true) { // precalc(); // //// System.out.println(""min = ""+ findMinimum(3210)); // // return; // } List lines = FileUtil.getLines(""/C-small-attempt0.in""); for(int i=1; i 0) { newn /= 10; digits++; scale *= 10; } scale /= 10; int temp = 0; for (int i = 0; i < digits; i++) { temp = n; temp /= 10; temp += scale * (n-(10*temp)); n = temp; greatest = Math.max(n,greatest); } return greatest; } public static void main(String[] args) { String fileName; String line; fileName = ""C-small-attempt0.in""; Scanner fromFile = null; try { fromFile = new Scanner(new File(fileName)); } catch (Exception e) {} int iterations = Integer.parseInt(fromFile.nextLine()); int count, lower, upper; int[] answers = new int[iterations]; HashMap map = null; Integer ordered = null; for (int i = 0; i < iterations; i++) { line = fromFile.nextLine(); String[] arguments = line.split("" ""); lower = Integer.parseInt(arguments[0]); upper = Integer.parseInt(arguments[1]); count = 0; map = new HashMap(); for (int j = lower; j <= upper; j++) { ordered = reorder(j); if (map.containsKey(ordered)) { int number = map.get(ordered); count += number; map.put(ordered, number+1); } else { map.put(ordered, 1); } } answers[i] = count; } try { fromFile.close(); } catch (Exception e){} PrintWriter toFile = null; try { File f = new File(""output.txt""); if (!f.exists()) f.createNewFile(); toFile = new PrintWriter(f); for (int i = 0; i < iterations; i++) { if (i == iterations - 1) { toFile.print(""Case #"" + (i + 1) + "": "" + answers[i]); } else { toFile.println(""Case #"" + (i + 1) + "": "" + answers[i]); } } toFile.close(); } catch (Exception e) {} } } " B12131,"import java.util.*; import java.io.*; class gcj2{ public static void main(String[] args) throws IOException{ BufferedReader inp = new BufferedReader(new FileReader(""inp.txt"")); BufferedWriter out = new BufferedWriter(new FileWriter(""out.txt"")); int test = Integer.parseInt(inp.readLine()); int p = 1; while(test>0){ String d[] = inp.readLine().split("" ""); int a = Integer.parseInt(d[0]); int b = Integer.parseInt(d[1]); int i = a; int count = 0; while(i<=b){ String s = new Integer(i).toString(); int j = 1; HashSet se = new HashSet(); while(j it = se.iterator(); while(it.hasNext()){ int gg = it.next(); if(gg>i&&gg<=b){ // System.out.println(gg +"" ""+i); count++; } } // System.out.println(""------------------""); i++; } out.write(""Case #""+p+"": ""+count+""\n""); System.out.println(count); test--; p++; } out.close(); } }" B10443,"package qualification.taskA; import java.util.Map; public class Task { private Map dictionary ; public Task(Map dictionary ) { this.dictionary = dictionary; } public String execute(String original) { StringBuilder result = new StringBuilder(); for(int i = 0; i < original.length(); i++){ result.append(dictionary.get(original.charAt(i))); } return result.toString(); } } " B12125,"import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.Scanner; public class Recycled { public static void main(String[] args) throws IOException{ Scanner sc = new Scanner(new File(""recycled.in"")); System.setOut(new PrintStream(new File(""recycled.out""))); int T = sc.nextInt(); LinkedList p; Pair add = null; for(int set=1; set<=T; set++){ p = new LinkedList(); int A = sc.nextInt(); int B = sc.nextInt(); for(int n=A; n results = new HashSet(); for (int num = A; num <= B; num++) { // max chunk size = floor(log(number)) final int numLen = digits(num); for (int chunkLength = 1; chunkLength < numLen; chunkLength++) { int recycled = recycle(num, numLen, chunkLength); if (recycled != num && recycled >= A && recycled <= B && digits(recycled) == numLen) { results.add(new Pair(num, recycled)); } } } return results.size(); } private static int digits(int num) { return 1 + (int) Math.log10(num); } private static int recycle(int num, int numLength, int endChunkLength) { int base = (int) Math.pow(10, endChunkLength); int result = (num % base) * ((int) Math.pow(10, numLength - endChunkLength)) + num / base; return result; } } " B10187,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; public class recycle { public static int factorial(int num){ if(num==0){ return 1; } int n = 1; for(int i = 1; i<=num;i++){ n*=i; } return n; } static int[] jt=new int[8]; public static void main(String args[]) throws IOException{ String[] ss = new String[2]; int num; FileInputStream fstream = new FileInputStream(""p:/C-small-attempt3.in""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String readLine; readLine = br.readLine(); num = Integer.valueOf(readLine); //System.out.println(num); FileWriter fstreamw = new FileWriter(""p:/C-small-attempt3.out""); BufferedWriter out = new BufferedWriter(fstreamw); // Read File Line By Line int number = 1; while ((readLine = br.readLine()) != null) { ss = readLine.split("" ""); ////System.out.println(ss[0]); ////System.out.println(ss[1]); int[] A = new int[ss[0].length()]; int[] B = new int[ss[0].length()]; int numA = Integer.valueOf(ss[0]); int numB = Integer.valueOf(ss[1]); int[] count=new int[8]; int counttemp = 1; int sum =0; int l=ss[0].length(); ////System.out.println(""l==""+l); int l2=(int)Math.pow(10, l-1); ////System.out.println(numA+"" ""+numB); // //System.out.print(ss[0].length()); for (int i = 0; i < l; i++) { A[i] = Integer.valueOf(ss[0].charAt(i)); // //System.out.print(ss[0].charAt(i)); } ////System.out.println(); for (int i = 0; i < l; i++) { B[i] = Integer.valueOf(ss[1].charAt(i)); } for (int j = numA; j <= numB; j++) { int jtemp = j; jt[0]=j; for (int i = 1; i < l; i++) { jtemp=(jtemp-(jtemp/(l2))*l2)*10+jtemp/l2; ////System.out.println(j+"" ""+jtemp); if((jtemp>=numA)&&(jtemp<=numB)&&(j!=jtemp)){ if(notequal(jtemp)){ counttemp = counttemp + 1; jt[i]=jtemp; //System.out.println(j+"" ""+jtemp); } ////System.out.println(j+"" ""+jtemp); } ////System.out.println(j); } for(int i=1;i<8;i++){ jt[i]=0; } if(counttemp!=1){ ////System.out.println(""counttemp=""+Math.ceil(counttemp)); ////System.out.println(counttemp); switch(counttemp){ case 1: count[1]=count[1]+factorial(counttemp)/(2*factorial(counttemp-2)); break; case 2: count[2]=count[2]+factorial(counttemp)/(2*factorial(counttemp-2)); break; case 3: count[3]=count[3]+factorial(counttemp)/(2*factorial(counttemp-2)); break; case 4: count[4]=count[4]+factorial(counttemp)/(2*factorial(counttemp-2)); break; case 5: count[5]=count[5]+factorial(counttemp)/(2*factorial(counttemp-2)); break; case 6: count[6]=count[6]+factorial(counttemp)/(2*factorial(counttemp-2)); break; case 7: count[1]=count[1]+factorial(counttemp)/(2*factorial(counttemp-2)); break; } ////System.out.println(""count=""+Math.ceil(count)); } counttemp=1; } sum = count[1]/1+count[2]/2+count[3]/3+count[4]/4+count[5]/5+count[6]/6+count[7]/7; //sum = count[1]+count[2]+count[3]+count[4]+count[5]+count[6]+count[7]; out.write(""Case #""); out.write(String.valueOf(number)); out.write("": ""); out.write(String.valueOf(sum)); if(number!=num){ out.write(""\r\n""); } number++; if(sum!=0){ //System.out.println(""sum=""+sum); ////System.out.println(factorial(count)/(2*factorial(count-2))); } for(int i =0;i<8;i++){ count[i]=0; } } out.close(); } private static boolean notequal(int i) { for(int i1=0;i1<7;i1++){ if(i==jt[i1]){ return false; } } return true; } } " B10197,"package codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; /* import lib.tuple.Pair; import lib.tuple.Tuple; import lib.util.StringUtil; */ public class CodeJam2012RQC { static final String fileIn = ""/Users/jhorwitz/Documents/workspace/test/src/codejam/data/RQ-C-in.txt""; //""data/in.txt""; static final String fileOut = ""/Users/jhorwitz/Documents/workspace/test/src/codejam/data/RQ-C-out.txt""; //""data/out.txt""; public static void main(String[] args) throws Exception { BufferedReader r = new BufferedReader(new FileReader(fileIn)); BufferedWriter w = new BufferedWriter(new FileWriter(fileOut)); String line = r.readLine(); int T = Integer.parseInt(line); for (int caseNum = 1; caseNum <= T; caseNum++) { line = r.readLine(); String str = ""Case #"" + caseNum + "": "" + solve(line); w.write(str + ""\n""); System.out.println(str); } w.close(); r.close(); } private static int solve(String line) { String[] stringVerOfAAndB = line.split("" ""); int A = Integer.parseInt(stringVerOfAAndB[0]); int B = Integer.parseInt(stringVerOfAAndB[1]); int digits = stringVerOfAAndB[0].length(); // == stringVerOfAAndB[1] (guaranteed by GCJ) int numRecycledPairsTimesTwo = 0; // each pair will be counted twice--we then simply divide by 2 in the end int rotatedNum; for (int curNum=A; curNum<=B; ++curNum) { for (int rot=1; rot<=digits; ++rot) { rotatedNum = rotate(curNum, rot, digits); if (A<=rotatedNum && rotatedNum<=B && isFirstSuchRotation(curNum,rotatedNum,rot,digits)) { ++numRecycledPairsTimesTwo; } } } return numRecycledPairsTimesTwo/2; } private static boolean isFirstSuchRotation(int numToRotate, int rotatedNum, int rot1, int digits) { for (int rot2=0; rot2 0){ int rem = dFrom%j; dFrom = dFrom/j; rem *= Math.pow(10, numDigits - count); dFrom += rem; if(dFrom > i && dFrom <=to) { array[arrayCount++] = dFrom; } ++count; dFrom = i; j *= 10; } Arrays.sort(array,0,arrayCount); outer: for(int w=0 ; w< arrayCount; w++){ for(int x=w + 1 ; x < arrayCount ; x++){ if(array[w] == array[x]) continue outer; } ++propCount; } } System.out.printf(""Case #%d: %d\n"", N + 1, propCount); } } }" B12618,"import java.io.IOException; import java.util.List; public class ReverseWords extends JamProblem { public static void main(String[] args) throws IOException { ReverseWords p = new ReverseWords(); p.go(); } @Override String solveCase(JamCase jamCase) { StringBuilder builder = new StringBuilder(); ReverseWordsCase c = (ReverseWordsCase) jamCase; int length = c.words.length; for (int i = 0; i < length; i++) { String word = c.words[length-i-1]; builder.append(word + "" ""); } return builder.toString(); } @Override JamCase parseCase(List file, int line) { ReverseWordsCase c= new ReverseWordsCase(); c.lineCount = 1; c.words = file.get(line).split("" ""); return c; } } class ReverseWordsCase extends JamCase{ String[] words; }" B10200,"import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Q3 { public static void main (String[] args) { Scanner s = new Scanner(System.in); int numTests = s.nextInt(); for (int test = 0; test < numTests; test++) { int a = s.nextInt(); int b = s.nextInt(); int count = 0; for (int i = a; i < b; i++) { String si = String.valueOf(i); Set found = new HashSet(); for (int j = 0; j < si.length(); j++) { String sj = si.substring(j) + si.substring(0, j); int other = Integer.parseInt(sj); if (!found.contains(other) && other > i && other <= b) { found.add(other); count++; } } } System.out.println(""Case #"" + (test+1) + "": "" + count); } } } " B12931,"import java.io.*; import java.util.*; public class recycled { private static int digits(int num) { int sol = 1; while (num / 10 != 0) { sol *= 10; num /= 10; } return sol; } /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { Scanner fe = new Scanner(new FileInputStream(""/home/gllera/Desktop/data.in"")); FileWriter fs = new FileWriter(""/home/gllera/Desktop/data.out""); int cases = fe.nextInt(); for (int i = 0; i < cases; i++) { int a = fe.nextInt(); int b = fe.nextInt(); int sol = 0; TreeSet tree = new TreeSet(); for (int n = a; n < b; n++) { tree.clear(); int digits = digits(n); int idigits = 10; int n1 = n / digits; int n2 = n % digits; while ( digits != 1 ) { int m = n2 * idigits + n1; if ( n < m && m <= b && !tree.contains(m) ) { tree.add(m); sol++; } digits /= 10; idigits *= 10; n1 = n / digits; n2 = n % digits; } } fs.write(""Case #"" + (i + 1) + "": "" + sol + '\n'); } fe.close(); fs.flush(); fs.close(); } } " B10448,"package MyAllgoritmicLib; public class BinaryPower { public static int binpow (int a, int n) { int r = 1; while (n > 0) if (n % 2 == 0) { a *= a; n /= 2; } else { r *= a; --n; } return r; } public static long binpow (long a, int n) { long r = 1; while (n > 0) if (n % 2 == 0) { a *= a; n /= 2; } else { r *= a; --n; } return r; } public static double binpow (double a, int n) { double r = 1; while (n > 0) if (n % 2 == 0) { a *= a; n /= 2; } else { r *= a; --n; } return r; } } " B12210,"package hk.polyu.cslhu.codejam.solution.impl; import hk.polyu.cslhu.codejam.solution.Solution; import java.util.ArrayList; import java.util.List; public class StoreCredit extends Solution { private int amountOfCredits, numOfItems; private List priceList; @Override public void setProblem(List testCase) { this.initial(testCase); } private void initial(List testCase) { // TODO Auto-generated method stub this.amountOfCredits = Integer.valueOf(testCase.get(0)); this.numOfItems = Integer.valueOf(testCase.get(1)); this.setPriceList(testCase.get(2)); } private void setPriceList(String string) { // TODO Auto-generated method stub String[] splitArray = string.split("" ""); if (splitArray.length != numOfItems) logger.error(""The price list does not include all items ("" + splitArray.length + ""/"" + this.numOfItems + "")""); this.priceList = new ArrayList(); for (String price : splitArray) { this.priceList.add(Integer.valueOf(price)); } } @Override public void solve() { for (int itemIndex = 0; itemIndex < this.priceList.size() - 1; itemIndex++) { for (int anotherItemIndex = itemIndex + 1; anotherItemIndex < this.priceList.size(); anotherItemIndex++) { if (this.priceList.get(itemIndex) + this.priceList.get(anotherItemIndex) == this.amountOfCredits) { this.result = (itemIndex + 1) + "" "" + (anotherItemIndex + 1); break; } } } } @Override public String getResult() { return this.result; } } " B12215,"package hk.polyu.cslhu.codejam.thread; import hk.polyu.cslhu.codejam.lib.ResultCollector; import hk.polyu.cslhu.codejam.solution.Solution; import hk.polyu.cslhu.codejam.solution.impl.StoreCredit; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.log4j.Logger; public class JamThreadManager { public static Logger logger = Logger.getLogger(JamThreadManager.class); private final ExecutorService pool; private Solution solutionPrototype; private List> testCaseList; private boolean allowMultiThreads; private int numOfThreads; private ResultCollector resultCollector; /** * Constructs an instance of JamThreadManager * * @param solutionPrototype Solution The prototype of solution * @param testCaseList List> The data of test cases * @param resultFile String The location of result file * @param allowMultiThreads boolean The multi-threads mode is enabled if true; otherwise single thread is used */ public JamThreadManager( Solution solutionPrototype, List> testCaseList, String resultFile, String resultPattern, boolean allowMultiThreads) { this.pool = Executors.newCachedThreadPool(); this.solutionPrototype = solutionPrototype; this.testCaseList = testCaseList; this.allowMultiThreads = allowMultiThreads; this.numOfThreads = this.allowMultiThreads ? Runtime.getRuntime().availableProcessors() : 1; this.resultCollector = new ResultCollector(testCaseList.size(), resultFile, resultPattern); } /** * Initialize the threads to set off * @throws CloneNotSupportedException */ public void runThreads() throws CloneNotSupportedException { List>> subTasks = this.divideTestCases(); int testCaseIndex = 1; for (List> subTask : subTasks) { JamThread jamThread = this.createJamThread(); jamThread.setSolution(this.solutionPrototype.clone()); jamThread.setIndexOfList(testCaseIndex); jamThread.setTestCaseList(subTask); jamThread.setResultCollector(this.resultCollector); // update testCaseIndex testCaseIndex++; // run the thread this.pool.execute(jamThread); } } /** * Divide the test cases into numOfThreads pieces * * @return List>> The subtasks */ private List>> divideTestCases() { // TODO Auto-generated method stub List>> subTasks = new ArrayList>>(); // set the number of test cases per subtask int numOfTestCasesPerSubtask = this.testCaseList.size(); if (this.allowMultiThreads) { if (this.testCaseList.size() < this.numOfThreads) numOfTestCasesPerSubtask = 1; else numOfTestCasesPerSubtask = (int) Math.floor(this.testCaseList.size() / this.numOfThreads); } // dive the test case list for (int i = 0; i < Math.min(this.testCaseList.size(), this.numOfThreads); i++) { int fromIndex = i * numOfTestCasesPerSubtask; int toIndex = (i == this.numOfThreads - 1) ? this.testCaseList.size() : (i + 1) * numOfTestCasesPerSubtask; subTasks.add(this.testCaseList.subList(fromIndex, toIndex)); } return subTasks; } // Factory method of creating jam thread private JamThread createJamThread() { // TODO Auto-generated method stub return new JamThread() { @Override public void run() { // TODO Auto-generated method stub List result = new ArrayList(); for (List testCase : this.getTestCaseList()) { this.getSolution().setProblem(testCase); this.getSolution().solve(); result.add(this.getSolution().getResult()); } this.getResultCollector().updateResult(this.getIndexOfList(), result); } }; } } " B11756," import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Map; import java.util.TreeMap; import java.util.Set; import java.util.TreeSet; class RecycledNumbers { private static int[] primeMap = new int[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(reader.readLine()); for (int i = 0; i < n; i++) { int counter = 0; String[] line = reader.readLine().split("" ""); int down = Math.max(10, Integer.parseInt(line[0])); int up = Integer.parseInt(line[1]); int tren = down; while (tren < up) { int limit = Math.min(up, (int) Math.pow(10, Math.ceil(Math.log10(tren + .1)))); Map> numbers = new TreeMap>(); for (; tren <= limit; tren++) { long hash = hash(tren); if (!numbers.containsKey(hash)) { numbers.put(hash, new TreeSet()); } numbers.get(hash).add(Integer.toString(tren)); } for (Long key : numbers.keySet()) { String[] vals = numbers.get(key).toArray(new String[] { }); for (int j = 0; j < vals.length - 1; j++) { for (int k = j + 1; k < vals.length; k++) { String first = vals[j]; String second = vals[k] + vals[k]; if (second.indexOf(first) != -1) { counter++; } } } } } System.out.println(""Case #"" + (i + 1) + "": "" + counter); } } private static long hash(int in) { long tmp = 1; while (in > 0) { tmp *= primeMap[in % 10]; in /= 10; } return tmp; } }" B12344,"import java.io.*; public class recycled { private boolean compare(String s1, String s2){ String s3 = s2+s2; boolean result = s3.contains(s1); return result; } private void go() throws Exception { File infile = new File(""C-small-attempt1.in""); BufferedReader br = new BufferedReader(new InputStreamReader( new FileInputStream(infile))); int num_of_cases = Integer.parseInt(br.readLine()); for (int i = 1; i <= num_of_cases; i++) { String[] case_str = br.readLine().split("" ""); int begin_num = Integer.parseInt(case_str[0]); int end_num = Integer.parseInt(case_str[1]); int satisifed = 0; for(int k=begin_num;k set = new HashSet(); int ans = 0; for (int i = A; i <= B; ++i) { String val = Integer.toString(i); HashSet set2 = new HashSet(); for (int j = 0; j < val.length()-1; ++j) { val = val.charAt(val.length()-1) + val.substring(0, val.length()-1); if (set2.contains(Integer.parseInt(val))) continue; if (set.contains(Integer.parseInt(val))) ++ans; set2.add(Integer.parseInt(val)); } set.add(i); } System.out.printf(""Case #%d: %d\n"", t, ans); } } } /* 4 1 9 10 40 100 500 1111 2222 */ " B12197,"package recyclednumbers; import java.io.*; import java.math.BigInteger; import java.util.Iterator; import java.util.Scanner; /** * * @author Diego Villatora */ public class RecycledNumbers { static int numberOfCases =0; static boolean first = true; static int currentInt = 0; static int firstNumber = 0; static int secondNumber = 0; static int[] founds = new int[]{}; /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { Scanner s = null; BufferedWriter output = null; int counter = 0; // for the output and the writing on file // Create file File file =null; FileWriter fstream = null; try { //input s = new Scanner(new BufferedReader(new FileReader(""C:\\Users\\Utente\\Downloads\\C-small-attempt5.in""))); //output file = new File(""C:\\Users\\Utente\\Downloads\\google3.out""); fstream = new FileWriter(file); output = new BufferedWriter(fstream); //while not EOF int i=0; while (s.hasNext()) { if(first){ numberOfCases = s.nextInt(); first=false; }else{ currentInt = s.nextInt(); //get int counter++; if(counter == 1){ firstNumber = currentInt; } else{ secondNumber = currentInt; counter = 0; } if (counter == 0){ i++; int maxNumberRecycled = getMaxRecycled(firstNumber,secondNumber); output.write(""Case #""+ i +"": "" + maxNumberRecycled); output.newLine(); } } } }catch (Exception e){//Catch exception if any System.out.println(""Error: "" + e.getMessage()); System.out.println(""Error: "" + e.toString()); //to close the file if still open }finally { if (s != null) s.close(); if (output != null) output.close(); } } private static int getMaxRecycled(int firstNumber, int secondNumber){ int total = 0; int partial = 0; int numberRotating = 0; while(firstNumber numberRotating){ if((new Integer(numberRotating).toString().length()) < (new Integer(firstNumber).toString().length())){ numberRotating = numberRotating * 10; } else{ numberRotating = shiftNumber(numberRotating); } }else{ numberRotating = shiftNumber(numberRotating); } } firstNumber++; } return total; } private static int findEquals(int toFind, int start, int end){ int found = 0; /*for(int i = 0; i< founds.length; i++){ if (toFind == founds[i]){ return found; } }*/ if(toFind <= end){ /*int[] appo = new int[]{toFind}; int[] C= new int[appo.length+founds.length]; System.arraycopy(appo, 0, C, 0, appo.length); System.arraycopy(founds, 0, C, appo.length, founds.length); founds = C;*/ found = 1; } return found; } private static int shiftNumber(int toShift){ double toAdd = 0; double partial = 0; double restoInit = toShift; double numExp = 0; while(restoInit > 9){ restoInit = Math.floor(restoInit / 10); numExp++; } toAdd = Math.floor(toShift / Math.pow(10.0, numExp)); toShift = toShift * 10; partial = toShift % Math.pow(10.0, numExp+1); partial = partial + toAdd; return new Double(partial).intValue(); } } " B11197,"import java.io.*; public class TaskC { public static void main(String[] args) { try { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.valueOf(input.readLine()); for(int z=1; z<=t; z++) { int out = 0; String[] line = input.readLine().split("" ""); int A = Integer.valueOf(line[0]), B = Integer.valueOf(line[1]); for(int i=A; i<=B; i++) bylo[i] = false; // czas na rotacje ileRot = line[0].length() - 1; for(int i=A; i<=B; i++) if(bylo[i] == false) { bylo[i] = true; int dodajnik = 1; int liczba = i; String ls = Integer.toString(liczba); // System.out.println(""Rotuje "" + ls); // rotuje ile sie da for(int rot=0; rot=A && liczba <= B) { // System.out.println(""Zgadza sie z "" + ls); bylo[liczba] = true; out += dodajnik; dodajnik += 1; } } } System.out.println(""Case #"" + z + "": "" + out); } } catch (Exception e) { System.err.println(e); } } static int ileRot; static boolean[] bylo = new boolean[2000001]; } " B10455,"package MyAllgoritmicLib; public class SimpleNumbers { public static boolean[] masInt; public static void initSimpleInt(int n) { // âõîäíûå äàííûå masInt = new boolean[n + 1]; for(int i=0; i<=n;i++){ masInt[i] = true; } masInt[0] = masInt[1] = false; // åñëè êòî-òî áóäåò èñïîëüçîâàòü ýòè // çíà÷åíèÿ for (int i = 2; i <= n; ++i) { if (masInt[i]) { for (int j = i + i; j < n; j += i) { masInt[j] = false; } } } } public static void main(String[] args) { initSimpleInt(1000000); int col = 0; int max = 0; for (int i = 0; i < 1000000; i++) { if (masInt[i]) { col++; max = i; } } System.out.println(max); System.out.println(col); } } " B11768,"package de.johanneslauber.codejam.model; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.List; /** * * @author Johannes Lauber - joh.lauber@googlemail.com * */ public abstract class BaseProblem implements IProblem { protected List listOfCases; private BufferedWriter out; private int countOutputLines = 0; public BaseProblem() { try { out = new BufferedWriter(new FileWriter(""output/output.out"")); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } @Override public void setListOfCases(List listOfCases) { this.listOfCases = listOfCases; } /** * * @author Johannes Lauber - joh.lauber@googlemail.com * @param stringArray * @return */ protected int[] toIntArray(String[] stringArray) { int[] intArray = new int[stringArray.length]; for (int i = 0; i < stringArray.length; i++) { intArray[i] = Integer.valueOf(stringArray[i]); } return intArray; } /** * * @author Johannes Lauber - joh.lauber@googlemail.com * @param line */ protected void writeToFile(String line) { countOutputLines++; try { out.write(""Case #"" + countOutputLines + "": "" + line); out.newLine(); } catch (IOException e) { e.printStackTrace(); } } /** * * @author Johannes Lauber - joh.lauber@googlemail.com */ protected void closeWriter() { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } }" B11300,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recyclednumbers; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; /** * * @author Jason */ public class NumberCruncher { public NumberCruncher(BufferedReader reader) { try { FileWriter outFile = new FileWriter((""output.txt"")); PrintWriter out = new PrintWriter(outFile); int cases = Integer.parseInt(reader.readLine()); for(int i=1;i<=cases;i++) { String list = reader.readLine(); String separator = "" ""; ArrayList nums = new ArrayList(Arrays.asList(list.split(separator))); int recycled = 0; //System.out.println(nums.toString()); HashSet result = new HashSet(); ArrayList aChars = StringToArrayList(nums.get(0)); //System.out.println(""aChars: "" + aChars.toString()); //System.out.println(""Value of aChars: "" + ValueOfList(aChars)); int A = Integer.parseInt(nums.get(0)); int B = Integer.parseInt(nums.get(1)); //System.out.println(""A: "" + A); //System.out.println(""B: "" + B); while (ValueOfList(aChars) < B) { ArrayList temp = new ArrayList(aChars); //System.out.println(""Value of aChars: "" + ValueOfList(aChars)); for(int j=0;j<(aChars.size()-1);j++) { String tStr = temp.get(aChars.size()-1); temp.remove(aChars.size()-1); temp.add(0, tStr); if(ValueOfList(temp) <= B && ValueOfList(aChars) < ValueOfList(temp) && temp.size() == aChars.size()) { recycled++; String toAdd = ValueOfList(aChars) + ""->"" + ValueOfList(temp); result.add(toAdd); //System.out.println(ValueOfList(aChars) + ""->"" + ValueOfList(temp) + "" IS RECYCLED!""); //System.out.println(""IS RECYCLED!""); } } aChars = Increment(aChars); } //System.out.println(""Case #""+i+"": "" + result.size()); out.println(""Case #""+i+"": "" + result.size()); } out.close(); }catch(IOException e){System.out.println(""Exception!"");} } private int ValueOfList(ArrayList l) { int sum = 0; int digits = l.size(); for(String str : l) { digits--; sum += (Integer.parseInt(str) * Math.pow(10, digits)); } return sum; } private ArrayList Increment(ArrayList l) { int v = ValueOfList(l); v++; String s = Integer.toString(v); return StringToArrayList(s); } private ArrayList StringToArrayList(String str) { ArrayList newArray = new ArrayList(); for(int i=0;i=from && recycled<=to) numPairs++; recycled = recycle(recycled, digitsPow10); } } caseNum++; out.println(""Case #""+caseNum+"": ""+(numPairs/2)); } public static int recycle(int num, int digitsPow10){ while(true){ int lastDigit = num%10; num = lastDigit*digitsPow10 + num/10; if(lastDigit!=0) break; } return num; } }" B13235,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; public class recyclednumbers { public static void main(String [] args) throws Exception { BufferedReader reader = new BufferedReader (new FileReader(""C:\\inputFile.txt"")); int number_of_TestCases = (int) Integer.parseInt(reader.readLine()); long testcases[] [] = new long [number_of_TestCases] [2]; for(int i=0;ia ) // also check for leading zero { pairs_count++; } b = rotate(b); } return pairs_count; } private static String rotate(String a) { String num = a; char[] digits= num.toCharArray(); String newNum = """"+digits[digits.length-1]; for(int i=0;i 0; i /= 10 ) { b[bc++] = i % 10; } int mlc = 0; don: for( int i = 1; i < bc; i++ ) { int m = 0; for( int j = bc-1; j >= 0; j-- ) { m = (m*10) + b[(j+i)%bc]; } if( m > n && m <= B ) { for (int j = 0; j < mlc; j++) { if( m == ml[j] ) { continue don; } } max++; ml[mlc++] = m; } } } println(""Case #"" + cc + "": ""+max); //System.out.format(""Case #%d: %.09f\n"", cc, total); } public static void run() throws Exception { String qprefix = ""C""; //init(qprefix+""-large""); //init(qprefix + ""-small-attempt1""); init(""test""); int cases = INT(); for (int cc = 1; cc <= cases; cc++) { new A(cc); } } static class Ct extends Thread { public void run() { } } static int[][] mapClone(int[][] map) { int[][] cmap = map.clone(); for (int i = 0; i < cmap.length; i++) { cmap[i] = map[i].clone(); } return cmap; } // ************************************************************************************* // *********************************** FRAMEWORK // ************************************************************************************* public static BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)); public static boolean isStandardInput = false; public static File input; public static FileReader inputreader; public static BufferedReader in; public static File output; public static FileWriter outputwriter; public static BufferedWriter out; public static StringTokenizer st; public static void main(String[] args) throws Exception { doSTDIN(true); setOutput(""test.out""); run(); close(); } public static void init(String problemName) throws Exception { doSTDIN(false); setInput(problemName + "".in""); setOutput(problemName + "".out""); } // **************** PRINT METHODS ********************** public static void println() throws IOException { out.write(""\n""); System.out.println(); } public static void println(Object obj) throws IOException { out.write(obj.toString()); out.write(""\n""); System.out.println(obj.toString()); } public static void print(Object obj) throws IOException { out.write(obj.toString()); System.out.print(obj.toString()); } public static void println(long number) throws IOException { out.write(Long.toString(number)); out.write(""\n""); System.out.println(number); } public static void print(long number) throws IOException { out.write(Long.toString(number)); System.out.print(number); } public static void println(char c) throws IOException { out.write(Character.toString(c)); out.write(""\n""); System.out.println(c); } public static void print(char c) throws IOException { out.write(Character.toString(c)); System.out.print(c); } public static void println(String line) throws IOException { out.write(line); out.write(""\n""); System.out.println(line); } public static void print(String line) throws IOException { out.write(line); System.out.print(line); } // ******************** INPUT DECLARATION ****************** public static void doSTDIN(boolean standard) { isStandardInput = standard; } public static void setInput(String filename) throws IOException { input = new File(filename); inputreader = new FileReader(input); in = new BufferedReader(inputreader); } public static void setOutput(String filename) throws IOException { output = new File(filename); outputwriter = new FileWriter(output); out = new BufferedWriter(outputwriter); } public static void close() throws IOException { if (in != null) in.close(); if (inputreader != null) inputreader.close(); if (out != null) out.flush(); if (out != null) out.close(); if (outputwriter != null) outputwriter.close(); } // ************************** INPUT READING ***************** static String LINE() throws IOException { return isStandardInput ? stdin.readLine() : in.readLine(); } static String TOKEN() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(LINE()); return st.nextToken(); } static int INT() throws IOException { return Integer.parseInt(TOKEN()); } static long LONG() throws IOException { return Long.parseLong(TOKEN()); } static double DOUBLE() throws IOException { return Double.parseDouble(TOKEN()); } static BigInteger BIGINT() throws IOException { return new BigInteger(TOKEN()); } } class AF { private Object array; private int oa = 0; private int ob = 0; private int as = 10; private int bs = 10; public AF(Object array) { this.array = array; } public AF(Object array, int oa, int ob) { this.array = array; this.oa = oa; this.ob = ob; } public AF(Object array, int oa, int ob, int as, int bs) { this.array = array; this.oa = oa; this.ob = ob; this.as = as; this.bs = bs; } public String toString() { StringBuilder sb = new StringBuilder(); for (int a = 0; a < as; a++) { sb.append(a + oa).append('['); for (int b = 0; b < bs; b++) { sb.append(get(a, b)); if (b != bs - 1) sb.append(','); } sb.append(""]\n""); } return sb.toString(); } private String get(int a, int b) { a += oa; b += ob; String s = "" ""; try { if (array instanceof int[][]) { int[][] na = (int[][]) array; s = Integer.toString(na[a][b]); } else if (array instanceof byte[][]) { byte[][] na = (byte[][]) array; s = Byte.toString(na[a][b]); } else if (array instanceof Object[][]) { Object[][] na = (Object[][]) array; s = na[a][b].toString(); } } catch (Exception e) { } while (s.length() < 2) { s = "" "" + s; } return s; } } class AF2 extends JFrame implements ActionListener { static Object lock = new Object(); private JTable jt; public AF2(String title, int[][] data) { super(title); setSize(150, 150); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { dispose(); System.exit(0); } }); jt = new JTable(new ITableModel(data)); jt.setDefaultRenderer(Integer.class, new CustomTableCellRenderer()); // jt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); JScrollPane pane = new JScrollPane(jt, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); getContentPane().add(pane); JButton button = new JButton(""Continue""); getContentPane().add(button, BorderLayout.SOUTH); button.addActionListener(this); pack(); setVisible(true); } public void updateData(int[][] data) { ((ITableModel) jt.getModel()).updateData(data); /*synchronized (lock) { try { lock.wait(); } catch (InterruptedException e) { } }*/ return; } public void actionPerformed(ActionEvent arg0) { synchronized (lock) { lock.notify(); } } } class ITableModel extends AbstractTableModel { int[][] data; int[][] old_data; public ITableModel(int[][] data) { if (data != null) this.data = data; else this.data = new int[1][1]; } public void updateData(int[][] p_data) { if( p_data.length == data.length && p_data[0].length == data[0].length ) { old_data = data; } else { old_data = null; } this.data = p_data; EventQueue.invokeLater(new Runnable() { public void run() { fireTableStructureChanged(); } }); } public int getColumnCount() { return data[0].length + 1; } public int getRowCount() { return data.length; } public String getColumnName(int column) { return Integer.toString(column - 1); } public Object getValueAt(int rowIndex, int columnIndex) { if (columnIndex == 0) return rowIndex; if( old_data != null && data[rowIndex][columnIndex - 1] != old_data[rowIndex][columnIndex - 1] ) { return """"+old_data[rowIndex][columnIndex - 1]+"" -> ""+data[rowIndex][columnIndex - 1]; } return data[rowIndex][columnIndex - 1]; } public Class getColumnClass(int arg0) { return getValueAt(0, arg0).getClass(); } } class CustomTableCellRenderer extends DefaultTableCellRenderer { public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if (column == 0) { cell.setBackground(Color.gray); } else if (value instanceof Integer) { Integer amount = (Integer) value; if (amount.intValue() <= 0) { cell.setBackground(Color.red); } else { cell.setBackground(Color.white); } } else { cell.setBackground(Color.yellow); } return cell; } } " B12833,"/** * C.java * @author Joel C. Soares */ import java.util.Scanner; import java.util.HashSet; public class C { public static int inv( int n, int l ) { int x = n % 10, p = ( int ) Math.pow( 10, l - 1 ); for( int i = 0; i < l - 1; i++ ) { x = x * 10 + n / p; n = n % p; p = p / 10; } return x; } // fim de método public static int length( int n ) { int i = 0; if( n == 0 ) return 1; while( n != 0 ) { n = n / 10; i++; } return i; } public static void main( String args[] ) { Scanner input = new Scanner( System.in ); int t, a, b, n, q, p, l, total, count; HashSet set = new HashSet(); t = input.nextInt(); for( int i = 0; i < t; i++ ) { a = input.nextInt(); b = input.nextInt(); // computa resultado set.clear(); total = 0; for( n = a; n < b; n++ ) { q = n; l = length( q ); set.add( q ); count = 1; for( int j = 0; j < l - 1; j++ ) { q = inv( q, l ); // verifica restricoes if( q >= a && q <= b && !set.contains( q ) ) { set.add( q ); count++; } // fim de if } total += ( count - 1 ) * count / 2; } // fim de for System.out.printf( ""Case #%d: %d\n"", i + 1, total ); } } }" B10150,"package com.nitrous.codejam; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; public class CodeJamProblem3 { public static void readFile(String inputFile) throws IOException { File in = new File(inputFile); File dir = in.getParentFile(); File outFile = new File(dir, in.getName()+"".out""); System.out.println(""Output file is ""+outFile.getAbsolutePath()); PrintWriter out = new PrintWriter(outFile); BufferedReader reader = new BufferedReader(new FileReader(in)); String line = null; int testCaseCount = Integer.parseInt(reader.readLine().trim()); System.out.println(""Read count=""+testCaseCount); for (int testCase = 0 ; testCase < testCaseCount; testCase++) { line = reader.readLine(); String[] numStrArr = line.split("" ""); int min = Integer.parseInt(numStrArr[0]); int max = Integer.parseInt(numStrArr[1]); int count = 0; for (int current = min; current <= max; current++) { count += countRecycled(current, max); } out.println(""Case #""+(testCase+1)+"": ""+count); } out.flush(); out.close(); } private static int countRecycled(int current, int maxValue) { String curAsStr = String.valueOf(current); int maxLen = curAsStr.length(); HashSet unique = new HashSet(); for (int len = 1; len < maxLen; len++) { String move = curAsStr.substring(0, len); String mid = curAsStr.substring(len); String newStr = mid + move; while (newStr.length() > 1 && newStr.startsWith(""0"")) { newStr = newStr.substring(1); } int newNum = Integer.parseInt(newStr); if (newNum > current && newNum <= maxValue) { unique.add(newNum); } } return unique.size(); } public static void main (String[] args) throws IOException { readFile(""D:/workspace/CodeJam/data/C-small-attempt0.in""); } } " B11836,"/* Sam1rm Google Code Jam */ import java.io.*; import java.util.*; class ProblemC { public static void main (String [] args) throws IOException { String filename = args[0]; BufferedReader f = new BufferedReader(new FileReader(filename + "".in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(filename + "".out""))); int numberOfTests = Integer.parseInt(f.readLine()); for(int n = 1; n <= numberOfTests; n++) { int solution = 0; String input = f.readLine(); solution = parseString(input); set = new HashSet(); out.println(""Case #"" + n + "": "" + solution); } out.close(); System.exit(0); } public static int parseString(String input1) { String[] inputs = input1.split("" ""); int solution = 0; int size = inputs[0].length(); if (size == 0) { return 0; } int A = Integer.parseInt(inputs[0]); int B = Integer.parseInt(inputs[1]); System.out.println(""I'm processing between the range"" + "" A: "" + A + "" B: "" + B); for (int i = A; i <= B; i++) { solution += isRecycled(i + """", B + """", size); } return solution; } public static int isRecycled(String a, String b, int size) { int solution = 0; if (a.equals(b)) { return 0; } String temp = a; for (int i = 0; i < size - 1; i++) { temp = rotate1(temp); int _a = Integer.parseInt(a); int _b = Integer.parseInt(b); int m = Integer.parseInt(temp); if (m > _a && m <= _b && !(m == _a) && !set.contains(_a + "" "" + m)) { System.out.println(a + "" "" + m); solution++; set.add(_a + "" "" + m); } } return solution; } public static String rotate1(String input) { return input.substring(1, input.length()) + input.substring(0, 1); } public static HashSet set = new HashSet(); } " B10125,"import java.io.*; import java.math.BigInteger; import java.util.Arrays; import java.util.Comparator; import java.util.StringTokenizer; public class C implements Runnable { private static final String PROBLEM_ID = ""C""; private class TestCaseRunner { int answer(int a, int b) { int result = 0; for (int i = a; i <= b; i++) { int p10 = 1; int pI = i; while (pI > 0) { pI /= 10; p10 *= 10; } p10 /= 10; int j = i; for (;;) { boolean leadingZero = (j % 10) == 0; j = (j / 10) + p10 * (j % 10); if (j == i) { break; } if (i < j && j <= b && !leadingZero){ result++; // System.out.println(i + "" -> "" + j); } } } return result; } public void handleCase() throws IOException { int a = nextInt(); int b = nextInt(); out.print(answer(a, b)); } } BufferedReader in; PrintWriter out; StringTokenizer tokenizer = new StringTokenizer(""""); public static void main(String[] args) { new Thread(new C()).start(); } public void run() { File[] all = new File(""."").listFiles(); Arrays.sort(all, new Comparator() { public int compare(File a, File b) { return a.getName().toLowerCase().compareTo(b.getName().toLowerCase()); } }); int processed = 0; for (File inFile : all) if (inFile.isFile()) { String name = inFile.getName().toLowerCase(); if (name.startsWith(PROBLEM_ID.toLowerCase()) && name.endsWith("".in"")) { try { runFile(inFile); processed++; } catch (Throwable t) { throw new IllegalStateException(""Fatal error"", t); } } } if (processed > 0) { System.out.println(""Processed "" + processed + "" files for problem "" + PROBLEM_ID); } else { System.err.println(""No input files found for problem "" + PROBLEM_ID); } } private void runFile(File inFile) throws IOException { in = new BufferedReader(new FileReader(inFile)); out = new PrintWriter(new FileWriter(inFile.getName() + "".out"")); long startTime = System.currentTimeMillis(); System.out.println(""Processing file: "" + inFile.getName()); int tc = nextInt(); for (int p = 0; p < tc; p++) { long nowTime = System.currentTimeMillis(); System.out.print(""Running test case #"" + (p + 1) + "" out of "" + tc); if (p > 0) { System.out.print("" (remaining time: "" + remainingTime(p, tc, startTime, nowTime) + "")""); } System.out.println(); out.print(""Case #"" + (p + 1) + "": ""); new TestCaseRunner().handleCase(); out.println(); } in.close(); out.close(); } private String remainingTime(int p, int tc, long startTime, long nowTime) { double secondsPerTestCase = 1.0e-3 * (nowTime - startTime) / p; double secondsRemaining = (tc - p) * secondsPerTestCase; double minutesRemaining = secondsRemaining / 60; int minutes = (int) Math.floor(minutesRemaining); int seconds = (int) Math.round(secondsRemaining - minutes * 60); return minutes + "" min "" + seconds + "" sec""; } private String nextToken() throws IOException { while (!tokenizer.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } tokenizer = new StringTokenizer(line); } return tokenizer.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private BigInteger nextBigInt() throws IOException { return new BigInteger(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }" B10355,"import java.io.*; import java.util.*; public class SpeakingTheTongues implements Runnable { public static void main(String[] args) throws IOException { new Thread(new SpeakingTheTongues()).start(); } public BufferedReader br; public StringTokenizer in; public PrintWriter out; public String nextToken() throws IOException { while (in == null || !in.hasMoreTokens()) { in = new StringTokenizer(br.readLine()); } return in.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } String[] s = { ""ejp mysljylc kd kxveddknmc re jsicpdrysi"", ""rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd"", ""de kr kd eoya kw aej tysr re ujdr lkgc jv"" }; String[] sa = { ""our language is impossible to understand"", ""there are twenty six factorial possibilities"", ""so it is okay if you want to just give up"" }; char[] to = new char[300]; public void precalc() { for (int i = 0; i < s.length; i++) { for (int j = 0; j < s[i].length(); j++) { to[s[i].charAt(j)] = sa[i].charAt(j); } } to['q'] = 'z'; to['z'] = 'q'; } public void solve() throws IOException { String s = br.readLine(); for (int i = 0; i < s.length(); i++) { out.print(to[s.charAt(i)]); } out.println(); } public void run() { try { br = new BufferedReader(new FileReader(""A-small.in"")); out = new PrintWriter(""a.out""); precalc(); int t = nextInt(); for (int i = 0; i < t; i++) { out.print(""Case #"" + (i + 1) + "": ""); solve(); } out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } } " B12731,"package qualifying; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; public class C { public static void main(String[] args) throws Exception { String fs_in = ""/Users/ctynan/Downloads/test.txt""; String fs_out = ""/Users/ctynan/Documents/C-out.txt""; String line; BufferedReader br = new BufferedReader(new FileReader(fs_in)); BufferedWriter bw = new BufferedWriter(new FileWriter(fs_out)); line=br.readLine(); line=line.toLowerCase(); int tst = Integer.valueOf(line); for(int ii=0;iii&&tm<=B) { boolean have = false; for(int l=0;l= B) { return 0; } int result = 0; n = new int[digits]; int counter = digits; int A_ = A; for (;--counter >= 0;) { n[counter] = A_ % 10; A_ = A_ / 10; } counter = B - A; for (int i = 0; i < counter; ++i) { HashSet unique = new HashSet(); for (int j = 1; j < digits; ++j) { if (isGreaterThanA(j) && isLessOrEqThanB(j)) { if(unique.add(m)) { ++result; } continue; } } incrementA(); } return result; } private boolean isLessOrEqThanB(int j) { return m <= B; } private boolean isGreaterThanA(int j) { m = 0; for (int k = j; k < digits; ++k) { m *= 10; m += n[k]; } for (int k = 0; k < j; ++k) { m *= 10; m += n[k]; } int A_ = 0; for (int k = 0; k < digits; ++k) { A_ *= 10; A_ += n[k]; } return m > A_; } /*private boolean isLessOrEqThanB(int j) { boolean notSwitched = true; for (int i = 0; i < digits; ++i) { if (notSwitched && i+j == digits) { j = -i; notSwitched = false; } if (b[i] > a[i+j]) { return true; } else if (b[i] < a[i+j]) { return false; } } return true; } private boolean isGreaterThanA(int j) { boolean notSwitched = true; for (int i = 0; i < digits; ++i) { if (notSwitched && i+j == digits) { j = -i; notSwitched = false; } if (a[i] > a[i+j]) { return false; } else if (a[i] < a[i+j]) { return true; } } return false; }*/ private void incrementA() { for (int i = digits - 1; i >= 0; --i) { if ((n[i] += 1) == 10) { n[i] = 0; } else { break; } } } /* (non-Javadoc) * @see code.google.codejam.Template#printInput() */ @Override protected void printInput() throws Exception { System.out.println(""Digits-"" +digits + "":"" + A + ""-"" + B); } /* (non-Javadoc) * @see code.google.codejam.Template#initializeTestCase() */ @Override protected void initializeTestCase() throws Exception { readLine(); A = readNextInteger(); digits = linePointer; B = readNextInteger(); } } " B13085,"import java.io.*; public class RecycledNo { public static void main (String arg[]) throws Exception { BufferedReader ob=new BufferedReader (new FileReader(""C-small-attempt2.in"")); PrintWriter pw=new PrintWriter (""output.txt""); String temp=""""; temp=ob.readLine(); int t=Integer.parseInt(temp); int a=0,b=0; for(int l=1;l<=t;l++) { temp=ob.readLine(); String str=""""; for(int i=0;ik) count++; } } temp=""Case #""+l+"": ""+count; pw.println(temp); } pw.close(); } } " B11902,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; public class RecycledNumbers { public static void main(final String[] args) throws IOException { if (args.length == 0) { System.out.println(""Input file must be provided as an input""); return; } PrintWriter pw = null; try { pw = new PrintWriter(new BufferedWriter(new FileWriter(args[1]))); List cases = parseInput(args[0]); for (final TestCase testCase : cases) { pw.println(""Case #"" + testCase.getCaseNumber() + "": "" + testCase.solve()); } } finally { if(pw != null) { pw.close(); } } } private static List parseInput(final String filename) throws IOException { final List res = new ArrayList(); BufferedReader br = null; try { br = new BufferedReader(new FileReader(filename)); int casesNum = Integer.parseInt(br.readLine()); for (int i = 1; i <= casesNum; ++i) { String[] args = br.readLine().split(""\\s""); res.add(new TestCase(i, Integer.parseInt(args[0]), Integer.parseInt(args[1]))); } } finally { if (br != null) { br.close(); } } return res; } private static class TestCase { private final int caseNumber; private final int a; private final int b; public TestCase(int caseNumber, int a, int b) { super(); this.caseNumber = caseNumber; this.a = a; this.b = b; } public int solve() { int res = 0; for(int i = a; i < b; ++i) { for(int j = i + 1; j <=b; ++j) { final String iStr = ("""" + i) + i; final String jStr = """" + j; if (iStr.contains(jStr)) { ++res; } } } return res; } public int getCaseNumber() { return caseNumber; } } } " B12462,"import java.io.*; import java.util.*; public class C { public static void main(String[] args) throws IOException { //variable initialization String inFile = args[0]; String outFile = inFile.split(""\\."")[0] + "".out""; //file reading... BufferedReader reader = new BufferedReader(new FileReader(inFile)); PrintWriter writer = new PrintWriter(new FileWriter(outFile)); //get input data int T = Integer.valueOf(reader.readLine()); for (int t = 0; t < T; t++) { String[] str_nums = reader.readLine().split("" ""); int A = Integer.valueOf(str_nums[0]); int B = Integer.valueOf(str_nums[1]); int count = 0; // for (int i = 1; i < 5; i++) { // for (int j = i+1; j < 5; j++) { // for (int k = 0; k < 10; k++) { // if (k == i || k == j) continue; // int shift = 1; // int n = i*100 + k*10 + j; // int m = n % (int)Math.pow(10, shift) * (int)Math.pow(10, 3 - shift) // + n / (int)Math.pow(10, shift); // count++; // System.out.print(n + ""->"" + m + "", ""); // shift = 2; // n = i*100 + j*10 + k; // m = n % (int)Math.pow(10, shift) * (int)Math.pow(10, 3 - shift) // + n / (int)Math.pow(10, shift); // count++; // System.out.print(n + ""->"" + m + "", ""); // // } // System.out.println(); // } // } int digits = String.valueOf(A).length(); for(int i = A; i < B; i++) { //Set chars = new HashSet(); //for (char c : String.valueOf(i).toCharArray()) chars.add(c); //if (chars.size() != digits) continue; Set olds = new HashSet(); for (int shift = 1; shift < digits; shift++) { int n = i; int m = n % (int)Math.pow(10, shift) * (int)Math.pow(10, digits - shift) + n / (int)Math.pow(10, shift); if (m < A || m > B || n >= m) continue; if (olds.contains(m)) continue; olds.add(m); count++; // if (t == 3) System.out.print(n + ""->"" + m + "", ""); } } String result = ""Case #"" + (t+1) + "": "" + count; writer.println(result); System.out.println(result); } reader.close(); writer.close(); } } " B11804,"package qual2012; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.Locale; import java.util.Set; import java.util.StringTokenizer; public class C { private static final String TASKNAME = ""input""; private void solve() throws IOException { int t = nextInt(); for (int i = 1; i <= t; i++) { int a = nextInt(); int b = nextInt(); int res = 0; for (int j = a; j < b; j++) { res += f(j, b); } println(""Case #"" + i + "": "" + res); } } private int f(int n, int b) { Set set = new HashSet(); int res = 0; int l = Integer.toString(n).length(); int p = 1; while (p <= n) { p *= 10; } p /= 10; int m = n; for (int i = 1; i < l; i++) { int x = m / 10 + (m % 10) * p; if (x > n && x <= b) { set.add(x); // res++; // System.err.println(n + "" "" + x); } m = x; } // return res; return set.size(); } private String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } private int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } private double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private void print(Object o) { writer.print(o); } private void println(Object o) { writer.println(o); } private void printf(String format, Object... o) { writer.printf(format, o); } public static void main(String[] args) { long time = System.currentTimeMillis(); Locale.setDefault(Locale.US); new C().run(); System.err.printf(""%.3f\n"", 1e-3 * (System.currentTimeMillis() - time)); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; private void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(System.out); reader = new BufferedReader(new FileReader(TASKNAME + "".in"")); writer = new PrintWriter(TASKNAME + "".out""); solve(); reader.close(); writer.close(); } catch (IOException e) { e.printStackTrace(); System.exit(13); } } }" B10456,"package Parser; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; public class MyWriter { Writer out; public MyWriter(String fileName) { // TODO Auto-generated constructor stub try { File file = new File(fileName); FileOutputStream fos; fos = new FileOutputStream(file); OutputStreamWriter osw = new OutputStreamWriter(fos); out = new BufferedWriter(osw); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void writeString(String text) { try { out.write(text + '\n'); } catch (IOException e) { } } public void close(){ try { out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B13090,"import java.io.File; import java.util.ArrayList; import java.util.Formatter; import java.util.List; import java.util.Scanner; public class recycled { static int A; static int B; static int count=0; static int n; private static Scanner x; private static Formatter y; static String newline = System.getProperty(""line.separator""); static List words = new ArrayList(); static int testCases; public static void main(String args[]){ // open input file try{ x= new Scanner(new File(""C-small-attempt0.in"")); }catch(Exception e){ System.out.println(""Could not find the file""); } while(x.hasNext()){ words.add(x.nextLine()); } testCases=Integer.parseInt(words.get(0)); words.remove(0); int cnt=0; // create output file try{ y= new Formatter(""recycled.ou""); //System.out.println(""sampleTongue.ou has been created""); }catch(Exception e){ System.out.println(""Could not create a file""); } //evaluate for(int k=0; kn && m<=B){ count++; System.out.println(n+"" ""+m); } //copying for(int j=0; j lines; private int numOfIntersections; public WiresCase(int order, int numberOfLines, IO io) { super(order, numberOfLines, io); } @Override public void initializeVars() { lines = new ArrayList(); } @Override public void addLine(String line) { String[] tmp = line.split("" ""); Short[] tmp2 = { Short.parseShort(tmp[0]), Short.parseShort(tmp[1]) }; this.lines.add(tmp2); } @Override public void printSolution() { System.err.println(""Case #"" + getOrder() + "": "" + numOfIntersections); } @Override public CaseSolver process() { Collections.sort(lines, new Comparator() { @Override public int compare(Short[] o1, Short[] o2) { return o1[0] - o2[0]; } }); //printList(); for (int i = 0; i < lines.size(); i++) { for (int j = i + 1; j < lines.size(); j++) { if (lines.get(i)[1] > lines.get(j)[1]) { numOfIntersections++; } } } return this; } private void printList() { for (Short[] a : lines) { System.err.println(Arrays.deepToString(a)); } } }" B12503,"package qualifier; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.HashMap; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class TC { public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); try { File file = new File(""src/qualifier/C-small-attempt0.in""); String a = file.getAbsolutePath(); in = new Scanner(file); out = new PrintWriter(new File(""src/qualifier/C-small-attempt0.out"")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } TC worker = new TC(); int n = in.nextInt(); for (int i=1; i<=n; i++) { out.println(""Case #"" + i + "": "" + worker.nums(in.nextInt(), in.nextInt(), out)); } out.flush(); } public int nums(int a,int b, PrintWriter out) { int sum = 0; int i = a; int order = 0; while (i>0) { i=i/10; order++; } for (i=a; i s = new HashSet(); for (int j=1; ji && tr<=b && !s.contains(tr)) { sum++; s.add(tr); } } } return sum; } } " B10478,"package qr; import java.io.File; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.Scanner; public class C { public static void main(String[] args) throws FileNotFoundException { Scanner scanner = new Scanner(new File(""C-small-attempt0.in"")); int tcn = scanner.nextInt(); int tc = 1; while (tc <= tcn) { int a = scanner.nextInt(); int b = scanner.nextInt(); int y = 0; // System.out.printf(""%d %d\n"", a, b); if (a > 9) { y = 0; for (int n = a; n < b; n++) { String ns = Integer.toString(n); // System.out.println(""ns="" + ns); int len = ns.length(); HashSet sss = new HashSet(); for (int i = 1; i < len; i++) { String ns1 = ns.substring(0, i); String ns2 = ns.substring(i, len); // System.out.printf(""ns1=%s ns2=%s\n"",ns1,ns2); if (ns2.charAt(0) == '0') continue; String ms = ns2 + ns1; // System.out.println(""ms=""+ms); int m = Integer.parseInt(ms); if (sss.contains(m)) continue; if (n < m && m <= b) { y++; sss.add(m); // System.out.printf(""%d <= %d < %d <= %d\n"", a, n, m, b); } } } } System.out.printf(""Case #%d: %d\n"", tc, y); tc++; } } } " B13072,"import java.util.*; import java.io.*; public class Recycler{ //Vector possibilities = new Vector(0,0); private static int[] slider; private static String numString; private static int rotCounter; private static int pairCount; private static String elements, toPrint; private static int testNum; private static Stack stack = new Stack(); public static void main(String args[]){ int testCounter = 1; System.out.println(""working .....""); try{ BufferedReader bf = new BufferedReader(new FileReader(args[0])); PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(""output.out"")), true); testNum = Integer.parseInt(bf.readLine()); while((elements=bf.readLine()) != null){ pairCount = 0; int end = Integer.parseInt(elements.split("" "")[1]); int start = Integer.parseInt(elements.split("" "")[0]); START : for (int i = start; i<=end;i++){ if(Integer.toString(i).length() < 2) continue; for(int j=i+1; j<=end; j++){ stackDigits(j); if(stack.search(i%10) == -1){ stack = new Stack(); continue; }else{ //System.out.println(i+"" ""+j+"" - ""+stack.search(i%10)); stack = new Stack(); } for(int a : rotations(j)){ if(a == i) pairCount++; //System.out.println(""We've got a pair heuston ""+i+"" ""+j); } } } toPrint = ""Case #""+testCounter+"": ""+pairCount; pw.println(toPrint); testCounter++; } }catch(Exception e){ e.printStackTrace(); } System.out.println(""Done!""); } private static void stackDigits(int num){ if(num/10 > 0) stackDigits(num/10); stack.push(num%10); } private static int[] rotations(int num){ //possibilities.clear(); numString = Integer.toString(num); rotCounter = 0; slider = new int[numString.length()]; numString = numString.charAt(numString.length()-1)+numString.substring(0, numString.length()-1); slider[rotCounter] = Integer.parseInt(numString); while(num != slider[rotCounter]){ rotCounter++; numString = numString.charAt(numString.length()-1)+numString.substring(0, numString.length()-1); slider[rotCounter] = Integer.parseInt(numString); } return slider; } }" B10922,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package utils; /** * * @author Fabien Renaud */ public interface JamParser { public JamCase getJamCase(int number); }" B11626,"import java.util.Scanner; public class Test { public static void main(String []args){ int numT=0; Scanner kb=new Scanner(System.in); numT = kb.nextInt(); int a[] = new int[numT]; int b[]=new int[numT]; for (int i = 0; i < numT; i++) { a[i] = kb.nextInt(); b[i]=kb.nextInt(); } for(int i=0;i=A&&sb!=i&&sb>i){ score++; } } } return score; } } " B11008,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.StringTokenizer; public class recycled { static String next() { if (st == null || !st.hasMoreTokens()) nextLine(); return st.nextToken(); } static int nextInt() { return Integer.parseInt(next()); } static void nextLine() { try { st = new StringTokenizer(f.readLine()); } catch (Exception e) { e.printStackTrace(); } } static StringTokenizer st; static PrintWriter out; static BufferedReader f; public static void main(String[] args) throws IOException { String progName = (recycled.class.getCanonicalName()) + "".out""; f = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); out = new PrintWriter(new BufferedWriter(new FileWriter(progName))); int T = nextInt(); for (int t = 1; t <= T; t++) { int count = 0; int A = nextInt(), B = nextInt(); for (int x = A; x <= B; x++) { HashSet hs = new HashSet(); String s = """" + x; for (int i = 1; i < s.length(); i++) { String ss = s.substring(i) + s.substring(0, i); if (ss.charAt(0) == '0') continue; int xx = Integer.parseInt(ss); if (xx >= A && xx <= B&&x curcase; } public Case nextCase() { if (!hasNext()) return null; curcase++; int a = sc.nextInt(); int b = sc.nextInt(); return new Case(curcase, a, b); } }" B11729,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package speaking; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.LinkedList; /** * * @author Marisol */ public class clsArchivo{ private LinkedList lista=new LinkedList(); public void clsArchivo(String src) { try { File file=new File(src); FileReader filereader = new FileReader(file); BufferedReader buffer = new BufferedReader(filereader); String linea=buffer.readLine(); lista.add(linea); while ((linea=buffer.readLine())!=null) { lista.add(linea); } } catch (Exception e) { System.out.println(""archivo incorrecto""); } } public LinkedList progra (){ String total = lista.get(0);//el primer elemento //Creamos un arreglo con los datos leidos LinkedList array = new LinkedList(); for (int i = 1; i < Integer.parseInt(total)+1; i++) { String linea=lista.get(i);//lectura de lineas String num[] = linea.split(""\\s+""); int res=0; int numero1 = Integer.parseInt(num[0]); int numero2 = Integer.parseInt(num[1]); for (int j = numero1; j < numero2; j++) { for (int k = j+1; k < numero2+1; k++) { String uno = """"+j; String dos = """"+k; String pal1=""""; if(uno.length() == dos.length()){ for (int l = 0; l < uno.length(); l++) { String pal2= """"+uno.charAt(l); if(dos.contains(pal1+pal2)==true){ pal1+=pal2; } else{ l=uno.length(); } } String pal4=""""; for (int l = pal1.length(); l < dos.length(); l++) { String pal3= """"+uno.charAt(l); if(dos.contains(pal4+pal3)==true){ pal4+=pal3; } else{ l=dos.length(); } } String res1 =pal4+pal1; if(dos.equals(res1)==true){ //System.out.println("" ""+ res1+ "" "" +dos); res++; } } } } System.out.println(""Case #""+ (i) +"": ""+res); array.add(res); } return array; } }" B12846,"package gcj2012.qr; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { public static int count(int a, int b) { int r = 0, len, m; String sn, sm; Set used = new HashSet(); for (int n = a; n < b; n++) { used.clear(); sn = Integer.toString(n); len = sn.length(); sn = sn + sn; for (int i = 1; i < len; i++) { if (sn.charAt(i) == '0') continue; sm = sn.substring(i, i + len); m = Integer.parseInt(sm); if ((m > n) && (m <= b) && !used.contains(m)) { r++; used.add(m); } } } return r; } public static void main(String[] args) throws NumberFormatException, IOException { if (args.length < 1 ) { System.out.println(""File name not given""); System.exit(1); } BufferedReader br = new BufferedReader(new FileReader(args[0])); int t = Integer.parseInt(br.readLine()); for (int i = 1; i <= t; i++) { String[] test = br.readLine().split("" ""); int a = Integer.parseInt(test[0]); int b = Integer.parseInt(test[1]); System.out.printf(""Case #%d: %d\n"", i, count(a, b)); } br.close(); } } " B11953,"package cs224n.gcj; import java.io.IOException; import java.util.HashSet; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.FileInputStream; import java.io.PrintWriter; import java.io.FileWriter; import java.io.File; public class ProbC { static int getNRecycledPair(int b, int B){ String s = new Integer(b).toString(); int nDigits = s.length(); String ls, rs; HashSet validPairs = new HashSet(); for(int i = 1; i < nDigits; i++){ ls = s.substring(0, i); rs = s.substring(i); int rotb = Integer.parseInt((rs+ls)); if(rotb > b && rotb <= B) validPairs.add(rotb); } return validPairs.size(); } static public int getTotRecycledPair(int A, int B){ int n = 0; for(int i = A; i <= B; i++){ n += getNRecycledPair(i, B); } return n; } static public void main(String[] args) throws IOException{ File inFile = new File(args[0]); File outFile = new File(args[1]); if(!inFile.exists()) System.out.println(""File Does Not Exist!""); BufferedReader in = new BufferedReader( new InputStreamReader( new FileInputStream(inFile) ) ); PrintWriter out = new PrintWriter( new FileWriter(args[1]), true ); String line; line = in.readLine(); int T = Integer.parseInt(line); for(int i = 1; i <= T; i++){ line = in.readLine(); String[] parts = line.split("" ""); int A = Integer.parseInt(parts[0]); int B = Integer.parseInt(parts[1]); out.print(""Case #""+i+"": ""); out.println( getTotRecycledPair(A,B) ); } in.close(); out.close(); } } " B10832,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; public class ProblemB { private static List digits100(int i) { List digits = new ArrayList(); while (i > 0) { digits.add(i % 10); i /= 10; } Collections.sort(digits); return digits; } private static List firstDigits1000(int i) { List digits = new ArrayList(); digits.add(i % 10); digits.add((i - (i % 10)) / 10); Collections.sort(digits); return digits; } private static List secondDigits1000(int i) { List digits = new ArrayList(); digits.add(i % 100); digits.add((i - (i % 100)) / 100); Collections.sort(digits); return digits; } public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new FileReader(""C-small-attempt0.in"")); PrintWriter out = new PrintWriter(new FileWriter(""output.txt"")); ArrayList> digitsList = new ArrayList>(); LinkedHashSet> digitsSet = new LinkedHashSet>(); int testCases = Integer.parseInt(br.readLine()); for (int i = 1; i <= testCases; i++) { out.print(""Case #""+i+"": ""); String[] str = br.readLine().split("" ""); int int1 = Integer.parseInt(str[0]); int int2 = Integer.parseInt(str[1]); for (int j = int1; j <= int2; j++) { if (j < 100) { digitsList.add(digits100(j)); digitsSet.add(digits100(j)); } else if (j < 1000) { if (firstDigits1000(j).get(1) > 9) { digitsList.add(firstDigits1000(j)); digitsSet.add(firstDigits1000(j)); } if (!firstDigits1000(j).equals(secondDigits1000(j)) && secondDigits1000(j).get(1) > 9) { digitsList.add(secondDigits1000(j)); digitsSet.add(secondDigits1000(j)); } } } out.println(digitsList.size() - digitsSet.size()); for (List li : digitsSet) { digitsList.remove(digitsList.indexOf(li)); } System.out.println(digitsList.toString()); System.out.println(digitsList.size()); // System.out.println(digitsSet.toString()); // System.out.println(firstDigits1000(100)); // System.out.println(secondDigits1000(100)); digitsSet.clear(); digitsList.clear(); } out.close(); } } " B11553,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Set; /** * * Google Code Jam 2012 Qualification Round - Problem C. Recycled Numbers * * @author matlock * */ public class RecycledNumbers { public static void main(String[] args) { RecycledNumbers g = new RecycledNumbers(); g.goGo(); } public void goGo() { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); try { int testCases = Integer.parseInt(in.readLine()); for (int i = 1; i <= testCases; i++) { String inputText = in.readLine(); String[] numberPair = inputText.split("" "", 2); int matches = runTestCase(Integer.valueOf(numberPair[0]), Integer.valueOf(numberPair[1])); System.out.println(""Case #"" + i + "": "" + matches); } } catch (IOException e) { System.out.println(""Exception: "" + e.getMessage()); } } public int runTestCase(int startVal, int endVal) { Set sourceSet = new HashSet(); Set discoveredSet = new HashSet(); int totalMatches = 0; // first store all the source numbers for (int j = startVal; j <= endVal; j++) { sourceSet.add(String.valueOf(j)); } for (int j = startVal; j <= endVal; j++) { StringBuffer buf = new StringBuffer(String.valueOf(j)); int len = buf.length() - 1; // don't need last rotation, so -1 // rotate the characters for (int k = 0; k < len; k++) { buf.append(buf.charAt(0)); buf.deleteCharAt(0); if (Integer.valueOf(buf.toString()) != j) { if (sourceSet.contains(buf.toString()) && !discoveredSet.contains(String.valueOf(j) + buf.toString())) { discoveredSet.add(String.valueOf(j) + buf.toString()); discoveredSet.add(buf.toString() + String.valueOf(j)); totalMatches++; sourceSet.remove(String.valueOf(j)); // remove from set } } } } return totalMatches; } } " B12209,"package hk.polyu.cslhu.codejam.solution.impl.qualificationround; import java.util.List; import hk.polyu.cslhu.codejam.solution.Solution; public class RecycledNumbers extends Solution { private int min, max; @Override public void setProblem(List problemDesc) { // TODO Auto-generated method stub String[] splitArray = problemDesc.get(0).split("" ""); this.min = Integer.valueOf(splitArray[0]); this.max = Integer.valueOf(splitArray[1]); } @Override public void solve() { // TODO Auto-generated method stub int numOfPairs = 0; for (int i = this.min; i < this.max; i++) { for (int j = i + 1; j <= this.max; j++) { if (this.isRecycledPair(i, j)) numOfPairs++; } } this.result = String.valueOf(numOfPairs); } private boolean isRecycledPair(int i, int j) { // TODO Auto-generated method stub if (i >= j) return false; String m = String.valueOf(j); String n = String.valueOf(i); for (int startIndex = 1; startIndex < n.length(); startIndex++) { String partToMove = n.substring(startIndex, n.length()); String newString = partToMove + n.substring(0, startIndex); if (newString.equals(m)) return true; } return false; } } " B11739,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Hashtable; public class C { ArrayList result=new ArrayList(); public void op(String A,String B) { Hashtable tet=new Hashtable(); long current_n; long current_m; int i_A=Integer.parseInt(A); long i_B=Integer.parseInt(B); long diff=i_B-i_A; long temp=i_A; String s; if(A.length()==1 && B.length()==1) { result.add(0+""""); return; } for(int i=0;i current_n && current_m >=i_A) { //System.out.println(current_n+"" ""+current_m); tet.put(current_n+""""+current_m, true); } } temp++; } //System.out.println(tet.size()); result.add(tet.size()+""""); } public void read_file() throws Exception { FileReader g = new FileReader(""C-small-attempt0.in""); BufferedReader br = new BufferedReader(g); int No_of_Cases = Integer.parseInt(br.readLine()); String s; String [] tete; for(int i=0;i */ package eu.positivew.codejam.framework; import java.io.BufferedReader; /** * CodeJam IO input interface. * * @author Üllar Soon */ public interface CodeJamInputParser { public CodeJamInputCase readCase(BufferedReader input); } " B10734,"import java.util.*; public class probC { public static int N=2000001, K=0 ; public static void main (String[] args) { Scanner scan = new Scanner (System.in) ; int A[] = new int[N]; boolean visited[] = new boolean [N]; for (int i=0 ; i set = new HashSet (); set.add(n); for (int off=0 ; off high){ int dif = playingWith-toMoveFront; j += dif; }else if(recycled > j){ count++; } } } } bw.write(""Case #"" + (c) + "": "" + count); System.err.println(""Case #"" + (c) + "": "" + count); bw.newLine(); } in.close(); bw.flush(); bw.close(); } } " B10773,"package RecycledNumbers; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class RecycledNumbers { public static int numCase = 0; public static int A = 0; public static int B = 0; public static void main(String[] args) throws NumberFormatException, IOException { process(); } public static void process() throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader( new FileInputStream(""RecycledNumbers.in""))); numCase = Integer.parseInt(br.readLine()); for (int i = 0; i < numCase; i++) { String str = br.readLine(); String[] arr = str.split("" ""); if (arr[0].length() == 1 && arr[1].length() == 1) { writeOut(i + 1, 0); continue; } A = Integer.valueOf(arr[0]); B = Integer.valueOf(arr[1]); if (B - A <= 5) { writeOut(i + 1, 0); continue; } process2(i + 1); } } public static void process2(int order) { //List lstB = new ArrayList(); int count = 0; for (int n = A; n < B; n++) { if (isAllZero(n)) { continue; } for (int m = n + 1; m <= B; m++) { if (!isAllZero(m) && isRecycledNumbers(n, m)) { count++; //lstB.add(m); } } } writeOut(order, count); } public static boolean isAllZero(int n) { int lengthN = String.valueOf(n).length(); int dec = 1; for (int i = 0; i < lengthN - 1; i++) { dec *= 10; } if (n % dec == 0) { return true; } return false; } public static boolean isRecycledNumbers(int n, int m) { String strN = String.valueOf(n); String strM = String.valueOf(m); int lengthStrN = strN.length(); for (int i = 1; i < lengthStrN; i++) { String prefix = strN.substring(lengthStrN - i, lengthStrN); if (!prefix.startsWith(""0"") && strM.startsWith(prefix)) { String t = prefix + strN.substring(0, lengthStrN - i); if (t.equals(strM)) { return true; } } } return false; } public static void writeOut(int order, int result) { System.out.format(""Case #%d: %d\n"", order, result); } } " B10391,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package gcj2012.qualification_round; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Scanner; /** * * @author langlv */ public class Dancing { private static int countDigit(int num) { Integer t = new Integer(num); int count = 0; while (t != 0) { t = t / 10; count++; } return count; } private static int recycledNumber(int num, int pos) { if (num < 10) { return 0; } if (pos > countDigit(num)) { return 0; } String n = String.valueOf(num); int res = Integer.parseInt(n.substring(pos) + n.substring(0, pos)); return res; } public static void main(String[] args) throws Exception { // Scanner sc = new Scanner(System.in); // PrintWriter pw = new PrintWriter(System.out); Scanner sc = new Scanner(new FileReader(""C:\\C-small-attempt0.in"")); PrintWriter pw = new PrintWriter(new FileWriter(""C:\\C-small-attempt0.out"")); try { int ntest = Integer.parseInt(sc.nextLine()); for (int test = 1; test <= ntest; ++test) { int A = sc.nextInt(); int B = sc.nextInt(); System.out.println(""--------------------------""); int res = 0; List num = new ArrayList(); for (int i = A; i <= B; i++) { for (int j = 1; j < countDigit(i); j++) { int rec = recycledNumber(i, j); if (A <= rec && rec <= B && i < rec) { num.add(rec); res++; System.out.println(res + "": "" + i + "","" + rec); } } } pw.print(""Case #"" + test + "": ""); pw.print(res); pw.println(); } } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); } finally { pw.close(); sc.close(); } } } " B12599,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.Writer; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class Main { public static void main(String arg[]) { try { FileInputStream fIn = new FileInputStream(""input.txt""); Charset cs = Charset.forName(""UTF-8""); InputStreamReader iRd = new InputStreamReader(fIn,cs); BufferedReader bRd = new BufferedReader(iRd); String str = bRd.readLine(); Integer line = Integer.parseInt(str); Writer output = null; File file = new File(""output.txt""); output = new BufferedWriter(new FileWriter(file)); for(int i = 0 ; i < line; ++i) { String inLine = bRd.readLine(); String[] nums = inLine.split("" ""); String start = nums[0]; String stop = nums[1]; int result = calculate(Integer.parseInt(start),Integer.parseInt(stop)); // System.out.println(""Case #"" + (i+1) + "": "" + result); output.write(""Case #"" + (i+1) + "": "" + result + ""\n""); } output.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static int calculate(Integer start, Integer stop) { int sum = 0; List ranges = separate(start,stop); for(int i = 0 ; i < ranges.size() ;) { Integer lowBound = ranges.get(i); Integer upBound = ranges.get(i+1); // System.out.println(ranges.get(i) + "" : "" + ranges.get(i+1)); sum += countCyclic(lowBound , upBound); i+=2; } return sum; } public static int countCyclic(Integer start,Integer stop) { int count = 0; int dec = start; boolean mark[] = new boolean[stop-start+1]; for(int i = start ; i < stop ; ++i) { if(!mark[i-dec]) { List shiftRes = shifting(i,start,stop); switch(shiftRes.size()) { case 2 : ++count;break; case 3 : count+=3;break; case 4 : count+=6;break; case 5 : count+=10;break; case 6 : count+=15;break; case 7 : count+=21;break; case 8 : count+=28;break; } for(int j = 0 ; j < shiftRes.size() ; ++j) { Integer num = shiftRes.get(j); mark[num-dec] = true; } } } return count; } public static List shifting(Integer seed ,Integer lowerBound, Integer upperBound) { List result = new ArrayList(); result.add(seed); String num = seed.toString(); int n = num.length()-1; for(int i = 0 ; i < n ; ++i) { num = num.substring(1) + num.charAt(0); Integer intNum = Integer.parseInt(num); if(num.charAt(0)!='0' && !result.contains(intNum) && intNum <= upperBound && intNum >= lowerBound) { result.add(intNum); } } return result; } public static List separate(Integer start, Integer stop) { List shift = null; if(stop.toString().length() > start.toString().length()) { int n = start.toString().length(); String wall = """"; while(wall.length() < n) { wall += 9; } Integer upBound = Integer.parseInt(wall); shift = separate(upBound+1,stop); shift.add(start); shift.add(upBound); } else { shift = new ArrayList(); shift.add(start); shift.add(stop); } return shift; } } " B10559,"package com.googlerese.file; import java.io.*; import java.util.Map; public class FileWrite { private static FileWrite fileWrite = new FileWrite(); private FileWrite() { } public static FileWrite getInstance() { return fileWrite; } public final void write( final String fileName, final Map output ) { FileWriter fstream = null; BufferedWriter out = null; try { // Create file fstream = new FileWriter( fileName ); out = new BufferedWriter( fstream ); int size = output.size(); for ( int i = 1; i <= size; i++ ) { final String outputStr = new StringBuffer( ""Case #"" ).append( i ).append( "": "" ).append( output.get( i ) ).toString(); out.write( outputStr ); if ( i != size ) { out.newLine(); } } } catch ( Exception e ) {//Catch exception if any System.err.println( ""Error: "" + e.getMessage() ); } finally { //Close the output stream try { if ( out != null ) { out.close(); } if ( fstream != null ) { fstream.close(); } } catch ( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } } } } " B11592,"package cj2012; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.HashSet; import java.util.Scanner; public class c { static PrintWriter pw; static int testOut = 1; /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { Scanner sc = new Scanner(new FileReader( ""C://CODEJAM//2012//C-small-0.in"")); pw = new PrintWriter(new FileWriter(""C://CODEJAM//2012//C-small-0.out"")); int ntest = sc.nextInt(); // sc.nextLine(); for (int test = 1; test <= ntest; ++test) { // sc.next(); int A = sc.nextInt(); int B = sc.nextInt(); int pairs = 0; for (int i = A; i <= B; i++) { // System.out.println(i); if (i > 9) { String is = """" + i; HashSet results = new HashSet(); for (int j = 1; j < is.length(); j++) { String changed = is.substring(is.length() - j, is.length()) + is.substring(0, is.length() - j); if (!results.contains(changed)) { int ci = Integer.parseInt(changed); if (ci > i && ci <= B) { //System.out.println(is + ""-"" + changed); pairs++; results.add(changed); } } } } } wc("""" + pairs); } pw.close(); sc.close(); System.out.println(""finished""); } // static int Digits(int number) { // int digits = 0; // int step = 1; // while (step <= number) { // digits++; // step *= 10; // } // if (digits == 0) // return 1; // else // return digits; // } private static void wc(String text) { String tt = ""Case #"" + testOut++ + "": "" + text; pw.print(tt); pw.println(); System.out.println(tt); } } " B10674,"import java.util.*; public class RecycledNumber { int digits; Collection set = new HashSet(); public int countInInterval(int a, int b) { int count = 0, rotation; String temp = """"+ a; this.digits = temp.length(); for(int i = a; ii&&!set.contains(i+"" ""+rotation)){ count++; set.add(i + "" "" + rotation); } } } return count; } private int rotate(int num, int distance) { String temp = """"+num; temp = temp.substring(distance)+temp.substring(0,distance); num = Integer.parseInt(temp); return num; } } " B10028,"import java.util.Scanner; class RecycledNumbers { Scanner s = new Scanner(System.in); public static void main(String args[]) { RecycledNumbers p = new RecycledNumbers(); p.run(); } void run() { int nCases = s.nextInt(); for (int i=0; i1) count+=(possibility *(possibility-1)) / 2; } return count; } int countPossibility(int v, int A, int B, int rotates, int level, boolean[] dids) { int count = 1; dids[v-A] = true; for (int i=0; iB) continue; if (dids[v-A]) continue; dids[v-A] = true; count++; } return count; } }" B12910,"package er.dream.codejam.helpers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.List; public class FileHandler { BufferedReader read; BufferedWriter write; public File[] listFiles(){ return new File(""data"").listFiles(); } public void loadFile(File file){ try { read = new BufferedReader(new FileReader(file)); write = new BufferedWriter(new FileWriter(new File(""output/""+file.getName().replace("".in"", "".out"")))); } catch (IOException e) { throw new IllegalStateException(""Couldn't load file: ""+file.getName(),e); } } public void closeConnection(){ try { read.close(); write.close(); } catch (IOException e) { throw new IllegalStateException(""Couldn't close connection"",e); } } public void writeOutput(List outputData){ int line = 1; for(String entry:outputData){ try { write.write(""Case #""+line+"": ""+entry+""\n""); } catch (IOException e) { throw new IllegalStateException(""Error while writing output"",e); } line++; } } public String readString(){ try { return read.readLine(); } catch (IOException e) { throw new IllegalStateException(""Error while reading input"",e); } } public int readInt(){ return Integer.parseInt(readString()); } public long readLong(){ return Long.parseLong(readString()); } public double readDouble(){ return Double.parseDouble(readString()); } public String[] readStringArray(){ return readString().split("" ""); } public int[] readIntArray(){ String[] strings = readStringArray(); int[] ints = new int[strings.length]; for(int i=0;i= m) { throw new IllegalArgumentException(""n >= m""); } String nStr = Integer.toString(n); String mStr = Integer.toString(m); return (mStr + mStr).contains(nStr); } } " B13013,"package gcj.gcj2012.qualif; import gcj.SolverBase; import java.io.BufferedReader; import java.io.PrintStream; import java.util.HashSet; import java.util.Set; public class ProblemC extends SolverBase { public ProblemC() { super(""Recycled Numbers""); } public static void main(String[] args) throws Exception { SolverBase problem = new ProblemC(); // problem.verbose = true; problem.solve(System.in, System.out); } @Override public void solveSingle(BufferedReader reader, PrintStream out) throws Exception { int[] AB = readSingleLineIntArray(reader); int A = AB[0]; int B = AB[1]; // How many digits? int d = (""""+A).length(); check(d == (""""+B).length()); int x = 0; Set done = new HashSet(); // Naive implementation 1 : full loop for(int i=A;i list = new ArrayList(); int count = 0; for(int j= 1;j list = new Vector(); N=Integer.toString(i); //M=N.substring(1)+N.charAt(0); for(int k=0;k listOfCases; public TaskC() { stdin = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } public void solve() throws IOException { Integer[] in = readInt(1); n = in[0]; nn = new Integer[n]; mm = new Integer[n]; array = new Boolean[1000001]; listOfCases = new ArrayList(); Arrays.fill(array, true); for (int i = 0; i < n; i++) { nm = readInt(2); nn[i] = nm[0]; mm[i] = nm[1]; } for (int i = 0; i < n; i++) { iii = 0; for (int j = nn[i]; j <= mm[i]; j++) { str = String.valueOf(j); for (int k = 1; k < str.length(); k++) { StringBuffer sb = new StringBuffer(); sb.append(str.substring(k, str.length())); sb.append(str.substring(0, k)); if (!sb.toString().startsWith(""0"")) { t = Integer.parseInt(sb.toString()); if (array[t] && (j < t && t <= mm[i])) { array[t] = false; iii++; } } } Arrays.fill(array, true); } out.println(""Case #"" + (i + 1) + "": "" + iii); } out.flush(); } public Integer[] readInt(int size) throws IOException { Integer[] result = new Integer[size]; String[] params = stdin.readLine().split("" ""); for (int i = 0; i < size; i++) { result[i] = Integer.parseInt(params[i]); } return result; } public static void main(String[] args) throws IOException { TaskC obj = new TaskC(); obj.solve(); obj.stdin.close(); obj.out.close(); } } " B10600,"import java.io.*; import java.util.*; class recycled { public static void main(String[] args) throws Exception { BufferedReader r=new BufferedReader(new InputStreamReader(System.in)); String inp; int i,j; int T=Integer.valueOf(r.readLine()); for(int a=0;a stv = new HashSet(); for(i=A;i<=B;i++) { String s = """"+i; for(j=1;ji && k<=B && !stv.contains(str)) { y++; stv.add(str); } } } System.out.println(""Case #""+(a+1)+"": ""+y); } } } " B10969,"package gcj2012; import java.io.File; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.Scanner; public class C { static String BASEPATH = ""x:\\gcj\\""; static boolean LARGE = false; static String INPATH = BASEPATH + C.class.getSimpleName().charAt(0) + (LARGE ? ""-large.in"" : ""-small-attempt0.in""); static String OUTPATH = INPATH.substring(0, INPATH.length()-3) + new SimpleDateFormat(""-HHmmss"").format(new Date()) + "".out""; static String INPUT = """"; public void call() { int A = ni(), B = ni(); int L = Integer.toString(A).length(); int d = 1; for(int i = 0;i < L;i++)d *= 10; int ct = 0; int[] q = new int[L]; for(int i = A;i <= B;i++){ int p = 0; inner: for(int j = 10;j <= A;j*=10){ int k = i%j*(d/j)+i/j; if(i < k && k <= B){ for(int m = 0;m < p;m++){ if(q[m] == k)continue inner; } q[p++] = k; } } ct += p; } out.println(ct); } Scanner in; PrintWriter out; int cas; public C(int cas, Scanner in, PrintWriter out) { this.cas = cas; this.in = in; this.out = out; } int ni() { return Integer.parseInt(in.next()); } long nl() { return Long.parseLong(in.next()); } double nd() { return Double.parseDouble(in.next()); } void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); } public static void main(String[] args) throws Exception { long start = System.currentTimeMillis(); boolean real = INPUT.isEmpty(); if(real){ System.out.println(""INPATH : "" + INPATH); System.out.println(""OUTPATH : "" + OUTPATH); } Scanner in = real ? new Scanner(new File(INPATH)) : new Scanner(INPUT); PrintWriter out = real ? new PrintWriter(new File(OUTPATH)) : new PrintWriter(System.out); int n = in.nextInt(); in.nextLine(); for(int i = 0;i < n;i++){ out.printf(""Case #%d: "", i+1); new C(i+1, in, out).call(); out.flush(); if(real)System.err.println(""case "" + (i + 1) + "" solved.\t""); } long end = System.currentTimeMillis(); System.out.println((end - start) + ""ms""); if(real){ System.out.println(""INPATH : "" + INPATH); System.out.println(""OUTPATH : "" + OUTPATH); } } } " B12161,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.Vector; public class problemC { Vector lines = new Vector(); public static void main(String[] arg) { problemC pc = new problemC(); pc.lines = pc.readfile(""C:\\eclipse\\Ashish\\files\\C-small-attempt0.in""); int nooftestcases = Integer.parseInt(pc.lines.elementAt(0)); System.out.println(nooftestcases); Vector outlines = new Vector(); //int j=1; for (int i=1; i<=nooftestcases; i++) { String[] s = pc.lines.elementAt(i).split("" ""); //int a = Integer.parseInt(s[0]); //int b = Integer.parseInt(s[1]); int k = pc.solveit(s[0], s[1]); String ol = ""Case #"" + i + "": "" + k; outlines.add(ol); System.out.println(s[0] + "" "" + s[1] + "":"" + k); } pc.writefile(""C:\\eclipse\\Ashish\\files\\otestc.txt"", outlines); } public int solveit(String fa, String fb) { int howmany =0; int len = fa.length(); int ia=Integer.parseInt(fa); int ib=Integer.parseInt(fb); for (int cand=ia; cand<=ib; cand++) { String a = String.valueOf(cand); Vector ms = new Vector(); System.out.println(a); String fno = a.substring(0, 1); //System.out.println(fno); int ifno = Integer.parseInt(fno); for (int i=1; iifno && isno !=0) { String rno = a.substring(i); String afno = a.substring(0, i); String nno = rno + afno; int inno = Integer.parseInt(nno); if (inno>cand && inno <= ib && ms.indexOf(nno) == -1) { ms.add(nno); howmany++; //System.out.println("" :"" + nno); } else { //System.out.println(""Rejected :"" + nno); } } else if (isno==ifno && isno !=0) { String rno = a.substring(i); String afno = a.substring(0, i); String nno = rno + afno; int inno = Integer.parseInt(nno); if (inno>cand && inno <= ib && ms.indexOf(nno) == -1) { ms.add(nno); howmany++; String srno = a.substring(i); String safno = a.substring(0, i); String snno = rno + afno; //System.out.println("" :"" + snno); } } } } return howmany; } public void writefile(String name, Vector l) { try{ // Create file FileWriter fstream = new FileWriter(name); BufferedWriter out = new BufferedWriter(fstream); for (int i=0; i readfile(String fp) { Vector lines = new Vector(); try { FileReader fr = new FileReader(fp); BufferedReader br = new BufferedReader(fr); String s; while((s = br.readLine()) != null) { //System.out.println(s); lines.addElement(s); } fr.close(); } catch (Exception e) { System.out.println(e); } return lines; } } " B11073,"package fixjava; import java.util.ArrayList; /** * String splitter, this fixes the problem that String.split() has of losing the last token if it's empty. It also uses * CharSequences rather than allocating new String objects. */ public class Split { /** * String splitter, this fixes the problem that String.split() has of losing the last token if it's empty. It also uses * CharSequences rather than allocating new String objects. */ public static ArrayList splitAsList(String str, String sep) { int strLen = str.length(); int sepLen = sep.length(); assert sepLen > 0; ArrayList parts = new ArrayList(); for (int curr = 0; curr <= strLen;) { // Look for next token int next = str.indexOf(sep, curr); // Read to end if none if (next < 0) next = strLen; // Add next token parts.add(str.subSequence(curr, next)); // Move to end of separator, or past end of string if we're at the end // (by stopping when curr <= strLen rather than when curr < strLen, // we avoid the problem inherent in the Java standard libraries of // dropping the last field if it's empty; fortunately // str.indexOf(sep, curr) still works when curr == str.length() // without throwing an index out of range exception). curr = next + sepLen; } return parts; } public static CharSequence[] splitAsArray(String str, String sep) { ArrayList list = splitAsList(str, sep); CharSequence[] arr = new CharSequence[list.size()]; list.toArray(arr); return arr; } public static ArrayList splitAsListOfString(String str, String sep) { ArrayList list = splitAsList(str, sep); ArrayList listOfString = new ArrayList(list.size()); for (CharSequence cs : list) listOfString.add(cs.toString()); return listOfString; } /** For compatibility only, slower because it creates new String objects for each CharSequence */ public static String[] split(String str, String sep) { ArrayList list = splitAsList(str, sep); String[] arr = new String[list.size()]; for (int i = 0; i < list.size(); i++) arr[i] = list.get(i).toString(); return arr; } // public static void main(String[] args) { // System.out.println(splitAsList("""", ""\t"")); // System.out.println(splitAsList(""\t"", ""\t"")); // System.out.println(splitAsList(""a\t"", ""\t"")); // System.out.println(splitAsList(""\ta"", ""\t"")); // System.out.println(splitAsList(""\ta\t"", ""\t"")); // System.out.println(splitAsList(""a\tb"", ""\t"")); // System.out.println(splitAsList(""a\tb\t"", ""\t"")); // System.out.println(splitAsList(""\ta\tb"", ""\t"")); // System.out.println(splitAsList("""", ""SEP"")); // System.out.println(splitAsList(""SEP"", ""SEP"")); // System.out.println(splitAsList(""aSEP"", ""SEP"")); // System.out.println(splitAsList(""SEPaSEPb"", ""SEP"")); // System.out.println(splitAsList(""aSEPbSEP"", ""SEP"")); // } } " B11266,"import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class c { public static void main(String[] args){ Scanner in = new Scanner(System.in); int numOfLines = new Integer(in.nextLine()); for (int i= 1; i<=numOfLines; i++) { int res =0; String [] lineValues = in.nextLine().split("" ""); int n = new Integer(lineValues[0]); int m = new Integer(lineValues[1]); for (Integer j = n; j parellesBones = new ArrayList(); for (int k = nS.length();k>=1;k--) { String endPart=nS.substring(k); String beginPart=nS.substring(0,k); Integer recycled = new Integer(endPart+beginPart); if (recycled >m) continue; if (recycled j) { parellesBones.add(recycled); res++; } } } System.out.format(""Case #%d: %d\n"", i, res); } return; } }" B10226,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.InputStream; import java.io.InputStreamReader; public class RecycledNumbers { public static void main(String[] args) { try { run(); } catch (Exception e) { e.printStackTrace(); } } private static void run() throws Exception { writeResult(calc(readInputData())); } private static int[] calc(Data[] data) { int[] res = new int[data.length]; for (int i = 0; i < data.length; i++) { res[i] = calc(data[i]); // System.out.println(""Case #"" + (i + 1) + "": "" + res[i]); } return res; } private static int calc(Data data) { if (data.len <= 1) return 0; int res = 0; for (int i = data.a; i < data.b; i++) { int pp = (int)Math.pow(10, data.len - 1); for (int j = 1, p = 10; j < data.len; j++, p *= 10, pp /= 10) { int x = i % p; int y = i / p; int rev = x * pp + y; if (x == y) break; if (rev > i && rev >= data.a && rev <= data.b) res++; } } return res; } private static Data[] readInputData() throws Exception { InputStream in = RecycledNumbers.class.getResourceAsStream(""/test.in""); BufferedReader br = new BufferedReader(new InputStreamReader(in)); int total = Integer.parseInt(br.readLine()); Data[] data = new Data[total]; for (int i = 0; i < total; i++) data[i] = new Data(br.readLine().split(""\\s"")); in.close(); return data; } private static void writeResult(int[] res) throws Exception { BufferedWriter out = new BufferedWriter(new FileWriter(""d:\\!!!\\test.out"")); for (int i = 1; i <= res.length; i++) out.write(""Case #"" + i + "": "" + res[i - 1] + ""\n""); out.close(); } } class Data { final int len; final int a; final int b; Data(int a, int b) { this.a = a; this.b = b; this.len = 0; } Data(String[] str) { this.a = Integer.parseInt(str[0]); this.b = Integer.parseInt(str[1]); this.len = str[0].length(); } @Override public String toString() { return ""["" + a + "";"" + b + ""]""; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Math.min(a, b); result = prime * result + Math.max(a, b); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Data other = (Data)obj; if (a != other.a) return false; if (b != other.b) return false; return true; } } " B13184,"import java.util.Scanner; import java.io.*; import java.lang.*; class recycle { static int attempts; public static void main(String args[]) throws IOException { int a[]=new int[50],b[]=new int[50],x; recycle obj=new recycle(); int i,m,n,result[]=new int[50]; Scanner cin=new Scanner(System.in); int k=cin.nextInt(); for(i=0;i3) return 0; if(temp1.equals(temp2)) return 1; else { char [] bArray=temp2.toCharArray(); int l=2,temp; temp=bArray[l]; while(l>0) {bArray[l]=bArray[l-1];l--;} bArray[0]=(char )temp; String str = new String(bArray); return three(temp1,str); } } public int four(String temp1, String temp2) { attempts++; if(attempts>4) return 0; if(temp1.equals(temp2)) return 1; else { char [] bArray=temp2.toCharArray(); int l=3,temp; temp=bArray[l]; while(l>0) {bArray[l]=bArray[l-1];l--;} bArray[0]=(char)temp; String str = new String(bArray); return four(temp1,str); } } }" B11487,"import java.io.File; import java.util.HashSet; import java.util.Scanner; public class recyle { public static int solve(String s) { String[] input = s.split("" ""); String a = input[0]; String b = input[1]; if (a.length() != b.length()) return 0; if (Integer.parseInt(b) <= 10) return 0; int rotats = a.length(); int largest = Integer.parseInt(b); int count = 0; HashSet done = new HashSet(); for (int i = Integer.parseInt(a); i <= largest; i++) { for (int j = 1; j < rotats; j++) { String n = String.valueOf(i); String x = n.substring(0, rotats - j); String y = n.substring(rotats - j); if (y.charAt(0) == '0') continue; // No zero startings int nn = (int) (Integer.parseInt(y) * Math.pow(10, rotats - j) + Integer.parseInt(x)); if (nn == i || i >= nn || nn > largest) continue; //sb.append(n); sb.append(String.valueOf(nn)); int key = nn << 8 | i; if (!done.contains(key)) { done.add(key); count++; } } } return count; } public static void main(String[] args) { Scanner scanner = null; try { //scanner = new Scanner(System.in); scanner = new Scanner(new File(""A-small-attempt0.in"")); }catch (Exception e){ System.out.println(e.getMessage()); } String c = scanner.nextLine(); int i = 1; while (scanner.hasNextLine()) { String input = scanner.nextLine(); System.out.println(""Case #"" + i + "": "" + solve(input)); i++; } } } " B11396,"/** * KSpokas: GCJ 2012 Qualification Round Problem C - Recycled Numbers */ import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Set; public class qualProblemC { private final static int EXPECTED_ARG_COUNT = 1; public static void main(String[] args) { if (args.length != EXPECTED_ARG_COUNT) { System.err.println(""Error: expecting "" + EXPECTED_ARG_COUNT); return; } String fileName = args[0]; try { FileInputStream fstream = new FileInputStream(fileName); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); BufferedWriter out = new BufferedWriter(new FileWriter(fileName + "".out"")); Integer testCaseCount = Integer.parseInt(br.readLine()); for (int i = 0; i < testCaseCount; i++) { String strLine = br.readLine(); StringBuilder sb = new StringBuilder(""Case #""); sb.append(i + 1).append("": ""); sb.append(calculate(strLine)); out.write(sb.toString()); out.newLine(); } in.close(); out.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } private static int calculate(String input) { String[] values = input.split("" ""); Integer min = Integer.parseInt(values[0]); Integer max = Integer.parseInt(values[1]); Set duplicates = new HashSet(); for (int i = min; i <= max; i++) { String num = String.valueOf(i); for (int j = 1; j < num.length(); j++) { Integer offset = Integer.parseInt(num.substring(j) + num.substring(0, j)); if (offset != i && offset <= max && offset >= min) { duplicates.add( (i < offset) ? num.toString() + "":"" + offset.toString() : offset.toString() + "":"" + num.toString()); } } } return duplicates.size(); } } " B11129,"package com.codegem.zaidansari; import java.util.ArrayList; import java.util.List; class Score { int score1, score2, score3; int bestScore; boolean isSurprising; public Score(int score1, int score2, int score3) { super(); this.score1 = score1; this.score2 = score2; this.score3 = score3; this.bestScore = Math.max(Math.max(score1, score2), score3); this.isSurprising = (Math.abs(score1 - score2) == 2) || (Math.abs(score1 - score3) == 2) || (Math.abs(score2 - score3) == 2); } public int getScore1() { return score1; } public void setScore1(int score1) { this.score1 = score1; } public int getScore2() { return score2; } public void setScore2(int score2) { this.score2 = score2; } public int getScore3() { return score3; } public void setScore3(int score3) { this.score3 = score3; } public int getBestScore() { return bestScore; } public void setBestScore(int bestScore) { this.bestScore = bestScore; } public boolean isSurprising() { return isSurprising; } public void setSurprising(boolean isSurprising) { this.isSurprising = isSurprising; } public static List getPossibleScoreCombinations(int totalScore) { List possibleScores = new ArrayList(); if (totalScore == 0) { possibleScores.add(new Score(0, 0, 0)); possibleScores.add(new Score(0, 0, 0)); return possibleScores; } int mean = totalScore / 3; int remainder = totalScore % 3; switch (remainder) { case 0: possibleScores.add(new Score(mean, mean, mean)); possibleScores.add(new Score(mean, mean - 1, mean + 1)); break; case 1: possibleScores.add(new Score(mean, mean, mean + 1)); possibleScores.add(new Score(mean - 1, mean + 1, mean + 1)); break; case 2: possibleScores.add(new Score(mean, mean, mean + 2)); possibleScores.add(new Score(mean, mean + 1, mean + 1)); break; } return possibleScores; } } public class ProblemB { private int noofGooglers; private int surprisingCount; public static int bestResult; // private List googlers = new ArrayList(); private BTree tree; public static List leafLevelNodes = new ArrayList(); public ProblemB(int noofGooglers, int surprisingCount, int bestResult, int[] totalScores) { super(); ProblemB.bestResult = bestResult; Node rootNode = new Node(new Score(0, 0, 0), totalScores, 0, 0); tree = new BTree(rootNode); this.noofGooglers = noofGooglers; this.surprisingCount = surprisingCount; // int[] childNodeScores = new int[totalScores.length - 1]; // for (int index = 1; index < totalScores.length; index++) { // childNodeScores[index - 1] = totalScores[index]; // } // List scores = Score.getPossibleScoreCombinations(totalScores[0]); // tree.getRootNode().setLeftNode(new Node(scores.get(0), childNodeScores, 0, 0)); // tree.getRootNode().setRightNode(new Node(scores.get(1), childNodeScores, 0, 0)); } public static void main(String[] args) { String inputLine = ""6 2 8 29 20 8 18 18 21""; String[] inputValues = inputLine.split("" ""); int noofGooglers = Integer.parseInt(inputValues[0]); int surprisingCount = Integer.parseInt(inputValues[1]); int bestResult = Integer.parseInt(inputValues[2]); int[] totalScores = new int[noofGooglers]; for (int index = 0; index < noofGooglers; index++) { totalScores[index] = Integer.parseInt(inputValues[3 + index]); } ProblemB problemB = new ProblemB(noofGooglers, surprisingCount, bestResult, totalScores); int result = -1; for (Node node : ProblemB.leafLevelNodes) { if (node.getParentNodesSuprisingCount() == surprisingCount) { result = Math.max(result, node.getParentBestMatchCount()); } } System.out.println(result); } } class BTree { private Node rootNode; public BTree(Node rootNode) { super(); this.rootNode = rootNode; } public Node getRootNode() { return rootNode; } public void setRootNode(Node rootNode) { this.rootNode = rootNode; } } class Node { private int parentNodesSuprisingCount; private int parentBestMatchCount; private Score score; private Node leftNode; private Node rightNode; public Node(Score score, int[] scores, int parentNodesSuprisingCount, int parentBestMatchCount) { this.parentNodesSuprisingCount = parentNodesSuprisingCount; this.parentBestMatchCount = parentBestMatchCount; this.score = score; int[] childNodeScores = null; if (scores != null && scores.length > 0) { childNodeScores = new int[scores.length - 1]; for (int index = 1; index < scores.length; index++) { childNodeScores[index - 1] = scores[index]; } } List scoresList = null; if (scores != null && scores.length > 0) scoresList = Score.getPossibleScoreCombinations(scores[0]); if (score != null) { this.setLeftNode(new Node((scoresList != null ? scoresList.get(0) : null), childNodeScores, parentNodesSuprisingCount + (scoresList != null && scoresList.get(0) != null && scoresList.get(0).isSurprising ? 1 : 0), parentBestMatchCount + (scoresList != null && scoresList.get(0) != null && scoresList.get(0).getBestScore() >= ProblemB.bestResult ? 1 : 0))); this.setRightNode(new Node((scoresList != null ? scoresList.get(1) : null), childNodeScores, parentNodesSuprisingCount + (scoresList != null && scoresList.get(1) != null && scoresList.get(1).isSurprising ? 1 : 0), parentBestMatchCount + (scoresList != null && scoresList.get(1) != null && scoresList.get(1).getBestScore() >= ProblemB.bestResult ? 1 : 0))); if (childNodeScores != null && childNodeScores.length == 0) { ProblemB.leafLevelNodes.add(this.leftNode); ProblemB.leafLevelNodes.add(this.rightNode); } } } public int getParentNodesSuprisingCount() { return parentNodesSuprisingCount; } public void setParentNodesSuprisingCount(int parentNodesSuprisingCount) { this.parentNodesSuprisingCount = parentNodesSuprisingCount; } public int getParentBestMatchCount() { return parentBestMatchCount; } public void setParentBestMatchCount(int parentBestMatchCount) { this.parentBestMatchCount = parentBestMatchCount; } public Score getScore() { return score; } public void setScore(Score score) { this.score = score; } public Node getLeftNode() { return leftNode; } public void setLeftNode(Node leftNode) { this.leftNode = leftNode; } public Node getRightNode() { return rightNode; } public void setRightNode(Node rightNode) { this.rightNode = rightNode; } } " B10532,"/** * */ package hu.herba.codejam.cj2012.qualification; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import hu.herba.codejam.AbstractCodeJamBase; /** * Recycled Numbers * * @author csorbazoli */ public class ProblemC extends AbstractCodeJamBase { public static void main(String[] args) { new ProblemC(args); } int T; // number of test case public ProblemC(String[] args) { super(args, AbstractCodeJamBase.READER_TYPE); } private boolean contains(String[] pairs, int found, String num) { boolean ret = false; for (int i = 0; i < found; i++) { if (num.equals(pairs[i])) { // * TEST */System.out.println("" Pair already found before: "" + // num); ret = true; break; } } return ret; } private int countRecycled(int A, int B) { int result = 0, len; String strA = Integer.toString(A); String strB = Integer.toString(B); String orig, numbers, num; len = Integer.toString(A).length(); String[] pairs = new String[len]; int found; if (len > 1) { for (int i = A; i <= B; i++) { orig = Integer.toString(i); numbers = orig + orig; found = 0; for (int j = 1; j <= len; j++) { num = numbers.substring(j, j + len); // each pair was counted twice // if (!num.equals(orig) && (num.compareTo(strA) >= 0) // && // (num.compareTo(strB) <= 0)) { if ((num.compareTo(orig) > 0) && (num.compareTo(strA) >= 0) && (num.compareTo(strB) <= 0) && !this.contains(pairs, found, num)) { // *TEST*/ System.out.println("" "" + orig + // "" recycled with "" + // num); pairs[found++] = num; result++; } } } } // *TEST*/System.out.println("" result: "" + result); return result; } /* * (non-Javadoc) * * @see hu.herba.codejam.AbstractCodeJamBase#process(java.io.BufferedReader, * java.io.PrintWriter) */ @Override protected void process(BufferedReader reader, PrintWriter pw) throws IOException, IllegalArgumentException { // The first line of the input gives the number of test cases, T. T test // cases follow, one per line. // Each test case consists of a single line containing the integers A // and B. this.T = this.readInt(reader, ""Number of cases""); int[] items; for (int i = 1; i <= this.T; i++) { items = this.readIntArray(reader, ""testCase""); if (items.length == 2) { if (Integer.toString(items[0]).length() != Integer.toString(items[1]).length()) { System.out.println(""Test case "" + i + "" INVALID: A and B has different length - "" + Arrays.toString(items)); } // * TEST */System.out.println(""Case #"" + i + "": input = "" + // Arrays.toString(items)); // For each test case, output one line containing ""Case #x: y"", // where x is the case number (starting from 1), and y is the // number of recycled pairs (n, m) with A ≤ n < m ≤ B. pw.println(""Case #"" + i + "": "" + this.countRecycled(items[0], items[1])); } else { System.out.println(""Test case "" + i + "" INVALID: test case should contain 2 integers A, B with same length"" + Arrays.toString(items)); } } } } " B11491," import java.io.*; import java.util.Scanner; public class Recycling { public static void main(String[] args) throws FileNotFoundException, IOException { FileInputStream file = new FileInputStream(""C:\\Users\\Taghi\\Downloads\\C-small-attempt1.in""); DataInputStream in2 = new DataInputStream(file); Scanner in=new Scanner(new InputStreamReader(in2)); int numberOfTests=in.nextInt(); int[] results=new int[numberOfTests]; for (int i=0;ij && n>left && n<=right) { numPairs++; } } } out.println(""Case #""+(k+1)+"": ""+numPairs); } out.close(); } } " B11006,"package contests.GoogleCodejam.GCJ2012.qualification; import contests.GoogleCodeJam.practice.GCJ2010.qualification.ProblemA; import java.io.FileNotFoundException; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * Created with IntelliJ IDEA. * User: vassili * Date: 4/14/12 * Time: 1:12 PM * */ public class ProblemC { public static void main(String args[]) throws FileNotFoundException { Scanner scanner = new Scanner(ProblemC.class.getResourceAsStream(""c_small.in"")); int tests = scanner.nextInt(); for (int test = 1; test <= tests; test++) { int A = scanner.nextInt(); int B = scanner.nextInt(); int result = 0; for(int i = A; i <= B; i++){ String num1 = """"+i; int len1 = num1.length(); for(int j = i + 1; j<=B; j++){ String num2 = """" + j; if(len1 != num2.length()){ break; } for(int k = 0; k < num2.length(); k++){ num2 = num2.charAt(len1-1) + num2.substring(0, len1-1); if(num2.equals(num1)){ result+=1; break; } } } } System.out.println(""Case #"" + test + "": "" + result); } } } " B11182,"import java.io.*; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { try { FileInputStream fstream = new FileInputStream(""CProblem/C-small-attempt2.in""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter fwstream = new FileWriter(""CProblem/Cout.txt""); BufferedWriter out = new BufferedWriter(fwstream); String strLine = br.readLine(); int n = 0; int A, B; RecycledNumbers recycledNumbers = new RecycledNumbers(); if (strLine != null) { n = Integer.parseInt(strLine); System.out.println(n); } // Read File Line By LIN for (int i = 0; i < n; i++) { if ((strLine = br.readLine()) != null) { String[] numbers = strLine.split("" ""); A = Integer.parseInt(numbers[0]); B = Integer.parseInt(numbers[1]); int count = recycledNumbers.calculate(A, B); out.write(""Case #""+(i+1)+"": ""+count+'\n'); } } // Close the input stream in.close(); out.close(); } catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } private int calculate(int A, int B) { int count = 0; int n,m; for (int i = A; i <= B; i++) { String num1 = String.valueOf(i); //String num2 = String.valueOf(B); String str=""""; n = Integer.parseInt(num1); if (num1.length() == 1) { return 0; } switch (num1.length()) { case 4: str = num1.charAt(num1.length() - 1) + num1.substring(0, 3); m = Integer.parseInt(str); count = check(count, A, n, m, B); str = num1.substring(2, 4) + num1.substring(0, 2); m = Integer.parseInt(str); count = check(count, A, n, m, B); str = num1.substring(1, 4) + num1.charAt(0); m = Integer.parseInt(str); count = check(count, A, n, m, B); break; case 3: str = num1.charAt(num1.length() - 1) + num1.substring(0, 2); m = Integer.parseInt(str); count = check(count, A, n, m, B); str = num1.substring(1, 3) + num1.charAt(0); m = Integer.parseInt(str); count = check(count, A, n, m, B); break; case 2: str = num1.charAt(num1.length() - 1) + num1.substring(0, 1); m = Integer.parseInt(str); count = check(count, A, n, m, B); break; default: break; } } return count; } public int check(int count, int A, int n, int m, int B) { if (A <= n && n < m && m <= B) { count++; } return count; } } " B10298,"package gcj; import java.io.BufferedReader; import java.io.FileReader; public class Gcj { private static final String path = ""/home/me/dev/gcj/""; private BufferedReader br = null; private String[] tokens; private int itoken,ntokens; static public void err(String e) { System.out.println(""\n**\n""+e+"" :-)\n""); System.exit(1); } public Gcj(String filename) { try { br = new BufferedReader(new FileReader(path + filename)); } catch (Exception e) { e.printStackTrace(); } } public String rawLine() { String line = null; try { line = br.readLine(); } catch (Exception e) { e.printStackTrace(); } return line; } public String[] readLine() { String line = rawLine(); if (line == null) { tokens = null; ntokens = 0; } else { tokens = line.trim().split(""\\s+""); ntokens = tokens.length; } itoken = 0; return tokens; } private String nextToken() { String err = null; if (ntokens < 1) err = ""There is no token""; else if (itoken >= ntokens) err = ""No more token""; else { return tokens[itoken++]; } Gcj.err(err); return null; } public String sToken() { return nextToken(); } public String[] sBunch() { String[] l = new String[ntokens-itoken]; int i=0; while (itoken < ntokens) l[i++] = tokens[itoken++]; return l; } public char cToken() { return nextToken().charAt(0); } public char[] cBunch() { char[] l = new char[ntokens-itoken]; int i = 0; while (itoken < ntokens) l[i++] = tokens[itoken++].charAt(0); return l; } public int iToken() { return Integer.parseInt(nextToken()); } public int[] iBunch() { int[] l = new int[ntokens-itoken]; int i = 0; while (itoken < ntokens) l[i++] = Integer.parseInt(tokens[itoken++]); return l; } public long lToken() { return Long.parseLong(nextToken()); } public long[] lBunch() { long[] l = new long[ntokens-itoken]; int i = 0; while (itoken < ntokens) l[i++] = Long.parseLong(tokens[itoken++]); return l; } public double dToken() { return Double.parseDouble(nextToken()); } public double[] dBunch() { double[] l = new double[ntokens-itoken]; int i = 0; while (itoken < ntokens) l[i++] = Double.parseDouble(tokens[itoken++]); return l; } // -- utils // keep leading zeroes... public int[] breakdownNumber(String s) { int n = (s == null ? 0 : s.length()); int[] aa = new int[n]; if (n > 0) { char[] cc = s.toCharArray(); for (int i=0 ; i st = new HashSet(); int pair(int v) { if(st.contains(v)) { return 0; } int res = 0; String s = v + """"; for(int i = 0; i < s.length(); i++) { s = s.charAt(s.length() - 1) + s.substring(0, s.length() - 1); if(s.charAt(0) != '0') { final int x = Integer.parseInt(s); if(A <= x && x <= B && !st.contains(x)) { st.add(x); res++; } } } return res * (res - 1) / 2; } final int MAX = 2000000; boolean[] visited = new boolean[MAX * 10]; int dfs(int x, int d) { if(d == 0) { // System.err.println(x + "" "" + pair(x)); return pair(x); } if(st.contains(x)) { return 0; } pair(x); int res = 0; for(int i = 0; i <= 9; i++) { if(x != 0 || i != 0) { res += dfs(x * 10 + i, d - 1); } } return res; } void run() throws IOException { int T = IOFast.nextInt(); while(T-- != 0) { A = IOFast.nextInt(); B = IOFast.nextInt(); st.clear(); int res = 0; for(int i = A; i <= B; i++) { if(!st.contains(i)) { res += pair(i); } } printCase(); IOFast.out.println(res); IOFast.out.flush(); } } void run1() throws IOException { IOFast.setReader(new FileReader(dir + ""\\"" + inputFileName)); IOFast.setWriter(new FileWriter(dir + ""\\"" + outputFileName)); run(); } private static int CASE; private static void printCase() { IOFast.out.print(""Case #"" + ++CASE + "": ""); } public static void main(String[] args) throws IOException { start(); IOFast.out.flush(); IOFast.in.close(); IOFast.out.close(); } static public class IOFast { private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); private static PrintWriter out = new PrintWriter(System.out); // private static final int BUFFER_SIZE = 50 * 200000; private static final StringBuilder buf = new StringBuilder(); private static boolean[] isDigit = new boolean[256]; private static boolean[] isSpace = new boolean[256]; static { for(int i = 0; i < 10; i++) { isDigit['0' + i] = true; } isDigit['-'] = true; isSpace[' '] = isSpace['\r'] = isSpace['\n'] = isSpace['\t'] = true; } static boolean endInput; public static void setReader(Reader r) { in = new BufferedReader(r); } public static void setWriter(Writer w) { out = new PrintWriter(w); } private static int nextInt() throws IOException { boolean plus = false; int ret = 0; while(true) { final int c = in.read(); if(c == -1) { endInput = true; return Integer.MIN_VALUE; } if(isDigit[c]) { if(c != '-') { plus = true; ret = c - '0'; } break; } } while(true) { final int c = in.read(); if(c == -1 || !isDigit[c]) { break; } ret = ret * 10 + c - '0'; } return plus ? ret : -ret; } private static long nextLong() throws IOException { boolean plus = false; long ret = 0; while(true) { final int c = in.read(); if(c == -1) { endInput = true; return Integer.MIN_VALUE; } if(isDigit[c]) { if(c != '-') { plus = true; ret = c - '0'; } break; } } while(true) { final int c = in.read(); if(c == -1 || !isDigit[c]) { break; } ret = ret * 10 + c - '0'; } return plus ? ret : -ret; } private static String next() throws IOException { buf.setLength(0); while(true) { final int c = in.read(); if(c == -1) { endInput = true; return ""-1""; } if(!isSpace[c]) { buf.append((char)c); break; } } while(true) { final int c = in.read(); if(c == -1 || isSpace[c]) { break; } buf.append((char)c); } return buf.toString(); } private static double nextDouble() throws IOException { return Double.parseDouble(next()); } } } " B12772,"import java.io.*; import java.util.*; public class Tres { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(""tres.txt"")); int T = Integer.parseInt(in.readLine()); for(int t = 0; t < T; t++) { String[] temp = in.readLine().split("" ""); int A = Integer.parseInt(temp[0]); int B = Integer.parseInt(temp[1]); HashMap matches = new HashMap(); for(int i = A; i <= B; i++) { String s = new Integer(i).toString(); int j; for(j = 0; j < s.length(); j++) { String stemp = s.substring(j) + s.substring(0,j); if(matches.containsKey(stemp)) { matches.put(stemp, matches.get(stemp)+1); //System.out.println(s + "" matched with "" + stemp); break; } } if(j == s.length()) matches.put(s, 1); } int answer = 0; for(String s : matches.keySet()) { int itemp = matches.get(s); answer += itemp*(itemp-1)/2; } System.out.println(""Case #"" + (t+1) + "": "" + answer); } in.close(); } }" B12097,"import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.LinkedList; import java.util.Scanner; public class cycle { public static Scanner setFileIn(){ try{ Scanner input = new Scanner(new FileInputStream(new File (""test.txt""))); return input; }catch(Exception e){ return null; } } public static Scanner setSysIn(){ Scanner input = new Scanner(new BufferedInputStream(System.in)); return input; } public static int dancer(int n, int s, int p,Scanner input){ int ans = 0; int noSur = 3*p-2; int sur = 3*p-4; if (p==1){ noSur = 1; sur = 1; } if(p==0){ noSur = 0; sur = 0; } while(n>0){ int score = input.nextInt(); //System.out.print("" ""+ score+"" ""); if (score>=noSur){ ans++; }else{ if ((score >= sur)&&(s>0)){ s--; ans++; } } n--; } return ans; } public static int[] move(int i){ String s = """"+i; int[] ans = new int[s.length()-1]; int counter = 0; int temp = i; int weishu = 1; while(temp>9){ temp = temp/10; weishu = weishu*10; } temp = i; while(counteri)&&(pos[j]<=b)&&(test[pos[j]]==0)){ ans++; test[pos[j]]=1; // System.out.println("" ""+ans+"" ""+i+"" ""+pos[j]+"" ""); } } for(int j = 0;j set = new HashSet(); int nc = sc.nextInt(); for (int tc = 1; tc <= nc; tc++) { int a = sc.nextInt(); int b = sc.nextInt(); int len = Integer.toString(a).length(); char[] c = new char[len]; int res = 0; for (int i = a; i <= b; i++) { set.clear(); int t = i; for (int j = len - 1; j >= 0; j--) { c[j] = (char) (t % 10 + '0'); t /= 10; } for (int j = 0; j < len - 1; j++) { char tmp = c[len - 1]; for (int k = len - 1; k > 0; k--) { c[k] = c[k - 1]; } c[0] = tmp; int blah = Integer.valueOf(new String(c)); if (blah > i && blah <= b) set.add(blah); } res += set.size(); } pw.printf(""Case #%d: %d\n"", tc, res); } pw.close(); } public static void main(String[] args) throws IOException { new C().work(); } } " B10365,"package com.codejam.practice; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class RecycledNumbers { public static void main(String[] args) { File inputFile = new File(""C:/Users/SNALLAMA/Desktop/C-small-attempt0.in""); File outputFile = new File(""C:/Users/SNALLAMA/Desktop/C-small-attempt0.out""); String line = null; int t, a, b, noOfDigits, divider, localnumber; Set finalOP = new HashSet(); //Set to avoid duplicates try { BufferedReader bReader = new BufferedReader(new FileReader(inputFile)); BufferedWriter bWriter = new BufferedWriter(new FileWriter(outputFile)); try { t = Integer.parseInt(bReader.readLine().trim()); for(int index=0;index(); if(noOfDigits!=1){ for(int i=a;i<=b;i++){ for(int localIndex=1;localIndex hs = new HashSet(); for(int i = 1; i < len; i++){ int rev = Integer.parseInt(s.substring(i) + s.substring(0, i)); if(rev > val && rev <= B) hs.add(rev); } return hs.size(); } void run() throws Exception{ Scanner sc = new Scanner(System.in); //BufferedReader sc = new BufferedReader(new InputStreamReader(System.in)); // only sc.readLine() is available int T = sc.nextInt(); for(int o = 1; o <= T; o++){ A = sc.nextInt(); B = sc.nextInt(); long ans = 0; for(int i = A; i <= B; i++) ans += calc(i); System.out.printf(""Case #%d: "", o); System.out.println(ans); } } } " B11647,"package com.codejam.two12.RecyledNumbers; public class Pair { private int a, b; public Pair(int a, int b){ this.a = a; this.b = b; } /** {@inheritDoc}*/ @Override public String toString() { return ""("" + a + "", "" + b + "")""; } /** {@inheritDoc}*/ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + a; result = prime * result + b; return result; } /** {@inheritDoc}*/ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (a != other.a) return false; if (b != other.b) return false; return true; } } " B10084,"import java.io.*; class yo { public static void main(String args[]) throws IOException { try { FileWriter fs=new FileWriter(""o1.out""); FileInputStream f1=new FileInputStream(""C-small-attempt1(1).in""); DataInputStream d=new DataInputStream(f1); BufferedReader br=new BufferedReader(new InputStreamReader(d)); BufferedWriter out=new BufferedWriter(fs); String s,s1; s=br.readLine(); int T=Integer.parseInt(s); int cnt=0,nn,f,ll,ul,p; String w1; char temp; for(int i=0;i0;l--) { c[l]=c[l-1]; } c[0]=temp; w1=""""; for(int m=0;mll) if(nn>f) if(nn<=ul) cnt=cnt+1; } f=f+1; } String h=Integer.toString(cnt); out.write(h); out.write(""\r\n""); cnt=0; } out.close(); br.close(); } catch(Exception e){ System.out.println(""Error :""+e); } } }" B13022,"import java.io.*; import java.util.*; public class RecycledNumbers { String shift(String a) { return a.substring(1) + a.charAt(0); } void solve() throws Exception { int a = nextInt(); int b = nextInt(); int length = (b + """").length(); Set set = new HashSet(); int ans = 0, eq = 0; for (int i = a; i <= b; i++) { String s = i + """"; set.clear(); for (int j = 0; j < length; j++) { int t = Integer.parseInt(s); if (t >= a && t <= b && t != i) { set.add(t); } s = shift(s); } ans += set.size(); } out.println(ans / 2); } void run() { try { in = new BufferedReader(new FileReader(""input.txt"")); out = new PrintWriter(""output.txt""); int tests = nextInt(); for (int i = 0; i < tests; i++) { out.print(""Case #"" + (i + 1) + "": ""); solve(); System.err.println(""test "" + (i + 1)); } out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } BufferedReader in; StringTokenizer st; PrintWriter out; final String filename = new String(""RecycledNumbers"").toLowerCase(); String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(nextToken()); } long nextLong() throws Exception { return Long.parseLong(nextToken()); } double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } public static void main(String[] args) { new RecycledNumbers().run(); } } " B10118,"package source; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) throws IOException{ Scanner scan = new Scanner(new File("""")); BufferedWriter bw = new BufferedWriter(new FileWriter("""")); int testCases = new Integer(scan.nextLine()); Set pairs = null; for(int i=0; i < testCases; i++){ String[] nums = scan.nextLine().split("" ""); int min = new Integer(nums[0]); int max = new Integer(nums[1]); pairs = new TreeSet(); int testNum = min; while(testNum <= max){ getRecycled(testNum, pairs, min, max); ++testNum; } bw.write(""Case #""+(i+1)+"": ""+pairs.size()+""\n""); } bw.flush(); bw.close(); } public static void getRecycled(int testNum, Set pairs, int min, int max){ int rec = 0; String number = Integer.toString(testNum); StringBuilder sb = new StringBuilder(""""); for(int i=1; i < number.length(); i++){ sb.append(number.substring(i)).append(number.substring(0, i)); try{ rec = new Integer(sb.toString()); if(testNum != rec && min <= rec && rec <= max && !pairs.contains(testNum+""-""+rec) && !pairs.contains(rec+""-""+testNum)){ pairs.add(testNum+""-""+rec); } } catch(NumberFormatException e){} sb.delete(0, sb.length()); } } } " B12516,"package qual; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { private Scanner scanner; private void solve() throws FileNotFoundException { File input = new File(""data\\qual\\C-small-attempt0.in""); scanner = new Scanner(input); File test = new File(""data\\qual\\C.out""); PrintStream out = new PrintStream(new FileOutputStream(test)); System.setOut(out); int testCase = scanner.nextInt(); scanner.nextLine(); for (int i = 1; i <= testCase; i++) { System.out.printf(""Case #%d: "", i); solveCase(); } } private void solveCase() { int[] p10 = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; int a = scanner.nextInt(); int b = scanner.nextInt(); int len = (a + """").length(); Set ans = new HashSet(); for (int i = 1; i < len; i++) { for (int prefix = p10[i - 1]; prefix < p10[i]; prefix++) { for (int suffix = p10[len - i - 1]; suffix < p10[len - i]; suffix++) { int n = prefix * p10[len - i] + suffix; int m = suffix * p10[i] + prefix; if (a <= n && n < m && m <= b) { // System.out.println(prefix + ""-"" + suffix + "" "" + n + "" "" + m); ans.add(n + ""#"" + m); } } } } System.out.println(ans.size()); } public static void main(String[] args) throws FileNotFoundException { new C().solve(); } } " B10306,"package bsevero.codejam.qualification; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; public class IOUtils { public static List readFile(String fileName) { try { File file = new File(fileName); FileReader fileReader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(fileReader); List fileLines = new ArrayList(); for(String line = bufferedReader.readLine(); line != null; line = bufferedReader.readLine()) { fileLines.add(line); } return fileLines; } catch(Exception e) { e.printStackTrace(); return Collections.emptyList(); } } public static void writeFile(String fileName, Map casesResult) { try { File file = new File(fileName); if(file.exists()) { file.delete(); } file.createNewFile(); FileWriter fileWriter = new FileWriter(file); PrintWriter printWriter = new PrintWriter(fileWriter); StringBuffer result = new StringBuffer(); for(int i = 1; i <= casesResult.size(); i++) { result.append(""Case #"" + i + "": "" + casesResult.get(i) + ""\n""); } printWriter.print(result.toString().substring(0, result.length() - 1)); printWriter.close(); fileWriter.close(); } catch(Exception e) { e.printStackTrace(); } } } " B10784,"/** * */ package br.com.softctrl.code.c; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.io.Writer; /** * @author timoshenko * */ public class CRecycledNumbers { private static int A = 0; private static int B = 0; private static int T = 4; private static int c = 0; private static String fileInput = ""/Users/timoshenko/Development/Projects/SoftCtrl.com/eclipse-jboss/workspaces/google-code-jam/GoogleCodeJam2012/src/br/com/softctrl/in/C-small-attempt0.in""; private static String fileOutput = ""/Users/timoshenko/Development/Projects/SoftCtrl.com/eclipse-jboss/workspaces/google-code-jam/GoogleCodeJam2012/src/br/com/softctrl/out/C-small-attempt0_in.txt""; private static SCFileReader scFr = null; private static SCFileWriter scFw = null; public static boolean valid(int n, int m) { // A ² n < m ² B // System.out.println(String.format(""A(%d)<=n(%d)= 1); length--) { String m = n.substring(length, n.length()) + n.substring(0, length); if (valid(Integer.parseInt(n), Integer.parseInt(m))) { count++; } } } return count; } } class SCFileReader { private Reader reader = null; private BufferedReader bufferedReader = null; private File file = null; public SCFileReader(String fileName) throws FileNotFoundException { file = new File(fileName); reader = new FileReader(file); bufferedReader = new BufferedReader(reader); } public boolean ready() { try { return bufferedReader.ready(); } catch (IOException e) { e.printStackTrace(); return false; } } public String readLine() throws IOException { return bufferedReader.readLine(); } public void close() { if (this.ready()) { try { bufferedReader.close(); reader.close(); } catch (IOException e) { e.printStackTrace(); } bufferedReader = null; reader = null; file = null; } } } class SCFileWriter { private Writer writer = null; private BufferedWriter bufferedWriter = null; private File file = null; public SCFileWriter(String fileName) throws IOException { file = new File(fileName); if (file.exists()) { file.delete(); } writer = new FileWriter(file); bufferedWriter = new BufferedWriter(writer); } public void write(String row) throws IOException { // System.out.println(row); bufferedWriter.write(row); } public void writeLn(String row) throws IOException { System.out.println(row); bufferedWriter.write(row + ""\n""); } public void save() { try { bufferedWriter.close(); writer.close(); } catch (IOException e) { e.printStackTrace(); } bufferedWriter = null; writer = null; file = null; } } " B10194,"import java.io.*; import java.util.Scanner; public class RecycledNumbers{ public static void main(String[] args){ //read filename from user Scanner request = new Scanner(System.in); System.out.println(""Enter file name""); String fileName = request.nextLine(); try{ //create a filereader to read through file contents Scanner inputFile = new Scanner(new File(fileName)); //create output file BufferedWriter outputFile = new BufferedWriter(new FileWriter(""output.txt"")); //read file contents int lineCount = inputFile.nextInt(); for(int i=0; i""+totalCount); outputFile.write(""Case #""+ (i+1) + "": "" +totalCount); outputFile.newLine(); } outputFile.close(); } catch(IOException e){ System.out.println(""Error getting file""); } }//end of main public static int recycle(int base, int max){ String num = base+""""; int length = num.length(); //System.out.println(num + "" ""+length); int loop = length-1; String front=""""; String back=""""; int result=0; int correct=0; int current=-99; for(int i=0; i<=loop; i++){ front = num.substring(0,loop-i); back = num.substring(loop-i); String res=back+front; result = Integer.parseInt(res); //System.out.println(result); if((result!=current) && (result > base) && (result <=max)){ current = result; correct++; } } return correct; }//end of recycle }//end of class" B12067,"package com.ivantod.codejam2012; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Numbers { private void process() throws Exception { Scanner s=new Scanner(System.in); int numCases=s.nextInt(); s.nextLine(); for (int ca=1; ca<=numCases; ca++) { int A=s.nextInt(); int B=s.nextInt(); Set pairs=new HashSet(); for (int i=A; i<=B; i++) { String num=Integer.toString(i); String flip=Integer.toString(i); for (int j=num.length(); j>1; j--) { flip=flip.charAt(flip.length()-1)+flip.substring(0,flip.length()-1); if (!flip.startsWith(""0"") && !num.equals(flip) && !pairs.contains(num+""_""+flip) && !pairs.contains(flip+""_""+num) && Integer.parseInt(flip) >= A && Integer.parseInt(flip) <= B) { pairs.add(num+""_""+flip); } } } System.out.println(""Case #""+ca+"": ""+pairs.size()); } } public static void main(String[] args) { Numbers b=new Numbers(); try { b.process(); } catch (Exception e) { e.printStackTrace(); } } }" B12379,"import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) throws IOException { File file = new File(""c:\\java\\results.txt""); file.createNewFile(); PrintStream out = new PrintStream(file); Scanner scanIn = new Scanner(System.in); int T = 0; int a = 0; int b = 0; int n = 0; int digits = 0; HashSet set = new HashSet();//store results T=scanIn.nextInt(); for(int i = 0; i < T; i++){ a = scanIn.nextInt(); b = scanIn.nextInt(); digits = numDigits(a); n = a; if(a>b){ //Zero out.println(""Case #""+(i+1)+"": 0""); continue; } if(digits == 1){ //Zero out.println(""Case #""+(i+1)+"": 0""); continue; } while(n < b){ int divisor = 10; int multiply = (int)Math.pow(10, (digits-1)); int remain = 0; int part = 0; int temp = 0; for(int j = 0; j < digits-1; j++, divisor*=10, multiply/=10){ remain = n%divisor; part = n/divisor; temp = (remain*multiply)+part; if(temp <= b && temp > n){ set.add(new Pair(n, temp)); } } n++; } out.println(""Case #""+(i+1)+"": ""+set.size()); set.clear(); }//End of main loop out.close(); } public static int numDigits(int number){ int divisor = 10; int digits = 1; while(true){ if(number%divisor == number){ return digits; } else{ digits++; divisor*=10; } } } } class Pair{ int n; int m; public Pair(){ n = 0; m = 0; } public Pair(int n, int m){ this.n = n; this.m = m; } public void printPair(){ System.out.printf(""n: ""+n); System.out.printf("" m: ""+m+""\n""); } public boolean equals(Object arg){ if(this==arg)return true; if(arg==null)return false; if(arg instanceof Pair){ Pair other = (Pair)arg; if(this.n == other.n && this.m == other.m){ return true; } else return false; } return false; } public int hashCode(){ int code = 3; code = (code >> 2) + n; code = (code << 2) + m; return code; } } " B10759,"package google.jam; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.TreeSet; public class RecycledNumbers { public static void main (String[] args){ System.out.println(""Please, type your input:""); BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); boolean checkLines = false; int numLines = 0, linesCounter = 0; String line; String output = """"; try { while((line = stdIn.readLine()) != null){ if(!checkLines){ numLines = Integer.parseInt(line); checkLines = true; }else{ linesCounter++; output += inputToOutput(line, String.valueOf(linesCounter)); } if(linesCounter >= numLines) break; } System.out.println(output); } catch (IOException e) { System.out.println(""Something went wrong with your input.""); e.printStackTrace(); } } public static String inputToOutput(String input, String lineNum){ TreeSet set = new TreeSet(); String[] numbers = input.split("" ""); if(numbers.length != 2) return ""Case #"" + lineNum + "": 0\n""; int start = Integer.parseInt(numbers[0]); int end = Integer.parseInt(numbers[1]); if(start >= end) return ""Case #"" + lineNum + "": 0\n""; int cur = start; while(cur <= end){ for(int i=String.valueOf(cur).length()-1; i>0; i--){ String number = String.valueOf(cur); if(number.charAt(i) == '0') continue; String newNum = number.substring(i) + number.substring(0, i); int newInt = Integer.parseInt(newNum); if( newInt > end || newInt < start || newNum.equals(number) ) continue; set.add( (number.compareTo(newNum) < 0)?(newNum+number):(number+newNum) ); } cur++; } return ""Case #"" + lineNum + "": "" + set.size() + ""\n""; } } " B10742,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.StringTokenizer; public class C { static BufferedReader br; static PrintWriter pw; static StringTokenizer st; static int k, ch, chmp, btmp, bchmp = 0; static int n, tmp; static String str, ch1, ch2; static String[] stray = new String[2]; static int[] intray = new int[2]; static String[] copy = new String[2000001]; String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } char nextChar() throws IOException { return (char) br.read(); } public static void main(String[] args) throws IOException { br = new BufferedReader(new FileReader(""input.in"")); pw = new PrintWriter(""output.out""); n = Integer.parseInt(br.readLine()); for (int i = 1; i <= n; i++) { str = br.readLine(); st = new StringTokenizer(str, "" \t\n\r,.""); while (st.hasMoreTokens()) { stray[k] = st.nextToken(); k++; } for (int j = 0; j < 2; j++) { intray[j] = Integer.parseInt(stray[j]); } for (int j = intray[0]; j < intray[1] - 1; j++) { for (int p = j + 1; p <= intray[1]; p++) { ch1 = Integer.toString(j); ch2 = Integer.toString(p); if (ch1.length() != ch2.length()) { continue; } tmp = ch1.length(); for (int k1 = 0; k1 < tmp; k1++) { ch1 = ch1.charAt(tmp - 1) + ch1; for (int k2 = 0; k2 < tmp; k2++) { if (ch1.charAt(k2) == ch2.charAt(k2)) { chmp++; } else { break; } } if (chmp == tmp) { for (int j1 = 0; j1 < btmp; j1++) { bchmp = 0; for (int k2 = 0; k2 < tmp; k2++) { if (ch1.charAt(k2) == copy[j1].charAt(k2)) { bchmp++; } else { continue; } } } if (bchmp == tmp) { chmp = 0; break; } str = """"; for (int j1 = 0; j1 < tmp; j1++) { str += ch1.charAt(j1); } copy[btmp] = str; btmp++; ch++; } chmp = 0; } bchmp = 0; } } btmp = 0; pw.println(""Case #"" + i + "": "" + ch); ch = 0; k = 0; } br.close(); pw.close(); } }" B12088,"package codejam; import java.io.*; import java.math.BigInteger; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class RecycledNumbers { public static final String LINE_SEPARATOR = System.getProperty(""line.separator""); public static int recycleNum(int a, int b) { Map map = new HashMap(); int n = String.valueOf(a).length(); int c = 0; for (int i = a; i <= b; i++) { for (int j = 1; j < n ; j++) { int rNum = rotateRight(i, j); if (i < rNum && rNum <= b) { if (!map.containsKey(rNum) || map.get(rNum) != i) { map.put(rNum, i); c++; } } } } return c; } private static int rotateRight(int i, int j) { int length = String.valueOf(i).length(); int sP = (int) Math.pow(10, j); int bP = (int) Math.pow(10, length - j); int rem = i % sP; return ((i - rem) / sP) + (rem * bP); } public static void main(String[] args) throws IOException { Scanner scanner = new Scanner(new File(""D:\\codejam\\C-small-attempt0.in"")); Writer writer = new OutputStreamWriter(new FileOutputStream(""D:\\codejam\\C-small-attempt.out"")); Integer n = Integer.valueOf(scanner.nextLine()); for (int i = 1; i <= n; i++) { System.out.println(); int a = scanner.nextInt(); int b = scanner.nextInt(); writer.write(""Case #"" + i + "": "" + recycleNum(a, b)); writer.write(LINE_SEPARATOR); } scanner.close(); writer.close(); } } " B12738,"import java.io.*; public class q3 { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String input = in.readLine(); int numCases = Integer.valueOf(input); for (int caseCount = 1; caseCount <= numCases; caseCount++) { input = in.readLine(); String A_string = input.split("" "")[0]; String B_string = input.split("" "")[1]; int A = Integer.valueOf(A_string); int B = Integer.valueOf(B_string); int n_int; int m_int; int recycledPairCount = 0; for (n_int = A; n_int < B; n_int++) { for (m_int = n_int + 1; m_int <= B; m_int++) { String n = Integer.toString(n_int); String m = Integer.toString(m_int); boolean found = false; for (int i = (n.length() - 1); i > 0 && found == false; i--) { String sub = n.substring(i); char[] array = n.toCharArray(); String shortened = new String(array, 0, i); sub = sub.concat(shortened); if (sub.equals(m)) { found = true; recycledPairCount++; } } } } System.out.println(""Case #"" + caseCount + "": "" + recycledPairCount); } } } " B10822,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; public class Fattom2012C { private final String _PROBLEM_NO = ""201201C""; private final String _FILE_DIRECTORY = ""K:/Dropbox/workspace/codejam/"" + _PROBLEM_NO + ""/""; private final String _FILE_PATH = _FILE_DIRECTORY + ""C-small-attempt4""; public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); new Fattom2012C().execute(); } public void execute() { BufferedReader br = null; PrintWriter pw = null; try { br = new BufferedReader(new FileReader(_FILE_PATH + "".in"")); pw = new PrintWriter(_FILE_PATH + "".out""); //main int caseno = Integer.parseInt(br.readLine()); Map m = new HashMap(); for(int i=10;i<=1000000;i++) { check(i,m); } // System.out.println(m.get(2)); for (int count = 1; count <= caseno; count++) { // if(count>4)break; pw.print(""Case #"" + count + "": ""); System.out.print(""Case #"" + count + "": ""); String line = br.readLine(); String[] splits = line.split("" ""); int A = Integer.parseInt(splits[0]); int B = Integer.parseInt(splits[1]); int r = 0; if(A < 10 || A >= 1000000 || A==B) { pw.print(""0""); System.out.print(""0""); } else { List tt = m.get((""""+A).length()); for(int t:tt) { // if(t >= A && t <= B) { r += check(A,B,t); // } } pw.print(r); System.out.print(r); } pw.print(""\n""); System.out.print(""\n""); } //end br.close(); pw.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if(pw != null) pw.close(); } catch(Exception e) {} try { if(br != null) br.close(); } catch(Exception e) {} } } private int check(int a, int b, int t) { String tt = """"+t; // System.out.println(tt); int r =0; Set rr = new HashSet(); for(int i=0;i=a&&t<=b) { // System.out.print(tt + ""!""); rr.add(t); } } r=rr.size(); // System.out.println(r); if(r==1) return 0; if(r!=0) r = (r*(r-1))/2; return r; } private void check(int i, Map m) { String in = """" + i; int b = in.length(); if(!dedup(i)) return; dedup.put(i, true); List target = m.get(b); if(target == null) { target = new ArrayList(); m.put(b, target); } target.add(i); } public static Map dedup = new HashMap(); private boolean dedup(int t) { String tt = """"+t; for(int i=0;i0) { int total=0; t--;ctr++; st=new StringTokenizer(br.readLine()); int A=Integer.parseInt(st.nextToken()); int B=Integer.parseInt(st.nextToken()); int i,j,k,l; int ctr1=0,ctr2=0; for(i=A;i<=B;i++) { String s=Integer.toString(i); l=s.length(); String s1=s; int a[]=new int[l+1]; a[0]=-1; for(j=0;ji && a[j]!=a[j-1]) { ctr1++; } } pw.println(""Case #""+ctr+"": ""+ctr1); } pw.flush(); } }" B11831,"import javax.swing.*; import java.util.Scanner; import java.io.*; class ProblemC { public static void main (String []sdvv) throws IOException { int cases=0, A=0, B=0, total; String num; Scanner sc; PrintWriter es; try { sc = new Scanner(new File(""Csmall.IN"")); es = new PrintWriter(new BufferedWriter(new FileWriter(""solutionC.txt""))); cases=Integer.parseInt(sc.nextLine()); for(int j=1;j<=cases;j++) { total=0; es.print(""Case #""+j+"": ""); A=sc.nextInt(); B=sc.nextInt(); for(int n=A;n set = new HashSet(); for(int k = 1; k <= m; k++){ int mod = (int)Math.pow(10, k); int lod = (int)Math.pow(10, m - k + 1); int r = j % mod; int l = j / mod; int trans = r * lod + l; if(A <= trans && trans <= B && trans != j){ if(set.add(trans)) count++; } } } out.println(""Case #"" + (i+1) + "": "" + count/2); } //long end = System.currentTimeMillis(); //System.out.println(end - start); out.close(); } } " B10400,"import java.io.*; class RecycledNumbers { public static void main(String[] args) { try { //parse the input FileInputStream fstream = new FileInputStream(args[0]); DataInputStream dstream = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(dstream)); String line = """"; int numCases = Integer.parseInt(br.readLine()); //System.out.println(""num cases: "" + numCases); for(int lineIdx = 0; lineIdx < numCases; lineIdx++) { line = br.readLine(); String[] words = line.split("" ""); int n = Integer.parseInt(words[0]); int m = Integer.parseInt(words[1]); //System.out.println(n + "" "" + m); int numRecycledNumbers = 0; for(int i = n; i <= m; i++) { for(int j = i+1; j <= m; j++) if(countRecycledNumbers(i, j)) numRecycledNumbers++; } //System.out.println(numRecycledNumbers); // write output BufferedWriter out = new BufferedWriter(new FileWriter(""outfilename"", true)); out.write(""Case #"" + (lineIdx+1) + "": "" + numRecycledNumbers + ""\n""); out.close(); } } catch(FileNotFoundException ex) { System.out.println(ex); } catch(IOException ex) { System.out.println(ex); } } static boolean countRecycledNumbers(int n, int m) { String nStr = """" + n; String mStr = """" + m; //System.out.println(nStr + "" "" + mStr); if(nStr.length() == mStr.length()) { //System.out.println(""length condition hit""); if( (nStr+nStr).indexOf(mStr) >= 0 ) { // System.out.println(""index condition hit""); return true; //System.out.println(numRecycledNumbers); } } return false; } } " B11625,"import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class Recycled { public static void main(String[] args) { try { //File input = new File(""/Users/mtervahauta/Dev/mikkot/codejam/recycled.input""); File input = new File(args[0]); FileInputStream fStream = new FileInputStream(input); BufferedReader bReader = new BufferedReader( new InputStreamReader(fStream)); int cases = Integer.parseInt(bReader.readLine()); for (int i = 1; i <= cases; i++) { String[] values = bReader.readLine().trim().split("" ""); solveRecycled(i, values[0], values[1]); } } catch (Exception e) { e.printStackTrace(); } } private static void solveRecycled(int caseNo, String aStr, String bStr) { long a = Long.parseLong(aStr); long b = Long.parseLong(bStr); Set nms = new HashSet(); for (long n = a; n <= b; n++) { findM(nms, a, n, b); } System.out.println(""Case #"" + caseNo + "": "" + nms.size()); } private static void findM(Set nms, long a, long n, long b) { List recycledValues = recycledStrings(Long.toString(n)); for (Long recycledN : recycledValues) { long m = recycledN.longValue(); if (n < m && m <= b) { nms.add(n+"":""+m); } } } private static List recycledStrings(String src) { List resp = new ArrayList(); int length = src.length(); String recycled = null; for (int i = 1; i < length; i++) { recycled = src.substring(length - i); recycled = recycled + src.substring(0, length - i); if (!recycled.startsWith(""0"")) resp.add(new Long(Long.parseLong(recycled))); } return resp; } }" B10586,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; public class C { public static void main(String[] args) throws Exception{ Scanner sc = new Scanner(new File(""C.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""C.out""))); int N = Integer.parseInt(sc.nextLine()); for(int i=1;i<=N;i++){ HashSet HS = new HashSet(); int A = sc.nextInt(); int B = sc.nextInt(); for(int a=A;a<=B;a++){ String x = a+""""; for(int b=1;b=A&&other<=B&&other!=a){ HS.add(x+"" ""+temp); } } } out.println(""Case #""+i+"": ""+(HS.size()>>1)); } out.close(); } } " B10287,"import java.io.*; import java.util.Scanner; public class jam3Rec { public static void main(String args[]) throws java.lang.Exception { int a,b,n,m, cnt=0,len=0; //a=1111;b=2222; int t,cas=1; //System.out.println(); //Scanner scan=new Scanner(System.in); //Scanner scan=new Scanner(new FileReader(""input3"" + "".in"")); Scanner scan=new Scanner(new FileReader(""C-small-attempt2"" + "".in"")); PrintWriter out=new PrintWriter(""SmallOutput5"" + "".out""); //PrintWriter out=new PrintWriter(""LocalOutput3"" + "".out""); //FileReader(""A-small-attempt1"" + "".in"") t=scan.nextInt(); while(t!=0) { t--; cnt=0; a=scan.nextInt(); b=scan.nextInt(); //a=100;b=500; String str1,tstr1; for(int i=a;i<=b;i++) { str1=Integer.toString(i); for(int j=a;j<=b;j++) { if(i!=j && i 0) { in = br.readLine(); out.write(""Case #"" + i + "": "" + solve(in) + ""\n""); testCases--; i++; } out.close(); } public static int solve(String in) { String[] data = in.split("" ""); int a = Integer.parseInt(data[0]); int b = Integer.parseInt(data[1]); int solution = 0; for(int i = a; i < b; i++) { int tmp = i; do{ tmp = shift(tmp); while (Math.floor(Math.log10(i)) != Math.floor(Math.log10(tmp))){ tmp *= 10; } if(tmp > i && tmp <= b){ solution++; } }while(tmp != i); } return solution; } public static int shift(int a){ int E = firstDigit(a); int T = 10 * trailing(a); return E + T; } public static int trailing(int x) { if (x == 0) return 0; return (int) Math.floor(x % Math.pow(10, Math.floor(Math.log10(x)))); } public static int firstDigit(int x) { if (x == 0) return 0; return (int) Math.floor(x / Math.pow(10, Math.floor(Math.log10(x)))); } }" B11707,"import java.util.*; class Recycle { public static int[] combi = {0,0,1,3,6,10,16,21}; public static boolean[] bool; public static int howMany(int x, int least, int greatest) { int rotate = x; int pair = 1; int i; int j; int dummy; ArrayList digit = new ArrayList(); bool[rotate]=true; while (rotate>0) { digit.add(rotate%10); rotate=rotate/10; } for (i=1; i=0; j--) rotate = rotate*10+digit.get(j); if (((rotate<=greatest) && (rotate>=least))&&(bool[rotate]==false)) { //System.out.println(rotate); bool[rotate]=true; pair++; } } } return (combi[pair]); } public static void main (String[] args) { Scanner myInput = new Scanner(System.in); int T; int t; T = myInput.nextInt(); int i; int A; int B; int result; for (t=1; t<=T; t++) { A=myInput.nextInt(); B=myInput.nextInt(); result=0; bool = new boolean[B+1]; for (i=A; i<=B; i++) if (bool[i]==false) result=result+howMany(i,A,B); System.out.println(""Case #""+t+"": ""+result); } } } " B11360,"import java.io.BufferedReader; import java.io.FileReader; import java.util.StringTokenizer; public class REcycledNumbers { public static void main(String args[]) throws Exception { String line = """"; BufferedReader br = new BufferedReader(new FileReader(""/Users/ravipalacherla/Documents/workspace/CodeJam/src/input.txt"")); int T = Integer.parseInt(br.readLine()); int j=0; while((line = br.readLine()) != null) { StringTokenizer st = new StringTokenizer(line,"" ""); String strA = st.nextToken(); String strB = st.nextToken(); int intA = Integer.parseInt(strA); int intB = Integer.parseInt(strB); int count = 0; int intn = intA; while(intn < intB) { String strn = Integer.toString(intn); for(int i = strn.length()-1; i>0;i--) { String strm = strn.substring(i)+strn.substring(0,i); if(strm.charAt(0) == '0') continue; int intm = Integer.parseInt(strm); if( ((""""+intn).length() != (""""+intm).length()) || ((""""+intn).length() != (""""+intA).length())) continue; if(intn == intm) continue; if ( ( intA <= intn) && (intn < intm) && (intm <= intB) ) { // System.out.println(""intN is "" + intn + "" intM is ""+ intm); count ++; } } intn++; } j++; System.out.println(""Case #""+ j +"": ""+count); } } } " B12460,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; class Input { int a; int b; public Input(String line) { String [] arr = line.split("" ""); a = Integer.parseInt(arr[0]); b = Integer.parseInt(arr[1]); } public String Rotate(String str) { char last = str.charAt(str.length()-1); return (last + str.substring(0,str.length()-1)); } public int Solve() { int count=0; int numDigits = Integer.toString(a).length(); for(int curr=a;curr<=b;curr++) { // For each number String strCurr = Integer.toString(curr); HashMap checker = new HashMap(); for(int rot=1;rot curr && newNum <= b) { String str = curr + "","" + newNum; if(!checker.containsKey(str)) count++; checker.put(str, 0); } } } return count; } } public class Main { /** * @param args */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub // Setup console BufferedReader c = new BufferedReader(new InputStreamReader(System.in)); // Read number of test cases int numCases = Integer.parseInt(c.readLine()); // Input Input [] testCases = new Input[numCases]; for(int i=0;i 0) { temp = temp / 10; power++; } int remainder = 0; for (int i = 0; i < power; i++) { remainder = (int) (num % Math.pow(10, (i + 1))); temp = (int) (num / Math.pow(10, i + 1)); int comp = (int) (temp + remainder * Math.pow(10, power - i)); if (comp > num && comp <= upperBound) { result++; } } return result; } public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new File(""input.txt"")); BufferedWriter out = null; try { FileWriter fstream = new FileWriter(""out.txt""); out = new BufferedWriter(fstream); int cases = Integer.parseInt(in.nextLine()); for (int i = 0; i < (cases); i++) { int result = 0; int lower = in.nextInt(); int upper = in.nextInt(); for (int j = lower; j < upper; j++) { result += getReycled(j, upper); } out.write(""Case #"" + (i + 1) + "": "" + result + ""\n""); } out.close(); } catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } } " B11442,"import java.util.LinkedList; import java.util.HashMap; import java.util.Scanner; public class Recycled { public static void main(String[] args) throws Exception { HashMap> lol = new HashMap>(); for( int i = 1 ; i <= 2500; i++ ) { LinkedList ll = new LinkedList(); String _i = i + """"; for( int k = 0 ; k < _i.length();k++) { String t = _i.substring( k , _i.length() ) + _i.substring( 0 , k ); for( int j = 4 - t.length(); j >= 0; j-- ) { ll.add( t ); t = t + ""0""; } } lol.put( i , ll ); } Scanner in = new Scanner( System.in ); int size = in.nextInt(); for( int pos = 1 ; pos <= size ;pos++ ) { int A = in.nextInt(); int B = in.nextInt(); String _A = A + """"; String _B = B + """"; int count = 0; for( int i = A ; i < B ; i++ ) { String a = i + """"; if( a.length() != _A.length() ) continue; for( int j = i + 1; j <= B; j++ ) { String b = j + """"; if( b.length() != _B.length() ) continue; LinkedList ll = lol.get( i ); if( ll.contains( b ) ) { count++; } } } System.out.println(""Case #"" + pos + "": "" + count); } } }" B11074,"package fixjava; /** * Convenience class for declaring a method inside a method, so as to avoid code duplication without having to declare a new method * in the class. This also keeps functions closer to where they are applied. It's butt-ugly but it's about the best you can do in * Java. */ public interface Lambda4 { public V apply(P param1, Q param2, R param3, S param4); } " B11807,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class RecycledNumbers { private static final String INPUT_FILE = ""input.txt""; private static final String OUTPUT_FILE = ""output.txt""; public int countSiblings(String lowerbound, String upperbound) { int n = lowerbound.length(); int start = Integer.parseInt(lowerbound); int end = Integer.parseInt(upperbound); char[] upChars = upperbound.toCharArray(); char[] lowChars = lowerbound.toCharArray(); boolean[] hasSibling = new boolean[end - start + 1]; int count = 0; for (int i = start; i <= end; i++) { if (hasSibling[i - start]) continue; char[] iChars = Integer.toString(i).toCharArray(); int buf = 0; for (int j = 1; j < n; j++) { if (iChars[j] > upChars[0] || iChars[j] < lowChars[0]) continue; int tenpowj = (int) Math.pow(10, n- j); int cycle = (int) (i / tenpowj + (i % tenpowj) * Math.pow(10, j)); if (cycle > end || cycle < start || hasSibling[cycle - start]) continue; if (cycle <= i) continue; else { hasSibling[i - start] = true; hasSibling[cycle - start] = true; buf++; } } count += (buf + 1) * buf /2; } return count; } public static void main(String[] args) throws NumberFormatException, IOException { RecycledNumbers recycledNumbers = new RecycledNumbers(); Parser parser = new Parser(); String[] input = parser.readInput(INPUT_FILE); String[] result = new String[input.length]; for (int i = 0; i < input.length; i++) { String[] data = input[i].split("" ""); result[i] = Integer.toString(recycledNumbers.countSiblings(data[0], data[1])); } parser.writeOutput(result, OUTPUT_FILE); } } class Parser { public String[] readInput(String fileName) throws NumberFormatException, IOException { BufferedReader reader = new BufferedReader(new FileReader(fileName)); int numberOfCases = Integer.parseInt(reader.readLine()); String[] input = new String[numberOfCases]; for (int i = 0; i < numberOfCases; i++) { input[i] = reader.readLine(); } reader.close(); return input; } public void writeOutput(String[] result, String file) throws IOException { FileWriter writer = new FileWriter(file); BufferedWriter bufferedWriter = new BufferedWriter(writer); for (int i = 0; i < result.length; i++) { bufferedWriter.write(""Case #"" + (i+1) +"": "" + result[i]); bufferedWriter.newLine(); } bufferedWriter.flush(); bufferedWriter.close(); } } " B12342,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; /** * * @author harit */ public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); int t1 = 1; int a, b; int count = 0; while (t1 <= t) { String s[] = br.readLine().split("" ""); a = Integer.parseInt(s[0]); b = Integer.parseInt(s[1]); count=0; for (int i = a; i < b; i++) { List lstR = getRnum(i); for (Integer j : lstR) { if (j >= i && j <= b) { count++; } } } System.out.println(""Case #""+ t1 + "": "" + count); t1++; } } public static List getRnum(int a) { List lstRnum = new ArrayList(); String s = """" + a; int l = s.length(); int modf = 10; int multf = (int) Math.pow(10, l - 1); int i = 1; boolean flag=true; while (i < l) { // System.out.println(""modf ""+modf); int x = ((a % modf) * multf) + a / modf; if (("""" + x).length() == l && x!=a) { for(int xx:lstRnum){ if(xx==x) flag=false;} if(flag){ lstRnum.add(x); } } modf = modf * 10; multf = multf / 10; i++; } return lstRnum; } } " B10545,"import java.io.*; import java.util.*; public class Q3{ public static void main(String args[]){ try { BufferedReader is = new BufferedReader( new InputStreamReader(new FileInputStream(new File(""C-small-attempt0.in"")))); BufferedWriter os = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(new File(""q3output-s.txt"")))); int num = Integer.parseInt(in(is)); for (int i=0;i dup = new HashSet(); while(num >= 10 ) { target = num % 10; num = num/10; out++; int convert = convert(num, i, out); if (target > first && target < border) { if(!dup.contains(convert)){ dup.add(convert); result++; } } else if(target == first && target == border) { if(!dup.contains(convert) && compare(convert, i) && !compare(convert, max)){ dup.add(convert); result++; } } else if(target == first) { if(!dup.contains(convert) && compare(convert, i) && !compare(convert, max)){ dup.add(convert); result++; } } else if(target == border) { if(!dup.contains(convert) && compare(convert, i) && !compare(convert, max)){ dup.add(convert); result++; } } } return result; } private static int first(int num){ int ret = num; while(ret >= 10) { ret = ret/10; } return ret; } private static int convert(int num, int all, int out){ int m = power(out); int p = digits(num); return (all - num * m) * p + num; } private static boolean compare(int n, int com){ return n > com; } private static int digits(int num){ int ret = 10; while(num >= 10) { num = num/10; ret*=10; } return ret; } private static int power(int out){ int ret = 1; for(int i =0;iii&&change<=B&&sign!=1){ count++; //System.out.print(""(""+ii+"",""+change+"") ""); } } } fw = new FileWriter(""result.txt"",true); String s =""Case #""+(i+1)+"": ""+count+""\n""; fw.write(s,0,s.length()); fw.flush(); System.out.println(""Case #""+(i+1)+"": ""+count); count=0; } } } " B12678,"import java.io.*; import java.util.HashMap; class GoogleRecycle{ public static int[] findNext(String s, int n) { int a[]= new int[n]; for (int i =0; i0) { temp=temp/10; n++; } line = line.substring(line.indexOf(' ')+1); int end = Integer.parseInt(line); int count =0; for (int j=start;j<=end;j++) { int[] a =new int[n]; Integer x = j; a= findNext(x.toString(),n); HashMap map = new HashMap(); int flag = 0; for (int p: a) { if(p>j && p<=end && p!=0 && !map.containsKey(p)) { map.put(p, null); count++; } } } //System.out.println(""Reached here also""); out.write(""Case #""+i+"": ""+count); if(i!=testcases) { out.write(""\n""); } } out.close(); br.close(); } }" B10006,"import java.io.*; import java.util.*; //import java.math.*; public class c { public static void main(String[] args) throws IOException { Scanner qwe = new Scanner(new File(""c.in"")); BufferedWriter out = new BufferedWriter(new FileWriter(""c.out"")); int t = qwe.nextInt(); for(int i = 1; i <= t; i++) { int a = qwe.nextInt(); int b = qwe.nextInt(); int[] been = new int[2000001]; long count = 0; for(Integer j =a; j <= b; j++) { //if(been[j] > 1 && i == 4) //System.out.println(i + "" "" +j + "" "" + been[j]); if(been[j] > 0) count += been[j]; String s = j.toString(); ArrayList tocheck = new ArrayList(); for(int k = 1; k < s.length(); k++) { String torec = s.substring(k); String end = s.substring(0,k); String combin = torec+end; if(!tocheck.contains(combin)) been[Integer.parseInt(combin)] += 1; tocheck.add(combin); } } out.write(""Case #"" + i + "": "" + count + ""\n""); } out.close(); } } " B11916," import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Set; public class RecycleNumber { /** * @param args */ public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("".in""))); int num =0; String line = null; line = br.readLine(); int i=0; num = Integer.parseInt(line); while(num-->0){ int result = 0; line = br.readLine(); i++; String[] nums = line.split("" ""); int min = Integer.parseInt(nums[0]); int max = Integer.parseInt(nums[1]); for(int t=min;t<=max;t++){ result += countRecyles(t,min,max); } System.out.println(""Case #""+i+"": ""+result/2); } br.close(); } public static int countRecyles(int num,int min,int max){ int count = 0; Set result = getNums(num); for(int i:result){ if(i>=min&&i<=max){ count++; // System.out.println(num+"",""+i); } } return count; } public static Set getNums(int num){ Set list = new HashSet(); StringBuilder sb = new StringBuilder(num+""""); for(int i=0;i list = new ArrayList(); static ArrayList list2; public static int convert(String input) { list2 = new ArrayList(); int output = 0; String[] pairs = input.split("" ""); String first = pairs[0]; String second = pairs[1]; if (first.length() != 1) { int firstInt = Integer.parseInt(first); int secondInt = Integer.parseInt(second); for (int k = firstInt; k < secondInt; k++) { String firstNum = k + """"; if (!same(firstNum)) { int len = firstNum.length(); for (int i = 0; i < len - 1; i++) { char lastChar = firstNum.charAt(len - 1); String newFirstNum = lastChar + firstNum.substring(0, len - 1); // System.out.println(firstNum + ""---"" + // newFirstNum); // list2.add(newFirstNum); int secondNum = Integer.parseInt(newFirstNum); if ((secondNum + """").length() == firstNum.length()) { if (secondNum <= secondInt && secondNum > k // && !list.contains(secondNum) ) { output++; // list.add(k); // System.out.println(k + ""---"" + // secondNum); } } firstNum = newFirstNum; } } } // output = getAll(firstInt,secondInt); } return output; } // private static int getAll(int firstInt, int secondInt) { // // System.out.println(""-----""+firstInt); // // System.out.println(""-----""+secondInt); // int count = 0; // for (int i = 0; i < list2.size(); i++) { // String str = list2.get(i); // if (str.charAt(0) != '0') { // int second = Integer.parseInt(str); // if (second <= secondInt && second >= firstInt) // count++; // } // } // count /= 2; // return count; // } private static boolean same(String s) { for (int i = 0; i < s.length() - 1; i++) { if (s.charAt(i) != s.charAt(i + 1)) return false; } return true; } public static void main(String[] args) { String inputFile = ""C-small-attempt2.in""; String outPutFile = ""C-small2.out""; try { FileInputStream fstream = new FileInputStream(inputFile); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter fstream2 = new FileWriter(outPutFile); BufferedWriter out = new BufferedWriter(fstream2); String strLine; strLine = br.readLine(); int casesNum = Integer.parseInt(strLine); for (int i = 0; i < casesNum; i++) { strLine = br.readLine(); String parse = ""Case #"" + (i + 1) + "": "" + convert(strLine); System.out.println(parse); if (i < casesNum - 1) parse += ""\n""; out.write(parse); } in.close(); out.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } } " B13024," import java.util.*; import java.io.*; public class template { private StringBuilder result = new StringBuilder(); public static void main(String[] args) { new template().go(); } public void go() { File inputFile = new File(""/Users/amornchaikanokpullwad/Documents/input.in""); BufferedReader br = null; try { br = new BufferedReader(new FileReader(inputFile)); int numTests = Integer.parseInt(br.readLine()); for (int testCounter = 0; testCounter < numTests; ++testCounter) { int count = 0; String text[] = br.readLine().split("" ""); long A = Long.parseLong(text[0]); long B = Long.parseLong(text[1]); for (long i = A; i <= B; i++) { for (int j = 1; j < Long.toString(i).length(); j++) { //System.out.println(j + "" "" + i); long temp = reverse(Long.toString(i),j); if (temp <= i) continue; if (temp <= B) { System.out.println(i+""+""+B); count++; } } //System.out.println(i+""+""+B); } appendResult(testCounter, count); } } catch (FileNotFoundException fe) { fe.printStackTrace(); } catch (IOException ie) { ie.printStackTrace(); } finally { try { if (br != null) { br.close(); } } catch (IOException ex) { ex.printStackTrace(); } } writeResultToFile(); System.out.println(result); } private void appendResult(int testCase, int outp) { result.append(""Case #"" + (testCase+1) + "": ""); result.append(outp+""""); result.append(""\n""); } private void writeResultToFile() { PrintWriter pr = null; try { pr = new PrintWriter(new File(""/Users/amornchaikanokpullwad/Documents/output.in"")); pr.print(result); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (pr != null) { pr.close(); } } } private long reverse(String in,int le){ StringBuilder temp = new StringBuilder(); for (int i = le; i > 0; i--) { //System.out.println(in); temp.append(in.charAt(in.length()-i)); } for (int i = 0; i < in.length()-le; i++) { temp.append(in.charAt(i)); } return Long.parseLong(temp.toString()); } }" B10171,"import java.io.File; import java.io.PrintWriter; import java.util.Scanner; public class RecycledNumbers { /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new File(""C-small-attempt0.in"")); PrintWriter pw = new PrintWriter(""C-small.out""); int tc = sc.nextInt(); for(int t=1; t<=tc; t++){ int A = sc.nextInt(); int B = sc.nextInt(); pw.println(""Case #"" + t + "": "" + count(A,B)); } pw.close(); sc.close(); } private static long count(int a, int b) { boolean[] flag = new boolean[b-a+1]; long gsum = 0; for(int v=Math.max(a, 12); v0){ i/=10; exp *= 10; } i = v; for(int e=10; e= a && num <= b){ flag[num-a] = true; sum++; } } gsum += (sum*(sum-1)/2); } return gsum; } } " B10067,"/** * @(#)RecycledNumbers.java * * * @author CristianDumitruPopov * @version 1.00 2012/4/14 */ import java.io.*; import java.util.*; public class RecycledNumbers { public static int lengthOf(int x) { int c = 0; while(x!=0) { x = x/10; c++; } return c; } public static int recycle(int z,int y) { return (((z%((int)Math.pow(10,y)))*((int)Math.pow(10,lengthOf(z)-y))) + z/((int)Math.pow(10,y))); } public static int trailing(int z) { int c = 1; while(z%10 == 0) { c++; z=z/10; } return c; } public static void write(String s) { try{ FileWriter fstream = new FileWriter(""out3.txt"",true); BufferedWriter out = new BufferedWriter(fstream); out.write(s); out.close(); }catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } public static void main(String [] args) { int T,A,B; int contor = 0; /* T = 12305; System.out.println(lengthOf(T)); int q = recycle(T,trailing(T)); System.out.println(q); q = recycle(q,trailing(q)); System.out.println(q); q = recycle(q,trailing(q)); System.out.println(q); q = recycle(q,trailing(q)); System.out.println(q); q = recycle(q,trailing(q)); System.out.println(q); q = recycle(q,trailing(q)); System.out.println(q);*/ try{ FileInputStream fstream = new FileInputStream(""C-small-attempt0.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String s; T = Integer.parseInt(br.readLine()); for(int i = 0 ; i < T;i++) { s = br.readLine(); StringTokenizer st = new StringTokenizer(s,"" ""); A = Integer.parseInt(st.nextToken()); B = Integer.parseInt(st.nextToken()); contor = 0; for(int j = A;j results = new ArrayList(); BufferedReader reader = new BufferedReader( new FileReader( ""C:\\file.in"") ); reader.readLine(); String line = reader.readLine(); while( line != null ) { String[] parameters = line.split( "" "" ); results.add( getRecycledPairs( Integer.valueOf( parameters[0] ), Integer.valueOf( parameters[1] ) ) ); line = reader.readLine(); } BufferedWriter writer = new BufferedWriter( new FileWriter( ""c:\\output.txt"" ) ); for( int i = 0; i < results.size(); i++ ) { writer.write( ""Case #"" + String.valueOf( i+1 ) + "": "" + String.valueOf( results.get( i ) ) ); writer.newLine(); } writer.close(); } catch( Exception e ) { } } private static int getRecycledPairs( int aMin, int aMax ) { if( String.valueOf( aMin ).length() != String.valueOf( aMax ).length() ) { return 0; } int result = 0; for( int i = aMin; i <= aMax; i++ ) { result += getNumberOfCombinations( i, aMax ); } return result; } private static int getNumberOfCombinations( int aNumber, int aMax ) { String string = String.valueOf( aNumber ); int numberOfDigits = string.length(); String temp; int result = 0; ArrayList values = new ArrayList(); for( int i = 1; i < string.length(); i++ ) { temp = string.substring( i, string.length() ) + string.substring( 0, i ); int value = Integer.valueOf( temp ); if( String.valueOf( value ).length() != numberOfDigits ) { continue; } if( (value > aNumber ) && (value <= aMax ) && !values.contains( value ) ) { result++; values.add( value ); } } return result; } } " B11368,"import java.io.File; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class recycled { static HashMap> found; static Set touched; public static int calc(long a, long b){ int compteur = 0; int nbchiffres = 1; long pow = 10; while(powpow){ pow=pow*10; nbchiffres++; } //System.out.println(n+"" ""+a+"" ""+b); compteur+= nbpossibleM(a,b,n, nbchiffres, pow); } return compteur; } private static int nbpossibleM(long a, long b, long n, int nbchiffre, long pow) { long smallpow = 10; long bigpow = pow/10; //System.out.println(""-------- ""+nbchiffre+"" ""+smallpow+"" ""+bigpow+""\n\n\n""); long m=0; int possibilities =0; touched.clear(); for(int k=1; k=a && !touched.contains(m)){ /*if(found.containsKey(m)){ HashMap map = found.get(m); if(map.containsKey(n)){ map.put(n, map.get(n)+1); } else{ map.put(n, 1); } } else{ HashMap map = new HashMap(); map.put(n, 1); found.put(m, map); }*/ possibilities++; touched.add(m); } smallpow=smallpow*10; bigpow=bigpow/10; } return possibilities; } public static void main(String[] args) throws FileNotFoundException{ //found = new HashMap>(); touched = new HashSet(); Scanner s = new Scanner(new File(""input.txt"")); int nbcas = s.nextInt(); for(int i=0; i map = found.get(m); for(long n: map.keySet()){ if(map.get(n)==2){ System.out .println(m+"" ""+n); } } }*/ } } " B12263,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; public class R1Q3 { public static HashMap wordMap; public static void main(String []args) throws NumberFormatException, IOException{ BufferedReader bf = new BufferedReader(new FileReader(new File(""input""))); BufferedWriter bw = new BufferedWriter(new FileWriter(new File(""output""))); int num = Integer.parseInt(bf.readLine()); String aString = ""123""; for (int i = 1 ; i<=num; i++){ int nums = 0; String line = bf.readLine(); String[] argss =line.split("" ""); int small = Integer.parseInt(argss[0]); int large = Integer.parseInt(argss[1]); HashSet already = new HashSet(); for (int j = small; j< large; j++){ if (j<10) continue; already.clear(); already.add(j); String temp = String.valueOf(j); for (int k = 1; k < temp.length(); k++){ int m = k; int newnum = j/(int)(Math.pow(10, temp.length()-k)); newnum+= (j%(int)(Math.pow(10, temp.length()-k)))*Math.pow(10, k); if (!already.contains(newnum)&&newnum<=large&&newnum>=small&&newnum>j){ nums++; already.add(newnum); } } if (j == 1221) System.out.println(already.toString()); } bw.write(""Case #""+i+"": ""+nums+""\n""); } bf.close(); bw.close(); } } " B12865,"import static java.lang.Double.parseDouble; import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.System.exit; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; public class C { static BufferedReader in; static PrintWriter out; static StringTokenizer tok; static int test; static void solve() throws Exception { long a = nextInt(); long b = nextInt(); long p10 = 10; long pp10 = 1; long ans = 0; for (long i = a; i <= b; i++) { while (p10 <= i) { pp10 = p10; p10 *= 10; } for (long x = 10, y = pp10; y > 1; x *= 10, y /= 10) { long ii = i % x * y + i / x; if (ii > i && ii <= b) { ++ans; } else if (ii == i) { break; } } } printCase(); out.println(ans); } static void printCase() { out.print(""Case #"" + test + "": ""); } static void printlnCase() { out.println(""Case #"" + test + "":""); } static int nextInt() throws IOException { return parseInt(next()); } static long nextLong() throws IOException { return parseLong(next()); } static double nextDouble() throws IOException { return parseDouble(next()); } static String next() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } public static void main(String[] args) { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); int tests = nextInt(); for (test = 1; test <= tests; test++) { solve(); } in.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); exit(1); } } }" B11277,"package problemc; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { int T = 1; String G = """"; String[] inputs; BufferedReader reader; reader = new BufferedReader(new InputStreamReader(System.in)); try { T = Integer.parseInt(reader.readLine()); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } StringBuffer buffer = new StringBuffer(); for (int X = 1; X <= T; X++) { try { G = reader.readLine(); inputs = G.split("" ""); int A = Integer.parseInt(inputs[0]); int B = Integer.parseInt(inputs[1]); int result = 0; int n; int m; Map pairs = new HashMap(); for (int i = A; i <= B; i++) { int x = 10; int shift = Integer.toString(i).length(); while (i % x < i) { shift--; if (i % x >= x / 10) { n = i; m = i % x; for (int j = 0; j < shift; j++) { m = m * 10; } m += (i / x); if (n >= m) { x = x * 10; continue; } if (m <= B) { if (pairs.get(n) == null || !pairs.get(n).equals(m)) { result++; pairs.put(n, m); // System.out.println(n+"", ""+m); } } } x = x * 10; } } buffer.append(""Case #"").append(X).append("": "").append(result) .append(""\r\n""); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println(buffer.toString()); } } " B11038,"import java.util.*; public class c{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int T = sc.nextInt(); long[] powers = new long[10]; for(int j = 0; j<10; j++){ powers[j]=(long)Math.pow(10,j); } for(int tt = 1; tt<=T; tt++){ int a =sc.nextInt(); int b =sc.nextInt(); int val=0; for(int i = a; i set = new HashSet(); for(int j = 1; ji && s3<=b&& !set.contains(s3)){ val+=1; } set.add(s3); } } System.out.println(""Case #""+tt+"": ""+val); } } } " B12407,"package de.pat.dev.y2012.qualification.c; import java.util.*; /** * @author pat.dev@alice.de */ public class RecycledNumber { private final long lower; private final long upper; private final long rotationFactor; public RecycledNumber(long lower, long upper) { this.lower = lower; this.upper = upper; int numberOfDigits = String.valueOf(lower).length(); rotationFactor = rotationFactor(numberOfDigits); } private long rotationFactor(int numberOfDigits) { long factor = 1; for (int i = 1; i < numberOfDigits; i++) { factor *= 10; } return factor; } public Set pairs() { Set pairs = new HashSet(); for (long number = lower; number <= upper; number++) { Set rotations = rotations(number); for (Long rotation : rotations) { pairs.add(new Pair(number, rotation)); } } return pairs; } public Set rotations(long number) { if (rotationFactor == 1) { return Collections.emptySet(); } Set rotations = new HashSet(); long rotation = rotate(number); while (rotation != number) { if (rotation > number && rotation <= upper) { rotations.add(rotation); } rotation = rotate(rotation); } return rotations; } private long rotate(long number) { long lastDigit = number % 10; return number / 10 + lastDigit * this.rotationFactor; } public static final class Pair { public final long m; public final long n; public Pair(long m, long n) { this.m = m; this.n = n; } @Override public String toString() { return ""Pair{"" + ""m="" + m + "", n="" + n + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Pair)) return false; Pair pair = (Pair) o; if (m != pair.m) return false; if (n != pair.n) return false; return true; } @Override public int hashCode() { int result = (int) (m ^ (m >>> 32)); result = 31 * result + (int) (n ^ (n >>> 32)); return result; } } } " B12557,"import java.util.Scanner; public class RecNum { public static void main(String[] args) { Scanner reader = new Scanner (System.in); int nCases = reader.nextInt(); for(int i=1; i<=nCases; i++) { int A = reader.nextInt(); int B = reader.nextInt(); int digits = 0; int nPair = 0; int tmp = A; while(tmp > 0) { digits++; tmp = tmp/10; } for(int j=A; j<=B; j++) { for(int k=1; kj && newInt<=B) { nPair++; } } } System.out.println(""Case #"" + i + "": "" + nPair); } } } " B11745,"package codejam; import java.io.*; import java.util.HashSet; import java.util.Set; /** * @author Dmitry Korolev */ public class Task3 { public static void main(String[] args) throws IOException { Reader inputReader = new FileReader(""C-small-attempt0.in""); Writer outputWriter = new FileWriter(""C-small-attempt0.out""); BufferedReader in = new BufferedReader(inputReader); BufferedWriter out = new BufferedWriter(outputWriter); String numStr = in.readLine(); int n = Integer.parseInt(numStr); for (int i = 0; i < n; i++) { String line = in.readLine(); String[] strs = line.split(""\\s""); int a = Integer.valueOf(strs[0]); int b = Integer.valueOf(strs[1]); out.write(""Case #"" + (i+1) + "": "" + count(a, b) + ""\n""); } in.close(); out.close(); assert count(1, 9) == 0; assert count(10, 40) == 3; assert count(100, 500) == 156; assert count(1111, 2222) == 287; } private static int count(int a, int b) { int length = Integer.toString(a).length(); Set pairs = new HashSet<>(); for (int x = a; x < b; x++) { for (int n = 1; n < length; n++) { int r = rotate(x, n); if (r > x && r <= b) { pairs.add((long) (x * 3000000 + r)); } } } return pairs.size(); } private static int rotate(int a, int n) { String number = Integer.toString(a); String head = number.substring(0, n); String tail = number.substring(n); return Integer.parseInt(tail + head); } } " B11593,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.StringTokenizer; public class Main { public static void main(String[] args){ StringBuffer fileData = new StringBuffer(1000000); BufferedReader reader = null; try { reader = new BufferedReader( new FileReader(""C-small-attempt0.in"")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } char[] buf = new char[1024]; int numRead=0; try { while((numRead=reader.read(buf)) != -1){ String readData = String.valueOf(buf, 0, numRead); fileData.append(readData); buf = new char[1024]; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } BufferedWriter out = null; try { out = new BufferedWriter(new FileWriter(""result.txt"")); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String inputString=fileData.toString(); StringTokenizer st=new StringTokenizer(inputString); int noOfcase=Integer.parseInt(st.nextToken()); for(int i=1;i<=noOfcase;i++){ int A=Integer.parseInt(st.nextToken()); int B=Integer.parseInt(st.nextToken()); String B_string=String.valueOf(B); int B_length=B_string.length(); int max=0; for(int n=A;nn && m<=B){ local_max++; } } if(local_max > 0 && n_length%2==0){ if(n_string.substring(0, n_length/2).equals(n_string.substring(n_length/2, n_length))) local_max/=2; } max+=local_max; n_string=""0""+n_string; } } try { out.write(""Case #""+i+"": ""+max); out.newLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B12650,"//lukewillson import java.io.PrintStream; import java.io.File; import java.util.Scanner; public class C { public static void main(String[] args) throws Exception { new DoC(); } } class DoC { public DoC() throws Exception { //long time=System.currentTimeMillis(); System.setOut(new PrintStream(new File(""C.out""))); Scanner sc = new Scanner(new File(""C-small-attempt0.in"")); int runs = Integer.parseInt(sc.nextLine()); int run = 0; while (run++ < runs) { System.out.print(""Case #"" + run + "": ""); int min=sc.nextInt(); int max=sc.nextInt(); int count=0; for(int i=min;i<=max;++i) { for(int j=i+1;j<=max;++j) { if(recycle(i,j)) count++; } } System.out.println(count); } //System.out.println(System.currentTimeMillis()-time); } public boolean recycle(int A,int B) { String a=""""+A; String b=""""+B; for(int i=0;i A; m--) { for(int n = A; n < m; n++) { if(isRecycled(n,m)) counter++; } } System.out.print(""Case #"" + l + "": "" + counter); System.out.println(); } } public static boolean isRecycled(int n, int m) { String str = Integer.toString(n); if(Integer.toString(n).length() != Integer.toString(m).length()) return false; else { for(int k = 1; k < str.length(); k++) { String temp = """"; temp = str.substring(str.length() - k, str.length()) + str.substring(0, str.length() - k); if(m == Integer.parseInt(temp)) return true; } } return false; } }" B11191,"package codejam.c; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Set; import codejam.TestCaseReader; public class Main { public static void main(String[] args) { TestCaseReader reader = new TestCaseReader(""in.txt"") { @Override protected int[] parseTestCase(String line) { String[] splitted = line.split(""\\s""); return new int[] { Integer.parseInt(splitted[0]), Integer.parseInt(splitted[1]) }; } }; BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(new File(""out.txt""))); } catch (IOException e) { e.printStackTrace(); } int testCases = reader.getTestCases(); int[] testCase = null; for (int i = 0; i < testCases; i++) { testCase = reader.getNextTestCase(); long result = Main.solveCase(testCase[0], testCase[1]); try { writer.write(""Case #"" + (i + 1) + "": "" + result); writer.newLine(); } catch (IOException e) { e.printStackTrace(); } } try { writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } private static long solveCase(int a, int b) { char[] bArray = Main.converToCharArray(b); Set counted = new HashSet(); for (int num = a; num <= b; num++) { char[] numArray = Main.converToCharArray(num); char[] numArrayPair = Main.converToCharArray(num); for (int i = 0; i < numArray.length - 1; i++) { Main.rotateCharArray(numArrayPair); if (Main.compare(numArrayPair, bArray) <= 0 && Main.compare(numArray, numArrayPair) < 0) { String pair = new String(numArray) + new String(numArrayPair); if (!counted.contains(pair)) { counted.add(pair); } } } } return counted.size(); } private static char[] converToCharArray(int num) { return new Integer(num).toString().toCharArray(); } private static void rotateCharArray(char[] array) { char tmp = array[array.length - 1]; for (int i = array.length - 1; i > 0; i--) { array[i] = array[i - 1]; } array[0] = tmp; } private static int compare(char[] a, char[] b) { for (int i = 0; i < a.length; i++) { if (a[i] < b[i]) { return -1; } else if (a[i] > b[i]) { return 1; } } return 0; } } " B11338,"import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { final static String FILENAME = ""C-small-attempt0""; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new FileReader(""/home/workshop/Documents/"" + FILENAME + "".in"")); BufferedWriter bw = new BufferedWriter(new FileWriter( ""/home/workshop/Documents/"" + FILENAME + "".out"")); int T = sc.nextInt(); sc.nextLine(); for (int ttt = 0; ttt < T; ttt++) { int A = sc.nextInt(); int B = sc.nextInt(); int count = 0; int digits = new Double(Math.floor(Math.log10(A) + 1)).intValue(); for (int num = A; num < B; num++) { Set hs = new HashSet(); for (int lastdigits = 1; lastdigits < digits; lastdigits++) { int tailmask = new Double(Math.pow(10, lastdigits)) .intValue(), headmask = new Double(Math.pow(10, digits - lastdigits)).intValue(); int newnum = num / tailmask + (num % tailmask) * headmask; if (num < newnum && !hs.contains(newnum) && newnum <= B) { // System.out.println(num + ""\t"" + newnum); count++; hs.add(newnum); } } // if (y < z) { // System.out.println(num + ""\t(1)""); // count++; // } // if (x < z || (x == z && x > y)) { // System.out.println(num + ""\t(2)""); // count++; // } // if (x < y && y != z) { // System.out.println(num + ""\t(3)""); // count++; // } // if (x < y && x != z) { // System.out.println(num + ""\t(4)""); // count++; // } // if (x < z || (x == z && x > y)) { // int newnum = z * 100 + x * 10 + y; // if (newnum <= B) { // System.out.println(num + ""\t"" + newnum + ""\t(2)""); // count++; // } // } // if (x < y || (x == y && y < z)) { // int newnum = y * 100 + z * 10 + x; // if (newnum <= B) { // System.out.println(num + ""\t"" + newnum + ""\t(4)""); // count++; // } // } } bw.write(""Case #"" + (ttt + 1) + "": "" + count); bw.newLine(); } bw.close(); sc.close(); } } " B11783,"package com.gcj2012.qr; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; public class ProblemC { private int caseNum = -1; private ArrayList testCases = new ArrayList(); private class Pair{ private int m; private int n; } private class Case{ private int A = 0; private int B = 0; private int digitNum = 0; private ArrayList pairs = new ArrayList(); } private void readDataFromFile(String fileName) throws IOException{ BufferedReader reader = new BufferedReader(new FileReader(ProblemC.class.getClassLoader().getResource(fileName).getPath().replaceAll(""%20"", "" ""))); String line = null; boolean isFirstLineRead = false; while ((line=reader.readLine()) != null) { if(!isFirstLineRead){ caseNum = Integer.valueOf(line); isFirstLineRead = true; }else{ String[] testCaseLine = line.split("" ""); Case testCase = new Case(); testCase.A = Integer.valueOf(testCaseLine[0]).intValue(); testCase.B = Integer.valueOf(testCaseLine[1]).intValue(); testCase.digitNum = testCaseLine[0].length(); this.testCases.add(testCase); } } reader.close(); } private boolean checkDuplicate(int curCase, int m, int n){ int size = this.testCases.get(curCase).pairs.size(); for(int i=0;i= testCases.get(i).A && j < resultInt && resultInt <= testCases.get(i).B){ if(!checkDuplicate(i,j,resultInt)){ recycleCount++; //System.out.println(""COUNT int: ""+resultInt); } //System.out.println(""COUNT""); } } } System.out.println(""Case #""+(i+1)+"": ""+recycleCount); } } private int moveDigitsForward(int inputInt, int numOfDigits){ String inputString = String.valueOf(inputInt); if(inputString.length() > 1){ String digitToMove = inputString.substring(inputString.length()- numOfDigits, inputString.length()); String digitToStay = inputString.substring(0, inputString.length() - numOfDigits); String resultString = digitToMove+digitToStay; if(String.valueOf(Integer.valueOf(resultString).intValue()).length() == inputString.length()){ return Integer.valueOf(resultString).intValue(); } return -1; }else{ return inputInt; } } public static void main(String[] args) { ProblemC c = new ProblemC(); try { c.readDataFromFile(""C-small-attempt0.in""); c.processCases(); } catch (IOException e) { e.printStackTrace(); } } } " B11217,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; public class Main { public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new FileReader(""C-small-attempt1.in"")); PrintWriter bw = new PrintWriter(new FileWriter(""C-small-attempt1.out"")); int num = Integer.parseInt(br.readLine()); for (int i = 0; i < num; i++) { String[] content=br.readLine().split(""[ ]""); int start=Integer.parseInt(content[0]); int end=Integer.parseInt(content[1]); int count=0; for (int j = start; j content = new ArrayList(); try { BufferedReader bis = new BufferedReader(new FileReader(filePath)); String current = null; while ((current = bis.readLine()) != null && current.length() > 0) { content.add(current); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return content.toArray(new String[content.size()]); } public static int getNumOfTestCases(String[] content) { // for code jam, it's in first line assert content != null; String numStr = content[0]; return Integer.parseInt(numStr); } public static String[] getAllTestCases(String[] content) { assert content != null; int len = content.length; String[] testCases = new String[len - 1]; for (int i = 0; i < len - 1; i++) { testCases[i] = content[i + 1]; } return testCases; } public static String formatTestResult(int index, String result) { assert result != null; return String.format(""Case #%1$d: %2$s"", index + 1, result); } public static void writeTestResult(String fileName, String[] results) { try { FileWriter fstream = new FileWriter(fileName); BufferedWriter out = new BufferedWriter(fstream); for (String result : results) { out.write(result + ""\n""); } out.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } public static long toNumber(String in) { return Long.valueOf(in); } public static long toNumber(char ch) { return toNumber(Character.toString(ch)); } public static char toChar(String in) { char[] chars = in.toCharArray(); if (chars.length <= 0) { return 0; } return chars[0]; } public static boolean isNumber(String in) { try { Integer.parseInt(in); return true; } catch (Exception e) { return false; } } public static String join(char[] chars, String delimiter) { int len = chars.length; String[] strArr = new String[len]; for (int i = 0; i < len; i++) { strArr[i] = Character.toString(chars[i]); } return join(strArr, delimiter); } public static String join(String[] strs, String delimiter) { int len = strs.length; StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i++) { if (sb.length() > 0) { sb.append(delimiter).append(strs[i]); } else { sb.append(strs[i]); } } return ""["" + sb.toString() + ""]""; } public static class Timer { private static long timestamp = System.currentTimeMillis(); public static void start() { Timer.timestamp = System.currentTimeMillis(); } public static void stop() { long current = System.currentTimeMillis(); long pass = current - timestamp; System.out.println(""total: "" + pass + "" ms""); } } } " B11800," import java.awt.Point; import java.io.*; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class ProblemC_Qual_2012 implements Runnable{ BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""""); void init() throws FileNotFoundException{ in = new BufferedReader(new FileReader(""C-small-attempt0.in"")); out = new PrintWriter(""output.txt""); } String readString() throws IOException{ while(!tok.hasMoreTokens()){ try{ tok = new StringTokenizer(in.readLine()); }catch (Exception e){ return null; } } return tok.nextToken(); } int readInt() throws IOException{ return Integer.parseInt(readString()); } long readLong() throws IOException{ return Long.parseLong(readString()); } double readDouble() throws IOException{ return Double.parseDouble(readString()); } public static void main(String[] args){ new Thread(null, new ProblemC_Qual_2012(), """", 256 * (1L << 20)).start(); } long timeBegin, timeEnd; void time(){ timeEnd = System.currentTimeMillis(); System.err.println(""Time = "" + (timeEnd - timeBegin)); } long memoryTotal, memoryFree; void memory(){ memoryFree = Runtime.getRuntime().freeMemory(); System.err.println(""Memory = "" + ((memoryTotal - memoryFree) >> 10) + "" KB""); } void debug(Object... objects){ if (DEBUG){ for (Object o: objects){ System.err.println(o.toString()); } } } public void run(){ try{ timeBegin = System.currentTimeMillis(); memoryTotal = Runtime.getRuntime().freeMemory(); init(); solve(); out.close(); time(); memory(); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } boolean DEBUG = false; void solve() throws IOException{ int t = readInt(); for (int it = 1; it <= t; it++){ out.print(""Case #"" + it + "": ""); int a = readInt(); int b = readInt(); boolean[] used = new boolean[b+1]; int x = a; int pow = 1; while (x >= 10){ x /= 10; pow *= 10; } long res = 0; for (int i = a; i <= b; i++){ if (used[i]) continue; x = i; long count = 0; do{ if (x / pow != 0 && x >= a && x <= b){ used[x] = true; count++; } x = x % pow * 10 + (x / pow); }while (x != i); used[i] = true; res += (count - 1) * count / 2; } out.println(res); } } } " B12529,"import java.util.ArrayList; /** * Created with IntelliJ IDEA. * User: student * Date: 4/14/12 * Time: 6:40 PM * To change this template use File | Settings | File Templates. */ public class Recycled { private static ArrayList validNumbers; private static int lower; private static int upper; public static void main(String[] args) { doProblems(""50\n"" + ""13 35\n"" + ""147 992\n"" + ""116 940\n"" + ""129 926\n"" + ""130 961\n"" + ""56 58\n"" + ""882 882\n"" + ""143 642\n"" + ""163 958\n"" + ""358 767\n"" + ""113 980\n"" + ""167 914\n"" + ""1 2\n"" + ""164 920\n"" + ""185 954\n"" + ""132 929\n"" + ""150 999\n"" + ""183 992\n"" + ""123 997\n"" + ""190 990\n"" + ""184 937\n"" + ""214 517\n"" + ""177 927\n"" + ""118 983\n"" + ""117 980\n"" + ""382 382\n"" + ""178 999\n"" + ""145 958\n"" + ""149 930\n"" + ""188 915\n"" + ""119 996\n"" + ""109 975\n"" + ""148 912\n"" + ""176 980\n"" + ""184 937\n"" + ""142 991\n"" + ""164 935\n"" + ""100 100\n"" + ""134 999\n"" + ""144 986\n"" + ""185 972\n"" + ""4 4\n"" + ""101 934\n"" + ""118 953\n"" + ""180 926\n"" + ""116 969\n"" + ""100 999\n"" + ""147 998\n"" + ""161 973\n"" + ""10 99\n""); } public static void doProblems(String input) { String[] problems = input.split(""\n""); for (int count = 0; count < Integer.valueOf(problems[0]); count++) { doProblem(problems[count + 1], count + 1); } } public static void doProblem(String input, int problemNumber) { validNumbers = new ArrayList(); String[] array = input.split("" ""); lower = Integer.valueOf(array[0]); upper = Integer.valueOf(array[1]); if (upper < 10) { System.out.println(""Case #"" + problemNumber + "": "" + 0); return; } for (int count = lower; count < upper; count++) { doNumber(count); } System.out.println(""Case #"" + problemNumber + "": "" + validNumbers.size()); } private static void doNumber(int n) { String current = String.valueOf(n); String nString = String.valueOf(n); for (int count = 0; count < nString.length(); count++) { // System.out.println(nString + "" "" + current + "" "" + count); int m = Integer.valueOf(current); if (m > n && m <= upper) { // System.out.println(""KJAWHEKJHAFKJHASKJITUAW""); String entry = nString + "" "" + current; if (!validNumbers.contains(entry)) { validNumbers.add(entry); } } current = current.substring(current.length() - 1, current.length()) + current.substring(0, current.length()-1); } } } " B12102,"import java.util.Scanner; import java.io.*; public class Recycled { public static void main(String[] args) throws FileNotFoundException, IOException { Scanner input = new Scanner(new File(args[0])); Scanner lin; int lines = 0; if (input.hasNextInt()) { lines = input.nextInt(); input.nextLine(); } String nLine; String numtostr; int tonumber; int count; int strl; int a, b; int addednums[]; boolean didrepeat; PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""output.txt""))); for (int i = 0; i < lines; i++) { nLine = input.nextLine(); lin = new Scanner(nLine); out.print(""Case #"" + (i + 1) + "": ""); a = lin.nextInt(); b = lin.nextInt(); count = 0; for (int k = a; k <= b; k++) { numtostr = """" + k; strl = numtostr.length(); addednums = new int[strl]; for (int j = 0; j < strl; j++) { didrepeat = false; tonumber = Integer.parseInt(numtostr.substring(j, strl) + numtostr.substring(0, j)); addednums[j] = tonumber; for (int l = 0; l < j; l++) { if (tonumber == addednums[l]) didrepeat = true; } if (k > tonumber && tonumber >= a && didrepeat == false) { count++; } } } out.println(count); } out.close(); } }" B10561,"package com.googlerese.core; import java.util.HashMap; import java.util.Map; import java.util.Set; import com.googlerese.file.FileRead; import com.googlerese.file.FileWrite; public class NumberRecycler { private static final String inputFileName = ""C:/Documents and Settings/garan14/Desktop/input.txt""; private static final String outputFileName = ""C:/Documents and Settings/garan14/Desktop/out.txt""; private static int divider = 1; public static void main( String[] args ) { NumberRecycler convertor = new NumberRecycler(); Map input = FileRead.getInstance().read( inputFileName ); int testCases = input.size(); Map output = new HashMap( testCases ); for ( int i = 1; i <= testCases; i++ ) { String[] arr = input.get( i ); String outputStr = convertor.convert( Integer.parseInt( arr[0] ), Integer.parseInt( arr[1] ) ); System.out.println( ""Output : "" + outputStr ); output.put( i, outputStr ); } FileWrite.getInstance().write( outputFileName, output ); } private String convert( final int start, final int end ) { int count = 0; for ( int i = start; i <= end; i++ ) { if ( i > 0 && i < 10 ) { divider = 1; } else if ( i > 9 && i < 100 ) { divider = 10; } else if ( i > 99 && i < 1000 ) { divider = 100; } else if ( i > 999 & i < 10000 ) { divider = 1000; } else if ( i > 9999 & i < 100000 ) { divider = 10000; } else if ( i > 99999 & i < 1000000 ) { divider = 100000; } int num = i; do { int rem = num % 10; num = num / 10; num = rem * divider + num; if ( num > i && num <= end ) { count++; } } while ( i != num ); } return """" + count; } } " B13254,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.HashSet; public class ProblemB { static HashSet pairs = new HashSet(); public static void main(String args[]) { ReadInFile(); } private static void ReadInFile() { try { FileWriter ofstream = new FileWriter(""c:/cygwin/out.txt""); BufferedWriter out = new BufferedWriter(ofstream); // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream( ""c:/cygwin/C-small-attempt1.in""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; // Read File Line By Line int i = 0; strLine = br.readLine(); while ((strLine = br.readLine()) != null) { pairs.clear(); // Print the content on the console System.out.println(strLine); String[] tokens = strLine.split(""\\s+""); System.out.println(""Case #"" + (++i) + "": "" + ReturnCount(Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1]))); out.write(""Case #"" + (i) + "": "" + ReturnCount(Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1])) + ""\n""); } // Close the input stream in.close(); out.close(); } catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } static int ReturnCount(int n, int m) { HashSet cycles = new HashSet(); for (int i = n; i <= m; i++) { // if (!cycles.contains(i)) cycles.addAll(GetCycles(i, n, m)); } return pairs.size(); } static private HashSet GetCycles(int in, int n, int m) { String s = String.valueOf(in); HashSet out = new HashSet(); for (int i = 0; i < s.length(); i++) { String sub1 = s.subSequence(0, i + 1).toString(); String sub2 = s.subSequence(i + 1, s.length()).toString(); int permutation = Integer.parseInt(sub2 + sub1); out.add(permutation); } for (int i : out) if (i >= n && i <= m && i > in) { pairs.add(in + "","" + i); // return out; } return out; } } " B13011,"import java.io.*; import java.util.*; class Replace { public static void main(String args[])throws Exception { //Scanner sc = new Scanner(System.in); // PrintWriter pw = new PrintWriter(System.out); Scanner sc = new Scanner(new FileReader(""C-small-attempt3.in"")); //Console console=System.console(new FileReader(""B-small-practice-1.in"")); PrintWriter pw = new PrintWriter(new FileWriter(""C-small-attempt3.out"")); int ntest = sc.nextInt(); //int a=100; //int b=500; for(int k=1;k<=ntest;k++) { int sum=0; int count=0; //int a=Integer.parseInt(sc.next()); //int b=Integer.parseInt(sc.next()); int a=sc.nextInt(); int b=sc.nextInt(); for(int i=a;i<=b;i++) { if(i>0 && i<100) { int rem=i%10; sum=rem*10+i/10; if(sum==i) { } else if(sum>=a && sum<=b) { count++; System.out.println(i); //System.out.println(""garg""); } } if(i>=100 && i<1000) { int rem=i%100; sum=rem*10+i/100; //System.out.println(i); if(sum==i) { } else if (sum>=a && sum<=b) { count++; //System.out.println(i); } //System.out.println(""lucky""); rem=i%10; sum=rem*100+i/10; if(sum==i) { } else if(sum>=a && sum<=b) { count++; //System.out.println(i); //System.out.println(""garg""); } } } pw.print(""Case #"" + k + "": ""); pw.print(count/2); pw.println(); } pw.close(); sc.close(); } }" B10450,"package MyAllgoritmicLib; public class NOK { public static int lcm (int a, int b) { return a * b / NOD.gcd (a, b); } public static long lcm (long a, long b) { return a * b / NOD.gcd (a, b); } public static double lcm (double a, double b) { return a * b / NOD.gcd (a, b); } } " B11826,"package gcj.y2012.qual; import java.io.*; import java.util.*; public class C { private static String fileName = C.class.getSimpleName().replaceFirst(""_.*"", """").toLowerCase(); private static String inputFileName = fileName + "".in""; private static String outputFileName = fileName + "".out""; private static Scanner in; private static PrintWriter out; private void solve() { int from = in.nextInt(); int to = in.nextInt(); int n = ("""" + to).length(); int ten = (int) Math.pow(10, n - 1); int ans = 0; Set recycled = new HashSet(); for (int a = from; a <= to; a++) { int b = a; for (int j = 1; j < n; j++) { int d = b % 10; b = (b / 10) + d * ten; if (a < b && b <= to) { recycled.add(b); } } ans += recycled.size(); recycled.clear(); } out.println(ans); } public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); if (args.length >= 2) { inputFileName = args[0]; outputFileName = args[1]; } in = new Scanner(new FileReader(inputFileName)); out = new PrintWriter(outputFileName); int tests = in.nextInt(); in.nextLine(); for (int t = 1; t <= tests; t++) { out.print(""Case #"" + t + "": ""); new C().solve(); System.out.println(""Case #"" + t + "": solved""); } in.close(); out.close(); } } " B12466,"import java.util.*; import java.io.*; public class B { private static boolean isRecyclePair(int n, int m){ String n_str=""""+n; String m_str=""""+m; for(int i=0; i k * 10) { p++; k *= 10; } long res = 0; for(int i = a; i <= b; i++) { //System.out.println(""in "" + i); if (u[i]) { //System.out.println("" skipped""); continue; } u[i] = true; if (i == k * 10) { p++; k *= 10; } // System.out.println("" p = "" + p); int ll = 1; int ii = i; for (int j = 0; j < p; j++) { ii = (ii / 10) + (ii % 10) * k; //System.out.println("" found "" + ii); if (a <= ii && ii <= b) { if (u[ii]) continue; //System.out.println("" ok""); u[ii] = true; ll++; } } //System.out.println("" ll = "" + ll); res += ll * (ll - 1) / 2; } out.println(""Case #"" + test + "": "" + res); } out.close(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { new Recycled().run(); } } " B10299,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class Learn { static void one(Object s) { System.out.print(""Object""); } static void one(List s) { System.out.print(""String""); } public static void main(String[] s) throws IOException { // one(null); FileInputStream fstream = new FileInputStream(""q.txt""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; // Read File Line By Line int tc; tc = Integer.parseInt(br.readLine()); for (int o = 0; o < tc; o++) { String line = br.readLine(); int n = Integer.parseInt(line.split("" "")[0]); int m = Integer.parseInt(line.split("" "")[1]); int res = 0; String s1, s2 = null; List l = new ArrayList(); for (int i = n + 1; i <= m; i++) { s1 = Integer.toString(i); for (int j = 1; j < s1.length(); j++) { String s3 = s1.substring(0, j); String s4 = s1.substring(j, s1.length()); String s5 = s4 + s3; if (s5.indexOf(""0"") == 0) continue; int y = Integer.parseInt(s5); String va = i + ""&"" + y; if (l.contains(va)) continue; l.add(va); if (y != i && y <= m && y >= n) { res++; } } } System.out.println(""Case #"" + (o+1) + "": ""+ res / 2); // Close the input stream in.close(); } } } " B12706,"import java.util.*; import java.math.*; import java.io.*; public class Main { public static void main(String args[]) throws IOException { Scanner c=new Scanner(System.in); int T=c.nextInt(); for(int i=0;i Tr=new TreeSet(); for(int j=1;jnum&&got>=A&&got<=B) Tr.add(got); } ans+=Tr.size(); } System.out.println(""Case #1: ""+ans); } } } //must declare new classes here" B10617,"package ProblemSolvers; import Controller.IO; public abstract class ProblemSolver { protected IO io; protected int cases; public ProblemSolver(String filePath) { io = new IO(filePath); } public abstract void process(); } " B13066,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class Recycled { private static boolean contains(List results, int result){ for(int i = 0; i < results.size(); i++){ if(results.get(i) == result){ return true; } } return false; } public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new FileReader(""A-small-practice.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""A-small-practice.out""))); StringTokenizer st = new StringTokenizer(f.readLine()); int tests = Integer.parseInt(st.nextToken()); for (int t = 1; t <= tests; t++){ out.printf(""Case #%d:"", t); st = new StringTokenizer(f.readLine()); int count = 0; String a = st.nextToken(); String b = st.nextToken(); for(int i = Integer.parseInt(a); i < Integer.parseInt(b); i++){ String m = Integer.toString(i); for(int j = 1; j < m.length(); j++){ int n = 0; List results = new ArrayList(); if(m.length() - j - 1 > 0){ n = Integer.parseInt(m.substring(m.length() - j) + m.substring(0, m.length() - j)); } else { n = Integer.parseInt(m.substring(m.length() - j) + m.charAt(0)); } if (n > Integer.parseInt(m) && Integer.parseInt(b) >= n && !contains(results, n)){ results.add(n); count++; } } } out.printf("" %d\n"", count); } out.close(); System.exit(0); } } " B12838,"/* ID: 14vikra1 LANG: JAVA TASK: recycled */ import java.io.*; import java.util.*; class recycled { public static void main (String [] args) throws IOException { long start = System.currentTimeMillis(); BufferedReader br = new BufferedReader(new FileReader(""recycled.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""recycled.out""))); int T = Integer.parseInt(br.readLine()); for (int i = 0; i < T; i++) { StringTokenizer st = new StringTokenizer(br.readLine()); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); int pairs = 0; int size = (int)(Math.floor(Math.log(A)/Math.log(10)))+1; for (int j = A; j < B; j++) { pairs += checkPairs(j, A, B, size); } out.println(""Case #"" + (i+1) + "": "" + pairs); } long end = System.currentTimeMillis(); System.out.println(end-start); out.close(); System.exit(0); } public static int checkPairs(int num, int A, int B, int size) { int numpairs = 0; ArrayList used = new ArrayList(); for (int i = 1; i < size; i++) { int move = (int)(num%Math.pow(10, i)); int test = (int)((num)/Math.pow(10,size-i+1)); if (move >= test) { int newnum = (int)((num - move)/Math.pow(10,i)); newnum = newnum + move*(int)(Math.pow(10,size-i)); if (newnum > num && newnum <= B && !used.contains(newnum)) { numpairs++; used.add(newnum); } } } return numpairs; } } " B12290,"import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStreamReader; public class Recycled { /** * @param args */ public static void main(String[] args) { try { System.setIn(new FileInputStream(""../C-small-attempt0.in"")); } catch (FileNotFoundException e) { e.printStackTrace(); System.exit(0); } InputStreamReader inp = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(inp); String line = """"; int inputs = 0; try{ line = br.readLine(); inputs = Integer.parseInt( line ); } catch(Exception x){ System.err.println(x); System.exit(1); } String[] data = {}; for(int i=0; i < inputs; i++){ int count = 0; try{ line = br.readLine(); data = line.split("" ""); } catch(Exception x){ System.err.println(x); System.exit(1); } int a = Integer.parseInt(data[0]); int b = Integer.parseInt(data[1]); for(int n=a; n < b; n++){ String m = """"+n; String[] dup = new String[data[0].length()]; int next = 0; //position to insert into dup for(int k=0; k < data[0].length(); k++){ m = Recycled.shuffle(m); if(a <= n && n < Integer.parseInt(m) && Integer.parseInt(m) <= b){ boolean found = false; for(int x=0; x input = new ArrayList(); SortedSet numbersFound = new TreeSet(); FileInputStream fstream = new FileInputStream(inputFilename); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine = """"; while ((strLine = br.readLine()) != null) { input.add(strLine); } in.close(); System.out.println(""Input:""); for (int i = 0; i < input.size(); i++) System.out.println(input.get(i)); System.out .println(""\n------------------------------------------\n""); // write to file FileWriter fwriter = new FileWriter(outputFilename); BufferedWriter bwriter = new BufferedWriter(fwriter); System.out.println(""Output""); for (int i = 1; i < input.size(); i++) { String inputVal[] = input.get(i).split("" ""); int A = Integer.parseInt(inputVal[0]); int B = Integer.parseInt(inputVal[1]); System.out.print(""Case #"" + i + "": ""); bwriter.write(""Case #"" + i + "": ""); for (int num = A; num <= B; num++) { for (int j = 1; j < (num + """").length(); j++) { String xStr = (num + """").substring(j); String yStr = (num + """").substring(0, j); int x = Integer.parseInt(xStr); int y = Integer.parseInt(yStr); String yxStr = xStr + """" + yStr; int yx = Integer.parseInt(yxStr); if (yx != num) if (checkNumber(yx, A, B)) { numbersFound.add(""[""+ num + "", "" + yx + ""]""); } } } System.out.print(numbersFound.size()/2 + """"); bwriter.write(numbersFound.size()/2 + """"); numbersFound.clear(); System.out.println(); bwriter.newLine(); } bwriter.close(); System.out.println(""Check output file..""); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public static boolean checkNumber(int x, int A, int B) { boolean checked = false; if (x >= A && x <= B) checked = true; return checked; } public static void printArray(String arr[]) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + "" ""); } } } " B10703,"import java.io.*; import java.util.Collections; public class C { public static void main (String[] args) { int[][] numbers = new int[1001][5]; try { BufferedReader reader = new BufferedReader (new InputStreamReader(System.in)); String line = reader.readLine(); int testCases = Integer.parseInt (line.trim()); for (int i = 0; i < testCases; i++) { numbers = new int[1001][5]; line = reader.readLine(); line.trim(); String[] nums = line.split ("" ""); int a = Integer.parseInt(nums[0]); int b = Integer.parseInt(nums[1]); for (int j = a; j <= b; j++) { String str = Integer.toString(j); //System.out.print (str + "" ""); int numDigits = str.length(); char[] digits = str.toCharArray(); reverseSort (digits); String sortedStr = new String (digits); int sortedInt = Integer.parseInt (sortedStr); numbers[sortedInt][numDigits] ++; } int numFound = 0; for (int j = 0; j < 1001; j++) { for (int k = 0; k < 5; k++) { if (numbers[j][k] > 1) { //System.out.println ("" found one at "" + numbers[j][k] + "" comb is "" + getCombination (numbers[j][k])); //System.out.println (""j is "" + j + "" k is "" + k); numFound += getCombination(numbers[j][k]); } } } System.out.println (""Case #"" + (i+1) + "": "" + numFound); } } catch (Exception e) { System.out.println (e); } } static void reverseSort (char[] digits) { int indexLargest = 0; for (int i = 1; i < digits.length; i++) { if (digits[i] > digits[indexLargest]) { indexLargest = i; } } while (indexLargest != 0) { shift (digits); indexLargest--; } if (digits.length == 3 && (digits[0] == digits[2])) { swap (digits, 2, 1); } } public static void shift (char[] digits) { char temp = digits[0]; for (int i = 0; i < digits.length-1; i++) { digits[i] = digits[i+1]; } digits[digits.length - 1] = temp; } public static void swap (char[] digits, int i, int j) { char temp = digits[i]; digits[i] = digits[j]; digits[j] = temp; } public static int getCombination (int a) { // replace with factorials? int numCombinations = 0; if (a == 2) { numCombinations = 1; } else if (a == 3) { numCombinations = 3; } else if (a == 4) { numCombinations = 6; } return numCombinations; } } " B10765,"package compete; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.StringTokenizer; import java.util.TreeSet; public class C { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(""C-small-attempt0.in"")); FileWriter fw = new FileWriter(""A-small.out""); int N = new Integer(in.readLine()); for (int cases = 1; cases <= N; cases++) { StringTokenizer st = new StringTokenizer(in.readLine()); int A = new Integer(st.nextToken()); int B = new Integer(st.nextToken()); fw.write(""Case #"" + cases + "": "" + nrecycled(A, B) + ""\n""); } fw.flush(); fw.close(); } private static int nrecycled(int a, int b) { int cpt = 0; for (int i = a; i < b; i++) { TreeSet l = listRecycled(i); for(Integer x:l) { if ((i listRecycled(int n) { TreeSet l = new TreeSet(); int nbChiffres = Integer.toString(n).length(); for(int i=1; i daddySet = new HashSet(); public ProbC() { super(); } public static void main(String[] args) { List inList = readFile(FILEPATH +File.separator +INFILE_NAME); List outList = new ArrayList(); int numTestCases = Integer.parseInt(inList.get(0)); System.out.println(""Number of Test Case : "" +numTestCases); for(int i =0 ; i< numTestCases; i++){ processDataForAB(inList.get(i+1)); for(int j = a; j <=b ; j++){ if (!daddySet.contains(j)){ Set retSet = getCyclicCombinations(new Integer(j).toString()); if (retSet.size() > 1){ count += getCombinations(retSet.size()); } } } outList.add(""Case #"" +i +"": "" +count); count = 0; } writeToFile(FILEPATH+File.separator+OUTFILE_NAME, outList); } private static int getCombinations(int n){ return n* (n-1) /2; } private static Set getCyclicCombinations(String strNum){ int len = strNum.length(); Set retSet = new HashSet(); StringBuilder strBuilder = new StringBuilder(strNum); retSet.add(Integer.parseInt(strNum)); for (int i =1; i=a ){ retSet.add(cyclicVal); } } if (retSet.size() > 1){ daddySet.addAll(retSet); } return retSet; } private static void processDataForAB(String inputLine){ String[] arrStr = inputLine.split("" ""); a = Integer.parseInt(arrStr[0]); b = Integer.parseInt(arrStr[1]); System.out.println(""PROCESSING FOR : "" +a +"" and "" +b); } private static List readFile(String filePath) { List retList = new ArrayList(); try { // Open the file that is the firstS // command line parameter FileInputStream fstream = new FileInputStream(filePath); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine = null; //Read File Line By Line while ((strLine = br.readLine()) != null) { // Print the content on the console retList.add(strLine); } //Close the input stream in.close(); return retList; } catch (Exception e) { //Catch exception if any System.err.println(""Error: "" + e.getMessage()); } return null; } private static void writeToFile(String filePath, List inputLines) { BufferedWriter bufferedWriter = null; try { //Construct the BufferedWriter object bufferedWriter = new BufferedWriter(new FileWriter(filePath)); //Start writing to the output stream for (String str : inputLines) { bufferedWriter.write(str); bufferedWriter.newLine(); } } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { //Close the BufferedWriter try { if (bufferedWriter != null) { bufferedWriter.flush(); bufferedWriter.close(); } } catch (IOException ex) { ex.printStackTrace(); } } } } " B11324,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Stack; public class Main { /** * @param args */ static int recyclePair(int A, int B){ int pairCount =0; HashSet hs = new HashSet(); for(int x=A;x digits = getDigits(x); for(int i =1;i getDigits(int x){ List list = new ArrayList(); Stack st = new Stack(); while(x>0){ st.push(x - ((int)(x/10))*10); x /= 10; } while(!st.isEmpty()){ list.add(st.pop()); } return list; } public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = null; BufferedWriter bw = null; try{ sc = new Scanner(new File(""input.txt"")); bw = new BufferedWriter(new FileWriter(""gcj3a.txt"")); int T = sc.nextInt(); int A, B, x; for(int i=0;i set = new HashSet(); for (int n = A; n < B; n++) { for (int i = 10; i < n; i*=10) { String p1 = (n/i) + """"; p1 = (n%i) + p1; int m = Integer.parseInt(p1); String t = n+""-""+m; if (m > n && m <= B && !set.contains(t)) { set.add(t); counter++; } } } System.out.println(""Case #"" + TC + "": "" + counter); out.println(""Case #"" + TC + "": "" + counter); } out.close(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { new C().run(); } } " B12972,"import java.io.*; import java.util.StringTokenizer; public class B { public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new FileReader(""B.in"")); System.setOut(new PrintStream(""B.out"")); int N = Integer.parseInt(bf.readLine()), caso = 1; while(N-->0){ boolean matriz[][] = new boolean[1005][1005]; StringTokenizer st = new StringTokenizer(bf.readLine()); int A = Integer.parseInt(st.nextToken()), B = Integer.parseInt(st.nextToken()); int min = Math.min(A, B), max = Math.max(A, B); int cont = 0; for(int j = min ;j<=max;j++){ String num = j+""""; for(int i=num.length()-1;i>=1;--i){ String aux = num.substring(i)+num.substring(0,i); int m = Integer.parseInt(aux); String au = m+""""; if(m>= min && m <= max && au.length() == num.length() && !matriz[j][m] && m != j ){ cont++; matriz[m][j] = matriz[j][m]=true; } } } System.out.println(""Case #""+(caso++)+"": ""+cont); } } } " B10242,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class Distincts { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(""input7.txt"")); BufferedWriter writer = new BufferedWriter(new FileWriter(""output1.txt"")); int cases = Integer.parseInt(reader.readLine()); for (int cs = 1; cs <= cases; cs++) { String line = reader.readLine(); String[] tokens = line.split("" ""); int count = 0; for (int i = Integer.parseInt(tokens[0]); i <= Integer.parseInt(tokens[1]); i++) { count += getGreaterRecycles(i, Integer.parseInt(tokens[1])); } writer.write(""Case #"" + cs + "": "" + count + ""\r\n""); } writer.close(); } static int getGreaterRecycles(int number, int max) { String ns = number + """"; Set result = new HashSet(); for (int i = 0; i < ns.length() - 1; i++) { ns = ns.substring(ns.length() - 1) + ns.substring(0, ns.length() - 1); int nr = Integer.parseInt(ns); if (nr > number && nr <= max) { result.add(nr); } } return result.size(); } } " B12813,"package Qualification_Round_2012; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.StringTokenizer; public class C { public static void main(String[] args) throws FileNotFoundException, IOException { BufferedReader in = new BufferedReader(new FileReader(""C-small-attempt0.in"")); PrintWriter out = new PrintWriter(""c.out""); StringTokenizer k; int t,a,b,x,y,count; HashSet h; String s; int ar [] = new int[7]; ar[0]=1; ar[1]=10; ar[2]=100; ar[3]=1000; ar[4]=10000; ar[5]=100000; ar[6]=1000000; t=Integer.parseInt(in.readLine().trim()); for (int i = 1; i <= t; i++) { count=0; k=new StringTokenizer(in.readLine()); a=Integer.parseInt(k.nextToken()); b=Integer.parseInt(k.nextToken()); for (int j = a; j <= b; j++) { h=new HashSet(6); x=j; s=j+""""; for (int l = 0; l < s.length()-1; l++) { y=x%10; y*=ar[s.length()-1]; y+=x/10; if(y>j && y<=b && y!=x){ if(h.add(y)) count++; } x=y; } } out.append(""Case #""+i+"": ""+count+""\n""); } out.close(); } } " B12469,"package com.paupicas.year2012.codejam.qr; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; public class C { public static void main(String[] args) throws Exception { String filename = ""C-small-attempt1""; BufferedReader inputFile = new BufferedReader(new FileReader(filename + "".in"")); FileWriter outputFile = new FileWriter(filename + "".out""); int casesNumber = Integer.valueOf(inputFile.readLine()); for (int cn = 1; cn <= casesNumber; cn++) { String result = ""Case #"" + cn + "": ""; String[] tn = inputFile.readLine().split("" ""); int a = Integer.valueOf(tn[0]); int b = Integer.valueOf(tn[1]); boolean[][] counted = new boolean[b - a + 1][b - a + 1]; int c = 0; for (int i = a; i <= b; i++) { String is = String.valueOf(i); // System.out.println(is); for (int j = 1; j < is.length(); j++) { String ps = is.substring(j, is.length()) + is.substring(0, j); int p = Integer.valueOf(ps); if (p > i && p <= b && !counted[i - a][p - a]) { c++; counted[i - a][p - a] = true; } // System.out.println(ps); } } result = result + c; System.out.println(result); outputFile.write(result); if (cn < casesNumber) { outputFile.write(""\n""); } } inputFile.close(); outputFile.close(); } } " B10986,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class ProbC { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new FileReader(""C-small-attempt0.in"")); BufferedWriter bw = new BufferedWriter(new FileWriter(""C-small-attempt0.out"")); String line = br.readLine(); int T = Integer.parseInt(line); for(int i = 0; i < T; i++) { line = br.readLine(); String[] tokens = line.split("" ""); int A = Integer.parseInt(tokens[0]); int B = Integer.parseInt(tokens[1]); int cnt = 0; for(int j = A; j < B; j++) { for(int k = j + 1; k <= B; k++) { String nstr = """" + j; String mstr = """" + k; if(nstr.length() != mstr.length()) { if(mstr.length() > nstr.length()) break; else continue; } String tstr = nstr + nstr; if(tstr.contains(mstr)) cnt++; } } String outputline = ""Case #"" + (i + 1) + "": "" + cnt; System.out.println(outputline); bw.write(outputline + ""\n""); } br.close(); bw.close(); } } " B11964,"import java.io.FileOutputStream; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; public class Recycled { public static void main(String[] args) throws IOException { int T; Scanner sc = new Scanner(System.in); FileOutputStream out = new FileOutputStream(""out.txt""); T = sc.nextInt(); sc.nextLine(); for (int i = 0; i < T; i++) { HashSet res = new HashSet(); int A = sc.nextInt(); int B = sc.nextInt(); for (int j = A; j <= B; j++) { String n = """" + j; for (int k = 1; k < n.length(); k++) { if (n.charAt(k) != '0') { String m = n.substring(k) + n.substring(0, k); if (j < Integer.valueOf(m) && Integer.valueOf(m) <= B) res.add(n + "" "" + m); } } } out.write((""Case #"" + (i + 1) + "": "" + res.size() + ""\n"").getBytes()); } } }" B12358,"package gcj.main; import gcj.cases.competition.qualification_round_2012.CaseC; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; public class Main { public static final void main (String[] args) throws Exception{ // doTask(""taskTeszt0"", ""/home/dev/Letöltések/0-teszt-practice.in"", ""/home/dev/Letöltések/0-teszt-practice.out"", new Case0()); // doTask(""taskSmall0"", ""/home/dev/Letöltések/A-small-attempt0.in"", ""/home/dev/Letöltések/A-small-attempt0.out"", new Case0()); // doTask(""taskTesztB"", ""/home/dev/Letöltések/B-teszt-practice.in"", ""/home/dev/Letöltések/B-teszt-practice.out"", new CaseB()); // doTask(""taskSmallB"", ""/home/dev/Letöltések/B-small-practice.in"", ""/home/dev/Letöltések/B-small-practice.out"", new CaseB()); // doTask(""taskLargeB"", ""/home/dev/Letöltések/B-large-practice.in"", ""/home/dev/Letöltések/B-large-practice.out"", new CaseB()); // doTask(""taskTesztC"", ""/home/dev/Letöltések/C-teszt-practice.in"", ""/home/dev/Letöltések/C-teszt-practice.out"", new CaseC()); doTask(""taskSmallC"", ""/home/dev/Letöltések/C-small-attempt0.in"", ""/home/dev/Letöltések/C-small-attempt0.out"", new CaseC()); // doTask(""taskLargeC"", ""/home/dev/Letöltések/C-large-practice.in"", ""/home/dev/Letöltések/C-large-practice.out"", new CaseC()); doTask(null, null, null, null); //because i hate the 'never used locally' warning... } private static final void doTask(String taskID, String inpFilePath, String outFilePath, Case c) throws Exception { if(taskID == null) return; BufferedReader br = null; BufferedWriter bw = null; String strLine; int caseNum = 0; System.out.println(taskID + "" strated...""); try{ { //open files br = new BufferedReader(new FileReader(new File(inpFilePath))); bw = new BufferedWriter(new FileWriter(new File(outFilePath))); } { //read caseNum value if ((strLine = br.readLine()) != null){ caseNum = Integer.parseInt(strLine); } System.out.println(""CaseNum: ""+caseNum); } for(int i=0; i args.length) { if(1 == countArgs) { message = ""ERROR: required "" + countArgs + "" ("" + usage + "") arg not present""; } else { message = ""ERROR: required "" + countArgs + "" ("" + usage + "") args not present""; } FileUtils.logFile.printf(""%s%n"",message); FileUtils.logFile.flush(); System.exit(1); } } // public static void checkArgs(int countArgs,String [] args,String usage) /********************************************************************* * Method to close a PrintWriter file. * @param theFile the PrintWriter file to close. **/ public static void CloseFile(PrintWriter theFile) { // FileUtils.logFile.printf(""%s enter (PrintWriter) CloseFile%n"",TAG); theFile.flush(); theFile.close(); // FileUtils.logFile.printf(""%s leave (PrintWriter) CloseFile%n"",TAG); } // public static void CloseFile(PrintWriter theFile) /********************************************************************* * Method to close a Scanner file. * @param theFile The Scanner file to close. **/ public static void CloseFile(Scanner theFile) { // FileUtils.logFile.printf(""%s enter (Scanner) CloseFile%n"",TAG); theFile.close(); // FileUtils.logFile.printf(""%s leave (Scanner) CloseFile%n"",TAG); } // public static void CloseFile(Scanner theFile) /********************************************************************* * Method to close the PrintWriter class log file. **/ public static void CloseLogFile() { // FileUtils.logFile.printf(""%s enter (PrintWriter) CloseLogFile%n"",TAG); FileUtils.logFile.flush(); FileUtils.logFile.close(); // FileUtils.logFile.printf(""%s leave (PrintWriter) CloseLogFile%n"",TAG); } // public static void CloseLogFile() /********************************************************************* * PrintWriterOpen method to open a file as a PrintWriter. * * The main purpose of this method is to do the error checking in * a subordinate method so as not to clutter up the code flow * in methods that have to open files. * * @param outFileName the String name of the file to open * @return The opened PrintWriter known to be not null **/ public static PrintWriter PrintWriterOpen(String outFileName) { PrintWriter localPrintWriter = null; // FileUtils.logFile.printf(""%s enter PrintWriterOpen%n"",TAG); if(outFileName.equals(""System.out"")) { localPrintWriter = new PrintWriter(System.out); } else { try { localPrintWriter = new PrintWriter(new File(outFileName)); } catch (FileNotFoundException fileException) { FileUtils.logFile.println(TAG + ""FILE ERROR opening outFile "" + outFileName); FileUtils.logFile.println(fileException.getMessage()); FileUtils.logFile.println(""in"" + System.getProperty(""user.dir"")); FileUtils.logFile.flush(); System.exit(1); } catch (SecurityException secException) { FileUtils.logFile.println(TAG + ""SECURITY ERROR opening outFile "" + outFileName); FileUtils.logFile.println(secException.getMessage()); FileUtils.logFile.println(""in"" + System.getProperty(""user.dir"")); FileUtils.logFile.flush(); System.exit(1); } } // FileUtils.logFile.printf(""%s leave PrintWriterOpen%n"",TAG); return localPrintWriter; } // public static PrintWriter PrintWriterOpen(String outFileName) /********************************************************************* * ScannerOpen method to open a file as a Scanner. * * The main purpose of this method is to do the error checking in * a subordinate method so as not to clutter up the code flow * in methods that have to open files. * * @param inFileName the String name of the file to open * @return The opened Scanner known to be not null **/ public static Scanner ScannerOpen(String inFileName) { Scanner localScanner = null; // FileUtils.logFile.printf(""%s enter ScannerOpen%n"",TAG); if(inFileName.equals(""System.in"")) { localScanner = new Scanner(System.in); } else { try { localScanner = new Scanner(new File(inFileName)); } catch (FileNotFoundException ex) { FileUtils.logFile.println(""TAG + ERROR opening inFile "" + inFileName); FileUtils.logFile.println(ex.getMessage()); FileUtils.logFile.println(""in"" + System.getProperty(""user.dir"")); FileUtils.logFile.flush(); System.exit(1); } } // FileUtils.logFile.printf(""%s leave ScannerOpen%n"",TAG); return localScanner; } // public static Scanner ScannerOpen(String inFileName) /********************************************************************* * Method to set the logFile given the name of the file. * * @param logFileName the String name of the log file. **/ public static void SetLogFile(String logFileName) { FileUtils.logFile = FileUtils.PrintWriterOpen(logFileName); } /********************************************************************* * Method to set the logFile given the PrintWriter file. * * @param logFile the PrintWriter log file. **/ public static void SetLogFile(PrintWriter logFile) { FileUtils.logFile = logFile; } /********************************************************************* * Method to convert a string to a double with error checking. * * @param ss the String value to convert. * @param value the default value for an empty string. * @return the converted value as a Double. **/ static public Double StringToDouble(String ss, Double value) { Double returnValue; returnValue = value; ss = ss.trim(); if(0 != ss.length()) { // FileUtils.logFile.printf(""nonempty string %s%n"", ss); returnValue = Double.valueOf(ss); } return returnValue; } // static public Double stringToDouble(String s, Double value) /********************************************************************* * Method to convert a string to an integer with error checking. * * @param ss the String value to convert. * @param value the default value for an empty string. * @return the converted value as an Integer. **/ static public Integer StringToInteger(String ss, Integer value) { Integer returnValue; returnValue = value; ss = ss.trim(); if(0 != ss.length()) { // FileUtils.logFile.printf(""nonempty string %s%n"", ss); returnValue = Integer.valueOf(ss); } return returnValue; } // static public Integer stringToInteger(String s, Integer value) } // public class FileUtils " B12433," import java.io.*; import java.util.HashSet; public class code33 { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); FileWriter fos = new FileWriter(""outfile"",false); BufferedWriter bw = new BufferedWriter(fos); int T=Integer.parseInt(br.readLine()), A , B , j ,i ; String str[]; for(j=1;j<=T; j++) { str=br.readLine().split("" ""); A= Integer.parseInt(str[0]); B= Integer.parseInt(str[1]); bw.write(""Case #""+j+"": ""+swapncal(A, B)+""\n""); } bw.close(); } public static int swapncal(int A,int B) { int n=0, p ,num; String xs; HashSet set = new HashSet(); for (int x= A; x <=(A+B); x++) { set.clear(); xs=x+""""; for(p=1;p< xs.length();p++) { num=Integer.parseInt(xs.substring(p)+xs.substring(0, p)); if( num > x && !set.contains(num) && num >=A && num <=B) { set.add(num); n++; } } } return n; } }" B10481,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class ProblemUtils { public static String[] readInput(String path) throws Exception { FileInputStream in = new FileInputStream(path); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); int nlines = Integer.parseInt(reader.readLine()); String[] lines = new String[nlines]; for (int i = 0; i < nlines; i++) { lines[i] = reader.readLine(); } return lines; } public static void writeOutput(String path, String[] lines) throws Exception { FileOutputStream out = new FileOutputStream(path); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out)); for (int i = 0; i < lines.length; i++) { writer.write(""Case #"" + (i + 1) + "": "" + lines[i]); if (i + 1 < lines.length) { writer.write(""\n""); } } writer.flush(); out.close(); } } " B12573,"package fr.lcwi.googlecodejam; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * For Google Code Jam 2012 */ public class ProblemC { private static Scanner scanner; private static int nbCases; public static void main(String[] args) throws IOException { String filename = args[0]; scanner = new Scanner(ProblemC.class.getClassLoader().getResourceAsStream(filename + "".in"")); nbCases = Integer.valueOf(scanner.nextLine()); BufferedWriter bWriter = null; try { bWriter = new BufferedWriter(new FileWriter(filename + "".out"")); for (int i = 1; i <= nbCases; i++) { resolveCase(i, bWriter); } } finally { if (bWriter != null) { bWriter.close(); } } } private static void resolveCase(int caseNb, BufferedWriter bWriter) throws IOException { int A = scanner.nextInt(); int B = scanner.nextInt(); int result = 0; for (int n = A; n < B; n++) { Set ms = new HashSet(); int length = (int) Math.floor(Math.log10(n)) + 1; if (length > 1) { for (int i = 0; i < length - 1; i++) { int puissanceA = (int) Math.pow(10, length - i - 1); int puissanceB = (int) Math.pow(10, i + 1); int digitsToMove = n % puissanceB; int ma = digitsToMove * puissanceA; if (ma >= puissanceB) { int mb = n / puissanceB; int m = ma + mb; if (n < m && m < B+1 && !ms.contains(m)) { result++; ms.add(m); } } } } } bWriter.write(""Case #"" + caseNb + "": "" + result); if (caseNb < nbCases) { bWriter.newLine(); } } } " B13212,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam2012; /** * * @author Abdelrahman */ import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; public class CaseC { public static void main(String[] args) throws FileNotFoundException, IOException { File f1 = new File(""E:\\new c++\\Google\\codejame 2011\\2012\\inputCodejame.txt""); BufferedReader reader = new BufferedReader(new FileReader(f1)); int count = Integer.parseInt(reader.readLine()); for (int i = 0; i < count; i++) { int counter = 0; String line = reader.readLine(); String[] twoInt = line.split("" ""); long A = Long.parseLong(twoInt[0]); long B = Long.parseLong(twoInt[1]); long n = A; for (long j = A; j < B; j++) { String t = Long.toString(n); int len=t.length(); HashMap dis=new HashMap(); for (int k = 1; k < len; k++) { String t2=t.substring(len-k) + t.substring(0, len-k); long m = Long.parseLong(t2); if (m > n && m <= B &&!dis.containsValue(m)) { dis.put(n, m); counter++; } } n++; } System.out.println(""Case #"" + (i + 1) + "": "" + counter); } } } " B12966,"package qualification.recycled.numbers; public class RecycledPair { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + m; result = prime * result + n; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RecycledPair other = (RecycledPair) obj; if (m != other.m) return false; if (n != other.n) return false; return true; } private int n; private int m; public RecycledPair(int n, int m) { if (m > n) { int temp = n; n = m; m = temp; } this.n = n; this.m = m; } } " B12268,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.StringTokenizer; public class RecycledNumbers { public static void main(String[] args) throws Exception{ char problem = 'C'; boolean smallCase = true; boolean practice = false; BufferedReader br = new BufferedReader(new FileReader(problem + ""-"" + (smallCase ? ""small"" : ""large"") + (practice ? ""-practice"" : """") + "".in"")); PrintWriter out = new PrintWriter(new FileWriter(problem + ""-"" + (smallCase ? ""small"" : ""large"") + (practice ? ""-practice"" : """") + "".out"")); int t = Integer.parseInt(br.readLine()); for(int i = 1; i <= t; i++) { out.println(""Case #"" + i + "": "" + solve(br.readLine())); } out.close(); System.exit(0); } public static int solve(String in) { StringTokenizer st = new StringTokenizer(in); String min = st.nextToken(); String max = st.nextToken(); int length = min.length(); int output = 0; // for(int shortL = 1; shortL <= length / 2; shortL++) { // int longL = length - shortL; // int numShort = Integer.parseInt(max.substring(0, shortL)) - Integer.parseInt(min.substring(0, shortL)) + 1; // int numLong = Integer.parseInt(max.substring(0, longL)) - Integer.parseInt(min.substring(0, longL)) + 1; // int num; // if(numShort > 2) { // output += (numShort - 2) * (numLong - 2); // } // if(numShort >= 2) { // num = (Integer.parseInt(max.substring(0, longL)) - 1) - Integer.parseInt(min.substring(shortL)) + 1; // if(num > 0) output += num; // num = Integer.parseInt(max.substring(shortL)) - (Integer.parseInt(min.substring(0, longL)) + 1) + 1; // if(num > 0) output += num; // } // if(numLong >= 2) { // num = (Integer.parseInt(max.substring(0, shortL)) - 1) - Integer.parseInt(min.substring(longL)) + 1; // if(num > 0) output += num; // num = Integer.parseInt(max.substring(longL)) - (Integer.parseInt(min.substring(0, shortL)) + 1) + 1; // if(num > 0) output += num; // } // if(numShort == 1) { // num = (Integer.parseInt(max.substring(0, longL)) - 1) - Integer.parseInt(min.substring(shortL)) + 1; // if(num > 0) output += num; // } // } int ma = Integer.parseInt(max); int mi = Integer.parseInt(min); if(length == 2) { for(int i = 1; i < 10; i++) { for(int j = i + 1; j < 10; j++) { if(10 * i + j >= mi && 10 * j + i <= ma) output ++; } } } else if(length == 3) { for(int i = 1; i < 10; i++) { for(int j = 10; j < 100; j++) { if(j != 11 * i && 100 * i + j <= ma && 100 * i + j >= mi && 10 * j + i <= ma && 10 * j + i >= mi) output ++; } } } return output; } } " B12010,"import java.io.*; import java.util.*; public class Main { private static IO io; public static void main(String[] args) throws IOException { new Main().run(); } private void run() throws IOException { io = new IO(System.getProperty(""ONLINE_JUDGE"")!=null);//false->files; true->console solve(); io.flush(); } private void solve() throws IOException { int n = io.nI(); for(int z = 1; z<=n; z++){ int a = io.nI(), b = io.nI(), l = String.valueOf(a).length(), r = 0; for(int i = a; i<=b; i++){ Set L = new HashSet(); String S = String.valueOf(i); char c[] = S.toCharArray(); for(int j = 0; j ss = new ArrayList(); if (b > 10 && a != b) { for(int i = a; i <= b; i++) { //Are there any rotations of i which is less than b String m = """" + i; for(int j = 0; j < m.length()-1; j++) { m = m.substring(1) + m.substring(0, 1); if(m.startsWith(""0"")) { continue; } int n = Integer.parseInt(m); if(n <= b && n > i) { String v = i + "" , "" + m; if(!ss.contains(v)) { //Skip cases such as ???????1212 , 2121 ss.add(v); out++; } } } } } return """" + out; } } " B13222,"import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.PrintWriter; public class Main3 { public static final String fileName = ""A-small-attempt0.in""; public static int[] power = new int[] { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; /** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new FileReader(fileName)); PrintWriter pw = new PrintWriter(new File(""out.txt"")); int num = Integer.valueOf(br.readLine()); for (int i = 0; i < num; i++) { String inline = br.readLine(); int result = 0; String[] tmp = inline.split("" ""); int a = Integer.valueOf(tmp[0]); int b = Integer.valueOf(tmp[1]); int size = 0; int a2 = a; while (a2 > 0) { a2 /= 10; size++; } for (int j = a; j < b; j++) { int prev = -1; for (int k = 1; k < size; k++) { int swapNum = swap(j, k, size); if (j < swapNum && swapNum <= b && swapNum != prev) { prev = swapNum; result++; } } } pw.println(""Case #"" + (i + 1) + "": "" + result); } pw.close(); } private static int swap(int raw, int posNum, int size) { return (raw % power[posNum]) * power[size - posNum] + raw / power[posNum]; } } " B11080,"package fixjava; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; public class IOUtils { public static void writeLinesToFile(List lineList, File outputFile) { try { PrintWriter writer = new PrintWriter(outputFile); for (String line : lineList) writer.println(line); writer.close(); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } public static void writeLinesToFile(List lineList, String outputFilename) { writeLinesToFile(lineList, new File(outputFilename)); } // --------------------------------------------------------------------------------------------------------- public static ArrayList readLinesFromFile(File inputFile) { ArrayList lines = new ArrayList<>(); for (String line : new FileLineIterator(inputFile)) lines.add(line); return lines; } public static ArrayList readLinesFromFile(String inputFilename) { return readLinesFromFile(new File(inputFilename)); } // --------------------------------------------------------------------------------------------------------- public static String readFileAsString(File inputFile) { int len = (int) inputFile.length() + 1; StringBuilder buf = new StringBuilder(len); for (String line : new FileLineIterator(inputFile)) { buf.append(line); buf.append('\n'); } return buf.toString(); } public static String readFileAsString(String inputFilename) { return readFileAsString(new File(inputFilename)); } } " B12699,"package gcj12; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class C { void solve() { Scanner scan = new Scanner(System.in); int tCase = scan.nextInt(); for (int i = 1; i <= tCase; i++) { int res = 0; int a = scan.nextInt(); int b = scan.nextInt(); for (int j = a; j <= b; j++) { int pow = 10; Map map = new HashMap(); while (j / pow > 0) { int tmp = Integer.valueOf((j % pow) + """" + (j / pow)); if (tmp > j && tmp <= b && map.get(tmp) == null) { map.put(tmp, tmp); res++; } pow *= 10; } } System.out.println(""Case #"" + i + "": "" + res); } } public static void main(String[] args) { new C().solve(); } } " B11490,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StreamTokenizer; import java.lang.reflect.Array; import java.util.ArrayList; public class C { private static ArrayList makeCycle(ArrayList digits) { if (digits.size() == 1) { return new ArrayList(digits); } ArrayList cycle = new ArrayList(); int tail = 0; while (tail < digits.size() && digits.get(tail) == 0) { ++tail; } cycle = new ArrayList(digits.subList(tail + 1, digits.size())); for (int i = 0;i <= tail; ++i) { cycle.add(digits.get(i)); } return cycle; } private static boolean sequenceEquals(ArrayList sec1, ArrayList sec2) { for (int i = 0;i < sec1.size(); ++i) { if (sec1.get(i) != sec2.get(i)) { return false; } } return true; } private static long value(ArrayList digits) { long val = 0; long pow = 1; for (int i = 0;i < digits.size(); ++i) { val += digits.get(i) * pow; pow *= 10; } return val; } /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StreamTokenizer tokenizer = new StreamTokenizer(in); int tests; tokenizer.nextToken(); tests = (int)tokenizer.nval; int[] answers = new int[tests]; for (int i = 0;i < tests; ++i) { long A, B; tokenizer.nextToken(); A = (long)tokenizer.nval; tokenizer.nextToken(); B = (long)tokenizer.nval; for (long n = A; n <= B; ++n) { ArrayList digits = new ArrayList(); long v = n; while (v > 0) { digits.add(Byte.valueOf(Long.toString(v % 10))); v = v / 10; } ArrayList cycled = new ArrayList(digits); while (!sequenceEquals(cycled = makeCycle(new ArrayList(cycled)), digits)) { long val = value(cycled); if (val <= B && val > n) { ++answers[i]; } } } } for (int i = 0;i < tests; ++i) { System.out.println(""Case #"" + (i + 1) + "": "" + answers[i]); } } } " B13209,"import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; public class RecycledNumbers { private static int lowRange = 0, highRange = 0; private static ArrayList list = null; private static ArrayList newList = null; /** * @param args */ public static void main(String[] args) { try { // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream( ""C-small-attempt0.in""); // Convert our input stream to aw // DataInputStream DataInputStream in = new DataInputStream(fstream); FileOutputStream out = new FileOutputStream(""C-small-attempt0.out""); PrintStream p = new PrintStream(out); int lineNo = 1; // Continue to read lines while // there are still some left to read while (in.available() != 0) { if (lineNo == 1) { cases(in.readLine(), in, p); } lineNo++; } in.close(); } catch (Exception e) { e.printStackTrace(); } } private static void cases(String firstLine, DataInputStream in, PrintStream p) throws IOException { int casesNo = Integer.parseInt(firstLine); for (int i = 0; i < casesNo; i++) { // System.out.print(""Case #"" + (i + 1) + "": ""); p.print(""Case #"" + (i + 1) + "": ""); String line = in.readLine(); numbers(line, p); } } private static void numbers(String line, PrintStream p) { String[] range = line.split("" ""); lowRange = Integer.parseInt(range[0]); highRange = Integer.parseInt(range[1]); int[] numbers = new int[highRange - lowRange + 1]; for (int i = 0; i < numbers.length; i++) { numbers[i] = lowRange + i; } list = new ArrayList(); newList = new ArrayList(); int total = recycled(numbers); // System.out.println(total); p.println(total); } private static int recycled(int[] numbers) { int total = 0; int dupliTotal = 0; for (int i = 0; i < numbers.length; i++) { int num = numbers[i]; int length = (int)(Math.log10(num)+1); int max = maxTen(length); int min = 10; while (num/min > 0){ int rem = num%min; int remNum = num/min; max /= min; int newNum = rem*max + remNum; if(newNum>num){ if (newNum <= highRange && newNum > lowRange) { // System.out.println(num + ""->"" + newNum); if (list.contains(num)) if (newList.get(list.indexOf(num))==newNum) dupliTotal++; list.add(num); newList.add(newNum); total++; } } min*=10; max = maxTen(length); } } return total-dupliTotal; } private static int maxTen(int length){ int result = 1; int len = (int)(Math.log10(result)+1); while(len!=length){ result*= 10; len = (int)(Math.log10(result)+1); } return result*10; } } " B12015,"import java.io.*; import java.util.*; import java.math.*; import java.text.*; public class RecycledNumbers { static final int INF = 1 << 28, MAX = 1000; static final double EPS = 1E-9; static int digits(int x) { int d; for (d = 0; x > 0; d++) x /= 10; return d; } static boolean recycled(int n, int m, int d) { int pow = 1; for (int i = 0; i < d-1; i++) pow *= 10; while (d-- > 0) { m = m / 10 + pow * (m % 10); if (m == n) return true; } return false; } static void solve() { Scanner scan = new Scanner(in); int T = scan.nextInt(); for (int t = 1; t <= T; t++) { out.print(""Case #"" + t + "": ""); int A = scan.nextInt(); int B = scan.nextInt(); int r = 0; for (int n = A; n <= B; n++) { int d = digits(n); for (int m = n+1; m <= B; m++) { if (d != digits(m)) break; if (recycled(n, m, d)) r++; } } out.println(r); } } static String read() { try { return in.readLine(); } catch (IOException e) { return null; } } public static void main(String[] args) throws IOException { // in = new BufferedReader(new InputStreamReader(System.in)); // out = new PrintWriter(new BufferedOutputStream(System.out)); String file = ""C-small""; in = new BufferedReader( new FileReader(file + "".in"") ); out = new PrintWriter( new FileOutputStream(file + ""_"" + System.currentTimeMillis() + "".out"") ); solve(); out.flush(); } static BufferedReader in; static PrintWriter out; } " B10440,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package problem3; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Scanner; import java.util.Set; /** * * @author lhideg */ public class Problem3 { private static String fileName = Problem3.class.getSimpleName().replaceFirst(""_.*"", """"); private static String inputFileName = fileName + "".in""; private static String outputFileName = fileName + "".out""; private static Scanner in; private static PrintWriter out; private int solve() { Map solutionMap = new HashMap(); int result = 0; String nStr = in.next(); String mStr = in.next(); Integer n = Integer.valueOf(nStr); Integer m = Integer.valueOf(mStr); Set watchedSet = new HashSet(); Set valueSet = new HashSet(); if (nStr.length() != 1) { for (int i = n; i <= m; i++) { String str = String.valueOf(i); watchedSet.add(i); String watchStr = str; for (int j = 0; j < str.length() - 1; j++) { watchStr = watchStr.substring(1) + watchStr.charAt(0); if (watchStr.charAt(0) == '0') { continue; } Integer watchInt = Integer.valueOf(watchStr); watchedSet.add(watchInt); if (watchInt > i && watchInt <= m && watchInt > i) { valueSet.add(str+watchStr); valueSet.add(watchStr+str); } } } } return valueSet.size()/2; } /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); if (args.length >= 2) { inputFileName = args[0]; outputFileName = args[1]; } in = new Scanner(new FileReader(inputFileName)); out = new PrintWriter(outputFileName); int tests = in.nextInt(); in.nextLine(); for (int t = 1; t <= tests; t++) { System.out.println(""#"" + t); out.print(""Case #"" + t + "": ""); out.print(new Problem3().solve() + ""\n""); } in.close(); out.close(); } } " B11682,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package uk.co.epii.codejam.common; import java.util.ArrayList; /** * * @author jim */ public class Input { private final String[] header; private final String[] data; public Input(ArrayList lines, int header) { int size = lines.size(); this.header = new String[header]; this.data = new String[size - header]; for (int i = 0; i < size; i++) { String line = lines.get(i); if (i < header) this.header[i] = line; else this.data[i - header] = line; } } public String[] getHeader() { return header; } public String[] getData() { return data; } } " B12113,"package com.renoux.gael.codejam.fwk; import java.io.File; import com.renoux.gael.codejam.utils.FluxUtils; import com.renoux.gael.codejam.utils.Input; import com.renoux.gael.codejam.utils.Output; import com.renoux.gael.codejam.utils.Timer; public abstract class Solver { public void run() { Timer.start(); if (!disableSample()) runOnce(getSampleInput(), getSampleOutput()); System.out.println(Timer.check()); Timer.start(); if (!disableSmall()) runOnce(getSmallInput(), getSmallOutput()); System.out.println(Timer.check()); Timer.start(); if (!disableLarge()) runOnce(getLargeInput(), getLargeOutput()); System.out.println(Timer.check()); } public void runOnce(String pathIn, String pathOut) { Input in = null; Output out = null; try { in = Input.open(getFile(pathIn)); out = Output.open(getFile(pathOut)); int countCases = Integer.parseInt(in.readLine()); for (int k = 1; k <= countCases; k++) { out.write(""Case #"", k, "": ""); solveCase(in, out); } } catch (RuntimeException e) { e.printStackTrace(); } finally { FluxUtils.closeCloseables(in, out); } } private File getFile(String path) { return new File(path); } protected abstract void solveCase(Input in, Output out); private String getFullPath(boolean input, String type) { if (input) return ""D:\\Downloads\\CodeJam\\"" + getProblemName() + ""\\"" + getProblemName() + ""_input_"" + type + "".txt""; else return ""D:\\Downloads\\CodeJam\\"" + getProblemName() + ""\\"" + getProblemName() + ""_output_"" + type + "".txt""; } protected String getSampleInput() { return getFullPath(true, ""sample""); } protected String getSmallInput() { return getFullPath(true, ""small""); } protected String getLargeInput() { return getFullPath(true, ""large""); } protected String getSampleOutput() { return getFullPath(false, ""sample""); } protected String getSmallOutput() { return getFullPath(false, ""small""); } protected String getLargeOutput() { return getFullPath(false, ""large""); } protected boolean disableSample() { return disable()[0]; } protected boolean disableSmall() { return disable()[1]; } protected boolean disableLarge() { return disable()[2]; } protected boolean[] disable() { return new boolean[] { false, false, false }; } protected abstract String getProblemName(); } " B11440,"//Kholofelo Moyaba //Problem C codejam //14 April 2012 import java.util.Scanner; class RecycledNumbers { public static void main(String[] args) { Scanner input = new Scanner(System.in); int cases = input.nextInt(); for(int i=1;i<=cases;i++) { int a = input.nextInt(); int b = input.nextInt(); int digits = (a+"""").length()-1;//number of digits -1 int factor = 1;//factor in order of a and b for(int j=0;j perm = new HashSet(); int ndig = str.length(); for (int k = 0; k < ndig - 1; k++) { str = str.substring(1) + str.charAt(0); int m = Integer.parseInt(str); if (n < m && m <= b) { perm.add(m); } } ret += perm.size(); } return ret; } } " B10975,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class CodeJam { static String [][] mapping = new String [6][]; static String f,s,t,ff,ss,tt; public static void map(){ f = ""ejp mysljylc kd kxveddknmc re jsicpdrysi""; s = ""rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd""; t = ""de kr kd eoya kw aej tysr re ujdr lkgc jv""; ff=""our language is impossible to understand""; ss=""there are twenty six factorial possibilities""; tt=""so it is okay if you want to just give up""; mapping[0] = f.split("" ""); mapping[1] = ff.split("" ""); mapping[2] = s.split("" ""); mapping[3] = ss.split("" ""); mapping[4] = t.split("" ""); mapping[5] = tt.split("" ""); } public static String returnLetter(String l){ if(l.equals(""q"")) return ""z""; if(l.equals(""z"")) return ""q""; for(int i=0;i<6;i+=2){ for(int j=0;j 0) { int A, B, count = 0; s = new StringTokenizer(in.readLine()); A = Integer.parseInt(s.nextToken()); B = Integer.parseInt(s.nextToken()); for(int i = A; i < B; i++) { for(int j = i + 1; j <= B; j++) { String str = i + """"; for(int c = 0; c < str.length(); c++) { String a = str.substring(c); String b = str.substring(0, c); String res = a + b; if(Integer.parseInt(res) == j) { count++; break; } } } } fw.write(""Case #"" + ++kase + "": "" + count + ""\n""); } fw.close(); } } " B11227,"package codezam.util; import java.io.File; import java.io.FileReader; import java.io.LineNumberReader; public class InputFile { private File file; FileReader freader; LineNumberReader lnreader; public void setFile(String filename) { try { file = new File(filename); freader = new FileReader(file); lnreader = new LineNumberReader(freader); } catch (Exception e) { e.printStackTrace(); } } public String readLine() { String line = null; try { line = lnreader.readLine(); //System.out.println(""Line: "" + lnreader.getLineNumber() + "": "" + line); if (line==null) { close(); } } catch (Exception e) { e.printStackTrace(); } return line; } private void close() { try { freader.close(); lnreader.close(); } catch (Exception e) { e.printStackTrace(); } } } " B11683,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package uk.co.epii.codejam.recyclednumbers; import java.util.TreeSet; import uk.co.epii.codejam.common.AbstractProcessor; /** * * @author jim */ public class RecycledNumbersProcessor extends AbstractProcessor { @Override public String processLine(String line) { DataRow dr = new DataRow(line); if (dr.A > dr.B) return ""0""; int count = 0; for (int n = dr.A; n < dr.B; n++) { String nStr = n + """"; TreeSet m = new TreeSet<>(); for (int c = 1; c < nStr.length(); c++) { int value = cycle(nStr, c); if (value > n && value <= dr.B) m.add(value); } count += m.size(); } return count + """"; } public int cycle(String n, int c) { String cycled = n.substring(c, n.length()) + n.substring(0, c); return Integer.parseInt(cycled); } } " B10484,"/* ID: yourID LANG: JAVA TASK: Recycled_Numbers */ import java.io.*; import java.math.*; import java.util.*; /*public class Recycled_Numbers { } */ public class Recycled_Numbers implements Runnable { // based on Petr's template boolean localDebug = false; private void solve() throws IOException { int a = this.nextInt(); int b = this.nextInt(); int mul = 1; while( mul * 10 <= a ) mul *= 10; int res = 0; for ( int i = a; i < b; i ++ ){ int m = i; HashSet< Integer > exist = new HashSet< Integer >(); for ( int j = 1; j < mul; j *= 10 ){ m = ( m % 10 ) * mul + m / 10; if ( m > i && m <= b && !exist.contains( m ) ){ exist.add( m ); res ++; } } } writer.println( res ); } public static void main(String[] args) { new Recycled_Numbers().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { if (localDebug) { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(new OutputStreamWriter(System.out)); } else { writer = new PrintWriter(new BufferedWriter(new FileWriter( ""C-small-attempt0.out""))); reader = new BufferedReader(new FileReader( ""C-small-attempt0.in"")); } tokenizer = null; int t = this.nextInt(); for (int i = 1; i <= t; i++) { writer.print(""Case #"" + i + "": ""); solve(); } reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } boolean hasNext() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { String nextLine = reader.readLine(); if (nextLine == null) return false; tokenizer = new StringTokenizer(nextLine); } return true; } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextLine() throws IOException { return reader.readLine(); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } BigInteger nextBigInteger() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return new BigInteger(tokenizer.nextToken()); } }" B12881," import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.StringTokenizer; public class Recycle { static String shiftRight( String s ) { String res = """" + s.charAt( s.length() - 1 ); res = res + s.substring( 0, s.length()-1 ); return res; } static int solve( int a, int b ) { HashSet h = new HashSet(); int res = 0; for( int i=a; i<=b; i++ ) { String curr = Integer.toString(i); if( h.contains( curr ) ) continue; // else compute number of shifts HashSet temp = new HashSet(); String s = curr; temp.add( curr ); h.add( curr); for( int j=0; j=a ) && ( x<=b )) { temp.add(s); h.add( s ); } } // now count how many such pairs ( n choose 2 = n( n-1 )/2 ) int k = temp.size(); res += k*( k-1 )/2; } return res; } public static void main( String[] args ) throws IOException { FileWriter fr= new FileWriter(""/home/gowri/Desktop/out.txt""); BufferedWriter out = new BufferedWriter( fr ); BufferedReader br = new BufferedReader( new InputStreamReader( System.in )); int t = Integer.parseInt( br.readLine() ); StringTokenizer tok; for( int i=0; i list = new InputFile().readFile(); int caseNumber =1; ArrayList output = new ArrayList(); for(int i=0 ;i> recycle = new HashMap>(); private void prepare() { int mul = 1; int dig = 1; for (int x = 10; x <= 2000000; x++) { if (mul * 10 == x) { mul *= 10; dig++; } Set recs = new HashSet(); int t = x; for (int i = 1; i < dig; i++) { int last = t % 10; t /= 10; t += last * mul; if (t > x) { recs.add(t); } } if (!recs.isEmpty()) { recycle.put(x, recs); } } } private BufferedReader reader; private StringTokenizer tt = new StringTokenizer(""""); private String nextToken() throws IOException { while (!tt.hasMoreTokens()) { tt = new StringTokenizer(reader.readLine()); } return tt.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private void run() throws IOException { String problem = ""C-small-attempt0""; reader = new BufferedReader(new FileReader(problem + "".in"")); PrintWriter writer = new PrintWriter(new File(problem + "".out"")); try { prepare(); int cases = nextInt(); int tc = 1; while (tc <= cases) { writer.print(""Case #"" + tc + "": ""); writer.println(solve()); tc++; } } finally { reader.close(); writer.close(); } } public static void main(String[] args) { try { new C().run(); } catch (IOException e) { e.printStackTrace(); } } }" B12577,"package codejam2012.q; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintStream; import java.util.Arrays; import java.util.Scanner; public class C { static public void solveOne(int caseNo, Scanner in, PrintStream out) { int A = in.nextInt(); int B = in.nextInt(); in.nextLine(); int size=0; int a=A; while( a>0 ) { a/=10 ; size++; } int count = 0; int[] rev = new int[10]; int[] pow = new int[]{ 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000 }; for( int n=A ; n<=B ; n++ ){ int ir = 0; for( int k=1 ; kn && m<=B) { int repeat = 0; for(int k= 0;k 11) x=a; else x = 12; while(x < b){ String entier = x+""""; if (!(entier.charAt(1)+"""").equals(""0"")){ int rec = Integer.parseInt(""""+entier.charAt(1)+entier.charAt(0)+""""); if (rec > x && rec < b+1 ) {System.out.println(rec);retour++;} } x++; } return retour; } return 0; } static int findLessThanThousand(int a, int b){ int retour = 0; ArrayList arr = new ArrayList(); if (a==b) return 0; int x = a; while (x < b+1){ if (!arr.contains(x+"""")){ boolean rec1good = false; int rec1=0,rec2=0; String entier= x+""""; if (!(""""+entier.charAt(2)+"""").equals(""0"") ){ rec1 = Integer.parseInt(""""+entier.charAt(2)+""""+entier.charAt(0)+""""+entier.charAt(1)+""""); if (rec1 > a && rec1 < b+1 && rec1 != x ) {;arr.add(rec1+"""");arr.add(x+"""");retour++;rec1good=true;} } if (!(""""+entier.charAt(1)+"""").equals(""0"") ){ rec2 = Integer.parseInt(""""+entier.charAt(1)+""""+entier.charAt(2)+""""+entier.charAt(0)+""""); if (rec2 > a && rec2 < b+1 && rec2 != rec1 && rec2 != x) {arr.add(rec2+"""");retour++; if (rec1good) retour++;} } System.out.println(""x==""+x+""rec1==""+rec1+""rec2==""+rec2+"" retour==""+retour); } x++; } return retour; } public static void main (String args[]) throws IOException{ BufferedReader in = new BufferedReader(new FileReader(new File(""recycled.in""))); PrintWriter out = new PrintWriter(new FileWriter(""recycled.out"")); //System.out.print(RecycledNumbers.findLessThanHundred(10,40)); //System.out.println(RecycledNumbers.findLessThanThousand(100,500)); String ligne=""""; int nbr_lignes = Integer.parseInt(in.readLine()); int index = 0; while(index < nbr_lignes){ int a,b; ligne=in.readLine(); StringTokenizer tok = new StringTokenizer(ligne); a = Integer.parseInt(tok.nextToken()); b = Integer.parseInt(tok.nextToken()); if (b<100) { if (index!=nbr_lignes-1){ out.println(""Case #""+(index+1)+"": ""+RecycledNumbers.findLessThanHundred(a, b)); } else out.print(""Case #""+(index+1)+"": ""+RecycledNumbers.findLessThanHundred(a, b)); } else if (a > 99) { if (index!=nbr_lignes-1){ out.println(""Case #""+(index+1)+"": ""+(RecycledNumbers.findLessThanThousand(a, b))); } else out.print(""Case #""+(index+1)+"": ""+(RecycledNumbers.findLessThanThousand(a, b))); } else { if (index!=nbr_lignes-1){ out.println(""Case #""+(index+1)+"": ""+(RecycledNumbers.findLessThanHundred(a, 99)+RecycledNumbers.findLessThanThousand(100, b))); } else out.print(""Case #""+(index+1)+"": ""+(RecycledNumbers.findLessThanHundred(a, 99)+RecycledNumbers.findLessThanThousand(100, b))); } index++; } out.close(); } } " B12497,"package com.google; import java.io.File; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { private static int numberOfRecycledPairsPossible(int a, int lowerLimit, int upperLimit) { int length = (a + """").length(); if (length == 1) { return 0; } int[] digits = new int[length]; int b = a; boolean isRecyclePossible = false; int temp = 0; ; Set set = new HashSet(); digits[length - 1] = b % 10; b /= 10; for (int i = length - 2; i >= 0; i--) { digits[i] = b % 10; b /= 10; if (digits[i] != digits[i + 1]) { isRecyclePossible = true; } } if (!isRecyclePossible) { return 0; } for (int i = 1; i < length; i++) { temp = 0; for (int j = i; j < length; j++) { temp = temp * 10 + digits[j]; } for (int j = 0; j < i; j++) { temp = temp * 10 + digits[j]; } if (temp <= upperLimit && temp >= lowerLimit && temp > a) { set.add(a + """" + temp); } } return set.size(); } private static int getRecycledNumbers(int start, int end) { int count = 0; for (int i = start; i <= end; i++) { count += numberOfRecycledPairsPossible(i, start, end); } return count; } public static void main(String[] args) throws FileNotFoundException { File file = new File(""d:\\codeJam\\Numbers\\test.txt""); Scanner scanner = new Scanner(file); int t = scanner.nextInt(); int count = 0; for (int i = 1; i <= t; i++) { count = getRecycledNumbers(scanner.nextInt(), scanner.nextInt()); System.out.println(""Case #"" + i + "": "" + count); } } } " B11559,"import java.io.*; import java.lang.*; import java.util.*; public class Recycle{ public static void main(String args []){ try{ FileInputStream fstream = new FileInputStream(""C-small-attempt0.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter ostream = new FileWriter(""recOut.txt""); BufferedWriter out = new BufferedWriter(ostream); String str = br.readLine(); int num = Integer.parseInt(str.replaceAll(""\\s"","""")); String [] AB = new String[num]; String temp; int k = 0; while((temp = br.readLine()) != null && k < num){ AB[k] = temp; ++k; } //for(int i=1; i<= num; i++){ for(int i=1; i<= num; i++){ String ABs = AB[i-1].trim(); int n = calcDig(ABs); out.write(""Case #"" + i + "": "" + n); out.write(""\n""); out.flush(); } out.close(); } catch(Exception e){} } public static int calcDig(String input){ String [] nums = input.split("" ""); int A = Integer.parseInt(nums[0].replaceAll(""\\s"","""")); int B = Integer.parseInt(nums[1].replaceAll(""\\s"","""")); if(A < 10) return 0; else return numRot(A, B); } public static int numRot(int A, int B){ int toRet = 0; int len = Integer.toString(A).length(); int cur = A; //System.out.println(A); //System.out.println(B); //System.out.println(len); HashMap sets = new HashMap(); while(cur < B){ for(int j=1; j< len; j++){ int newPerm = Rotate(cur, j, len); int newLen = Integer.toString(newPerm).length(); //System.out.println(cur + "" "" +newPerm); if(B >= newPerm && newLen == len && cur < newPerm){ ++toRet; //sets.put(cur, newPerm); if(sets.containsKey(cur)){ if(sets.get(cur) == newPerm){ //System.out.println(""Found: "" + sets.get(cur)); --toRet; } } else{ sets.put(cur, newPerm); } } /* else System.out.println("" perm "" + newPerm + "" not counted""); */ } ++cur; } return toRet; } public static int checkRot(int A, int B, int len){ //System.out.print(""A: "" + A); //System.out.println(""B: "" + B); List aList = new ArrayList(); List bList = new ArrayList(); int a = A; int b = B; while(a > 0){ aList.add(a % 10); bList.add(b % 10); a /= 10; b /= 10; } Collections.sort(aList); Collections.sort(bList); if(aList.equals(bList)){ //nreturn iterRot(A, B, len); return 0; } else return 0; } /* public static int iterRot(int A, int B, int len){ int toRet = 0; for(int i=1; i mPairs = new HashSet(); for(int i=0; inIter && m<=max && !mPairs.contains(m)){ solution++; mPairs.add(m); } } } } @Override public void generateOutput(BufferedWriter bw, boolean needBR) throws Exception { bw.write(""Case #"" + this.caseNum + "": "" + this.solution); if(needBR){ bw.newLine(); } } } " B11754,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; public class CodeJamTextInputReader { private final BufferedReader reader; private final int numberOfTestCases; private int lastReadTestCase = 0; public CodeJamTextInputReader(File inputFile) throws IOException, InvalidInputException { reader = new BufferedReader(new FileReader(inputFile)); numberOfTestCases = readInNumberOfTestCases(); } private int readInNumberOfTestCases() throws IOException, InvalidInputException { String firstLine = reader.readLine(); try { return Integer.parseInt(firstLine); } catch (NumberFormatException e) { throw new InvalidInputException(""Expected first line to be number of test cases"", e); } } public boolean hasNextTestCase() { return numberOfTestCases != lastReadTestCase; } public String readNextLine() throws IOException { ++lastReadTestCase; return reader.readLine(); } public int getLastReadTestCaseNumber() { return lastReadTestCase; } public void close() throws IOException { this.reader.close(); } } " B12568," import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author JOSE */ public class RecycledNumbers { public void process() { ArrayList inputList = readFile(""C-small-attempt0.in""); String output = """"; int testCase = 0; for (int i = 0; i < inputList.size(); i++) { String input = inputList.get(i); if (i == 0) { testCase = Integer.parseInt(input); } else { int recycledNo=findRecycledNO(input); output = output + ""Case #"" + i + "": ""+recycledNo; if (i != (inputList.size() - 1)) { output = output + '\n'; } } } writeFile(output); } public int findRecycledNO(String input) { String spliInput[] = input.split(""\\s""); int A = Integer.parseInt(spliInput[0]); int B = Integer.parseInt(spliInput[1]); int n = 0; int m = 0; int resultCount = 0; String[] ab = new String[(B - A) + 1]; for (int i = 0; i < ab.length; i++) { ab[i] = """" + (A + i); } for (String t : ab) { n = Integer.parseInt(t); for (int i = 0; i < t.length() - 1; i++) { t = t.substring(t.length() - 1) + t.substring(0, t.length() - 1); m = Integer.parseInt(t); if ((A <= n) && (n < m) && (m <= B)) { // System.out.println(A + "" < "" + n + "" < "" + m + "" < "" + B); resultCount++; } } // System.out.println(t); } return resultCount; } private ArrayList readFile(String fileName) { BufferedReader br = null; ArrayList inputList = null; try { File file = new File(fileName); br = new BufferedReader(new FileReader(file)); String message = null; inputList = new ArrayList(); while ((message = br.readLine()) != null) { inputList.add(message); } } catch (IOException ex) { ex.printStackTrace(); } finally { try { br.close(); } catch (IOException ex) { ex.printStackTrace(); } return inputList; } } private void writeFile(String message) { BufferedWriter bw = null; try { File file = new File(""Output.txt""); bw = new BufferedWriter(new FileWriter(file)); bw.write(message); } catch (IOException ex) { ex.printStackTrace(); } finally { try { bw.close(); } catch (IOException ex) { ex.printStackTrace(); } } } public static void main(String[] args) { RecycledNumbers rn = new RecycledNumbers(); rn.process(); } } " B11212,"import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { static String shift(String s) { return s.charAt(s.length() - 1) + s.substring(0, s.length() - 1); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for (int t = 1; t <= T; ++t) { int A = sc.nextInt(), B = sc.nextInt(), count = 0; for (int n = A; n <= B; ++n) { String s0 = Integer.toString(n); Set matches = new HashSet(); for (String s = shift(s0); !s.equals(s0); s = shift(s)) { if (!s.startsWith(""0"")) { int m = Integer.parseInt(s); if (m >= A && m <= B) matches.add(m); } } count += matches.size(); } System.out.printf(""Case #%d: %d\n"", t, count/2); } } } " B12178,"package codejam; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class QualificationC extends CodeJam { public QualificationC(String file) throws Exception { super(file); } @Override public Object processCase(int caseNumber) throws Exception { String readLine = readLine(); String[] split = readLine.split("" ""); int a = Integer.parseInt(split[0]); int b = Integer.parseInt(split[1]); Set found = new HashSet(); for (int i = a; i <= b; i++) { char[] n = (i+"""").toCharArray(); int cN = i; String cM = i+""""; int len = n.length; for (int j = 0; j < len; j++) { cM = cM.substring(len-1) + cM.substring(0, len - 1); int intCm = Integer.parseInt(cM); if (intCm <= b && intCm > cN && intCm >= a) { found.add(cN+' '+cM); } } } return found.size(); } public static void main(String[] args) throws IOException, InterruptedException, Exception { new QualificationC(""C-small-attempt0.in"").start(); } } " B10128,"import java.util.HashSet; import java.util.Scanner; public class Main { public static void main(String[] args){ int t; Scanner s = new Scanner(System.in); t=s.nextInt(); for(int k=1;k<=t;k++){ int a,b; a=s.nextInt(); b=s.nextInt(); int al=a/10,d=1; while(al>0){ d++; al/=10; } int count=0; for(int i=a;i<=b;i++){ HashSet hs = new HashSet(); for(int j=1;j=a && n<=b && n!=i) { if(!hs.contains(n)){ count++; hs.add(n); } } } } System.out.println(""Case #""+k+"": ""+(count/2)); } } } " B10573,"import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.HashMap; public class Recycled { public static void main(String args[]) { try { BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(""c:\\gcj\\C\\C-small-attempt0.in""))); String line=br.readLine(); PrintStream ps=new PrintStream(""c:\\gcj\\C\\C-Small.out""); int n=Integer.parseInt(line); for(int i=1;i<=n;i++) { line=br.readLine(); String[] nums=line.split("" ""); long A=Long.parseLong(nums[0]); long B=Long.parseLong(nums[1]); ps.println(""Case #""+i+"": ""+getCount(A,B)); } } catch(Exception e) { e.printStackTrace(); } } } " B11336,"import java.io.InputStream; import java.io.PrintStream; import java.util.Scanner; public abstract class AbstractCodeJam { public void solveProblems(InputStream in, PrintStream out) { Scanner scan = new Scanner(in); int nb = scan.nextInt(); scan.nextLine(); for (int i = 1; i <= nb; i++) { Problem problem = readProblem(scan); // problem.print(); problem.solve(); out.println(""Case #"" + i + "": "" + problem.getSolution()); } } protected abstract Problem readProblem(Scanner scan); } " B11461,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.util.Scanner; public class C { /** * @param args */ public static void main(String[] args) throws Exception { PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(""c.txt""))); // Scanner s = new Scanner(System.in); Scanner s = new Scanner(new File(""c.in"")); // BufferedReader in = new BufferedReader(new FileReader(new File(""a-small.in""))); int n = s.nextInt(); for(int t=1;t<=n;t++){ int a = s.nextInt(), b = s.nextInt(); System.out.println(""Case #""+t+"": ""+go(a,b)); pw.println(""Case #""+t+"": ""+go(a,b)); pw.flush(); } } static int go(int a,int b){ int r = 0; for(int n=a;n=0 && k<=' ') k=in.read(); StringBuilder bld = new StringBuilder(); while(k>' ') { bld.append((char)k); k=in.read(); } return bld.toString(); } public void solve() throws Exception { int T = iread(); for(int t=1; t<=T; t++) { String A_temp = readword(); int l = A_temp.length(); int A = Integer.parseInt(A_temp); int B = iread(); int result = 0; ArrayList done = new ArrayList(B-A); for(int i=A; i=A && (int)Integer.parseInt(tp2)<=B && !done.contains(tp2)){ ++r_count; done.add(tp2); } } result += r_count*(r_count-1)/2; } out.write(""Case #""+t+"": ""+result+""\n""); } } public void run() { try{ in = new BufferedReader(new FileReader(inputFile)); out = new BufferedWriter(new FileWriter(outputFile)); solve(); out.flush(); }catch(Exception e){ e.printStackTrace(); } } public static void main(String[] args) { new Thread(new C()).start(); } } " B11548,"import java.io.*; import java.util.StringTokenizer; public class RecycledNumbers { static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner(String fileName) throws IOException { br = new BufferedReader(new FileReader(new File(fileName))); } public String nextToken() throws IOException, NullPointerException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public String nextString() throws IOException, NullPointerException { st = null; return br.readLine(); } public Integer nextInt() throws IOException { return Integer.parseInt(nextToken()); } void close() throws IOException { br.close(); } } public static void main(String[] args) throws IOException { final String name = ""C-small-attempt0""; MyScanner in = new MyScanner(name + "".in""); PrintWriter out = new PrintWriter(name + "".txt""); int t = in.nextInt(); for (int i = 1; i <= t; i++) { int a = in.nextInt(); int b = in.nextInt(); int res = 0; for (int n = a; n < b; n++) { int m = n; int l = 0; int k = 1; while (m != 0) { m /= 10; l++; k *= 10; } m = n; k /= 10; int[] w = new int[l]; for (int j = 1; j < l; j++) { m = (m % 10) * k + m / 10; w[j] = m; boolean f = true; for (int q = 1; q < j; q++) { if (m == w[q]) { f = false; continue; } } if (m > n && a <= m && m <= b && f) { res++; } } } out.println(""Case #"" + i + "": "" + res); } in.close(); out.close(); } } " B10660,"package algorithm.adhoc; import java.io.*; import java.util.*; import java.math.*; /** * Created by IntelliJ IDEA. * User: Administrator * Date: 4/15/12 * Time: 1:00 AM * To change this template use File | Settings | File Templates. */ public class GoogleCodeJam { public static void main(String[] arg) throws IOException { Scanner scanner = new Scanner(new FileReader(""G:\\C-small-attempt1.in"")); PrintWriter pw = new PrintWriter(""output.txt""); int t, tcase = 1; int a, b, start, end, temp; int count = 0; t = scanner.nextInt(); String tempStr, tempStr2; char[] chars; char tmp, temp1; while (t > 0) { count = 0; a = scanner.nextInt(); b = scanner.nextInt(); start = a; end = b; for (int i = start; i <= end; ++i) { tempStr = Integer.toString(i); if (tempStr.length() != 1) { if (tempStr.length() == 2) { chars = tempStr.toCharArray(); tmp = chars[0]; chars[0] = chars[1]; chars[1] = tmp; tempStr2 = new String(chars); temp = Integer.parseInt(tempStr2); if (temp > i && temp <= b) ++count; } else if (tempStr.length() == 3) { chars = tempStr.toCharArray(); tmp = chars[0]; chars[0] = chars[2]; chars[2] = tmp; tmp = chars[1]; chars[1] = chars[2]; chars[2] = tmp; tempStr2 = new String(chars); temp = Integer.parseInt(tempStr2); if (temp > i && temp <= b) ++count; chars = tempStr.toCharArray(); tmp = chars[0]; chars[0] = chars[1]; chars[1] = tmp; tmp = chars[1]; chars[1] = chars[2]; chars[2] = tmp; tempStr2 = new String(chars); temp = Integer.parseInt(tempStr2); if (temp > i && temp <= b) ++count; } } } //System.out.println(count); pw.println(""Case #"" + tcase + "": "" + count); --t; ++tcase; } pw.close(); scanner.close(); } } " B12986,"import static java.lang.System.*; import java.util.*; import java.io.*; public class jellyfish { public static void one()throws IOException{ TreeMapt=new TreeMap(); Scanner keyb=new Scanner(new File(""A-small-attempt2.in"")); t.put(""a"",""y""); t.put(""o"",""e""); t.put(""z"",""q""); t.put(""q"",""z""); t.put(""i"",""k""); String a=""ejp mysljylc kd kxveddknmc re jsicpdrysirbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcdde kr kd eoya kw aej tysr re ujdr lkgc jv""; String b=""our language is impossible to understandthere are twenty six factorial possibilitiesso it is okay if you want to just give up""; String c[]=a.split(""""); String d[]=b.split(""""); for(int x=1;xt=new TreeSet(); for(int x=c;x0;y--){ String l=""""; l+=g.substring(y,g.length()); l+=g.substring(0,y); int q=Integer.parseInt(l); String s=Integer.toString(q); if(s.length()==g.length()&&x9){ // t=(i%10==0); // j=(i/10)+(i%10)*pow[(int)Math.round(Math.floor(Math.log(i)/Math.log(10)))]; si=""""+i; // tj=(int)(j%10); // d=z+tj; sj=si; sk=""""; sk=sk+sj.charAt(sj.length()-1); for(k=1;ki && j<=B && j>=A && sk.charAt(0)!=0 && si.charAt(0)!=0) sum++; sj=sk; sk=""""; sk=sk+sj.charAt(sj.length()-1); for(k=1;k i && workingOnIt <= B[whichLine] && permutations[whichEntry][j].charAt(0) != '0' && (i != lastI || workingOnIt != lastWorkingOnIt)) { numberOfSolutions[whichLine]++; lastI = i; lastWorkingOnIt = workingOnIt; } } } return numberOfSolutions[whichLine]; } String rotator(String original, int numberOfTimes) { char[] originalChar = original.toCharArray(); char temp; for (int i = 0; i < numberOfTimes; i++) { temp = originalChar[0]; for (int j = 1; j < originalChar.length; j++) { originalChar[j - 1] = originalChar[j]; } originalChar[originalChar.length - 1] = temp; } String rotatedString = new String(originalChar); return rotatedString; } }" B10356,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recycled; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; /** * * @author Calido */ class myobj { long n; long m; public myobj(long n,long m) { this.n=n; this.m=m; } } public class Recycled { /** * @param args the command line arguments */ public static void main(String args[]) { ArrayList list=new ArrayList(); int t; long a,b,cnt; try { Scanner scnr=new Scanner(new File(args[0])); PrintWriter out=new PrintWriter(new File(args[1])); t=scnr.nextInt(); for(int i=1;i<=t;i++) { //cnt=0; list.clear(); a=scnr.nextLong();//inputing a b=scnr.nextLong();//inputing b for(long j=a;j<=b;j++) { long n=j; long m; long tmp1; int len=String.valueOf(n).length(); for(int k=1;k map) { String str1 = new Integer(num).toString(); char[] arr = str1.toCharArray(); int len = arr.length; if(len <= 1) { return 0; } int cnt = 0; String str = str1 + str1; for (int i = 0; i < len-1; i++) { char ch = arr[len - 1]; for (int j = len - 1; j > 0; j--) { arr[j] = arr[j - 1]; } arr[0] = ch; String str2 = new String(arr); int c2 = Integer.parseInt(str2); if(c2 != num && (c2 >= num) && (c2 <= b) && str.contains(str2)) { if(!map.containsKey(str1+"",""+str2)) { map.put(str1+"",""+str2, null); cnt ++; } } } return cnt; } public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); if (args.length >= 2) { inputFileName = args[0]; outputFileName = args[1]; } in = new Scanner(new FileReader(inputFileName)); out = new PrintWriter(outputFileName); int tests = in.nextInt(); //in.nextLine(); int a, b; HashMap map; for (int t = 1; t <= tests; t++) { a = in.nextInt(); b = in.nextInt(); map = new HashMap(); System.out.println(""A == ""+a+"" B ==""+ b); int totalCnt = 0; while(a <= b) { totalCnt += rotateAndCount(a, b, map); a++; } System.out.println(""Case #"" + t + "": ""+totalCnt); out.println(""Case #"" + t + "": ""+totalCnt); } in.close(); out.close(); } } " B11053,"package recycled; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; public class Main { public static void main(String[] args) throws IOException { File file = new File(""C-small-attempt0.in""); FileReader fr = new FileReader(file); BufferedReader in = new BufferedReader(fr); String line=in.readLine(); String[] tokens; int num = Integer.parseInt(line); int i=1; int A,B; String str; int n,count; while(i<=num){ line=in.readLine(); tokens = line.split("" ""); A = Integer.parseInt(tokens[0]); B = Integer.parseInt(tokens[1]); count = 0; for(int m=A;mm && n<=B){ count++; } if(n==m){ break; } } } System.out.println(""Case #""+i+"": ""+count); i++; } } } " B12981,"import java.io.*; import java.util.*; public class ReNum { static BufferedReader br; static PrintWriter pw; public static void main(String args[]) { try { br = new BufferedReader(new FileReader(""C-small-attempt1.in"")); pw = new PrintWriter(new File(""ReNumAns.out"")); String no = br.readLine(); int number = Integer.parseInt(no); for (int h = 0; h <= number - 1; h++) { int finAns =0; String nos = br.readLine(); String[] n = nos.split("" ""); int num1 = Integer.parseInt(n[0]); int e = Integer.parseInt(n[1]); int size = n[0].length(); for (int i=num1;i<=e;i++){ String t = Integer.toString(i); for (int j = 1;ji && num2<=e && num2>=num1){ finAns++; } } } int caseNo = 1 + h; String ans = ""Case #"" + caseNo + "": "" + finAns; pw.println(ans); pw.flush(); } } catch (IOException e) { e.printStackTrace(); } } } " B12866,"package javaapplication2; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { private final static String INPUT_PATH = ""resources/recycled_numbers.in""; private final static String OUTPUT_PATH = ""resources/recycled_numbers.out""; private static int caseNumber = 0; private final static int[] TEN_POWS = new int[]{1, 10, 100, 1000, 10000, 100000, 1000000}; public static void main(String[] args) throws FileNotFoundException, IOException { try (Scanner scanner = new Scanner(new File(INPUT_PATH))) { int T = scanner.nextInt(); try (FileWriter out = new FileWriter(OUTPUT_PATH)) { for (int i = 0; i < T; ++i) { processCase(scanner, out); } } } } private static void processCase(Scanner scanner, FileWriter out) throws IOException { out.write(""Case #"" + (++caseNumber) + "": ""); Set pairs = new HashSet<>(); int A = scanner.nextInt(); int B = scanner.nextInt(); int result = 0; for (int n = A; n <= B; ++n) { int shiftCount = ((int) Math.floor(Math.log10(n))); for (int i = 1; i <= shiftCount; ++i) { int right = n / TEN_POWS[i]; int left = n % TEN_POWS[i]; int shifted = left * TEN_POWS[shiftCount + 1 - i] + right; if (shifted != n && shifted <= B && shifted >= A && ((int) Math.floor(Math.log10(n))) == shiftCount) { Pair pair = new Pair(n, shifted); if (!pairs.contains(pair)) { ++result; pairs.add(pair); } } } } out.write(result + """"); out.write(""\n""); } private static class Pair { private int a, b; public Pair(int a, int b) { this.a = a; this.b = b; } @Override public boolean equals(Object that) { if (that instanceof Pair) { Pair pair = (Pair) that; if (this.a == pair.a && this.b == pair.b) { return true; } if (this.a == pair.b && this.b == pair.a) { return true; } } return false; } @Override public int hashCode() { return new Integer(a).hashCode() + new Integer(b).hashCode(); } } } " B12360,"package codejam.qualification; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class Main { public static void main(String[] args) throws IOException { Scanner in = new Scanner(new File(""input.txt"")); FileWriter out = new FileWriter(""output.txt""); // ignore test cases in.nextLine(); int count = 1; while (in.hasNext()) { out.write(""Case #"" + count++ + "": "" + calc(in.nextLong(), in.nextLong()) + ""\n""); } out.flush(); out.close(); in.close(); } public static long calc(long A, long B) { long count = 0; for (long n=A; n dictionary = createDictionary(); int taskLength = Integer.parseInt(myReader.read()); for (int i = 1; i <= taskLength; i++) { String taskString = myReader.read(); Task task = new Task(dictionary); String result = task.execute(taskString); myWriter.writeString(""Case #"" + i + "": "" + result); System.out.println(""Case #"" + i + "": "" + result); } myWriter.close(); } private static Map createDictionary() { Map result = new HashMap(); result.put('q', 'z'); result.put('z', 'q'); String[] originals = { ""ejp mysljylc kd kxveddknmc re jsicpdrysi"", ""rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd"", ""de kr kd eoya kw aej tysr re ujdr lkgc jv"" }; String[] results = { ""our language is impossible to understand"", ""there are twenty six factorial possibilities"", ""so it is okay if you want to just give up"" }; for(int i = 0; i < originals.length; i++){ for(int p = 0; p < originals[i].length(); p++){ if (!result.containsKey(originals[i].charAt(p))){ result.put(originals[i].charAt(p), results[i].charAt(p)); } } } return result; } } " B12603,"import java.io.*; import java.util.*; public class C extends CodeJammer { public void process() throws IOException { long[] input = reader.readLongArray(); long a = input[0]; long b = input[1]; int digits = 0; long a1 = a; while (a1>0) { a1 /= 10; digits++; } long total = 0; for (long x=a; x<=b; x++) { total += count(x,a,b, digits); } output(total); } public long count(long x, long a, long b, int d) { Set s = new HashSet(); long y = x; for (int i=1; ix && y>=a && y<=b) s.add(y); } return s.size(); } public long rotate(long y, int d) { long digit = y%10; long rest = y/10; digit *= Math.pow(10,d-1); return digit + rest; } public static void main(String[] args) { C c = new C(); c.run(args); } } " B10900,"import java.io.File; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class C { public static void main(String[] args) throws Exception{ long tIni=System.currentTimeMillis(); Scanner s=new Scanner(new File(""./data/C.txt"")); PrintWriter pw=new PrintWriter(new File(""./data/C_sol.txt"")); int ncases=s.nextInt();s.nextLine(); for(int curr=0;currA && resp<=B && resp>j ) { boolean ok=true; for(int i=0;ii && Integer.parseInt(o)<=B ){ boolean ok=true; int resp=Integer.parseInt(o); for(int j=0;j=a && num<=b && j!=num) { if(j<=num) { if(add(j,num)) result++; } else { if(add(num,j)) result++; } } } } } if(ex2==true) { //Do Nothing } if(ex3==true) { //Do Nothing } System.out.println(""Case #""+(i+1)+"": ""+result); } } static boolean add(int m,int n) { //Pass such that m0 ){ d++; x /= 10; } return d; } static int power(int x){ int n = 1; while(x>0){ n *= 10; x--; } return n; } static int cirNum(int n, int m){ int d = digit(n); n = (n%power(d-m))*power(m) + (n/power(d-m)); return n; } static int result(int A, int B){ int d = digit(A); int count = 0; for(int i = A; i <= B; i++){ int[] key = new int[d-1]; for(int j = 1; j < d; j++){ key[j-1] = cirNum(i, j); for(int k = 0; k < j-1; k++){ if( key[j-1] == key[k] ){ if( key[j-1] != i && key[j-1] >= A && key[j-1] <= B ) count--; } } if( key[j-1] != i && key[j-1] >= A && key[j-1] <= B ){ count++; } } } return count/2; } public static void main(String[] args){ Scanner stdIn = new Scanner(System.in); int T = stdIn.nextInt(); // the number of test cases String[] str = new String[T+1]; String[][] data = new String[T][2]; for(int i = 0; i < T+1; i++){ str[i] = stdIn.nextLine(); } for(int i = 0; i < T; i++){ data[i] = str[i+1].split("" "", 2); } int[] A = new int[T]; int[] B = new int[T]; for(int i = 0; i < T; i++){ A[i] = Integer.parseInt(data[i][0]); B[i] = Integer.parseInt(data[i][1]); } for(int i = 0; i < T; i++){ System.out.println(""Case #"" + (i+1) + "": "" + result(A[i], B[i])); } } } " B11091,"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; import proba.Main; /** * 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 currLineTokens = new ArrayList(); 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 = Main.class.getName(); int dotIdx = fullClassName.indexOf('.'); String pkgName = fullClassName.substring(0, dotIdx).toLowerCase(); pkgName = ""probc""; 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() { @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 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(); } " B12138,"import java.util.*; import java.io.*; class RecycledNumbers{ static int A,B,l,count=0; static int v[]=new int[10000]; public static void main(String[] args){ try { File file = new File(""C-small-attempt1.in""); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); File file1 = new File(""Coutput2.in""); FileWriter fw = new FileWriter(file1); PrintWriter pw = new PrintWriter(fw); int T= Integer.valueOf(br.readLine()); int i,p=1,j,k; while(p<=T) { String G=br.readLine(); j=0;i=0;k=1; int m=1; String r=""""; if(G==null)break; int l; for(l=0;l0) { c++; a=a/10; } return c; } static int shiftone(int n) { int v=n%10; n=n/10; return (n+v*pow(10,length(n))); } static int shifttwo(int n) { int v=n%100; n=n/100; return (n+v*pow(10,length(n))); } static int pow(int i,int j) { if(j==0) return 1; return i*pow(i,j-1); } static boolean range(int m) { for(int i=A;i<=B;i++) { if(m==i){ return true; } } return false; } }//class " B10670," package recyclednumbers; import java.io.*; /** * * @author Kuzu */ public class RecycledNumbers { public static void main(String[] args) { try{ FileInputStream fstream = new FileInputStream(""C-small-attempt3.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String numberOfTest = br.readLine(); int numberOfTestCases = Integer.parseInt(numberOfTest); Recycler recycler = new Recycler(numberOfTestCases + 1); for(int i = 0; i < numberOfTestCases; i++){ String line = br.readLine(); int spaceIndex = line.indexOf("" ""); String char3 = line.substring(0,spaceIndex); int char1 = Integer.parseInt(char3); char3 = line.substring(spaceIndex+1); int char2 = Integer.parseInt(char3); recycler.addNumbers(char1, char2); } recycler.convert(); in.close(); } catch (IOException | NumberFormatException e){ System.err.println(""Error: "" + e.getMessage()); } } public static class Recycler { public int caseNumber; int [] lines = new int[100]; int index, ind, count; public Recycler(int n) { caseNumber = n; index = 0; ind = -2; count = 0; } public void convert() throws IOException{ try (BufferedWriter out = new BufferedWriter(new FileWriter(""Output-C-small.txt""))) { for(int a = 1; a < caseNumber; a++){ out.write(""Case #"" + a + "": "" ); ind = ind +2; count = 0; for(int i = lines[ind]; i < lines[ind+1];){ if((i/10 == 0)&&(i <= 100)) i++; else if((i % 10 == 0)&&(i <= 100)) i++; else { if(i < 100) { String temp = Integer.toString(i); String compare = temp.substring(1,2) + temp.substring(0,1); int compare1 = Integer.parseInt(compare); if((i < compare1) && (compare1 <= lines[ind+1])){ count++; i++; } else i++; } if((i>99) && (i<1000)){ String temp = Integer.toString(i); String compare = temp.substring(2,3) + temp.substring(0,2); int compare1 = Integer.parseInt(compare); if((i < compare1) && (compare1 <= lines[ind+1])){ count++; } compare = temp.substring(1,3) + temp.substring(0,1); compare1 = Integer.parseInt(compare); if ((i < compare1) && (compare1 <= lines[ind+1])){ count++; i++; if(temp.substring(1,2).equals(""0"")) count--; } else i++; } } } out.write("""" + count); out.write(""\r\n""); } out.close(); } } private void addNumbers(int ch1, int ch2) { lines[index] = ch1; index++; lines[index] = ch2; index++; } } } " B12243,"public class RecycledNumbers { public static void main(String[] args) { java.util.Scanner console = new java.util.Scanner(System.in); int T = 0; int A = 0, B = 0; int numRecycledNumbers = 0; T = console.nextInt(); console.nextLine(); for (int i = 0; i < T; i++) { A = console.nextInt(); B = console.nextInt(); console.nextLine(); // do stuff numRecycledNumbers = findRecycledNumbers(A, B); System.out.println(""Case #"" + (i + 1) + "": "" + numRecycledNumbers); } return; } private static int findRecycledNumbers(int A, int B) { int n = B; int magnitude= 0; int pairs = 0; boolean alreadySubtractedOne = false; String str_m = String.valueOf(A); String str_n = String.valueOf(B); String firstHalf = """"; String secondHalf = """"; // m = x.y * 10^magnitude // magnitude 1 less then number of digits magnitude = str_n.length() - 1; // halfPower is used to retrieve the first half of m. int halfPower = 1; for (int i = 0; i < (magnitude + 1) / 2; i++) halfPower *= 10; for (int m = A; m <= B; m++) { str_m = String.valueOf(m); for (int j = magnitude ; j > 0; j--) { // Substring goes from start to end - 1, hence need to add 1 // as 'magnitude' already has 1 subtracted from it. str_n = str_m.substring(j, magnitude + 1) + str_m.substring(0, j); n = Integer.parseInt(str_n); if ((n > m) && (n <= B)) { // If m is of even length and first half matches second half // two duplicate entries can be generated, so subtract 1 from count // ie. xyz|xyZ => Zxyz|xy or z|xyZxy if (!alreadySubtractedOne && (((m % halfPower) * halfPower) == (m - (m % halfPower)))) { alreadySubtractedOne = true; pairs--; } pairs++; } } } return pairs; } } " B10192," import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.Scanner; public class C { public static HashMap> recycledNumbers = new HashMap>( ); public ArrayList getRecycledNumbers( Integer n, Integer a, Integer b ) { if ( n < 10 || ( n < 100 && n % 10 == 0 ) ) return null; ArrayList aList = recycledNumbers.get( n ); if ( aList == null ) { aList = new ArrayList( ); String s = n.toString( ); int len = s.length( ); for ( int i = 1; i < len; i++ ){ Integer m = new Integer( s.substring( len-i ) + s.substring( 0, len-i) ); if ( m > n && m.toString( ).length( ) == s.length( ) ) { if ( !aList.contains( m ) ) { aList.add( m ); } } } recycledNumbers.put( n, aList ); } return filterRecycledNumbers( aList, a, b ); } public ArrayList filterRecycledNumbers( ArrayList list, Integer a, Integer b ) { ArrayList retList = new ArrayList( ); Iterator iterator =list.iterator( ); while ( iterator.hasNext( ) ) { Integer i = iterator.next( ); if ( ( a <= i && i <= b ) ) { retList.add( i ); } } return retList; } public void solve( Scanner sc, PrintWriter pw ) { int tests = sc.nextInt( ); sc.nextLine( ); for ( int i = 0 ; i < tests; i++ ) { int a = sc.nextInt( ); int b = sc.nextInt( ); ArrayList recycledNumbers = new ArrayList( ); for ( int j = a; j <= b; j++ ) { ArrayList lst = getRecycledNumbers( j, a, b ); if ( lst != null && lst.size( ) > 0 ) { recycledNumbers.addAll( lst ); } } pw.print( ""Case #"" + (i+1) + "": "" + recycledNumbers.size( ) ); pw.println( ); pw.flush( ); } } public static void main ( String[] args ) throws IOException { Scanner sc = new Scanner(new FileReader(""C-small-attempt0.in"")); PrintWriter pw = new PrintWriter(new FileWriter(""C-small-attempt0.out"")); new C( ).solve( sc, pw ); pw.close( ); sc.close( ); } }" B12736,"import java.util.Scanner; public class C_RecycledNumbers { static int[] bases = {0, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000}; static int digits(int value) { int i = 0; for (; i < bases.length && value >= bases[i]; i++); return i; } static int shift(int value, int len) { int last = value % 10; return (int)(Math.pow(10, len - 1)) * last + (value / 10); } static int countRecycled(int value, int B) { int shifted = value; int len = digits(value); int[] cache = new int[len]; int ck = 0; out: for (int i = 0; i < len - 1; i++) { shifted = shift(shifted, len); if (shifted > value && shifted <= B) { for (int j = 0; cache[j] != 0; j++) if (cache[j] == shifted) continue out; //System.out.println(""n="" + value + "", m="" + shifted); cache[ck++] = shifted; } } return ck; } /** * @param args */ public static void main(String[] args) { /*int A = 1; int B = 500; int count = 0; for (int val = A; val <= B; val++) { count += countRecycled(val, B); } System.out.println(count);*/ Scanner scan = new Scanner(System.in); int test = scan.nextInt(); for (int t = 1; t <= test; t++) { int A = scan.nextInt(); int B = scan.nextInt(); int count = 0; for (int val = A; val <= B; val++) { count += countRecycled(val, B); } System.out.println(""Case #"" + t + "": "" + count); } } } " B12637,"import java.util.Scanner; public class C { public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); in.nextLine(); //for each test case for (int i = 1; i <= T; i++) { int A = in.nextInt(); int B = in.nextInt(); int result = 0; for (int n = A; n <= B - 1; n++) for (int m = n + 1; m <= B; m++) if (isRecycledPair(n, m)) result++; System.out.format(""Case #%d: %d\n"", i, result); } } private static boolean isRecycledPair(int n, int m) { String strN = """" + n; String strM = """" + m; int length = strN.length(); for (int i = 0; i < length; i++) { boolean good = true; for (int j = 0; j < length; j++) { if (strN.charAt(j) != strM.charAt((i + j) % length)) { good = false; break; } } if (good) return true; } return false; } }" B12961,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.StringTokenizer; import java.util.TreeSet; public class Recycle { static TreeSet set = new TreeSet(); public static void main(String[] args) { System.out.println(""\t****** Recycle numbers ******""); long start = System.currentTimeMillis(); String tokenStr; int test;int y=0,a=0,b=0; try { BufferedReader in = new BufferedReader(new FileReader(""C-small-attempt0.in"")); PrintWriter out = new PrintWriter(new FileWriter(""C-small-output0.txt"")); //read the first line of the file test = Integer.parseInt(in.readLine()); for(int i = 1; i <= test; i++) { tokenStr = in.readLine(); StringTokenizer tok = new StringTokenizer(tokenStr); a = Integer.parseInt(tok.nextToken()); b = Integer.parseInt(tok.nextToken()); ///////////// set.clear();y=0; for (int j=a;j<=b;j++) { if (set.contains(j)) continue; y += group(j,a,b); } /////////////// out.println(""Case #"" + i +"": "" +y); }//for out.flush();out.close();in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } long time = System.currentTimeMillis()-start; System.out.println(""time = ""+time); } private static int group(int j, int a, int b) { String s = String.valueOf(j); boolean zero=false; int len = s.length(); int msb = (int) Math.pow(10, (len-1)); int n=j;int count=0; for (int i=0;i=a && n<=b) { if (!set.contains(n)) { set.add(n); count++; } } //calcolo prox giro. int r = n %10; zero = (r==0);//se leading zero salto a prox iterazione n = n/10 + r*msb; } return count*(count-1)/2; // nume coppie combinazioni di count su 2 } } " B10889,"package de.at.codejam.gui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTextArea; import de.at.codejam.util.CodeJamConstants; import de.at.codejam.util.StatusListener; import de.at.codejam.util.TaskStatus; public class CodeJamStatusPanel extends JPanel implements CodeJamConstants, StatusListener { private static final long serialVersionUID = -4645339049484500917L; private int currentLogLevelTreshold = StatusListener.LOGLEVEL_INFO; private JPanel statusIconPanel = new JPanel() { private static final long serialVersionUID = -1109894604603210990L; public Insets getInsets() { return new Insets(10, 10, 10, 10); } }; private JTextArea consoleArea = new JTextArea(); private JProgressBar progressBar = new JProgressBar(); public CodeJamStatusPanel() { super(new BorderLayout()); setPreferredSize(DEFAULT_STATUSPANEL_SIZE); statusIconPanel.setBackground(Color.WHITE); statusIconPanel.setBorder(BorderFactory.createRaisedBevelBorder()); statusIconPanel.setPreferredSize(new Dimension(128, 128)); statusIconPanel.setSize(128, 128); add(statusIconPanel, BorderLayout.WEST); consoleArea.setText(""All console input goes here ..."" + '\n'); JPanel consolePanel = new JPanel(); consolePanel.setLayout(new BorderLayout()); consolePanel.add(new JScrollPane(consoleArea), BorderLayout.CENTER); JPanel loglevelPanel = new JPanel(new BorderLayout()); loglevelPanel.setBorder(BorderFactory.createTitledBorder(""LogLevel"")); JRadioButton loglevelButtonTrace = new JRadioButton(""Trace""); loglevelButtonTrace.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { CodeJamStatusPanel.this.currentLogLevelTreshold = StatusListener.LOGLEVEL_TRACE; } }); JRadioButton loglevelButtonInfo = new JRadioButton(""Info""); loglevelButtonInfo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { CodeJamStatusPanel.this.currentLogLevelTreshold = StatusListener.LOGLEVEL_INFO; } }); JRadioButton loglevelButtonWarning = new JRadioButton(""Warning""); loglevelButtonWarning.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { CodeJamStatusPanel.this.currentLogLevelTreshold = StatusListener.LOGLEVEL_WARN; } }); JRadioButton loglevelButtonError = new JRadioButton(""Error""); loglevelButtonError.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { CodeJamStatusPanel.this.currentLogLevelTreshold = StatusListener.LOGLEVEL_ERROR; } }); if (StatusListener.LOGLEVEL_TRACE == currentLogLevelTreshold) { loglevelButtonTrace.setSelected(true); } else if (StatusListener.LOGLEVEL_INFO == currentLogLevelTreshold) { loglevelButtonInfo.setSelected(true); } else if (StatusListener.LOGLEVEL_WARN == currentLogLevelTreshold) { loglevelButtonWarning.setSelected(true); } else if (StatusListener.LOGLEVEL_ERROR == currentLogLevelTreshold) { loglevelButtonError.setSelected(true); } ButtonGroup loglevelGroup = new ButtonGroup(); loglevelGroup.add(loglevelButtonTrace); loglevelGroup.add(loglevelButtonInfo); loglevelGroup.add(loglevelButtonWarning); loglevelGroup.add(loglevelButtonError); JPanel levelGrid = new JPanel(new GridLayout(1, 4)); levelGrid.add(loglevelButtonTrace); levelGrid.add(loglevelButtonInfo); levelGrid.add(loglevelButtonWarning); levelGrid.add(loglevelButtonError); loglevelPanel.add(levelGrid); consolePanel.add(loglevelPanel, BorderLayout.NORTH); JPanel progressPanel = new JPanel(new BorderLayout()); progressPanel.setBorder(BorderFactory.createTitledBorder(""Progress"")); progressPanel.add(progressBar, BorderLayout.CENTER); consolePanel.add(progressPanel, BorderLayout.SOUTH); add(consolePanel, BorderLayout.CENTER); } @Override public Insets getInsets() { return new Insets(10, 10, 10, 10); } @Override public void updateStatus(TaskStatus taskStatus) { progressBar.setStringPainted(true); boolean indeterminate = (UNDEFINED == taskStatus.getNumberCases()) || (UNDEFINED == taskStatus.getNumberCurrentCase()); if (!indeterminate) { progressBar.setMaximum(taskStatus.getNumberCases()); progressBar.setMinimum(1); progressBar.setValue(taskStatus.getNumberCurrentCase()); } progressBar.setIndeterminate(indeterminate); if (TaskStatus.STATUS_WAITING == taskStatus.getCurrentTaskStatus()) { progressBar.setString(""Waiting""); statusIconPanel.setBackground(COLOR_WAITING); } else if (TaskStatus.STATUS_RUNNING == taskStatus .getCurrentTaskStatus()) { progressBar.setString(""Running""); statusIconPanel.setBackground(COLOR_RUNNING); } else if (TaskStatus.STATUS_DONE == taskStatus.getCurrentTaskStatus()) { progressBar.setString(""Done""); statusIconPanel.setBackground(COLOR_DONE); } else if (TaskStatus.STATUS_ERROR == taskStatus.getCurrentTaskStatus()) { progressBar.setString(""Sad Panda""); statusIconPanel.setBackground(COLOR_ERROR); } } @Override public void log(int logLevel, String message) { if (logLevel > currentLogLevelTreshold) { return; } StringBuilder newConsoleText = new StringBuilder(consoleArea.getText()); newConsoleText.append(""\n""); newConsoleText.append(message); consoleArea.setText(newConsoleText.toString()); } } " B12436,"import java.util.ArrayList; import java.util.Scanner; import java.io.*; /** * */ /** * @author Daniel * */ public class Recycled { public static ArrayList generateRecycled(int seed){ String seeds = Integer.toString(seed); ArrayList recycled = new ArrayList(); Integer temp; for (int i = 1; i < seeds.length(); i++){ temp = Integer.parseInt(seeds.substring(i) + seeds.substring(0, i)); if (temp.intValue()!=seed && !recycled.contains(temp)) recycled.add(temp); } return recycled; } /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { if (args.length!=2){ System.err.println(""Error with arguments""); System.exit(-1); } // Configuring input and output Scanner input = new Scanner(new FileReader(new File(args[0]))); Writer output = new BufferedWriter(new FileWriter(new File(args[1]))); int T = input.nextInt(); int A, B, count, temp; for (int i = 1; i <= T; i++){ System.out.print(""Case #"" + i + "": ""); output.write(""Case #"" + Integer.toString(i) + "": ""); A = input.nextInt(); B = input.nextInt(); count = 0; temp = 0; ArrayList found = new ArrayList(); for (int j = A; j <= B; j++){ if (found.contains(Integer.valueOf(j))) continue; ArrayList recycled = new ArrayList(generateRecycled(j)); temp = 0; for (Integer e :recycled){ if ((e.intValue() >= A) && (e.intValue() <= B)){ found.add(e); temp ++; } } if (temp > 0){ count += temp * (temp+1) / 2; } } System.out.print(count); output.write(Integer.toString(count)); System.out.println(); output.write(""\n""); } output.close(); } } " B10623,"package CaseSolvers; import Controller.IO; public class RecycledNumbersCase extends CaseSolver { public RecycledNumbersCase(int order, int numberOfLines, IO io) { super(order, numberOfLines, io); } int a, b; @Override public void addLine(String line) { String[] str = line.split("" ""); a = Integer.parseInt(str[0]); b = Integer.parseInt(str[1]); } @Override public void printSolution() { System.err.println(""Case #"" + getOrder() + "": "" + cont); } int cont; @Override public CaseSolver process() { for (int m = a; m < b; m++) { for (int n = m + 1; n <= b; n++) { //System.err.println(m + "" e "" + n); if (isRecycled(m, n)) { cont++; } } } return this; } private boolean isRecycled(int m, int n) { StringBuilder a = new StringBuilder("""" + m); String b = """" + n; for (int i = 0; i < a.length() - 1; i++) { a.insert(0, a.charAt(a.length() - 1)).deleteCharAt(a.length() - 1); if (a.toString().equals(b)) { return true; } } return false; } @Override public void initializeVars() { // TODO Auto-generated method stub } } " B10549," import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.FileReader; import java.io.OutputStream; import java.io.PrintStream; import java.util.HashSet; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author bgamlath */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) throws Exception { // TODO code application logic here Integer.parseInt(""00001""); BufferedReader in = new BufferedReader(new FileReader(""input.txt"")); PrintStream out = new PrintStream(""output.txt""); int n = Integer.parseInt(in.readLine()); for(int i = 1; i<=n; i++){ out.println(""Case #"" + i + "": "" + getRes(in.readLine())); } } static int getRes(String str){ String[] m = str.split("" ""); int a = Integer.parseInt(m[0]); int b = Integer.parseInt(m[1]); int res = 0; for(int i = a; i<=b; i++){ res += count(i, b); } return res; } static int count(int i, int b){ HashSet k = new HashSet(); String s = i + """"; int len = s.length(); int t = i; for(int j = 1; j< len; j++){ k.add(Integer.parseInt((s.substring(j) + s.substring(0,j)))); } int res = 0; for(int j: k){ if((j+"""").length()==len && j>i && j<=b) res++; } return res; } } " B12145,"import java.io.File; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { static HashSet set; public static int solve(int A, int B) { int count = 0; for(int n = A; n < B;n++) { String temp = n+""""; int len = temp.length(); for(int j = 0;j < len-1;j++) { temp = temp.charAt(len-1)+temp.substring(0,len-1); int m = Integer.parseInt(temp); if(set.contains(""""+m)) continue; if(m > n && m <= B) count++; set.add(""""+m); } set.clear(); } return count; } public static void main(String[] args) { set = new HashSet(); Scanner sc = null; try { sc = new Scanner(new File(""C:\\Users\\oibe\\Desktop\\C-small-attempt1.in"")); } catch (FileNotFoundException e) { e.printStackTrace(); } int numCases = Integer.parseInt(sc.nextLine()); for(int i = 1; i <= numCases;i++) { String[] vals = sc.nextLine().split("" ""); int A = Integer.parseInt(vals[0]); int B = Integer.parseInt(vals[1]); System.out.println(""Case #""+i+"": ""+solve(A,B)); } } } " B12713,"import java.io.IOException; import java.util.InputMismatchException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.math.BigInteger; import java.util.HashSet; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author lwc626 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; MyInputReader in = new MyInputReader(inputStream); MyOutputWriter out = new MyOutputWriter(outputStream); C_Recycled_Numbers solver = new C_Recycled_Numbers(); solver.solve(1, in, out); out.close(); } } class C_Recycled_Numbers { public void solve(int testNumber, MyInputReader in, MyOutputWriter out) { int test = in.nextInt() ; for (int tc = 0; tc < test; tc++) { int A = in.nextInt() ; int B = in.nextInt() ; HashSet> myset = new HashSet>(); int len = Integer.toString( A ).length() , d = power( len ) ; //out.printLine( d , len ); for( int n = A ; n <= B-1 ; n ++ ){ if( Integer.toString(n).length() > len ){ len ++ ; d *= 10 ;} int nn = n ; for( int i = 1 ; i < len ; i ++ ){ int last = nn % 10 ; nn = nn / 10 + last * d ; if( last == 0) continue; if( nn > n && nn <= B ){ myset.add( Pair.makePair( n ,nn) ); } } } //if( tc < 2 )out.printLine( myset.toString()); out.printLine(""Case #"" + (tc+1) + "": "" + myset.size() ); } } private int power(int d) { int ret = 1 ; for( int i = 1 ; i < d ; i ++ ) ret *= 10 ; return ret; } } class MyInputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public MyInputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt(){ return readInt() ; } public static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } class MyOutputWriter { private final PrintWriter writer; public MyOutputWriter(OutputStream outputStream) { writer = new PrintWriter(outputStream); } public MyOutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } } class Pair implements Comparable> { public final U first; public final V second; public Pair(U first, V second) { this.first = first; this.second = second; } public static Pair makePair(U first, V second) { return new Pair(first, second); } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; return !(first != null ? !first.equals(pair.first) : pair.first != null) && !(second != null ? !second.equals(pair.second) : pair.second != null); } public int hashCode() { int result = first != null ? first.hashCode() : 0; return 31 * result + (second != null ? second.hashCode() : 0); } public String toString() { return ""("" + first + "","" + second + "")""; } public int compareTo(Pair o) { int value = ((Comparable)first).compareTo(o.first); if (value != 0) return value; return ((Comparable)second).compareTo(o.second); } } " B11248,"import java.util.*; import java.io.*; public class Recycled { public static void main(String[] sArgs)throws IOException { Scanner oScan = new Scanner(new File(""recycled.in"")); PrintWriter out = new PrintWriter(""recycled.out""); int o_0 = oScan.nextInt();oScan.nextLine(); for(int o_o=1;o_o<=o_0;o_o++) { int A = oScan.nextInt(),B=oScan.nextInt(); int count=0,base=0; for(int i=1;i<=A;i*=10)base+=i; for(int i=A;i nums = new ArrayList(); if(i%base==0) { //System.out.println(""same ""+i); continue; } for(int j=1;ji&&rec<=B&&!nums.contains(rec)){count++;nums.add(rec);} } } out.println(""Case #""+o_o+"": ""+count); } out.close(); } }" B11352,"import java.io.*; import java.util.*; public class dancing { public static void main(String[] args)throws Exception { BufferedReader br = new BufferedReader(new FileReader(""dancing.in"")); PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(""dancing.out""))); int n = Integer.parseInt(br.readLine()); for(int i = 0; i < n; i++) { StringTokenizer st = new StringTokenizer(br.readLine() + "" ""); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); int count = 0; for(int k = a; k <= b; k++) { if(k == 1000) continue; if(k / 10 == 0) continue; if(k / 100 == 0) { String s = """" + (k % 10) + """" + (k / 10); int si = Integer.parseInt(s); if(si < k && si >= a) count++; continue; } if(k / 1000 == 0) { String s1 = """" + (k%100) + """" + (k/100); int i1 = Integer.parseInt(s1); if(i1 >= a && i1 < k) count++; String s2 = """" + (k%10) + """" + (k/10); int i2 = Integer.parseInt(s2); if(i2 < k && i2 >= a) count++; } } pw.println(""Case #"" + (i+1) + "": "" + count); } pw.close(); System.exit(0); } } " B12856,"import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) throws NumberFormatException, IOException { FileInputStream inFile = new FileInputStream(new File(""resources/codejam/RecycledNumbers.in"")); DataInputStream in = new DataInputStream(inFile); FileOutputStream outFile = new FileOutputStream(new File(""resources/codejam/RecycledNumbers.out"")); DataOutputStream out = new DataOutputStream(outFile); int cases = Integer.parseInt(in.readLine()); for(int i=0;i 1) { //check for recycles String firstStr = String.valueOf(numbers.charAt(0)); int firstNo = Integer.parseInt(firstStr); HashSet record = new HashSet(); for(int j = 1; j < len; j++) { int currNo = Integer.parseInt(String.valueOf(numbers.charAt(j))); if(currNo > firstNo || currNo == 0) { continue; } String newNo = numbers.substring(j) + numbers.substring(0, j); Integer newVal = Integer.valueOf(newNo); if(newVal < i && newVal >= a) { record.add(newVal); } } recycles+= record.size(); } } sb.append(recycles); out.writeBytes(sb.toString()); } } " B10601,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; public class main { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { BufferedReader dat=new BufferedReader(new FileReader(""input"")); int BRCASE=Integer.parseInt(dat.readLine()); for(int ic=1;ic<=BRCASE;ic++){ String str[]= dat.readLine().split("" ""); System.out.println(""Case #""+ic+"": ""+test(Integer.parseInt(str[0]),Integer.parseInt(str[1]))); } } public static int test(int n, int m){ boolean [] pominati= new boolean[m-n+10]; int rez=0; for(int i=n;i<=m;i++){ int ttl=0; int tmp=i; if(!pominati[tmp-n]){ do{ if(tmp>=n && tmp<=m){ if(!pominati[tmp-n]){ pominati[tmp-n]=true; ttl++; } } tmp=rotate(tmp); }while(tmp!=i); } rez+=(ttl>=2)?comb(ttl,2):0; } return rez; } public static int rotate(int x){ int pow = (int)Math.log10(x); do{ if(x%10!=0){ x = (int) ((int)x%10*Math.pow(10, pow)+(int)x/10); break; }else{ x = (int) ((int)x%10*Math.pow(10, pow)+(int)x/10); } }while(true); return x; } public static int fact(int x){ int ret=1; for(int i=1;i<=x;i++){ ret*=i; } return ret; } public static long comb(int n, int k){ if(k>(n-k)) k=n-k; long c=1; for(int i=0; i nbs; int pairs = 0, casenb; private ThreadDispatcher td; private int A, B; public SolveThread(int A, int B, int casenb, ThreadDispatcher td){ nbs = new TreeSet(); this.A = A; this.B = B; for(int i = A; i <= B; i++){ nbs.add(i); } this.casenb = casenb; this.td = td; } public void solve(){ while(!nbs.isEmpty()){ int n = nbs.first(); findAndRemoveRecycledOf(n); } } private void findAndRemoveRecycledOf(int n) { nbs.remove((Integer)n); String nstr = """" + n; if(nstr.length() == 1) return; int nbInPair = 1; for(int i = 0; i < nstr.length()-1;i++){ String sstr = shiftRight(nstr,i); sstr.replaceFirst(""^0+(?!$)"", """"); int sn = Integer.parseInt(sstr); if(nbs.contains(sn)){ nbInPair++; nbs.remove((Integer)sn); } } pairs += nbInPair * (nbInPair - 1) / 2; } private String shiftRight(String nstr, int i) { return nstr.substring(nstr.length() - 1 - i, nstr.length()) + nstr.substring(0, nstr.length() - 1 - i); } @Override public void run() { solve(); td.finish(this); } } " B13195," import java.io.*; import java.util.*; public class CodeJam2012_Q_C { public int calc(int A, int B) { boolean[] checked = new boolean[B-A+1]; int cnt = 0; int D = String.valueOf(A).length(); int unit =1; for(int i=1; i { @Override protected boolean useCaseSolver(CaseSolver caseSolver, Problem3Case caseToSolve) { return false; } @Override protected CaseSolver buildCaseSolver(Problem3Case caseToSolve) { return new Problem3CaseSolver(); } @Override protected InputFileParser createInputFileParser(File inputFile) { return new Problem3InputFileParser(inputFile); } @Override protected AbstractOutputFileWriter createOutputFileWriter( File outputFile) { return new Problem3OutputFileWriter(outputFile); } } " B12150,"import java.util.Scanner; import java.io.OutputStream; import java.io.IOException; import java.io.FileOutputStream; import java.io.PrintWriter; import java.io.FileInputStream; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Prabu */ public class Main { public static void main(String[] args) { InputStream inputStream; try { inputStream = new FileInputStream(""IO/C-small-attempt0.in""); } catch (IOException e) { throw new RuntimeException(e); } OutputStream outputStream; try { outputStream = new FileOutputStream(""IO/C-small-attempt0.out""); } catch (IOException e) { throw new RuntimeException(e); } Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); CJ2012QR_RecycledNumbers solver = new CJ2012QR_RecycledNumbers(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } } class CJ2012QR_RecycledNumbers { public void solve(int testNumber, Scanner in, PrintWriter out) { int A = in.nextInt(); int B = in.nextInt(); if(B < 10) { out.printf(""Case #%d: 0\n"", testNumber); return; } boolean[] visited = new boolean[B-A+1]; int nDigits = String.valueOf(A).length()-1; int cycleCount, pairCount, tempi; StringBuilder sb; pairCount = 0; for(int i = A; i <= B; i++) { if(visited[i - A]) continue; sb = new StringBuilder(String.valueOf(i)); sb.insert(0, sb.charAt(sb.length() - 1)); sb.deleteCharAt(sb.length() - 1); tempi = Integer.parseInt(sb.toString()); cycleCount = 0; while(i != tempi) { if(tempi >= A && tempi <= B && visited[tempi - A] == false) { cycleCount++; visited[tempi - A] = true; } sb.insert(0, sb.charAt(sb.length() - 1)); sb.deleteCharAt(sb.length() - 1); tempi = Integer.parseInt(sb.toString()); } pairCount += (cycleCount * (cycleCount + 1)) / 2; } out.printf(""Case #%d: %d\n"", testNumber, pairCount); } } " B12364,"import java.util.Scanner; import java.io.*; public class Recycle { static String out="""",output=""""; public static void main(String[] args) { try { Scanner in = new Scanner(new File(""recycle.in"")); // STATE THE INPUT FILE int n = in.nextInt(); //INITIALIZE NUMBER OF CASES 'N' int count = 1; String out = """"; while(in.hasNext()) { // INITIALIZE OTHER STUFFS HERE int a = in.nextInt(); int b = in.nextInt(); //PROCESS DATA HERE AND WRITE EACH RESULT TO THE output VARIABLE //END OF PROCESS out += ""Case #""+count+"": ""+ process(a,b)+""\n""; count++; try { File file = new File(""output.dat""); PrintWriter output = new PrintWriter(file); output.write(out); output.close(); } catch(Exception exception) { System.out.println(""CANNOT WRITE TO FILE""); } } }catch(Exception exception){ System.out.println(""CANNOT READ FROM FILE""); } System.out.println(""DATA HAS BEEN WRITTEN TO FILE""); } public static int process(int A, int B) { int counter = 0; //String all[] = getGenerated(Integer.toString(A)); //THE TRUE VALUES ARE NOT GETTING INSIDE ALL[] for(int i = A; i <= B; i++) { String all[] = getGenerated(Integer.toString(i)); for(int j = 0; j < all.length; j++) { if((i < Integer.parseInt(all[j])) && (Integer.parseInt(all[j]) <= B)) { counter++; } } } return counter; } public static String[] getGenerated(String word) { String[] all = new String[word.length()-1];//changed frm len - 1 for(int i = 0; i < all.length; i++) { all[i] = generate(word); word = generate(word); } return all; } public static String generate(String w) { String ans = w.substring(w.length()-1); for(int i = 0; i < w.length()-1; i++) { ans += w.substring(i,i+1); } return ans; } } " B12415,"import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.util.HashSet; import java.util.Set; public class Recycle { public static void main(String[] args) throws IOException { long time = System.currentTimeMillis(); File iFile = new File(""A-large-practice.in""); BufferedReader in= new BufferedReader(new FileReader(iFile)); File oFile = new File(""A-large-practice.out""); FileOutputStream fos = new FileOutputStream(oFile); BufferedOutputStream bos = new BufferedOutputStream(fos); PrintStream out = new PrintStream(bos); int numCases = Integer.parseInt(in.readLine()); for(int i=0; i possibleMs = new HashSet(); for(int rotate=1; rotate i && thisNum<=B){ possibleMs.add(thisRot); } } return possibleMs.size(); } }" B11967,"package com.niall.codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; public class ProbC { String english, goglish; public ProbC(){ } public int solve(int a, int b){ int count = 0; HashSet set; for(int n = a; n<= b; n++){ String x = n + """"; set = new HashSet(); for(int j = 0; j < x.length() - 1; j++){ x = push(x); int m = Integer.parseInt(x); if(n < m && m <=b ){ set.add(m); } } count += set.size(); } return count; } public String push(String x){ return x.substring(1) + x.charAt(0); } /** * @param args */ public static void main(String[] args) { String infile = ""probCin""; String outfile = ""probCans""; try { BufferedReader br = new BufferedReader(new FileReader(new File(infile))); BufferedWriter bw = new BufferedWriter(new FileWriter(new File(outfile))); ProbC p1 = new ProbC(); br.readLine(); int i = 1; String s; while((s=br.readLine())!= null){ String[] ss = s.split("" ""); int a = Integer.parseInt(ss[0]); int b = Integer.parseInt(ss[1]); bw.write(""Case #"" + i + "": "" + p1.solve(a,b)); bw.newLine(); i++; } bw.close(); br.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B11170,"package qualification; import java.io.*; import java.util.Arrays; import java.util.Scanner; /** * @author Roman Elizarov */ public class C { public static void main(String[] args) throws IOException { new C().go(); } Scanner in; PrintWriter out; private void go() throws IOException { init(); in = new Scanner(new File(""src\\qualification\\c.in"")); out = new PrintWriter(new File(""src\\qualification\\c.out"")); int t = in.nextInt(); for (int tn = 1; tn <= t; tn++) { out.println(""Case #"" + tn + "": "" + solveCase()); } in.close(); out.close(); } int[] p = new int[10]; int[] u = new int[2000001]; int uh; private void init() { p[0] = 1; for (int i = 1; i < p.length; i++) p[i] = p[i - 1] * 10; Arrays.fill(u, -1); } private int getP(int a) { int i = Arrays.binarySearch(p, a); return i < 0 ? -i - 2 : i; } private int solveCase() { int a = in.nextInt(); int b = in.nextInt(); int ap = getP(a); int bp = getP(b); int cnt = 0; for (int p0 = ap; p0 <= bp; p0++) { int a0 = p0 == ap ? a : p[p0]; int b0 = p0 == bp ? b : p[p0 + 1] - 1; cnt += solveCase(a0, b0, p0 + 1); } return cnt; } private int solveCase(int a, int b, int d) { int cnt = 0; for (int n = a; n < b; n++) { for (int i = 1; i < d; i++) { int m = (n % p[i]) * p[d - i] + n / p[i]; if (m > n && m <= b && u[m] < 0) { cnt++; u[m] = uh; uh = m; } } while (uh > 0) { int next = u[uh]; u[uh] = -1; uh = next; } } return cnt; } } " B10140,"import java.io.*; import java.util.*; public class taskC { PrintWriter out; BufferedReader br; StringTokenizer st; String nextToken() throws IOException { while ((st == null) || (!st.hasMoreTokens())) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public void solve() throws IOException { int a = nextInt(); int b = nextInt(); int d = 1; int ans = 0; for (int i = a; i <= b; i++) { int t = i; while (t / (d * 10) != 0) { d *= 10; } do { t = (t % d) * 10 + (t / d); if ((t > i) && (t <= b)) ans++; } while (t != i); } out.println(ans); } public void run() { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); br = new BufferedReader(new FileReader(""taskC.in"")); out = new PrintWriter(""taskC.out""); int n = nextInt(); for (int i = 0; i < n; i++) { out.print(""Case #"" + (i + 1) + "": ""); solve(); } out.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { new taskC().run(); } } " B10640,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package a2012; import java.util.*; import java.io.*; /** * * @author G */ public class C { static int[] pot10=new int[]{1,10,100,1000,10000,100000,1000000,10000000}; static File home=new File(""F:/Documents/Downloads/""); public static void main(String...arg)throws Exception{ Scanner sc = new Scanner(new File(home,""C-small-attempt0.in"")); System.setOut(new PrintStream(new File(""c.out""))); final int casos=sc.nextInt(); for(int caso=1;caso<=casos;caso++){ int A=sc.nextInt(),B=sc.nextInt(); final int digits=(""""+A).length(); int tot=0; HashSet encontrados=new HashSet(1000); for(int n=A;n<=B;n++){ //System.out.println(e); for(int i=1;i=A&&j<=B&&j!=n&&!encontrados.contains(t)){ tot++; encontrados.add(t); } //System.out.println(j); } } System.out.println(""Case #""+caso+"": ""+tot); } System.out.close(); } } " B12681,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.util.ArrayList; public class main { /** * @param args * @throws Exception */ public static int[] flag; public static ArrayList[] array; public static void main(String[] args) throws Exception { // TODO Auto-generated method stub Input in = new Input(""small.txt""); File file = new File(""out.txt""); FileWriter filewriter = new FileWriter(file); BufferedWriter bw = new BufferedWriter(filewriter); PrintWriter pw = new PrintWriter(bw); int n = in.getInt(); for(int i = 0; i < n ; i ++){ int result = 0; int num = i + 1 ; int a = in.getInt(); int b = in.getInt(); int d = Integer.toString(a).length(); array = new ArrayList[b+1]; for(int j = a ; j <= b; j++){ array[j] = new ArrayList(); } for(int j = a ; j <=b ; j++){ String s = Integer.toString(j) + Integer.toString(j); result += solve(s,d,a,b,j); } String ans = ""Case #"" +num +"": ""+result; pw.println(ans); System.out.println(ans); } pw.close(); bw.close(); filewriter.close(); } public static int solve(String s , int d,int a , int b,int j){ int result = 0; int original = j; for(int i = 0 ; i < d ; i++){ String sub = s.substring(i+1, i+1+d); int subint = Integer.parseInt(sub); if(subint >= a && subint <=b && subint !=original){ if(subint 0) { try { sc = new Scanner(new File(args[0])); if (args.length > 1) { System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(new File(args[1])), 128))); } } catch (FileNotFoundException e) { // e.printStackTrace(); sc = new Scanner(System.in); } } else { sc = new Scanner(System.in); } int T = Integer.valueOf(sc.nextLine()); for (int i = 0; i < T; i++) { int A = sc.nextInt(); int B = sc.nextInt(); int answer = solve(A, B); System.out.printf(""Case #%d: %d\n"", i + 1, answer); } System.out.close(); } public static int solve(int A, int B) { int answer = 0; int seedNum = A; do { answer += hasRecycled(seedNum++, A, B); } while (seedNum < B); return answer; } public static int hasRecycled(long seedNum, long A, long B) { int count = 0; int ptr; char[] old_num_chars = String.valueOf(seedNum).toCharArray(); int length = old_num_chars.length; char[] moved_num_chars = new char[length]; List newNumList = new ArrayList(); for (int i = length - 1; i > 0; i--) { ptr = i; for (int j = 0; j < length; j++) { if (ptr == 0) { moved_num_chars[ptr] = old_num_chars[length - 1]; } else { moved_num_chars[ptr] = old_num_chars[ptr - 1]; } if (--ptr < 0) { ptr += length; } } long newNum = Long.valueOf(new String(moved_num_chars)); if ( seedNum < newNum && newNum <= B) { boolean isNew = true; for (Iterator it = newNumList.iterator(); it.hasNext();) { Long l = it.next(); if (l.equals(newNum)) { isNew = false; break; } } if (isNew) { newNumList.add(newNum); count++; } } old_num_chars = moved_num_chars.clone(); } return count; } } " B11823,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) throws FileNotFoundException { // //////////////////////////////////// // Begin Code Jam regular code // // //////////////////////////////////// Scanner inFile = new Scanner(new File(""C-small-attempt0.in"")); PrintStream outFile = new PrintStream(new File(""C-small0-out.txt"")); int numCases = inFile.nextInt(); inFile.nextLine(); // Gets rid of newline char // //////////////////////////////////// // End Code Jam regular code // // //////////////////////////////////// for (int i = 1; i <= numCases; i++) { int A = inFile.nextInt(); int B = inFile.nextInt(); int recycleCount = 0; for(int n = A; n < B; n++) { HashSet recycled = new HashSet(); for(int j=1; j n && numDigits(shifted) == numDigits(n) && !recycled.contains(Integer.valueOf(shifted))) { recycleCount++; recycled.add(Integer.valueOf(shifted)); //System.out.println(""recycled ("" + n + "","" + shifted + "")""); } else { //System.out.println(""skipped ("" + n + "","" + shifted + "")""); } } } printCase(outFile, i, recycleCount); } } private static void printCase(PrintStream outStream, int i, int n) { outStream.println(""Case #"" + i +"": "" + n); } private static int numDigits(int n) { int count = 0; while(n != 0) { n = n / 10; count++; } return count; } private static int shiftNumPlaces(int n, int shiftAmount) { //String numStr = Integer.toString(n); String savedDigits = """"; for(int i=0; i { private int input; @Override public boolean readLine(String data) { input = Integer.parseInt(data); return false; } @Override public Integer generateObject() { return input; } } " B12888,"import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.LinkedHashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { static int[] p10 = {1,10,100,1000,10000,100000,1000000,10000000}; public static int perm(int x, int n, int l){ int y = x/p10[n]; int z = x-y*p10[n]; return z*p10[l-n] + y; } public static int longueur(int a){ int i = 1; while(a / p10[i] != 0) i++; return i; } public static void main(String[] args) throws IOException { // TODO Auto-generated method stub File f = new File( ""C-small-attempt0.in"" ); FileWriter out=new FileWriter(""output.txt""); Scanner in = new Scanner(new FileReader(f)); if(f.exists()){ int T; int A, B; int r; int l; int y; Set s = new LinkedHashSet(); T = in.nextInt(); for(int i = 1; i <= T ; i++){ A = in.nextInt(); B = in.nextInt(); l = longueur(A); r = 0; for(int x = A; x < B; x++){ s.clear(); for(int n = 1; n < l ; n++){ y = perm(x, n, l); if(y > x && y <= B && !s.contains(y)){ r++; s.add(y); } } } out.write(""Case #"" + i + "": "" + r + ""\n""); } } in.close(); out.close(); } } " B10691,"package codejam.world2012.qualification.c; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class C { /** * @param args */ public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(""src/codejam/world2012/qualification/c/small.in"")); BufferedWriter out = new BufferedWriter(new FileWriter(""src/codejam/world2012/qualification/c/small.out"")); int T = 0; T = Integer.parseInt(in.readLine()); for (int t = 0; t < T; t++) { String[] line = in.readLine().split("" ""); Long answer = 0L; Long A = Long.parseLong(line[0]); Long B = Long.parseLong(line[1]); Set history = new HashSet(); for (Long n = A; n < B; n++) { String current = n.toString(); for (int i = current.length() -1; i> 0; i--) { StringBuilder recycled = new StringBuilder(); recycled.append(current.substring(i)); recycled.append(current.substring(0, i)); Long m = Long.parseLong(recycled.toString()); if ((m > n) && (B>= m)) { if (!history.contains(current +"":"" + recycled) && !history.contains(recycled +"":"" + current)) { answer++; history.add(current +"":"" + recycled); } } } } out.write(""Case #""+String.valueOf(t+1) +"": ""+answer.toString()); if (t < T-1) out.write(System.getProperty(""line.separator"")); } out.close(); } } " B10901,"import java.io.*; import java.util.*; public class Main { public static void main(String[] args)throws IOException { new Main().start(); } public void start()throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; int test=Integer.parseInt(br.readLine()); int ans=0; int ind=1; while(test-->0){ ans=0; st=new StringTokenizer(br.readLine()); int A=Integer.parseInt(st.nextToken()); int B=Integer.parseInt(st.nextToken()); HashSet hs; for(int num=A;num<=B;num++){ String n=num+""""; int len=n.length(); hs=new HashSet(); for(int i=1;i=A && m>num){ hs.add(m); } } ans+=hs.size(); } System.out.println(""Case #""+ind+"": ""+ans); ind++; } } }" B10389,"import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; import java.util.Vector; public class C { public static void main(String[] args) { Vector num = new Vector(); Vector counts = new Vector(); int count = 0; int cases = 0; int n = 0; boolean seen = false; int start, end; String num1, num3 = null; char num2[]; try { Scanner in = new Scanner(new FileReader(""C-small-attempt0.in"")); cases = in.nextInt(); for (int i = 0; i < cases; i++) { count = 0; start = in.nextInt(); end = in.nextInt(); num1 = Integer.toString(start); for (int j = start; j < end; j++) { num1 = Integer.toString(j); if (num.contains(j) == false) { num.add(Integer.parseInt(num1)); num2 = num1.toCharArray(); //System.out.print(num1); n = 0; for (int k = 0; k < num2.length - 1; k++) { seen = false; char temp = num2[num2.length - 1]; for (int l = num2.length - 1; l >= 1; l--) { num2[l] = num2[l - 1]; } num2[0] = temp; num3 = new String(num2); //System.out.println(""2 "" + num3); seen = num.contains(Integer.parseInt(num3)); if (seen == false && num2[0] != '0' && Integer.parseInt(num3) <= end && Integer.parseInt(num3) >= start && num3.equals(num1) == false) { //System.out.println(""Original "" + num1); //System.out.print("", "" + num3); num.add(Integer.parseInt(num3)); n++; //System.out.println(""n: "" + n); } } //System.out.println(); count += (n * (n + 1) / 2); } } num = new Vector(); counts.add(count); System.out.println(count); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { FileWriter out = new FileWriter(""C.out""); BufferedWriter writer = new BufferedWriter(out); for (int i = 0; i < cases; i++) { writer.write(String.format(""Case #%d: %d\n"", i + 1, counts.get(i))); } writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B10461," import java.io.*; import java.util.StringTokenizer; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Hamada */ public class Recylced { public static void main(String [] args) { String [] [] s= TextLines(""C:\\C-small-attempt0.in""); int count[]=new int[s.length]; for(int i=0;in && m<=B) count++; } return count; } public static int crossOver(String s, int cuttingPoint) { String s1=""""; String s2=""""; String result=""""; int r; char [] c=s.toCharArray(); for(int i=0;i pares = new ArrayList(); String sN = N + """"; //Si es un solo digito no hay par if (sN.length() <= 1) { return 0; } //Evaluamos si el numero tiene los digitos iguales //En este caso el par es el mismo numero //Y como los pares no pueden ser iguales se descarta este caso boolean sameDigit = true; for (int i = 1; i < sN.length() && sameDigit; i++) { sameDigit = sN.charAt(i - 1) == sN.charAt(i); } if (sameDigit) { return 0; } //Comenzamos a buscar los pares String N1, N2; int split = 1; int M, numPair = 0; while (split < sN.length()) { N1 = sN.substring(0, split); N2 = sN.substring(split); M = Integer.parseInt(N2 + N1); //Si empieza en cero, ya los digitos no concuerdan //O Si M es mayor que B se sale del rango //O si N>=M no cumple con la restriccion A ≤ n < m ≤ B if ((N2.indexOf(""0"") == 0) || (M > B) || (N>=M)) { split++; continue; } if(!pares.contains(M)){ pares.add(M); }else{ split++; continue; } numPair++; debug(sN + "" => "" + M + ""["" + N1 + ""-"" + N2 + ""]""); split++; } return numPair; } public static void debug(Object obj) { // System.out.println(obj); } } " B11840,"package info.m3o.gcj2012.recyclednumber; public class RecycledNumber { protected String numStr; protected int numDigits; protected int minA, maxB; public RecycledNumber(String s, int mina, int maxb){ numStr = new String(s); numDigits = s.length(); minA = mina; maxB = maxb; } // public RecycledNumber(String s){ // numStr = new String(s); // numDigits = s.length(); // } public RecycledNumber(int p, int mina, int maxb){ numStr = new String(String.valueOf(p)); numDigits = numStr.length(); minA = mina; maxB = maxb; } // public RecycledNumber(int p){ // numStr = new String(String.valueOf(p)); // numDigits = numStr.length(); // } public static String recycleAt(String s, int i){ assert ((i>0) && (i= this.minA) && (intS2 <= this.maxB)) { recycledNumberSet.add(new MyNumberStringPair(this.numStr, sNum2)); } tested.add(numStr); tested.add(sNum2); } public void addRecycledNumbers(MyNumberStringPairSet recycledNumberSet, MyNumberStringSet tested){ if (tested.contains(numStr) == true){ // This value has been tested already. return; } for(int i=1; i < this.numDigits; i++){ String s = new String (recycleAt(numStr, i)); // HERE TODO tested.add(s); int intS = Integer.valueOf(s); if ((s.startsWith(""0"")==false) && (numStr.compareTo(s) != 0) && (intS >=this.minA) && (intS <= this.maxB)){ recycledNumberSet.add(new MyNumberStringPair(s, numStr)); } // if (s.startsWith(""0"")== false){ // tested.add(s); // Here is the part // } } tested.add(numStr); } public static boolean testrecycleAt(){ boolean retb = false; boolean []b = new boolean[4]; String str1 = ""12345""; String str2 = recycleAt(str1, 1); b[0] = (""23451"".compareTo(str2)==0); str2 = recycleAt(str1, 2); b[1] = (""34512"".compareTo(str2) == 0); str2 = recycleAt(str1, 3); b[2] = (""45123"".compareTo(str2) == 0); str2 = recycleAt(str1, 4); b[3] = (""51234"".compareTo(str2) == 0); retb = (b[0] && b[1] && b[2] && b[3]); assert (retb == true) : ""something is wrong with recycleAt method.""; return retb; } public String getNumStr() { return numStr; } public void setNumStr(String numStr) { this.numStr = numStr; } public int getNumDigits() { return numDigits; } public void setNumDigits(int numDigits) { this.numDigits = numDigits; } } " B12237,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class recycled { static int f_recycled(String s_min,String s_max){ int num_recycled=0; int min=Integer.parseInt(s_min); int max=Integer.parseInt(s_max); //System.out.println(""______________________________________\nNúmeros reciclados entre ""+s_min+"" y ""+s_max); if (max>10){ int cab_max=s_max.charAt(0); int cab_min, num; String string_v; int i, j, final_v; String string_final_v; List soluciones_valor=new ArrayList(); boolean enc; int v=min; while(v<=max){ string_v=String.valueOf(v); cab_min=Character.getNumericValue(string_v.charAt(0)); for(i=1;i= cab_min ){ // cambio de dígitos no es menor que el valor original string_final_v=string_v.substring(i)+string_v.substring(0, i); final_v=Integer.parseInt(string_v.substring(i)+string_v.substring(0, i)); // back + front if(string_v.length()==string_final_v.length() && min<=v && v list = readIntegersInLine(); int N = list.get(0), M = list.get(1); String o = ""Case #"" + i +"": "" + findCount(N, M); System.out.println(o); fw.write(o + '\n'); }while(++i <= CASES); fw.close(); } private int findCount(int A, int B) { int count = 0; Set pairs = new HashSet(); for(int num = A;num0;i/=10, count++); byte[] bnum =new byte[count]; int tmpNum = num; for(int i=count-1;i>=0;i--){ bnum[i] = (byte) (num % 10); num/=10; } trace(""getDigits:: "" + tmpNum + "": "" + Arrays.toString(bnum)); return bnum; } private int rotate(byte[] bnum){ trace(""rotate:: before: ""+ Arrays.toString(bnum)); byte tmp = bnum[bnum.length-1]; for(int i=bnum.length-1;i>0;i--){ bnum[i] = bnum[i-1]; } bnum[0] = tmp; int result = 0; for(int i=0;i readIntegersInLine() throws IOException{ List list = new ArrayList(); StringTokenizer stok = new StringTokenizer(BR.readLine()); while(stok.hasMoreTokens()){ String token = stok.nextToken(); list.add(Integer.parseInt(token)); } return list; } private int readInteger() throws NumberFormatException, IOException{ return Integer.parseInt(BR.readLine()); } private void trace(String s){ if(TESTING)System.out.println(s); } } class Pair{ private int n; private int m; public Pair(int n, int m) { if(n>=m){ throw new IllegalArgumentException(""N not less than M: ["" + n + "", "" + m + ""]""); } this.n = n; this.m = m; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + m; result = prime * result + n; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (m != other.m) return false; if (n != other.n) return false; return true; } @Override public String toString() { return ""Pair [n="" + n + "", m="" + m + ""]""; } } " B10213,"package com.google.codejam.recyclednumbers; import java.io.*; public class RecycledNumbers { private static String filename = ""small""; public static void main(String[] args) throws Exception { RandomAccessFile input = new RandomAccessFile(filename + ""_in.txt"", ""r""); RandomAccessFile output = new RandomAccessFile(filename + ""_out.txt"", ""rw""); int cases = Integer.valueOf(input.readLine()); for(int i = 0; i < cases; i++){ String[] nrs = input.readLine().split("" ""); int A = Integer.valueOf(nrs[0]); int B = Integer.valueOf(nrs[1]); int solved = solve(A, B); System.out.println(""Case #"" + (i + 1) + "": "" + solved); output.writeBytes(""Case #"" + (i + 1) + "": "" + solved + ""\n""); } output.close(); input.close(); } private static int solve(int A, int B){ int count = 0; String a; String b; for(int n = A; n < B; n++){ a = String.valueOf(n); for(int k = n + 1; k <= B; k++){ b = String.valueOf(k); if(a.length() != b.length())continue; for(int i = 0; i < b.length(); i++){ if(a.charAt(i) == b.charAt(0)){ boolean match = true; for(int j = 0; j < b.length(); j++){ if(b.charAt(j) != a.charAt((i + j) % b.length())){ match = false; break; } } if(match){ count++; i++; break; } } } } } return count; } } " B11023,"package org.moriraaca.codejam; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface TestConfiguration { Class> solverClass(); } " B11447,"/** * */ package org.codejam.rn; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.util.HashMap; import java.util.Map; /** * * @author juanjo */ public class RecycledNumbersMain { public static String newline = System.getProperty(""line.separator""); private static void generateNumbers(Map pairs, int A, int B, int n) { int m; String s = String.valueOf(n); String pair = null; int length = s.length() - 1; int[] data = new int[length]; for (int i = 0; i < length; i++) { //s = s.charAt(length) + s.substring(0, length); s = new StringBuilder().append(s.charAt(length)).append(s.substring(0, length)).toString(); data[i] = Integer.parseInt(s); m = Integer.parseInt(s); if ((A <= n) && (n < m) && (m<=B)) { pair = new StringBuilder().append(n).append(""-"").append(m).toString(); if (!pairs.containsKey(pair)); pairs.put(pair, pair); } } } private static int getRecyledPairsCount(int A, int B) { Map pairs = new HashMap(); for (int n = A; n <= B; n++) { generateNumbers(pairs, A, B, n); } return pairs.size(); } /** * @param args */ public static void main2(String[] args) { long time = System.currentTimeMillis(); System.out.println(""getRecyledPairsCount: "" + getRecyledPairsCount(100,500)); System.out.println(""Execution time ms.: "" + (System.currentTimeMillis() - time) ); } public static void main(String[] args) { long time = System.currentTimeMillis(); if (args.length != 2) { System.out.println(""Usage: java "" + RecycledNumbersMain.class + "" inputFile outputFile""); System.exit(0); } int count = 0; BufferedReader in = null; FileWriter out = null; String line = null; int testCasesTotal = 0; int testCasesCount = 0; String result; int A, B; String s[]; try { in = new BufferedReader(new FileReader(args[0])); out = new FileWriter(args[1]); while ( (line = in.readLine()) != null) { count++; if (count == 1) { testCasesTotal = Integer.valueOf(line); System.out.println(""In file number of test cases: "" + testCasesTotal + "".""); } //if else { s = line.split("" ""); A = Integer.parseInt(s[0]); B = Integer.parseInt(s[1]); result = String.valueOf(getRecyledPairsCount(A, B)); testCasesCount++; result = ""Case #"" + testCasesCount + "": "" + result; System.out.println(result + "" -- Line: "" + testCasesCount + "": "" + line); out.write(result + newline); } } if (out != null) { out.close(); } } //try catch (Exception e) { e.printStackTrace(); } finally { System.out.println(""Execution time ms.: "" + (System.currentTimeMillis() - time) ); } } // Main } " B11842,"package info.m3o.gcj2012.recyclednumber; public class TestMainRecycledNumber { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int inA, inB; int caseCount = 0; // System.out.println(""T="" + inT); ResultUtil resultUtil = new ResultUtil(); // inA = Integer.valueOf(s[0]); // inB = Integer.valueOf(s[1]); inA = 1000000; // inB = 2000000; inB = 2000000; // System.out.println(""A="" + inA + ""B="" + inB ); caseCount++; /* * Start the actual Job */ resultUtil.clearSets(); int n, numRecycledNumber; RecycledNumber recycledNumber; for (n = inA; n <= inB; n++) { recycledNumber = new RecycledNumber(n, inA, inB); recycledNumber.addRecycledNumbers(resultUtil.recycledNumberSet, resultUtil.testedNumberSet); for (String s : RecycledNumber.getCycledNumber(recycledNumber .getNumStr())) { recycledNumber.addRecycledNumbers(resultUtil.recycledNumberSet, resultUtil.testedNumberSet, s); } // recycledNumber.addRecycledNumbers(resultUtil.recycledNumberSet, // resultUtil.testedNumberSet); } numRecycledNumber = resultUtil.recycledNumberSet.size(); System.out.print(""Case #"" + caseCount + "": ""); System.out.println(numRecycledNumber); // for (MyNumberStringPair mnsp : resultUtil.recycledNumberSet) { // System.out.println(""("" + mnsp.getS1() + "", "" + mnsp.getS2() + "") ""); // } // System.out.println(""END""); // System.out.println(""TestRecycleat = "" + // RecycledNumber.testrecycleAt()); // System.out.println(""caseCount=""+caseCount); // assert (inT == caseCount) : ""CaseCount mismatch""; } } " B12016,"import java.util.Scanner; public class Recycle { /** * @param args */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int numLines = sc.nextInt(); int lineCounts = 1; while (numLines > 0) { String A = sc.next(); String B = sc.next(); // System.out.println(A + "" "" + B); int result = findRecyclePairs(A, B); System.out.println(""Case #"" + lineCounts + "": "" +result); numLines--; lineCounts++; } } private static int findRecyclePairs(String a, String b) { int result = 0; int strLength = a.length(); int pos; int num1 = Integer.parseInt(a); int num2 = Integer.parseInt(b); int i; int j; String str1; String str2; String strTemp; String front; if (strLength > 1) { for (i = num1; i < num2; i++) { str1 = Integer.toString(i); for (j = i+1; j <= num2; j++) { str2 = Integer.toString(j); for (pos = 1; pos < strLength; pos++) { strTemp = str1.substring(pos); front = str1.substring(0, pos); // System.out.println(str2+ "" "" + front); strTemp = strTemp.concat(front); // System.out.println(""Str2: ""+ str2); if (!str2.startsWith(""0"") && !str1.startsWith(""0"")) { if (strTemp.equals(str2)) { result++; } } } } } } return result; } } " B11287," import java.util.*; import java.io.*; public class c { public static void main(String arg[]){ int T; Scanner cin=new Scanner(System.in); T=cin.nextInt(); for(int t=0;t150) // break; int size=1; int num=0; while (true){ num++; if(i>=size && i now= new ArrayList(); for(int j=0;ji && copy <=m && now.indexOf(copy)==-1){ ans++; // System.out.println("" "" + i + "" "" +copy); now.add(copy); } } } System.out.println( ""Case #"" +( t+1 )+ "": "" + ans ); } } } " B11731,"/* * SpeakingView.java */ package speaking; import org.jdesktop.application.Action; import org.jdesktop.application.ResourceMap; import org.jdesktop.application.SingleFrameApplication; import org.jdesktop.application.FrameView; import org.jdesktop.application.TaskMonitor; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Timer; import javax.swing.Icon; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.filechooser.FileNameExtensionFilter; /** * The application's main frame. */ public class SpeakingView extends FrameView { public SpeakingView(SingleFrameApplication app) { super(app); initComponents(); // status bar initialization - message timeout, idle icon and busy animation, etc ResourceMap resourceMap = getResourceMap(); int messageTimeout = resourceMap.getInteger(""StatusBar.messageTimeout""); messageTimer = new Timer(messageTimeout, new ActionListener() { public void actionPerformed(ActionEvent e) { statusMessageLabel.setText(""""); } }); messageTimer.setRepeats(false); int busyAnimationRate = resourceMap.getInteger(""StatusBar.busyAnimationRate""); for (int i = 0; i < busyIcons.length; i++) { busyIcons[i] = resourceMap.getIcon(""StatusBar.busyIcons["" + i + ""]""); } busyIconTimer = new Timer(busyAnimationRate, new ActionListener() { public void actionPerformed(ActionEvent e) { busyIconIndex = (busyIconIndex + 1) % busyIcons.length; statusAnimationLabel.setIcon(busyIcons[busyIconIndex]); } }); idleIcon = resourceMap.getIcon(""StatusBar.idleIcon""); statusAnimationLabel.setIcon(idleIcon); progressBar.setVisible(false); // connecting action tasks to status bar via TaskMonitor TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext()); taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent evt) { String propertyName = evt.getPropertyName(); if (""started"".equals(propertyName)) { if (!busyIconTimer.isRunning()) { statusAnimationLabel.setIcon(busyIcons[0]); busyIconIndex = 0; busyIconTimer.start(); } progressBar.setVisible(true); progressBar.setIndeterminate(true); } else if (""done"".equals(propertyName)) { busyIconTimer.stop(); statusAnimationLabel.setIcon(idleIcon); progressBar.setVisible(false); progressBar.setValue(0); } else if (""message"".equals(propertyName)) { String text = (String)(evt.getNewValue()); statusMessageLabel.setText((text == null) ? """" : text); messageTimer.restart(); } else if (""progress"".equals(propertyName)) { int value = (Integer)(evt.getNewValue()); progressBar.setVisible(true); progressBar.setIndeterminate(false); progressBar.setValue(value); } } }); } @Action public void showAboutBox() { if (aboutBox == null) { JFrame mainFrame = SpeakingApp.getApplication().getMainFrame(); aboutBox = new SpeakingAboutBox(mainFrame); aboutBox.setLocationRelativeTo(mainFrame); } SpeakingApp.getApplication().show(aboutBox); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings(""unchecked"") // //GEN-BEGIN:initComponents private void initComponents() { mainPanel = new javax.swing.JPanel(); jButton2 = new javax.swing.JButton(); menuBar = new javax.swing.JMenuBar(); javax.swing.JMenu fileMenu = new javax.swing.JMenu(); javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem(); javax.swing.JMenu helpMenu = new javax.swing.JMenu(); javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem(); statusPanel = new javax.swing.JPanel(); javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator(); statusMessageLabel = new javax.swing.JLabel(); statusAnimationLabel = new javax.swing.JLabel(); progressBar = new javax.swing.JProgressBar(); jButton1 = new javax.swing.JButton(); mainPanel.setName(""mainPanel""); // NOI18N org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(speaking.SpeakingApp.class).getContext().getResourceMap(SpeakingView.class); jButton2.setText(resourceMap.getString(""jButton2.text"")); // NOI18N jButton2.setName(""jButton2""); // NOI18N jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel); mainPanel.setLayout(mainPanelLayout); mainPanelLayout.setHorizontalGroup( mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 400, Short.MAX_VALUE) .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(mainPanelLayout.createSequentialGroup() .addGap(0, 163, Short.MAX_VALUE) .addComponent(jButton2) .addGap(0, 164, Short.MAX_VALUE))) ); mainPanelLayout.setVerticalGroup( mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 254, Short.MAX_VALUE) .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(mainPanelLayout.createSequentialGroup() .addGap(0, 115, Short.MAX_VALUE) .addComponent(jButton2) .addGap(0, 116, Short.MAX_VALUE))) ); menuBar.setName(""menuBar""); // NOI18N fileMenu.setText(resourceMap.getString(""fileMenu.text"")); // NOI18N fileMenu.setName(""fileMenu""); // NOI18N javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(speaking.SpeakingApp.class).getContext().getActionMap(SpeakingView.class, this); exitMenuItem.setAction(actionMap.get(""quit"")); // NOI18N exitMenuItem.setName(""exitMenuItem""); // NOI18N fileMenu.add(exitMenuItem); menuBar.add(fileMenu); helpMenu.setText(resourceMap.getString(""helpMenu.text"")); // NOI18N helpMenu.setName(""helpMenu""); // NOI18N aboutMenuItem.setAction(actionMap.get(""showAboutBox"")); // NOI18N aboutMenuItem.setName(""aboutMenuItem""); // NOI18N helpMenu.add(aboutMenuItem); menuBar.add(helpMenu); statusPanel.setName(""statusPanel""); // NOI18N statusPanelSeparator.setName(""statusPanelSeparator""); // NOI18N statusMessageLabel.setName(""statusMessageLabel""); // NOI18N statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); statusAnimationLabel.setName(""statusAnimationLabel""); // NOI18N progressBar.setName(""progressBar""); // NOI18N javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel); statusPanel.setLayout(statusPanelLayout); statusPanelLayout.setHorizontalGroup( statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE) .addGroup(statusPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(statusMessageLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 230, Short.MAX_VALUE) .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(statusAnimationLabel) .addContainerGap()) ); statusPanelLayout.setVerticalGroup( statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(statusPanelLayout.createSequentialGroup() .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(statusMessageLabel) .addComponent(statusAnimationLabel) .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(3, 3, 3)) ); jButton1.setText(resourceMap.getString(""jButton1.text"")); // NOI18N jButton1.setName(""jButton1""); // NOI18N setComponent(mainPanel); setMenuBar(menuBar); setStatusBar(statusPanel); }// //GEN-END:initComponents private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: String archivo=""""; JFileChooser select =new JFileChooser(); FileNameExtensionFilter filtro = new FileNameExtensionFilter(""Archivo IN"",""in""); select.setFileFilter(filtro); int x=select.showDialog(null, null); if(x==JFileChooser.APPROVE_OPTION ){ clsArchivo arc=new clsArchivo(); archivo=select.getSelectedFile().getPath(); arc.clsArchivo(archivo); arc.progra(); } }//GEN-LAST:event_jButton2ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JPanel mainPanel; private javax.swing.JMenuBar menuBar; private javax.swing.JProgressBar progressBar; private javax.swing.JLabel statusAnimationLabel; private javax.swing.JLabel statusMessageLabel; private javax.swing.JPanel statusPanel; // End of variables declaration//GEN-END:variables private final Timer messageTimer; private final Timer busyIconTimer; private final Icon idleIcon; private final Icon[] busyIcons = new Icon[15]; private int busyIconIndex = 0; private JDialog aboutBox; } " B12779,"import java.io.*; import java.util.*; import java.math.*; /** @author Samuel Ahn */ public class C { public static void main(String args[]) throws Exception { Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int i = 1; i <= T; i++) { int A = in.nextInt(); int B = in.nextInt(); int sum = 0; for (int n = A; n < B; n++) { String x = Integer.toString(n); ArrayList list = new ArrayList(); for (int j = 1; j < x.length(); j++) { String a = x.substring(0, j); String b = x.substring(j); int tmp = Integer.parseInt(b + a); if ((tmp > n) && (tmp <= B) && (!list.contains(tmp))) { sum++; list.add(tmp); //break; } } } System.out.printf(""Case #%d: %d\n"", i, sum); } } }" B10519,"import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintWriter; import java.util.Scanner; import java.util.TreeMap; /** * Created with IntelliJ IDEA. * User: akim * Date: 4/14/12 * Time: 7:45 PM * To change this template use File | Settings | File Templates. */ public class C { String makeHash(int a) { String t = Integer.toString(a); String ans = t; for (int i = 0; i < t.length(); ++i) { t = t.substring(1)+t.charAt(0); if (ans.compareTo(t) > 0) ans = t; } // System.out.println(a + "" - "" + ans); return ans; } void solve() throws FileNotFoundException { PrintWriter out = new PrintWriter(new FileOutputStream(""output.txt"")); Scanner in = new Scanner(new FileInputStream(""input.txt"")); int t = Integer.parseInt(in.nextLine()); System.err.println(t); TreeMap ans = new TreeMap(); for (int i = 0; i < t; ++i) { ans.clear(); int A = in.nextInt(); int B = in.nextInt(); for (int qqq = A; qqq <= B; ++qqq) { String hash = makeHash(qqq); if (!ans.containsKey(hash)) ans.put(hash, 0L); long tmp = ans.get(hash); ans.put(hash, tmp + 1); } long rrr = 0; /*for (int a = A; a <= B; ++a) for (int b = a + 1; b <= B; ++b) if (makeHash(a).equals(makeHash(b))) --rrr;*/ for (String h : ans.keySet()) { long tmp = ans.get(h); rrr += tmp * (tmp - 1) / 2; } out.println(""Case #"" + (i + 1) + "": "" + rrr); System.err.println((i + 1) + "" "" + rrr); } out.flush(); out.close(); } public static void main(String[] args) throws FileNotFoundException { new C().solve(); } } " B10994,"import java.util.*; import java.io.*; class Node implements Comparable{ int x, y; public Node(){} public Node(int a, int b){ x = a; y = b; } public boolean equals(Object key){ Node tmp = (Node)key; if(x==tmp.x && y==tmp.y) return true; else return false; } public int compareTo(Object key){ Node tmp = (Node)key; if(x == tmp.x) return y-tmp.y; else return x-tmp.x; } } public class C{ Set hash = new TreeSet(); void Cal(int A, int B, int n, PrintWriter cout){ int ct = 0; String sn = Integer.valueOf(n).toString(); for(int i = 1; i < sn.length(); i++){ String sm = sn.substring(i) + sn.substring(0, i); int m = Integer.parseInt(sm); Node tmp = new Node(n, m); if(m>n && m<=B && !hash.contains(tmp)) hash.add(tmp); //System.out.println(hash.size()); } } void solve() throws FileNotFoundException{ File fin = new File(""data.in""); File fout = new File(""data.out""); Scanner cin = new Scanner(fin); PrintWriter cout = new PrintWriter(fout); int T, A, B; T = cin.nextInt(); for(int k = 1; k <= T; k++){ A = cin.nextInt(); B = cin.nextInt(); hash.clear(); for(int i = A; i < B; i++) Cal(A, B, i, cout); cout.printf(""Case #%d: %d\n"", k, hash.size()); } cout.flush(); } public static void main(String [] args) throws Exception{ C test = new C(); test.solve(); } } " B11564,"package codejam.is; /** * Created with IntelliJ IDEA. * User: ofer * Date: 4/13/12 * Time: 8:49 PM * To change this template use File | Settings | File Templates. */ public abstract class TestAbstract implements Test { private final static String newline = System.getProperty(""line.separator""); @Override public String getOutput(int testNum) { return ""Case #"" + testNum + "": "" + getTestResult() + newline; } protected abstract String getTestResult(); } " B10091,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Recycle; import java.io.BufferedReader; import java.io.FileReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.StringTokenizer; /** * * @author hemal */ public class Main { public static void main(String[] args) { try { BufferedReader bf = new BufferedReader(new FileReader(System.getProperty(""user.dir"") + ""/src/Recycle/"" + ""input.in"")); String s = bf.readLine(); int t = Integer.parseInt(s); // for (int i = 1; i <= t; i++) { // int count = 0; // String s1 = bf.readLine(); // String s2[] = s1.split("" ""); // int a = Integer.parseInt(s2[0]); // int b = Integer.parseInt(s2[1]); // int size = s2[0].length(); // System.out.println(""size "" + size); // for (int j = a; i <= b; j++) { //// for(int k=0;k b) { //// break; //// } //// } // } // System.out.println(""Case #"" + i + "": "" + count); // } PrintWriter pw = new PrintWriter(""output.out""); pw.println(""Omg! It works!""); ArrayList ar=new ArrayList(); ar.add(""1""); ar.add(""1""); HashMap hm=new HashMap(); hm.put(""1"", 12); hm.put(""1"", 32); System.out.println(hm); } catch (Exception e) { e.printStackTrace(); } } } " B10902,"package recycled; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Recycle { public static void main(String[] args)throws IOException { BufferedWriter saida = new BufferedWriter(new FileWriter(""saida.out"")); File file = new File(""C-small-attempt0.in""); Scanner scan = new Scanner(file); int casos; String a; String b; String linha; String[] divisao; String novo; ArrayList list = new ArrayList(); int tamanhoN; casos = Integer.parseInt(scan.nextLine()); String n; String m; for (int i =1; i <= casos;i++){ saida.write(""Case #"" + i + "": ""); int pares = 0; linha = scan.nextLine(); divisao = linha.split(""\\s+""); a = divisao[0]; b = divisao[1]; n = a; do{ m = n; tamanhoN = n.length(); for(int j = 0; j < tamanhoN;j++){ m = desloca(m); novo = (""("" + n + "","" + m + "") ""); if(!(list.contains(novo))){ if(Long.parseLong(a) <= Long.parseLong(n) && Long.parseLong(n) < Long.parseLong(m) && Long.parseLong(m) <= Long.parseLong(b)){ pares++; } } } n = String.valueOf(Long.parseLong(n) + 1); }while(Long.parseLong(n) < Long.parseLong(b)); System.out.println(pares); saida.write(pares + """"); saida.newLine(); } if (saida != null){ saida.flush(); saida.close(); } } public static String desloca(String n){ StringBuffer temp = new StringBuffer(n); char primeiro = n.charAt(0); for (int j=1; j < temp.length(); j++) { char c = n.charAt(j); temp.setCharAt(j-1, c); } temp.setCharAt(n.length()-1, primeiro); n = temp.toString(); return n; } } " B12336,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.StringTokenizer; public class ProblemC { private static final String OUT = ""C:/workspaces/tc/CodeJam/src/C.out""; private static final String IN = ""D:/downloads/C-small-attempt0.in""; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new FileReader(IN)); BufferedWriter bw = new BufferedWriter(new FileWriter(OUT)); int T = Integer.parseInt(br.readLine()); for (int i = 0; i < T; i++) { StringTokenizer st = new StringTokenizer(br.readLine()); String num = st.nextToken(); int k = num.length(); int A = Integer.parseInt(num); int B = Integer.parseInt(st.nextToken()); int res = 0; int mult = 1; for (int j = 0; j < k - 1; j++) { mult *= 10; } Map> map = new HashMap>(2000000); for (int j = A; j <= B; j++) { int t = j; for (int l = 0; l < k - 1; l++) { int rem = t % 10; t = rem * mult + t / 10; if (t > j && t <= B && t >= A) { Set set = map.get(j); if (set == null) { set = new HashSet(6); } set.add(t); map.put(j, set); } } } for (Entry> entry : map.entrySet()) { res += entry.getValue().size(); } bw.write(""Case #"" + (i + 1) + "": "" + res + ""\n""); } bw.close(); } } " B12160,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Vector; public class Main { /** * @param args */ public static void main(String[] args) { try{ // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(""C-small-attempt7.in""); // FileInputStream fstream = new FileInputStream(""in.txt""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; FileWriter foutstream = new FileWriter(""output.out""); BufferedWriter out = new BufferedWriter(foutstream); System.out.println (br.readLine()); int Case = 0; while ((strLine = br.readLine()) != null) { Case+=1; out.write(""Case #"" + Case + "": ""); System.out.println (strLine); String str[] = strLine.split("" ""); int A = Integer.parseInt(str[0]); int B = Integer.parseInt(str[1]); char a[] = str[0].toCharArray(); char b[] = str[1].toCharArray(); int recs = 0; List check3 = new ArrayList(); for (int i=A;i<=B;i++) { int prev =0; char[] curr = String.valueOf(i).toCharArray(); if (curr.length==b.length) { for (int j=0;j=A)&&(number<=B)&&(i=A)&&(number<=B)&&(i=A)&&(number<=B)&&(i=A)&&(number<=B)&&(i=0) { rec[i] = c[c.length-1-fromback]; fromback--; } else rec[i] = c[i-f-1]; } return i(rec); } public static int i(char c) { return Integer.parseInt(Character.toString(c)); } public static int i(char[] c) { return Integer.parseInt(String.valueOf(c)); } public static boolean checkexistence(List a,int c,int d) { boolean bool = false; if ((a.indexOf(c + "" "" + d)==-1)&&(a.indexOf(d + "" "" + c)==-1)) bool=true; else bool=false; return bool; } } " B12075,"package jp.funnything.competition.util; public class Prof { private long _start; public Prof() { reset(); } private long calcAndReset() { final long ret = System.currentTimeMillis() - _start; reset(); return ret; } private void reset() { _start = System.currentTimeMillis(); } @Override public String toString() { return String.format( ""Prof: %f (s)"" , calcAndReset() / 1000.0 ); } public String toString( final String head ) { return String.format( ""%s: %f (s)"" , head , calcAndReset() / 1000.0 ); } } " B10282," /** * Shashank Gupta * * ****SinnerShanky**** */ import java.io.*; public class problem_C { void main() { try { FileReader fr=new FileReader(""C:\\USERS\\SHASHANK GUPTA\\DOWNLOADS\\C-small-attempt0.in""); BufferedReader br=new BufferedReader(fr); int n=Integer.parseInt(br.readLine()); for(int i=1;i<=n;i++) { int count=0; String s=br.readLine(); int b=0; int a=0; for(int j=0;j=0;i--) { s1=s.substring(0,i); s1=s.substring(i)+s1; int a=Integer.parseInt(s1); if(a==b) return true; } return false; } } " B11113,"package com.lewis.codeJamInJava; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.StringTokenizer; /** * @author patrick * */ public class RecycledNumers { /** * @param args */ public static void main(String[] args) { try { File outpuFile = new File(""output.txt""); FileWriter fileWriter = new FileWriter(outpuFile); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); BufferedReader bufferedReader; File inputFile = new File(""input.txt""); FileReader fileReader = new FileReader(inputFile); bufferedReader = new BufferedReader(fileReader); int numTestCases = Integer.parseInt(bufferedReader.readLine()); for (int i = 1; i <= numTestCases; i++) { StringTokenizer st = new StringTokenizer( bufferedReader.readLine()); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); int recycledPairs = recycle(A, B); bufferedWriter.write(""Case #"" + i + "": "" + recycledPairs + ""\r\n""); } bufferedWriter.flush(); bufferedWriter.close(); } catch (Exception e) { e.printStackTrace(); } } private static int recycle(int a, int b) { int recycledPairs = 0; for (int i = a; i < b; i++) { String tmp = Integer.toString(i); int digits = tmp.length(); int currentPairs[] = new int[digits]; for (int j = 0; j < digits; j++) { // move digits and check int movedInt = Integer.parseInt(tmp.substring(j + 1) + tmp.substring(0, j + 1)); CHECKPAIR: if (movedInt <= b && movedInt > i) { for (int k = 0; k < digits; k++) { if (movedInt == currentPairs[k]) { break CHECKPAIR; } } currentPairs[j] = movedInt; recycledPairs++; } } } return recycledPairs; } } " B11065,"package fixjava; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import java.util.Map.Entry; public class CountedSet implements Set { HashMap map = new HashMap(); private static final Integer ONE = new Integer(1); public CountedSet(Iterable collection) { for (T t : collection) add(t); } @Override public boolean add(T item) { Integer count = map.get(item); if (count == null) { map.put(item, ONE); return true; } else { map.put(item, count + 1); return false; } } /** New method to fetch count, not in normal Sets. Returns null if key is not in set. */ public Integer get(String key) { return map.get(key); } /** New method to fetch count, not in normal Sets. Returns zero if key is not in set. */ public int getCount(String key) { Integer count = map.get(key); return count == null ? 0 : count; } /** Extra method to iterate over entries consisting of both items and counts */ public Iterator> iteratorWithCounts() { return map.entrySet().iterator(); } /** Extra method to iterate over entries consisting of both items and counts */ public Iterable> iteratableWithCounts() { return map.entrySet(); } /** Convert into sorted list of pairs */ public ArrayList> toListSortedByCount(boolean ascending) { ArrayList> list = Pair.mapToList(map); Pair.sortPairsByRight(list, ascending); return list; } // ----- boilerplate stuff: ----- @Override public boolean addAll(Collection collection) { boolean changed = false; for (T item : collection) { add(item); changed = true; } return changed; } @Override public void clear() { map.clear(); } @Override public boolean contains(Object item) { return map.containsKey(item); } @Override public boolean containsAll(Collection collection) { boolean containsAll = true; for (Object item : collection) { if (!contains(item)) { containsAll = false; break; } } return containsAll; } @Override public boolean isEmpty() { return map.isEmpty(); } /** Just iterates over keys, not counts */ @Override public Iterator iterator() { return map.keySet().iterator(); } @Override public boolean remove(Object item) { return map.remove(item) != null; } @Override public boolean removeAll(Collection collection) { boolean changed = false; for (Object item : collection) { if (remove(item)) { changed = true; break; } } return changed; } @Override public boolean retainAll(Collection arg0) { throw new RuntimeException(""Not implemented""); } @Override public int size() { return map.size(); } /** Just returns keys in array, not counts */ @Override public Object[] toArray() { return map.keySet().toArray(); } /** Just returns keys in array, not counts */ @Override public U[] toArray(U[] arr) { return map.keySet().toArray(arr); } } " B11929,"import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Scanner; public class Main { /** * @param args */ private static boolean [] used; public static int cnt(int a) { int res = 0; while(a != 0) { a/=10; res++; } return res; } public static int tenMult(int n) { int res = 1; for(int i = 0; i < n -1; i++) res *= 10; return res; } public static int solve(int n, int limit) { int res = 0; int c = cnt(n); int tmp = n; used = new boolean[2000000]; for(int i = 0; i < c-1; i++) { int rem = tmp%10; tmp /= 10; tmp += tenMult(c) * rem; if(tmp <= 2000000 && tmp > n && tmp <= limit && used[tmp] == false) { used[tmp] = true; //System.out.println(""for "" + n + "" = "" + tmp); res++;} } return res; } public static void main(String[] args) throws FileNotFoundException { // TODO Auto-generated method stub System.setIn(new FileInputStream(""input"")); Scanner s = new Scanner(System.in); int n = s.nextInt(); //used = new boolean[2000000]; for(int j = 1; j <= n; j++) { int A = s.nextInt(); int B = s.nextInt(); int res = 0; for(int i = A; i <= B; i++) { res += solve(i,B); } System.out.println(""Case #"" + j + "": "" + res); } } } " B11867,"package es.uam.eps.abk.qualification2012; import java.io.FileInputStream; import java.io.InputStream; import java.io.PrintStream; import java.util.Scanner; /** * * Recycled Numbers * * Do you ever become frustrated with television because you keep seeing the same * things, recycled over and over again? Well I personally don't care about * television, but I do sometimes feel that way about numbers. * * Let's say a pair of distinct positive integers (n, m) is recycled if you can * obtain m by moving some digits from the back of n to the front without changing * their order. For example, (12345, 34512) is a recycled pair since you can * obtain 34512 by moving 345 from the end of 12345 to the front. Note that n * and m must have the same number of digits in order to be a recycled pair. * Neither n nor m can have leading zeros. * * Given integers A and B with the same number of digits and no leading zeros, * how many distinct recycled pairs (n, m) are there with A ≤ n < m ≤ B? * * @author Alejandro */ public class C { private static void solve(InputStream in, PrintStream out) { Scanner scan = new Scanner(in); int T = scan.nextInt(); // test cases for (int t = 1; t <= T; t++) { int a = scan.nextInt(); int b = scan.nextInt(); int n = getRecycled(a, b); out.println(""Case #"" + t + "": "" + n); } } private static int getRecycled(int A, int B) { int r = 0; for (int n = A; n < B; n++) { for (int m = n + 1; m <= B; m++) { if (n == m) { continue; } if (isRecycled(n, m, A, B)) { r++; } } } return r; } private static boolean isRecycled(int A, int B, int AA, int BB) { String a = """" + A; String b = """" + B; if (a.length() != b.length()) { return false; } for (int i = 0; i < a.length(); i++) { String aa = a.substring(i) + a.substring(0, i); if (("""" + Integer.parseInt(aa)).equals(b)) { return true; } } return false; } public static void main(String[] args) throws Exception { String file = null; file = ""inputC2012.txt""; file = ""2012C-small-attempt0.in""; file = ""2012C-small-attempt1.in""; // file = ""A-large.in""; InputStream in = new FileInputStream(file); PrintStream out = new PrintStream(""output."" + file); solve(in, out); in.close(); out.close(); } } " B11050,"package com.clausewitz.codejam; import com.clausewitz.codejam.qr2012.Recycled; public class CodeJam { /** * @param args */ public static void main(String[] args) { //Solver s = new Googlerese(); //s.solve(""res/qr2012/A-small-attempt.in""); Solver s = new Recycled(); s.solve(""res/qr2012/small.in""); } } " B11525,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; public class Main { /** * @param args */ public static void main(String[] args) { FileInputStream fstream = null; try { fstream = new FileInputStream(args[0]); //fstream = new FileInputStream(""input.txt""); } catch (FileNotFoundException e) { // TODO Auto-generated catch block System.out.println(""Input File Not Found.""); System.exit(1); } DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); int lines = 0; try { lines = Integer.parseInt(br.readLine()); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } BufferedWriter out = null; try { // Create file FileWriter outstream = new FileWriter(""output.txt""); out = new BufferedWriter(outstream); } catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } String line[] = null; Integer numberA; Integer numberB; String sN; String sM; int m; for (int i = 1; i <= lines; i++) { try { line = br.readLine().split(""\\s+""); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } numberA = Integer.parseInt(line[0]); numberB = Integer.parseInt(line[1]); String parte1; String parte2; //System.out.println(""Number A is "" + numberA + "" and number B is "" // + numberB); int counter = 0; for (int n = numberA; n < numberB; n++) { sN = Integer.toString(n); // Aqui temos o número n (n,m) HashSet respostas = new HashSet(); for (int pos = (sN.length() - 1); pos >= 0; pos--) { parte1 = sN.substring(pos); parte2 = sN.substring(0, pos); sM = parte1.concat(parte2); // Transformado m = Integer.parseInt(sM); if (numberA <= n && n < m && m <= numberB) { // System.out.println(sNumberA + "" <= "" + n + "" < "" + m // + "" <= "" + sNumberB); // counter++; respostas.add(m); } } counter += respostas.size(); } System.out.println(""Case #"" + i + "": "" + counter); try { out.write(""Case #"" + i + "": "" + counter + ""\n""); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B10615,"package ProblemSolvers; import CaseSolvers.AllYourBaseCase; public class AllYourBase extends ProblemSolver { public AllYourBase(String filePath) { super(filePath); } @Override public void process() { cases = io.readInt(); for (int i = 1; i <= cases; i++) { new AllYourBaseCase(i, 1, io).process().printSolution(); } } } " B12556,"import java.io.*; public class Main { public static void main(String[] args) { try{ FileReader in = new FileReader(""input.txt""); BufferedReader inFile = new BufferedReader(in); FileWriter outFile = new FileWriter(""output.txt""); int test = Integer.parseInt(inFile.readLine()); for(int i=1;i<=test;i++){ String line = inFile.readLine(); String values[]=line.split("" ""); int A = Integer.parseInt(values[0]); int B = Integer.parseInt(values[1]); int count = 0; for(int j=A;jn) { if(check_recycled(n,m)) { p++; } } } } out.println(""Case #""+(q+1)+"":""+"" ""+p); q++; } out.flush(); } catch(Exception e) { System.out.print(e.toString()); } } } " B11891,"package gcj2012.qualification; import java.io.File; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C_Recycled_Numbers { private static boolean SMALL = true; private static String PROBLEM = ""C""; public static void main(String[] args) { try { Scanner scan = new Scanner(new File(String.format(""%s-%s.in"", PROBLEM, (SMALL ? ""small"" : ""large"")))); PrintWriter pw = new PrintWriter(new File(String.format(""%s-%s.out"", PROBLEM, (SMALL ? ""small"" : ""large"")))); int NUM_CASES = scan.nextInt(); scan.nextLine(); System.out.println(String.format(""%d test cases:"", NUM_CASES)); long start = System.currentTimeMillis(), t1, left; for (int CASE = 1; CASE <= NUM_CASES; ++CASE) { t1 = System.currentTimeMillis(); System.out.print(String.format(""%d.[%s] "", CASE, new SimpleDateFormat(""HH:mm:ss.SSS"").format(new Date(t1)))); final int A = scan.nextInt(), B = scan.nextInt(); int cnt = 0, pow1, pow2, l, m; final Set pairs = new HashSet(); for (int n = A; n < B; ++n) { l = String.valueOf(n).length(); pow1 = (int)Math.pow(10, l); pow2 = 1; pairs.clear(); for (int j = 1; j < l; ++j) { pow1 /= 10; pow2 *= 10; m = ((n % pow1) * pow2 + n / pow1); if (m <= B && m > n && pairs.add(n + "" "" + m)) { cnt++; } } } String res = String.format(""%d"", cnt); pw.println(String.format(""Case #%d: %s"", CASE, res)); left = (System.currentTimeMillis() - start) * (NUM_CASES - CASE) / CASE; System.out.println(String.format(""%s (%dms, ~%dms left)"", res, (System.currentTimeMillis() - t1), left)); } pw.close(); scan.close(); } catch (Exception e) { e.printStackTrace(); } } } " B12298,"import java.util.*; import java.io.*; import java.text.*; import java.math.*; public class RecycledNumbers { public static BufferedReader BR; public static String readLine() { try { return BR.readLine(); } catch(Exception E) { System.err.println(E.toString()); return null; } } // ****** MAIN ****** public static void main(String [] args) throws Exception { BR = new BufferedReader(new InputStreamReader(System.in)); int testcases = Integer.parseInt(readLine()); for (int t = 1; t <= testcases; t++) { RecycledNumbers instance = new RecycledNumbers(); instance.solve(t); } } // ****** GLOBAL VARIABLES ****** public RecycledNumbers() { } public boolean solve(int caseNumber) { StringTokenizer st = new StringTokenizer(readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); int n = Integer.toString(a).length(); long result = 0; for (int i = a; i <= b; ++i) { String s = Integer.toString(i); Set seen = new HashSet(); for (int j = 1; j < n; ++j) { int rotated = Integer.parseInt(s.substring(j) + s.substring(0,j)); if (i < rotated && rotated <= b && !seen.contains(rotated)) { seen.add(rotated); ++result; } } } System.out.println(""Case #"" + caseNumber + "": "" + result); return false; } } " B10569,"package gcj; import java.util.*; import java.io.*; public class RecycledNumbers { final static String PROBLEM_NAME = ""rnum""; final static String WORK_DIR = ""D:\\Gcj\\"" + PROBLEM_NAME + ""\\""; void solve(Scanner sc, PrintWriter pw) { int A = sc.nextInt(); int B = sc.nextInt(); int res = 0; for (int n=A; n <= B; n++) { String s = """" + n; Set cand = new HashSet(); for (int st=1; st < s.length(); st++) { String ss = s.substring(st) + s.substring(0, st); int m = Integer.parseInt(ss); if (n < m && m >= A && m <= B) cand.add(m); } res += cand.size(); } pw.println(res); } public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new FileReader(WORK_DIR + ""input.txt"")); PrintWriter pw = new PrintWriter(new FileWriter(WORK_DIR + ""output.txt"")); int caseCnt = sc.nextInt(); for (int caseNum=0; caseNum map = new HashSet(); public static void main (String[] args) throws IOException { new RecycledNumbers().soilve(); } int nextInt () throws IOException { in.nextToken(); return (int)in.nval; } void soilve () throws IOException { in = new StreamTokenizer(new BufferedReader(new FileReader(""./src/codejam/input.txt""))); out = new PrintWriter(new FileWriter(""./src/codejam/output.txt"")); int t = nextInt(); for (int i = 0; i < t; i++) { int cnt = 0; int a = nextInt(); int b = nextInt(); int len = Chain.getLen(a); for (int j = a; j <= b; j++) { cnt += check(a, b, j, len); } out.println(""Case #"" + (i + 1) + "": "" + cnt); } out.flush(); } int check(int a, int b, int q, int len) { // Chain chain = new Chain(q); // if (map.contains(chain)) { // return 0; // } // map.add(chain); int first = q; int cnt = 0; for (int i = 1; i < len; i++) { int last = q % 10; q /= 10; q += last * (int)Math.pow(10, len - 1); if ((first < q) && (a <= q) && (q <= b)) { cnt++; } } return cnt; } } class Chain { int a; Chain(int a) { this.a = a; } @Override public boolean equals(Object b) { Chain c = (Chain)b; int lenC = getLen(c.a); int lenA = getLen(a); if (lenA != lenC) { return false; } if (lenA == 1) { return a == c.a; } for (int i = 1; i < lenA; i++) { int last = c.a % 10; c.a /= 10; c.a += last * (int)Math.pow(10, lenA - 1); if (c.a == a) { return true; } } return false; } public static int getLen (int a) { int i = 1; int len = 0; while (a / i != 0) { len++; i *= 10; } return len; } } " B11180,"import java.util.Scanner; public class Recycled{ private Scanner input; public Recycled(){ input = new Scanner(System.in); } public void run(){ int T = input.nextInt(); for(int i = 1; i<=T; i++){ int A = input.nextInt(); int B = input.nextInt(); System.out.printf(""Case #%d: %d\n"",i,results(A,B)); } } public int results(int A, int B){ if(A == B) return 0; int result = 0; for(int m = B; m > A; m--){ String mString = String.valueOf(m); for(int n = m-1; n >= A; n--){ String nString = String.valueOf(n); for(int i = 1; i shift(int value){ Set retorno = new HashSet(); // length = 1 have no possibilities if(value < 10 ){ return retorno; } String strValue = Integer.toString(value); String nextToAnalyze = strValue; for (int i = 1; i <= strValue.length()-1 ; i++) { char[] shifted = new char[nextToAnalyze.length()]; for (int j = 0; j < nextToAnalyze.length(); j++) { if(j == 0){ shifted[nextToAnalyze.length()-1] = nextToAnalyze.charAt(j); } else { shifted[j-1] = nextToAnalyze.charAt(j); } } nextToAnalyze = new String(shifted); // check for leading zeros if(nextToAnalyze.charAt(0) != '0'){ retorno.add(Integer.parseInt(nextToAnalyze)); } } return retorno; } } " B11764,"package de.johanneslauber.codejam.model.impl; import de.johanneslauber.codejam.model.BaseProblem; import de.johanneslauber.codejam.model.ICase; import de.johanneslauber.codejam.model.IProblem; /** * * @author Johannes Lauber - joh.lauber@googlemail.com * */ public class RecycledNumbersProblem extends BaseProblem implements IProblem { @Override public void solveCases() { for (ICase currentCase : super.listOfCases) { int countPairs = 0; RecycledNumbersCase recycledNumbersCase = (RecycledNumbersCase) currentCase; int a = recycledNumbersCase.getA(); int b = recycledNumbersCase.getB(); for (int n = a; n < b; n++) { for (int m = (n + 1); m <= Math.min(10 * n, b); m++) { if (isRecycledPair(n, m)) { countPairs++; } } } this.writeToFile(String.valueOf(countPairs)); } this.closeWriter(); } private boolean isRecycledPair(int n, int m) { String nString = String.valueOf(n); char[] nCharArray = nString.toCharArray(); int lengthBegin; StringBuilder builder; int recycledN; // try every possible length to cut of the end and move to the front for (int i = 1; i < nCharArray.length; i++) { lengthBegin = nCharArray.length - i; builder = new StringBuilder(); builder.append(nString.substring(lengthBegin, nCharArray.length)); builder.append(nString.substring(0, lengthBegin)); recycledN = Integer.parseInt(builder.toString()); if (recycledN == m) { return true; } } return false; } } " B10301,"import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class CodeJam { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); try { int testCaseCount = scanner.nextInt(); for (int i = 0; i < testCaseCount; i++) { int A = scanner.nextInt(); int B = scanner.nextInt(); int counter = 0; Set pairs = new HashSet(); for (int n = A; n < B; n++) { String startString = String.valueOf(n); for (int k = 1; k < startString.length(); k++) { int startPos = startString.length() - k; if (startString.charAt(startPos) == '0') { continue; } StringBuilder sb = new StringBuilder(startString); char[] chars = new char[k]; sb.getChars(startPos, startString.length(), chars, 0); sb.delete(startPos, startString.length()); sb.insert(0, chars); int m = Integer.valueOf(sb.toString()); if (n < m && m <= B) { pairs.add(String.format(""%d %d"", n, m)); } } } System.out.println(String.format(""Case #%d: %d"", i + 1, pairs.size())); } } finally { scanner.close(); } } } " B10588,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Number { public static void main(String[] args) throws IOException { BufferedReader s = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(s.readLine()); for (int i = 1; i <= t; i++){ String[] a = s.readLine().split("" ""); int A = Integer.parseInt(a[0]); int B = Integer.parseInt(a[1]); int temp = 0; int result = 0; for (int j = A; j < B; j++) { String str = """" + j ; int n = str.length(); for (int k = 1; k < n; k++) { str = """" + str.charAt(n-1) + str.substring(0, n-1); temp = Integer.parseInt(str); if (temp > j && temp <= B) result++; } } System.out.println(""Case #""+ i + "": ""+ result); } } }" B11399,"import java.awt.Point; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; public class RecycledNumbers { public static void main(String[] args) throws FileNotFoundException, IOException { int t = 0; FileInputStream fstream = new FileInputStream(new File(args[0])); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line = br.readLine(); t = Integer.parseInt(line); System.out.println(t); String output; FileWriter fw = new FileWriter(new File(""C-small-attempt0.out"")); HashSet points = new HashSet(); for(int i = 0; i < t; i++) { int counter = 0; line = br.readLine(); String[] parameters = line.split("" ""); int a = Integer.parseInt(parameters[0]); System.out.println(""a: "" + a); int number = a; int possibleRecycled = 0; int b = Integer.parseInt(parameters[1]); System.out.println(""b: "" + b); int numberOfDigits = 1; while(a/(int)Math.pow(10, numberOfDigits) != 0){ numberOfDigits++; } while(number <= b){ int[] digits = new int[numberOfDigits - 1]; int holder = number; int j = 0; while (j < numberOfDigits - 1){ digits[j] = holder % 10; holder = holder / 10; j++; } boolean next = true; for(int k = 0; k < digits.length && next ; k++){ if(digits[k] * Math.pow(10, numberOfDigits - 1) < b){ next = false; } } if(!next){ int digitStep = 1; int lastDigit = 0; possibleRecycled = number; while(digitStep < numberOfDigits){ lastDigit = possibleRecycled % 10; possibleRecycled = (int) (lastDigit * Math.pow(10, numberOfDigits - 1) + ( possibleRecycled / 10)); if(possibleRecycled > number && possibleRecycled <= b && !points.contains(new Point(number,possibleRecycled))){ points.add(new Point(number,possibleRecycled)); counter++; // System.out.println(number + "" "" + possibleRecycled ); } digitStep++; } } number++; } output = ""Case #"" + (i + 1) + "": "" + counter + ""\n""; fw.write(output); points.clear(); } fw.flush(); fw.close(); } } " B10553,"import java.util.*; import java.io.*; public class Tester { public static void main(String[]args) throws IOException { Scanner sc = new Scanner(new File(""C-small-attempt1.in"")); int intNum = sc.nextInt(); sc.nextLine(); String[] first = new String[intNum]; String[] second =new String[intNum]; for(int i =0;ij) { //If it is greater than the first number recycle++;recycled.add(append); } } } } } System.out.println(""Case #"" + (i+1) + "": "" + recycle); } } } " B12418,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int T = 0; int A = 0; int B = 0; int n = 0; int m = 0; int tmp = 0; int totalPasses = 0; int passCtr = 0; int pairs = 0; int movDig = 0; int prevN = 0; //These 4 variables are to capture possible duplicates int prevM = 0; int prevN2 = 0; int prevM2 = 0; String currentCase = null; String inputFilename = ""C-small-attempt0.in""; String outputFilename = ""C-small-attempt0.out""; BufferedWriter out = null; try { out = new BufferedWriter(new FileWriter(outputFilename)); } catch (IOException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } FileInputStream fStream = null; try { fStream = new FileInputStream(inputFilename); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } DataInputStream in = new DataInputStream(fStream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); try { T = Integer.parseInt(br.readLine()); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } for(int i=0;i> h=new HashMap>(); int temp=b,d=0,req=0; // System.out.println(a+"" ""+b); // System.out.println(""********""); while(temp!=0) { temp/=10; d++; } for(int j=a;j=a && oth>j) { if(h.containsKey(j)) { if(h.get(j).containsKey(oth)) continue; h.get(j).put(oth,1); // System.out.println(j+"" ""+oth); req++; } else { HashMap ht=new HashMap(); ht.put(oth,0); h.put(j,ht); // System.out.println(j+"" ""+oth); req++; } } } } ans[i]=""Case #""+(i+1)+"": ""+req; // System.out.println(""------""); // System.out.println(req); // System.out.println(""**********""); } for(int i=0;i1) { // reord = Integer.toString(n); tmp1=Integer.toString(n); for (d =1;d0) cmp = in.substring(d,l); if (cmp.equals(""0"")) return false; else return true; // } // return true; } catch (NumberFormatException ex) { return false; } } public static String Rev (String n) { int r,t=0; String rev=""""; // while (n>0) // { if (checkIfNumber(n)) { t = Integer.parseInt( n ); } r=t%10; rev=rev+r; t/=10; if (n.length()>1) rev=rev+n.substring(0,n.length()-1); else rev=rev+t; // } return rev; } public static void main(String[] args) throws Exception { solve(); } } " B13194,"import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.File; import java.io.PrintStream; import java.util.Scanner; import java.util.Arrays; import java.util.ArrayList; public class Numbers{ public static ArrayList scores; public static void main(String arg[]){ System.out.print(""Enter the file path of the input file : ""); String path = new Scanner(System.in).nextLine(); String ANS ="""", output=""""; int a, b; try{ Scanner read = new Scanner(new File(path)); int testCases = Integer.parseInt(read.nextLine()); int cn=0; String tongue; while(cn++ to exit...""); (new Scanner(System.in)).nextLine(); System.exit(1); } } public static void writeToFile(String file, String text){ PrintStream out = null; try { out = new PrintStream(new FileOutputStream(file)); out.print(text); } catch(Exception e){} finally { if (out != null) out.close(); } } public static int solve(int a, int b){ int counter=0; for(int i=a; i<=b; i++){ counter += recycle(""""+i,b); } System.out.println(counter); return counter; } public static int recycle(String numb, int max){ int numbOfLoops=numb.length()-1, count=0; int newNumb, success=0; String first="""", second=""""; int last=-10; while(count< numb.length()-1){ second = numb.substring(numbOfLoops-count); first = numb.substring(0,numbOfLoops-count); newNumb = Integer.parseInt(second+first); if(newNumb != last && newNumb > Integer.parseInt(numb) && newNumb <= max){ last = newNumb; success++; } count++; } return success; } } " B10959,"import java.util.Arrays; import java.util.Scanner; import java.util.StringTokenizer; public class RecycledNumbers { public static void main(String[] args) { Scanner in=new Scanner(System.in); int cases=Integer.parseInt(in.nextLine())+1; Boolean[] arr=new Boolean[2000001]; Arrays.fill(arr,false); for(int tt=1;tt=low){ count++; arr[j]=true; } j=back(j); } if(count>0){ pair+=(count*(count+1)/2); //System.out.println(i+"" ""+arr2[i]); arr[i]=true; } } System.out.printf(""Case #%d: %d\n"",tt,pair); for(int i=low;i<=high;i++){ arr[i]=false; } } } public static int back(int n){ int r=n%10; String str=n+""""; if(r>0){ str=r+str.substring(0,str.length()-1); //System.out.println(""1 ""+str); } if(r==0){ int i; for(i=str.length()-1;str.charAt(i)=='0';i--); str=str.substring(i)+str.substring(0,i); //System.out.println(""2 ""+str); } n=Integer.parseInt(str); return n; } } " B13160," import java.io.*; import java.util.ArrayList; import java.util.HashSet; import java.util.Scanner; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author joshuahm */ public class codejamC { public static void main(String[] args) throws FileNotFoundException, IOException { FileReader inFile = new FileReader(""C-small-attempt0.in""); Scanner in = new Scanner(inFile); FileWriter outFile = new FileWriter(""C-small-attempt0.out""); PrintWriter out = new PrintWriter(outFile); //Scanner in = new Scanner(System.in); ArrayList temp2 = new ArrayList(); String temp; for(int i=1;i<10;i++) for(int j=0;j<10;j++) { temp = """" + i + j; temp2.add(temp); } for(int i=1;i<10;i++) for(int j=0;j<10;j++) for(int k=0;k<10;k++) { temp = """" + i + j + k ; temp2.add(temp); } for(int i=1;i<10;i++) for(int j=0;j<10;j++) for(int k=0;k<10;k++) for(int l=0;l<10;l++) { temp = """" + i + j + k + l; temp2.add(temp); } for(int i=1;i<10;i++) for(int j=0;j<10;j++) for(int k=0;k<10;k++) for(int l=0;l<10;l++) for(int m=0;m<10;m++) { temp = """" + i + j + k + l + m; temp2.add(temp); } for(int i=1;i<10;i++) for(int j=0;j<10;j++) for(int k=0;k<10;k++) for(int l=0;l<10;l++) for(int m=0;m<10;m++) for(int n=0;n<10;n++) { temp = """" + i + j + k + l + m + n; temp2.add(temp); } for(int j=0;j<10;j++) for(int k=0;k<10;k++) for(int l=0;l<10;l++) for(int m=0;m<10;m++) for(int n=0;n<10;n++) for(int p=0;p<10;p++) { temp = """" + '1' + j + k + l + m + n + p; temp2.add(temp); } String[] perms = new String[temp2.size()]; temp2.toArray(perms); int total=0; int x; int T= in.nextInt(); for(int t=0;t distinct = new HashSet(); for(int i=0;iB) break; distinct.clear(); temp = perms[i]; if(Integer.parseInt(perms[i])>=A && Integer.parseInt(perms[i])<=B) { distinct.add(Integer.parseInt(perms[i])); for(int j=0;j=A && temp.charAt(0) != '0') distinct.add(x); } total+= distinct.size()-1; //if(distinct.size()>1) // System.out.println(perms[i] + "" "" + (distinct.size()-1)); } } out.println(""Case #""+ (t+1) +"": "" + total/2); } in.close(); out.close(); } } " B11441,"package com.gcj; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; public class HallOfMirrors { public static Integer mirrors(String A, String B) { int lowerB = Integer.parseInt(A); int upperB = Integer.parseInt(B); int mirror = 0; int mirrorAdvised = 0; Map> uniq = new HashMap>(); for (int i = lowerB; i <= upperB; i++) { String num = Integer.toString(i); // System.out.println(num + "" "" + num.length()); for (int j = 1; j <= num.length(); j++) { String numA = num.substring(j, num.length()) + num.substring(0, j); // String numB = new StringBuffer(numA).reverse().toString(); // mirror += (lowerB <= Integer.parseInt(numA) && // Integer.parseInt(numB)<= upperB ) ? 1 : 0; // mirror += (lowerB <= Integer.parseInt(numA) && Integer.parseInt(numA)< Integer.parseInt(numB) // && Integer.parseInt(numB) <= upperB) ? 1 : 0; if(lowerB <= Integer.parseInt(num) && Integer.parseInt(num) < Integer.parseInt(numA) && Integer.parseInt(numA) <= upperB) { // System.out.println(numA + "" "" + num); if(uniq.containsKey(Integer.parseInt(num))) { List some = uniq.get(Integer.parseInt(num)); if(some.contains(Integer.parseInt(numA))) { // System.out.println(""GOTnum="" + num); // System.out.println(""GOT YOU"" + numA); mirrorAdvised--; } some.add(Integer.parseInt(numA)); mirrorAdvised++; } else { List x = new ArrayList(); x.add(Integer.parseInt(numA)); uniq.put(Integer.parseInt(num), x); mirrorAdvised++; } mirror++; } } } // Set xa = new TreeSet(); // for(Map.Entry> a : uniq.entrySet()) // { // if(a.getValue().size()>0) // { //// System.out.println(a.getKey()-a.getValue().get(0)); // xa.add(a.getKey()); // System.out.println(a.getKey() + "" "" + a.getValue()); // } // } // System.out.println(xa.size()); return mirrorAdvised; } public static void readFile() { try { BufferedReader in = new BufferedReader(new FileReader( ""C://dev//gcj//C-small-attempt0.in"")); String str; boolean first = true; int num = 0; int k = 0; List testCases = new ArrayList(); while ((str = in.readLine()) != null) { if (first) { num = Integer.parseInt(str); first = false; } else { String[] input = str.split("" ""); String A = input[0]; String B = input[1]; Integer result = mirrors(A, B); System.out.println(""Case #"" + (++k) + "": "" + result); } } in.close(); } catch (IOException e) { } } public static void main(String args[]) { readFile(); } } " B10793,"import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; class Factory implements TestCaseFactory { @Override public TestCase getInstance(int number) { return new RecycledNumbers(number); } } public class RecycledNumbers extends TestCase { int caseItem; int A; int B; int order; int power; int count; public RecycledNumbers(int caseItem) { this.caseItem = caseItem; } @Override public void readInput(BufferedReader in) throws IOException, MalformedInputFileException { final String str1 = in.readLine(); final String[] tokens = str1.split(""\\s""); A = Integer.parseInt(tokens[0]); B = Integer.parseInt(tokens[1]); } private int pow(int x, int p) { int result = 1; for (int i = 0; i < p; i++) { result *= x; } return result; } private int shift(int x) { final int digit = x / power; final int remainder = x % power; return remainder * 10 + digit; } private int findNumberOfPairs(int x) { final Set distint = new HashSet(); distint.add(x); int shifted = x; for (int i = 0; i < order; i++) { shifted = shift(shifted); if (shifted >= A && shifted < x) { return 0; // we've already seen all these permutations } else if (shifted > x && shifted <= B) { distint.add(shifted); } } final int size = distint.size(); return size * (size - 1) / 2; } @Override public void solve() { order = (int) Math.log10(A); power = pow(10, order); count = 0; for (int x = A; x < B; x++) { count += findNumberOfPairs(x); } } @Override public void writeOutput(PrintWriter out) { out.print(""Case #"" + (caseItem + 1) + "": ""); out.print(count); out.print(""\n""); } public static void main(String[] args) throws IOException, MalformedInputFileException { new Processor().process(new Factory(), args[0], args[1]); } }" B12719,"package y2012; import java.io.File; import java.io.PrintWriter; import java.util.HashMap; import java.util.Scanner; public class QR3 { public static void main(String[] args) throws Exception { Scanner inputFile=new Scanner(new File(args[0])); PrintWriter outputFile=new PrintWriter(new File(args[1])); int t=Integer.parseInt(inputFile.nextLine()); for(int i=0;i result = new HashMap(); String[] aCase = inputFile.nextLine().split("" ""); int iFrom = Integer.parseInt(aCase[0]); int iTo = Integer.parseInt(aCase[1]); String sFrom = String.valueOf(iFrom); String sTo = String.valueOf(iTo); int numDigit = sFrom.length(); if(numDigit != 1) { for(int curr = iFrom; curr < iTo; curr++) { String sCurr = String.valueOf(curr); for(int j=1; j s = new HashSet(); int count = 0; for(int i=A;i<(B+1);i++) { int[] perm = rotations(i); for(int e: perm) { if((e>=A)&&(e<=B)&&(e>i)) { s.add(e); count++; } } } out.printf(""Case #%d: %d\n"",(zz+1),count); } } static int[] rotations(int n) { // Max places for small set: 4 // Max places for large set: 7 int places = 1; if((n/1000>0)) { if (n == 1000) { return new int[]{1000, 100, 10, 1}; } int a,b,c,d; d = n%10; a = n/1000; b = (n-(a*1000))/100; c = ((n%100)-d)/10; return new int[]{(a*1000+b*100+c*10+d),(b*1000+c*100+d*10+a),(c*1000+d*100+a*10+b),(d*1000+a*100+b*10+c)}; } if ((n / 100) > 0) { if (n == 100) { return new int[]{100, 10, 1}; } int x, y, z; z = n%10; x = n/100; y = (n-(x*100)-z)/10; return new int[]{(x * 100) +(y * 10) + z, (y * 100 + z * 10 + x), (z * 100 + x * 10 + y)}; } if((n/10)>0) { if(n == 10) return new int[]{10,1}; int x,y; x = n/10; y = n%10; return new int[]{x*10+y,y*10+x}; } return new int[]{n}; } } " B12684,"import java.io.FileReader; import java.io.LineNumberReader; import java.io.PrintStream; public class RecycledNumbers { public boolean testRecycled(int a, int b) { String sa = String.valueOf(a); String sb = String.valueOf(b); // if(sa.indexOf('0')!=-1 || sb.indexOf('0')!=-1) // return false; int n = sa.length(); for(int i=0; i iLst=getIntLstFromString(str); minNumb=iLst.get(0); maxNumb=iLst.get(1)+1; for(int a=minNumb;a is=new HashSet(); for(int i=1;i it=is.iterator();it.hasNext();){ int a1=it.next(); if(a1>a && a1 getIntLstFromString(String str){ //将一行数字的字符串转为整型List; List iLst=new ArrayList(); int j=0; for(int i=0;i availablesNumbers = new ArrayList(); Set pairs = new HashSet(); for (int number = a; number <= b; number++) availablesNumbers.add(number); for (Integer integer : availablesNumbers) { String string = integer.toString(); for (int index = 1; index <= string.length(); index++) { String newString = string.substring(index) + string.substring(0, index); Integer newNumber = Integer.parseInt(newString); if (!availablesNumbers.contains(newNumber)) continue; if (integer.equals(newNumber)) continue; if (integer < newNumber) continue; pairs.add(new Pair(integer, newNumber)); } } return pairs.size(); } public static class Pair { Integer a; Integer b; public Pair(int a, int b) { this.a = a; this.b = b; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((a == null) ? 0 : a.hashCode()); result = prime * result + ((b == null) ? 0 : b.hashCode()); return result; } @Override public boolean equals(Object obj) { if (obj.getClass() != Pair.class) return false; Pair other = (Pair) obj; if (other.a.equals(a) && other.b.equals(b)) return true; if (other.a.equals(b) && other.b.equals(a)) return true; if (other.b.equals(a) && other.a.equals(b)) return true; return false; } @Override public String toString() { return ""[ "" + a + "", "" + b + "" ]""; } } } " B11742,"import java.util.*; public class C { public static void main(String[] args){ Scanner in = new Scanner(System.in); int T = in.nextInt(); for(int zz = 1; zz <= T;zz++){ int A = in.nextInt(); int B = in.nextInt(); int result = 0; for(int i=A;i<=B;i++) { ArrayList pairs = new ArrayList(); String ns = i+""""; for (int j=ns.length()-1;j>0;j--) { String k = ns.substring(j); String newval = k + ns.substring(0,j); int m = Integer.parseInt(newval); if (m>i && A=m) { if (pairs.indexOf(m)==-1) pairs.add(m); } } result += pairs.size(); } System.out.format(""Case #%d: %d\n"", zz, result); } } } " B13126,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class Pairs { /** * @param args */ public static int counter=0; public static void checkhelper(String a,String b) { if(a.length()!=b.length()) return; if(a.concat(a).contains(b)) counter++; } public static void check(int a,int b) { for(int i=a;i<=b;i++) { for(int j=i+1;j<=b;j++) checkhelper(""""+i, """"+j); } } public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedWriter bw=new BufferedWriter(new FileWriter(""out2.out"")); BufferedReader bf=new BufferedReader(new FileReader(""input.txt"")); int count=Integer.parseInt(bf.readLine()); for(int i=0;i n && m >= A && m <= B) { found = 0; for (int l = 0; l < count; l++) if (rep[l] == m) { found = 1; } if (found == 0) { rep[count] = m; count++; sum++; // System.out.println(n + "" "" + m); } } } } pw.println(""Case #"" + (i + 1) + "": "" + sum); System.out.println(""Case #"" + (i + 1) + "": "" + sum); } pw.close(); } } " B12238,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package googlerecyclenum; import java.util.*; import java.io.*; /** * * @author Aaron */ public class GoogleRecycleNum { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here try { File file = new File (""input.txt""); PrintWriter pw = new PrintWriter (new FileWriter (""output.txt"")); if (file.exists ()) { FileReader f_rd = new FileReader (file); LineNumberReader l_rd = new LineNumberReader(f_rd); String input_s; input_s = l_rd.readLine(); int num_case; if (input_s!= null) { num_case = Integer.parseInt (input_s); } else { throw new IllegalArgumentException(""Invalid Input File""); } for (int i = 0; i< num_case;i++) { int num_a; int num_b; input_s = l_rd.readLine(); String[] values = input_s.split("" ""); int result = 0; num_a = Integer.parseInt(values[0]); num_b = Integer.parseInt(values[1]); for ( int j = num_a; j<= num_b; j++) { result += valid_recycle(j, num_a, num_b); } pw.println (""Case #""+ (i+1)+"": "" + result); } pw.close(); l_rd.close (); } } catch (IOException e) { e.printStackTrace(); } } static int getNumTen (int input_num) { int n = 1; while (input_num/n > 0) n *= 10; return n/10; } static int valid_recycle (int input_num, int num_a, int num_b) { int count = 0; //try to recycle the number to check if it is valid if (input_num < 10) return 0; //input_num = 1212; int temp = getNumTen (input_num); ArrayList result = new ArrayList (); breakall: for (int n = 10; n <= input_num; n *= 10) { int upper = input_num/n; int lower = input_num%n; if (lower == 0 || lower < n/10) { temp = temp/10; continue; } int n_num = lower*temp + upper; if (n_num >= num_a && n_num <= num_b && n_num > input_num) { //System.out.println (""Getnerate "" + input_num + "" ==> "" + n_num); int len = result.size(); for (int i = 0; i < len; i++) { if (n_num == result.get(i)) { temp = temp/10; continue breakall; } } result.add (n_num); count++; } temp = temp/10; } return count; } } " B13208,"package probs; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; public class Problem3 { public static void main(String[] args) { try { String filePath = ""in-small-3.txt""; List input = readInput(filePath); int[] output = process(input); writeOutput(output); } catch (Exception e) { e.printStackTrace(); } } private static int[] process(List input) { int[] result = new int[input.size()]; int count = 0; for (String eachLine : input) { String[] split = eachLine.split("" ""); String min = split[0]; String max = split[1]; int eachResult = processEachTestCase(min, max); result[count] = eachResult; count++; } return result; } private static int processEachTestCase(String min, String max) { int result = 0; int length = min.length(); int minValue = Integer.parseInt(min); int maxValue = Integer.parseInt(max); for (int x = minValue; x <= maxValue; x++) { // System.out.println(""trying for "" + x); Set set = new HashSet(); // performing rotations on a number x for (int i = 0; i < length; i++) { int y = rotate(x, i, length); if (x < y && y <= maxValue) { if(!set.contains(y)){ set.add(y); result++; } } } } return result; } private static int rotate(int x, int i, int length) { int y; int temp = (int) Math.pow(10, i); int remainder = x % temp; y = x / temp; y = y + remainder * (int) (Math.pow(10, (length - i))); return y; } private static List readInput(String filePath) throws FileNotFoundException { List list = new ArrayList(); File file = new File(filePath); Scanner scanner = new Scanner(file); if (scanner.hasNextLine()) { String line = scanner.nextLine(); int testCases = Integer.parseInt(line); } while (scanner.hasNextLine()) { String line = scanner.nextLine(); // System.out.println(line); list.add(line); } return list; } private static void writeOutput(int[] list) { int n = list.length; for (int i = 0; i < n; i++) { System.out.println(""Case #"" + (i + 1) + "": "" + list[i]); } } } " B10870,"import static java.lang.System.*;import static java.lang.Math.*;import static java.lang.Character.*;import java.io.*;import java.text.*;import java.util.*;import java.util.regex.*; public class Recycled { public static Scanner in; public static PrintWriter out; public static String nl(){return in.nextLine();} public static int ni(){return in.nextInt();} public static double nd(){return in.nextDouble();} public static int pi(String a){return Integer.parseInt(a);} public static double pd(String a){return Double.parseDouble(a);} public static void pl(Object o) { out.println(o); } public static void plf(String f, Object... o) { out.printf(f, o); out.println(); } public static String nt(){return in.next();} public static void pt(Object o) {out.print(o);} public static void main(String[]args) throws IOException { in=new Scanner(new File(""C-small-attempt0.in"")); out = new PrintWriter(new BufferedWriter(new FileWriter(""C-small-attempt0.out""))); // in=new Scanner(System.in); int xxxxxx=pi(nt());nl(); for (int xxxxx=1;xxxxx<=xxxxxx;xxxxx++) { pt(""Case #""+xxxxx+"": ""); int min = ni(); int max = ni(); int count = 0; for(int i=min;i<=max;i++){ for(int j=max;j>i;j--){ String si = Integer.toString(i); String sj = Integer.toString(j); if(si.length()!=sj.length()) continue; if(recycled(si,sj)) count++; } } pl(count); } out.close(); System.exit(0); } static boolean recycled(String a, String b){ for(int x=0;x set; public static void main(String[] args) throws Exception { FileIO fileHandler = new FileIO(); int totalTestCases = Integer.parseInt(fileHandler.readLine()); for (int tc = 0; tc < totalTestCases; tc++) { set = new HashSet(); String input = fileHandler.readLine(); String nm[] = input.split("" ""); int start = Integer.valueOf(nm[0]); int end = Integer.valueOf(nm[1]); for(int i=start; i<=end; i++){ String currVal = String.valueOf(i); countPairs(currVal, start, end, nm); } fileHandler.writeLine(String.valueOf(set.size())); } fileHandler.closeFileIO(); } public static void countPairs(String input, int start, int end, String[] nm){ String clonedValue = new String(input); if(nm[1].length() <= 1) return; else{ int length = input.length(); for(int i=0; i= start && !rotated.equals(clonedValue) ){ if(Integer.valueOf(clonedValue) < Integer.valueOf(rotated)) set.add(clonedValue+""-""+rotated); else set.add(rotated+""-""+clonedValue); } input = rotated; } } } public static String rotate(String input){ return input.substring(1) + input.charAt(0); } } /* * File IO is used to read and Write - Keep it simple. */ class FileIO { private FileReader inFileReader; private FileWriter outFileWriter; private BufferedReader br = null; private BufferedWriter bw = null; private int lineNumber = 1; public FileIO() throws Exception { inFileReader = new FileReader(""C:\\CodeJam2012\\in.txt""); br = new BufferedReader(inFileReader); outFileWriter = new FileWriter(""C:\\CodeJam2012\\out.txt""); bw = new BufferedWriter(outFileWriter); } public FileIO(String in, String out) throws Exception { inFileReader = new FileReader(in); br = new BufferedReader(inFileReader); outFileWriter = new FileWriter(out); bw = new BufferedWriter(outFileWriter); } /* * This procedure returns null if all the rows are read from input file. */ public String readLine() throws Exception { return br.readLine(); } /* * This procedure writes a line to output file as per the google codejam * standard */ public void writeLine(String line) throws Exception { bw.write(""Case #"" + lineNumber + "": "" + line + ""\r\n""); lineNumber++; } public void closeFileIO() throws Exception { br.close(); bw.flush(); bw.close(); } }" B12208,"package hk.polyu.cslhu.codejam.solution.impl.qualificationround; import java.util.ArrayList; import java.util.List; import hk.polyu.cslhu.codejam.solution.Solution; public class DancingWithTheGooglers extends Solution { private int N, S, p; private List totalPointList; @Override public void setProblem(List problemDesc) { // TODO Auto-generated method stub String[] splitArray = problemDesc.get(0).split("" ""); this.N = Integer.valueOf(splitArray[0]); this.S = Integer.valueOf(splitArray[1]); this.p = Integer.valueOf(splitArray[2]); this.totalPointList = new ArrayList(); for (int i = 3; i < splitArray.length; i++) { this.totalPointList.add(Integer.valueOf(splitArray[i])); } if (this.totalPointList.size() != this.N) logger.error(""Found an error for "" + problemDesc.get(0)); } @Override public void solve() { // TODO Auto-generated method stub int minNotSupSum = this.p * 3 - 2; int minSupSum = this.p > 1 ? (this.p * 3 - 4) : 1; int totalNotSup = 0; int totalSup = 0; for (Integer point : this.totalPointList) { if (point >= minNotSupSum) totalNotSup++; else if (point >= minSupSum) totalSup++; } if (totalSup + totalNotSup < this.S) logger.error(""Found an error for suprising cases""); this.result = String.valueOf(totalNotSup + Math.min(totalSup, this.S)); } } " B11607,"import java.io.*; import java.util.*; public class ProbC { public static void main(String[] args) throws FileNotFoundException, IOException { ProbC p = new ProbC(); p.solveAll(); } int tests = 0; Scanner in; BufferedWriter out; public ProbC() throws FileNotFoundException, IOException { out = new BufferedWriter(new FileWriter(""c.out"")); in = new Scanner(new File(""c.in"")); tests = in.nextInt(); in.nextLine(); //System.out.println(tests); } public void solveAll() throws IOException { //System.out.println(move(11, 1)); ///* for(int i = 0; i < tests; i++) { solve(i+1); } out.close(); in.close();//*/ } public void solve(int casenr) throws IOException { int A, B, res = 0; A = in.nextInt(); B = in.nextInt(); int[] perm = new int[100]; for(int i = A; i <= B; i++) { int d = digits(i); for(int j = 1; j < d; j++) { int m = move(i, j); boolean found = false; for(int k = 1; k < j; k++) { if(perm[k] == m) found = true; } perm[j] = m; if(!found && valid(A, B, i, m)) res++; } } out.write(""Case #""+casenr+"": ""); out.write(new Integer(res).toString()); out.write('\n'); } public int digits(int nr) { int d = 0; while(nr > 0) { nr /= 10; d++; } return d; } public int move(int nr, int pos) { String nrs = new Integer(nr).toString(); String rs = nrs.substring(nrs.length()-pos); rs = rs + nrs.substring(0, nrs.length()-pos); return new Integer(rs).intValue(); } public boolean valid(int A, int B, int n, int m) throws IOException { /*if(A <= n && n < m && m <= B) out.write(n+"" ""+m+"" ""+'\n');//*/ return A <= n && n < m && m <= B; } }" B13100,"/* * @(#)CJ2012C.java * por Jorge López Palacios * * Más información y descripción del Copyright©. * */ /** * Clase CJ2012C * @author Jorge López Palacios * @version 1.0 */ //***************** PACKAGES ****************************// package codejam; //***************** IMPORTS *****************************// import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class CJ2012C { //***************** CONSTANTES ****************************// private static final String SPATHFILEINPUT = ""C:\\C-small-attempt0.in""; private static final String SPATHFILEOUTPUT = ""C:\\CJ2012C.txt""; //***************** ATRIBUTOS *****************************// private static BufferedReader brBuffer; private static String sFileLine = """"; private static PrintWriter pwFileOutput; //***************** METODOS SELECTORES ********************// //***************** METODOS MODIFICADORES *****************// //***************** CONSTRUCTORES *************************// //***************** MAIN **********************************// /** * @param args the command line arguments */ public static void main(String[] args) { int iNumberCases = 0; int iCurrentLine = 0; int aiNumbers[] = new int[2]; String asNumbers[] = new String[2]; String sDummy = """"; String sNNormal = """"; //String sNBackward = """"; int iCountRecycled = 0; //String sBackwardDummy = """"; try{ // Recogemos los datos del fichero brBuffer = getFileToString(SPATHFILEINPUT); // Recogemos el fichero de salida pwFileOutput = getFile(); // Leemos cada línea del fichero while((sFileLine = brBuffer.readLine()) != null){ // Inicializo el contador de números reciclados iCountRecycled = 0; // Recojo el número de casos if(iCurrentLine == 0){ iNumberCases = Integer.parseInt(sFileLine); }else{ // Recojo los números asNumbers = sFileLine.split("" ""); aiNumbers = new int[asNumbers.length]; for(int i = 0; i <= asNumbers.length - 1; i ++){ aiNumbers[i] = Integer.parseInt(asNumbers[i]); } // Recojo todos los números de A hasta B for(int n = aiNumbers[0]; n <= aiNumbers[1]; n ++){ // Recojo todos los números de B hasta A for(int m = aiNumbers[1]; (m > n); m --){ // Compruebo si la combinacion (n, m) es de números reciclados sNNormal = n + """"; for(int i = 0; (i <= sNNormal.length() - 1); i ++){ sDummy = sNNormal.substring((sNNormal.length() - i), sNNormal.length()) + sNNormal.substring(0, (sNNormal.length() - i)); if((Integer.parseInt(sDummy) == m) && ((Integer.parseInt(sDummy) + """").length() == (m + """").length())){ iCountRecycled ++; } } } } } if(iCurrentLine == 0){ System.out.println(""Numero de casos: "" + iNumberCases); }else{ printToFile(""Case #"" + iCurrentLine + "": "" + iCountRecycled); //System.out.println(""Case #"" + iCurrentLine + "": "" + iCountRecycled); } // Incrementamos el número de línea iCurrentLine ++; } //Cerramos el buffer del fichero closeInputStream(brBuffer); }catch (Throwable th){ System.err.println(""Error: "" + th.toString()); } } //***************** METODOS PÚBLICOS **********************// //***************** METODOS PRIVADOS **********************// /** * Devuelve los datos de un fichero indicado por parametro * * @param ai_sPathFile: Ruta del fichero * @throws IOException */ private static BufferedReader getFileToString(String ai_sPathFile) throws IOException{ // Abrimos el fichero FileInputStream fisFile = new FileInputStream(ai_sPathFile); // Recojo los datos del fichero DataInputStream disData = new DataInputStream(fisFile); brBuffer = new BufferedReader(new InputStreamReader(disData)); return brBuffer; } /** * Cierra el buffer del fichero * * @param ai_bfrBuffer * @throws IOException */ private static void closeInputStream(BufferedReader ai_bfrBuffer) throws IOException{ if(ai_bfrBuffer != null){ ai_bfrBuffer.close(); } } /** * Recoge el fichero de salida en memoria * * @throws FileNotFoundException */ private static PrintWriter getFile() throws FileNotFoundException{ pwFileOutput = new PrintWriter(SPATHFILEOUTPUT); return pwFileOutput; } /** * Escribe en el fichero de salida * * @param ai_sText */ public static void printToFile(String ai_sText){ // Escribo en el fichero pwFileOutput.append(ai_sText); pwFileOutput.println(); // Cierro el fichero pwFileOutput.flush(); } }//FIN DE LA CLASE" B12465,"import java.io.*; import java.util.StringTokenizer; public class Ricky { public static void main(String []args) { try{ FileInputStream fstream = new FileInputStream(""input.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; int n=0; FileWriter fstream1 = new FileWriter(""out.in""); BufferedWriter out = new BufferedWriter(fstream1); int i; while ((strLine = br.readLine()) != null) { n=n+1; if (n==1) i = Integer.parseInt(strLine); else { System.out.println (parse(strLine,n-1)); out.write(parse(strLine,n-1)+""\n""); } } out.close(); in.close(); }catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } private static String parse(String string1,int oo) { String str=""""; int count =0; long aa = 0; long bb = 0; StringTokenizer stringTokenizer = new StringTokenizer(string1); while(stringTokenizer.hasMoreTokens()) { aa = Integer.parseInt(stringTokenizer.nextToken()); bb = Integer.parseInt(stringTokenizer.nextToken()); } for (long i = aa ; i < bb; i = i+1) { if(i<10) { count = 0; } else if(i>=10 && i<100) { int m = (int) (i/10); int n = (int) (i%10); int nm = 10*n + m; if(i=100 && i<1000) { int mn = (int) (i/10); int z = (int) (i%10); int zmn = 100*z + mn; if(i=1000 && i<10000) { int mnz = (int) (i/10); int t = (int) (i%10); int tmnz = 1000*t + mnz; if(i=10000 && i<100000) { int mnzt = (int) (i/10); int w = (int) (i%10); int wmnzt = 10000*w + mnzt; if(i=100000 && i<1000000) { int mnzt = (int) (i/10); int w = (int) (i%10); int wmnzt = 100000*w + mnzt; if(i=1000000 && i<10000000) { int mnzt = (int) (i/10); int w = (int) (i%10); int wmnzt = 1000000*w + mnzt; if(i=10000000 && i<100000000) {} else {} } return ""Case #""+oo+"": ""+count; } }" B12517," import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class Recycled_Numbers { /** * @param args */ public static void main(String[] args) { try { Scanner sc = new Scanner(new File(""C-small-attempt0.in"")); int caseNo = sc.nextInt(); FileWriter fstream = new FileWriter(""C-small-attempt0.out""); BufferedWriter out = new BufferedWriter(fstream); for(int i = 1; i <= caseNo; i++) { int a = sc.nextInt(); int b = sc.nextInt(); int recyclableNo = 0; int start; int end; if(a > b) { end = a; start = b; } else { end = b; start = a; } System.out.println(""test""); for(int j = start; j <= end; j++) { for(int k = end; k > j; k--) { if(isPermutation(j, k)) { if(isEquivalent(j, k)) { recyclableNo++; } } } } System.out.println(""Case #"" + i + "": "" + recyclableNo); out.write(""Case #"" + i + "": "" + recyclableNo); out.newLine(); } //Close the output stream out.close(); } catch (IOException e) { e.printStackTrace(); } } private static int getNoOfDigits(long num) { int digitCount = 0; while(num > 0) { num /= 10; digitCount++; } return digitCount; } private static boolean isPermutation(int num1, int num2) { boolean result = false; int[] arr = new int[10]; int temp = num2; while (temp > 0) { arr[temp % 10]++; temp /= 10; } temp = num1; while (temp > 0) { arr[temp % 10]--; temp /= 10; } for (int i = 0; i < 10; i++) { if (arr[i] != 0) { result = true; } } return !result; } private static boolean isValidPermutation(int num1, int num2) { boolean result = false; int noOfMatches = 0; int currentPointToBegin = -1; int temp = num2 % 10; int[] arr1 = getDigitsInArray(num1); for(int i = 0; i < arr1.length; i++) { if(arr1[i] == temp) { noOfMatches++; if(currentPointToBegin == -1) { currentPointToBegin = i; } } } int temp2 = num2; while(temp2 > 0) { if(noOfMatches > 0) { noOfMatches--; for(int i = 0; i < arr1.length; i++) { } } } return result; } private static int[] getDigitsInArray(int num) { int i = getNoOfDigits(num); int[] arr = new int[i]; while(num > 0) { arr[i - 1] = num % 10; num /= 10; i--; } return arr; } private static boolean isEquivalent(int num1, int num2) { boolean result = false; int rem; int digitNo = getNoOfDigits(num1); for(int i = 0; i < digitNo; i++) { if(num1 == num2) { result = true; break; } rem = num1 % 10; num1 /= 10; num1 += rem * Math.pow(10, digitNo - 1); } return result; } } " B11574,"package recyclednumbers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; public class SimpleWriter { private BufferedWriter bw; private int line; public SimpleWriter() { String filename = prompt(); setWriter(filename); } public SimpleWriter(String filename) { setWriter(filename); } private String prompt() { System.out.println(""Output file: ""); BufferedReader bufr = new BufferedReader( new InputStreamReader(System.in)); String filename = null; try { filename = bufr.readLine(); } catch (IOException e) { System.err.println(""At prompt: "" + e.getMessage()); } return filename; } private void setWriter(String filename) { try { bw = new BufferedWriter(new FileWriter(filename)); } catch (IOException e) { System.err.println(e.getMessage()); } } public void writeLine(String str) { try { line++; bw.write(str + ""\n""); } catch (IOException e) { System.err.println(""Line "" + (line - 1) + "": "" + e.getMessage()); } } public void writeLine(int i) { writeLine(i + """"); } public void writeLine(int[] arr) { String line = """"; for (int i : arr) { line = line + i + "" ""; } line = line.trim(); writeLine(line); } public void flush() { try { bw.flush(); } catch (IOException e) { System.err.println(""At flush: "" + e.getMessage()); } } } " B13220,"import java.util.Scanner; public class NumberRecycling { public static void main( String args[] ) { new NumberRecycling(); } public NumberRecycling() { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for( int j=1; j<=T; j++ ) { System.out.println( ""Case #""+ j + "": "" + doCase(sc) ); } } public int doCase( Scanner sc ) { int A = sc.nextInt(); int B = sc.nextInt(); int pairs = 0; for( int i=A+1; i<=B; i++ ) pairs += numberOfLowerPairNumbers(A,i); return pairs; } public int numberOfLowerPairNumbers( int lowerBound, int num ) { String number = Integer.toString(num); String tmp = new String(number); int result = 0; for( int i=0; i= lowerBound ) result++; } return result; } }" B10326,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map.Entry; import java.util.Set; public class CodeJam { private Set generateCombination(Integer i, Integer max) { final Set output = new HashSet(); final Integer len = String.valueOf(i).length(); Integer num = i; double pow = Math.pow(10, len - 1); for (int j = 0; j < len - 1; ++j) { num = (int) ((num % pow) * 10 + (num / pow)); if (num > i && num <= max) output.add(num); } return output; } private List> getInputValue() { List> inpVal = new ArrayList>(); BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); try { final String tc_ = stdin.readLine(); Integer testCase = Integer.parseInt(tc_); while (testCase-- > 0) { // System.err.println(""tc#"" + testCase); final String[] input = stdin.readLine().split("" ""); final int min = Integer.parseInt(input[0]); final int max = Integer.parseInt(input[1]); inpVal.add(new HashMap() { { put(min, max); } }); } return inpVal; } catch (IOException e) { e.printStackTrace(); } return null; } public static void main(String[] args) { CodeJam cj = new CodeJam(); List> inp = cj.getInputValue(); int count = 1; for (HashMap tc : inp) { // operating for tc int min = 0, max = 0; int answer = 0; for (Entry e : tc.entrySet()) { min = e.getKey(); max = e.getValue(); } for (int i = min; i <= max; ++i) { answer += cj.generateCombination(i, max).size(); } System.out.println(""Case #"" + count++ + "": "" + answer); } // System.err.println(cj.generateCombination(24, 40)); } } " B13192,"import java.io.*; import java.util.*; public class RecycledNumbers { BufferedReader in; StringTokenizer st; PrintWriter out; String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } double nextDouble() throws Exception { return Double.parseDouble(next()); } void solve() throws Exception { int l = nextInt(), r = nextInt(); HashMap c = new HashMap(); for (int i = l; i <= r; i++) { HashSet alr = new HashSet(); alr.add(i); for (int j = 10; j <= i; j *= 10) { int rot = Integer.parseInt((i % j) + """" + (i / j)); if (!alr.contains(rot)) { alr.add(rot); if (c.containsKey(rot)) { int curr = c.get(rot) + 1; c.put(rot, curr); } else c.put(rot, 1); } } } long ans = 0; for (int i = l; i <= r; i++) { ans += c.get(i) == null ? 0 : c.get(i); } out.print(ans / 2); } void run() { try { Locale.setDefault(Locale.US); in = new BufferedReader(new FileReader(""input.txt"")); out = new PrintWriter(new FileWriter(""output.txt"")); int t = nextInt(); for (int tc = 1; tc <= t; tc++) { out.print(""Case #"" + tc + "": ""); solve(); out.println(); } out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } public static void main(String[] args) { new RecycledNumbers().run(); } } " B12514,"import java.io.*; import java.util.*; import java.math.*; public class recycle { static int A=0; static int B=0; static int C=0; static int T=0; static int ans=0; static HashSet ansset= new HashSet(); public static void main(String[] args) { Scanner scan= new Scanner(System.in); T=scan.nextInt(); for(int i=1; i<=T; i++) { A=scan.nextInt(); B=scan.nextInt(); String s1=""""; C=0; ans=0; if(B>10) for(int n=A; nn && C<=B) ansset.add(C); } ans+=ansset.size(); } System.out.println(""Case #""+i+"": ""+ans); } } }" B12863,"package google.codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; public class Main { private static boolean debug = false; public static void main(String [] args){ if(args!=null && args.length==2){ FileInputStream fstream = null; try { fstream = new FileInputStream(args[0]); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; File file = new File(args[1]); FileWriter fstreamOut = new FileWriter(file.getAbsolutePath()); BufferedWriter out = new BufferedWriter(fstreamOut); int lineNum = Integer.parseInt(br.readLine()); GoogleSolver solver = new RecycledNumberSolver(); //GooglereseSolver.calcualteMapping(); for(int i=0 ; i"" + resultStr); }else{ String output = ""Case #""+(i+1) +"": "" + resultStr; System.out.println (output); out.write(output+""\n""); } } out.close(); in.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } " B10105,"import java.io.FileInputStream; import java.util.*; public class Q_C { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new FileInputStream(""C:\\C-small-attempt0.in"")); Set set = new HashSet(); int tests = sc.nextInt(); for (int i = 0; i < tests; i++) { int a = sc.nextInt(); int b = sc.nextInt(); for (int j = a; j < b; j++) { List list = getRecycledNumbers(j); for (int k : list) { if (k > j && k <= b) { set.add(j + "" "" + k); } } } System.out.println(""Case #"" + (i+1) + "": "" + set.size()); set.clear(); } } private static List getRecycledNumbers(int num) { List list = new ArrayList(); String s = String.valueOf(num); for (int i = s.length() - 1; i > 0; i--) { String temp = s.substring(i, s.length()) + s.substring(0, i); if (!temp.startsWith(""0"")) { int cur = Integer.valueOf(temp); list.add(cur); } } return list; } } " B10341,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Saransh */ import java.io.*; import java.util.*; import java.math.*; import java.lang.*; public class Main { static int pts[]; static int n,s,p; static int memo[][]; static boolean marked[][]; public static void main(String[] args) { try { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); int test=1; while(t-->0) { int A=sc.nextInt(); int B=sc.nextInt(); int count=0; for(int i=A;i<=B;i++) { String str=i+""""; HashSet set=new HashSet(); for(int i1=0;i1<=str.length();i1++) { String tmp=str.substring(i1)+str.substring(0,i1); if(tmp.charAt(0)!='0') { int temp=Integer.parseInt(tmp); if(temp>i&&temp<=B&&!set.contains(temp)) { set.add(temp); count++; } } } } System.out.println(""Case #""+test+"": ""+count); test++; } } catch(Exception e) { e.printStackTrace(); } } } " B12014,"import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Hashtable; import java.util.Scanner; public class done { public static void main(String args[]) throws IOException { Hashtable a = new Hashtable(); ArrayList f = new ArrayList(); Scanner in = new Scanner(System.in); DataInputStream d = new DataInputStream(new BufferedInputStream(new FileInputStream(""C:/Users/ANKIT/Desktop/C-small-attempt0.in""))); //DataInputStream d = new DataInputStream(new BufferedInputStream(new FileInputStream(""C:/Users/ANKIT/Desktop/hj.txt""))); String num = d.readLine(); int num1; num1 = Integer.parseInt(num); for(int i=0;ii && res[j]<=upper && res[j]>=lower) {try{ String S = ""Case #""+Integer.toString(k)+"" ""+Integer.toString(i)+"": ""+Integer.toString(res[j]); outft.write(S); outft.newLine(); outft.flush(); cnt++;} catch(IOException r) { } } } } } int[] span(int num,int num_size) { int[] res = new int[num_size]; String rec = Integer.toString(num); char[] previous = new char[rec.length()]; rec.getChars(0,rec.length(), previous, 0); res [0] = new Integer(rec); //store 1st for(int j = 1; j < num_size; j++) { char first = previous[0]; for(int i = 0;i orgNumber && number <= b) { // System.out.println( ""no: "" + number + "", "" + check); counter++; } } return counter; } public static void main(String[] args) throws FileNotFoundException { if (args.length == 0) { throw new IllegalArgumentException(""no file given""); } String filename = args[0]; Scanner scanner = new Scanner(new File(filename)); int numOfLines = scanner.nextInt(); scanner.nextLine(); for (int lineIdx = 0; lineIdx < numOfLines; lineIdx++) { final int start = scanner.nextInt(); final int end = scanner.nextInt(); int ans = 0; for (int l = start; l <= end; l++) { ans += solve(l, end); } System.out.printf(""Case #%d: %d\n"", lineIdx + 1, ans); } } } " B11703,"import java.io.*; import java.util.*; import java.awt.*; import static java.lang.System.*; public class C { public static void main (String [] args) throws IOException {new C().run();} public void run() throws IOException{ Scanner file = new Scanner(new File(""C-small-attempt0.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""C.out""))); int times = file.nextInt(); for(int asdf = 0; asdf set = new HashSet(); for(int i = a; i<=b; i++){ String s = """"+i; for(int j = 1; j= s.charAt(0) ){ int x = Integer.parseInt(s.substring(j,s.length()) +s.substring(0,j)); if( i uniquePairs = new HashSet(); if (minValueChar.length > 1) { for (int j = 0; j < minValueChar.length - 1; j++) { for (int k = minValue; k < maxValue; k++) { int lastDigits = k % (int) Math.pow(10, j + 1); int firstDigits = k / (int) Math.pow(10, j + 1); int replacement = 0; if (lastDigits != firstDigits) { replacement = Integer.valueOf("""" + lastDigits + firstDigits); } if (replacement > k && replacement <= maxValue) { if (!uniquePairs.contains(k + "" "" + replacement) || uniquePairs.contains(replacement + "" "" + k)) { noOfPossibilities++; uniquePairs.add(k + "" "" + replacement); System.out.println(k + "" "" + j + "" "" + lastDigits + "" "" + firstDigits + "" "" + replacement); } } } } } return noOfPossibilities; } private static String[] readSamplesFromFile(int noOfInputs, BufferedReader fin) throws IOException { String[] samples = new String[noOfInputs]; for (int i = 0; i < noOfInputs; i++) { samples[i] = fin.readLine(); } return samples; } } " B12506,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class ProblemC { public static void main(String[] args) throws FileNotFoundException { String test = ""4\n"" + ""1 9\n"" + ""10 40\n"" + ""100 500\n"" + ""1111 2222\n""; Scanner sc = new Scanner(new File(""C-small-attempt0.in"")); int teller = 0; int numLines = 0; String finalOut = """"; boolean print = false; int n = 0;// smal number int m = 0;// big number int A = 0; // min number int B = 0; // max number int S = 0; // answare String[] split; while (true) { String line = sc.nextLine(); if (teller == 0) { numLines = Integer.valueOf(line); } else { print = true; split = line.split("" ""); A = Integer.valueOf(split[0]); B = Integer.valueOf(split[1]); for (n = A; n < B; n++) { for (m = n + 1; m <= B; m++) { S += check(n, m); } } } if (print) { if (teller == numLines) { System.out.println(""Case #"" + teller + "": "" + S); finalOut += ""Case #"" + teller + "": "" + S; break; } else { System.out.println(""Case #"" + teller + "": "" + S); finalOut += ""Case #"" + teller + "": "" + S + ""\n""; } S = 0; } teller++; } PrintWriter writer = new PrintWriter(new File(""out.txt"")); writer.print(finalOut); writer.close(); } private static int check(int n, int m) { String N = """" + n; String M = """" + m; if (M.length() == 1) { return 0; } for (int i = 1; i < N.length(); i++) { String temp = N.substring(N.length() - (i), N.length()); temp += N.substring(0, N.length() - (i)); if (temp.equals(M)) { return 1; } } return 0; } } " B10457,"package Parser; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; public class MyReader { public String[] taskArray; public int currentString; public MyReader(String fileName) { // TODO Auto-generated constructor stub String taskString = readString(fileName); if (taskString.indexOf('\r') == -1) { taskArray = taskString.split(""\n""); } else { taskArray = taskString.split(""\r\n""); } currentString = 0; } public String readString(String fileName) { StringBuffer buffer = new StringBuffer(); try { File file = new File(fileName); FileInputStream fis = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(fis); Reader in = new BufferedReader(isr); int ch; while ((ch = in.read()) > -1) { buffer.append((char) ch); } in.close(); return buffer.toString(); } catch (IOException e) { return """"; } } public String read() { return taskArray[currentString++]; } } " B12992,"package mgg.utils; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; /** * @author manolo * @date 13/04/12 */ public class FileUtil { FileReader reader; FileWriter writer; public FileUtil(String input, String output) { try { reader = new FileReader(input); writer = new FileWriter(output); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public String getLine(){ try { StringBuilder builder = new StringBuilder(); char c = (char) reader.read(); while (c != '\n') { builder.append(c); //System.out.println(""\t\t\t> char: '"" + c + ""'""); c = (char) reader.read(); } ; System.out.println(""\t\t\t----------> line: '"" + builder.toString() + ""'""); return builder.toString(); } catch (IOException e) { e.printStackTrace(); } return null; } public void printLine(int lineNumber, String line){ try { writer.write(""Case #"" + lineNumber + "": "" + line + ""\n""); } catch (IOException e) { e.printStackTrace(); } } public void closeFiles(){ try { reader.close(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } } " B10942,"import java.io.*; import java.util.*; public class Main { public static void main(String[] args)throws IOException { new Main().start(); } public void start()throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; int test=Integer.parseInt(br.readLine()); int ans=0; int ind=1; while(test-->0){ ans=0; st=new StringTokenizer(br.readLine()); int A=Integer.parseInt(st.nextToken()); int B=Integer.parseInt(st.nextToken()); for(int num=A;num<=B;num++){ String n=num+""""; int len=n.length(); for(int i=1;i=A && m>num){ ans++; //System.out.print(m+"" ""); } } } System.out.println(""Case #""+ind+"": ""+ans); ind++; } } }" B13028,"import java.awt.Polygon; import java.awt.geom.Point2D; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class C implements Runnable { int rotate(int a, int pw) { return (a / 10) + (a % 10) * pw; } private void solve() throws IOException { int a = nextInt(); int b = nextInt(); int pw10 = 1; for (; pw10 * 10 <= a; pw10 *= 10) ; // System.out.println(rotate(1, 10)); boolean[] was = new boolean[b + 1]; int qlen = 0; long ans = 0; for (int i = a; i <= b; ++i) { qlen = 1; was[i] = true; for (int j = rotate(i, pw10); j > b || !was[j]; j = rotate(j, pw10)) { if (a <= j && j <= b) { was[j] = true; ++qlen; } } ans += qlen * (qlen - 1) / 2; } out.println(ans); } /** * @param args */ public static void main(String[] args) { (new Thread(new C())).start(); } private BufferedReader br; private StringTokenizer st; private PrintWriter out; private String filename = """"; @Override public void run() { try { br = new BufferedReader(new FileReader(""input.txt"")); st = new StringTokenizer(""""); out = new PrintWriter(""output.txt""); int T = nextInt(); for (int i = 1; i <= T; ++i) { out.print(""Case #"" + i + "": ""); solve(); } out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } String next() throws IOException { while (!st.hasMoreTokens()) { String temp = br.readLine(); if (temp == null) { return null; } st = new StringTokenizer(temp); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } } " B12251,"import java.util.ArrayList; import java.util.LinkedList; public class RecycledNumbers { public static void solve(String fname) { Read r = new Read(); r.Read(fname); int numOfTestCases=r.noOfTestCases; int[] numbers = r.nums; String finalAnser=""""; for(int i=0;i number = new LinkedList(); for (int k = 0; k < numb.length(); k++) { String first = numb.substring(0,k); String last = numb.substring(k,numb.length()); String newNumb = last+first; int numbC = Integer.parseInt(newNumb); if((numbC<=secondNum)&&(numbC>j)){ noOfans++; } } int x=0; // int k=0; // while(!number.isEmpty()){ // x=(int) (x+number.removeLast()*Math.pow(10, k)); // k++; // } } answer = ""Case #""+(i+1)+"": ""+noOfans; finalAnser = finalAnser+answer+""\n""; } r.write(""out"", finalAnser); System.out.println(finalAnser); } public static void main(String[] args) { solve(""test""); } } " B13237,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; public class RecycledNumbers { static int caso=0; static int valor=0; static String output=""""; static String thisline=""""; static String filesalida=""/home/rik/filenumbers.txt""; static String n1; static String n2; public static void analize(String[] numbers){ n1=numbers[0]; n2=numbers[1]; valor=0; for(int x=Integer.parseInt(n1);x<=Integer.parseInt(n2);x++){ runString(String.valueOf(x)); } caso++; output+=""Case #""+caso+"": ""+valor+""\n""; } public static void runString(String num){ for(int x=1;xInteger.parseInt(num)){ if(Integer.parseInt(inic+from)>=Integer.parseInt(n1)&&Integer.parseInt(inic+from)<=Integer.parseInt(n2)&&Integer.parseInt(from+inic)>=Integer.parseInt(n1)&&Integer.parseInt(from+inic)<=Integer.parseInt(n2)){ valor++; }else{ continue; } } } } public static void readFile(String filename){ BufferedReader entrada; BufferedWriter salida; try { entrada = new BufferedReader(new FileReader(filename)); entrada.readLine(); while(entrada.ready()){ String[] numbers; numbers=entrada.readLine().split("" ""); analize(numbers); } }catch (Exception e){ e.printStackTrace(); } System.out.println(output); try { salida= new BufferedWriter(new FileWriter(filesalida)); salida.write(output); try { if (salida != null) { salida.flush(); salida.close(); } } catch (IOException ex) { ex.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } public static void main (String args[]){ System.out.print(""file path: ""); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { String userinput; userinput = br.readLine(); readFile(userinput); } catch (IOException ioe) { System.out.println(""IO error""); System.exit(1); } } } " B13010,"import java.io.*; import java.util.*; public class RecycledNumbers { private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer st; public static void main ( String [] args ) throws IOException { int T = Integer.parseInt(br.readLine()); for(int i = 0;i < T; i++) { System.out.print(""Case #"" + (i+1) + "": ""); new RecycledNumbers().cal(); } } private void cal() throws IOException { int A, B; st = new StringTokenizer(br.readLine()); A = Integer.parseInt(st.nextToken()); B = Integer.parseInt(st.nextToken()); int len = Integer.toString(A).length(); // if ( len == 1 ) System.out.println(""0""); int num = 0; for(int n = A; n < B; n++) { HashSet s = new HashSet(); for(int i = 1; i < len; i++) { int m = getRecycledNumbers(n, i); if ( n < m && m <= B && !s.contains(m)) { // System.out.println(""["" + num + ""] (n,m) = ("" + n + "","" + m + "")""); s.add(m); num++; } } } System.out.println(num); } private int getRecycledNumbers(int n, int i) { String target = Integer.toString(n); String compared = target.substring(i) + target.substring(0, i); return Integer.parseInt(compared); } } " B13134,"import java.io.BufferedReader; import java.util.*; import java.io.File; import java.io.FileReader; import java.io.IOException; public class program { public static void main(String args[]) { File inFile = new File(""C-small-attempt0.in""); try { Scanner scanner = new Scanner(inFile); int tmp = 0; int i = 1; tmp = scanner.nextInt(); while(i <= tmp) { System.out.print(""\nCase #"" + i + "": "" + Danc3.solveC(scanner.nextInt(), scanner.nextInt())); i++; } } catch (IOException e) { System.out.println(""Exception Caught: "" + e); } } }" B10987," import java.io.*; import java.util.*; public class trie { public static void main(String[] args)throws IOException { int i,j,a,b,n,ans; String s1="""",p1=""""; solver h1=new solver(); Scanner fin=new Scanner(new File(""A.txt"")); s1=fin.nextLine(); n=Integer.parseInt(s1); FileWriter fstream=new FileWriter(""out.txt""); BufferedWriter out=new BufferedWriter(fstream); for(i=0;ilist = new ArrayList(); for(int i=A; i<=B; i++) { String num=""""+i; for(int j=0; j0){ t--; cnt++; int ans=0; String data = in.readLine(); String[] ss = data.split("" ""); int a = Integer.parseInt(ss[0]); int b = Integer.parseInt(ss[1]); //System.out.println(a + "" ""+ b); for(int i=a; i mySet = new HashSet(); for(int i=0; i k && generatedNumber<= max && !contains){ ans++; } } return ans; } } " B11710,"import java.io.*; import java.util.*; import java.math.*; import java.text.*; public class C { public static void pl(Object O) {System.out.println(O);} public static void pl() {System.out.println();} public static void pr(Object O) {System.out.print(O);} public static void p(Object O) {System.out.print(O);} public static void pf(String f, Object...args) {System.out.printf(f,args);} public static Scanner sc; public static String n() {return sc.next();} public static String nl() {return sc.nextLine();} public static int ni() {return sc.nextInt();} public static double nd() {return sc.nextDouble();} public static void main(String[] args) throws Exception { String file = args.length>0?args[0]:""c-sample.in""; sc = new Scanner(new File(file)); int kk = ni(); nl(); for (int qq = 0; qq < kk; qq++) { System.out.printf(""Case #%d: "",qq+1); int A = ni(); int B = ni(); int count = 0; for (int n = A; n < B; n++) { for (int m = n+1; m <= B; m++) { boolean recycled = isRecycled(n,m); if(recycled) { count++; // System.out.printf(""(%d,%d) is recycled\n"",n,m); } } } p(count); pl(); } } /** * A pair is a recycled pair if you can rotate the digits of n to get m. In * order words, if you let N:=string(n)+string(n) and string(m) is a * substring of N, then the pair (n,m) is a recycled pair. * * @param n * @param m * @return true if recycled pair */ public static boolean isRecycled(int n, int m) { String N = """"+n+n; String M = """"+m; // System.out.println(N); // System.out.println(M); return N.contains(M); } } " B12153,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.Writer; import java.util.ArrayList; import java.util.HashSet; public class q3 { public static void main(String args[]) throws Exception { String path = ""./src/""; String ifile = path + ""C-small-attempt0.in""; String ofile = path + ""C-small-attempt0.out""; int i = 0, j = 0; BufferedReader in = new BufferedReader(new FileReader(ifile)); StringBuilder os = new StringBuilder(); String line = null; int ln = 0; in.readLine(); while ((line = in.readLine()) != null) { String vs[] = line.split("" ""); ++ln; os.append(String.format(""Case #%d: %d"", ln, rnum(Long.parseLong(vs[0]), Long.parseLong(vs[1])))); os.append('\n'); } in.close(); Writer out = new BufferedWriter(new FileWriter(ofile)); out.write(os.toString()); out.close(); } static long rnum(long min, long max) { long c = 0, i = 0; int j = 0, k = 0; for (i = min; i <= max; ++i) { int length = (int)Math.log10(i) + 1; int num[] = new int[length]; long t = i; j = 0; while (t > 0) { num[j++] = (int)t%10; t = t / 10; } int first = num.length - 1; HashSet s = new HashSet(); for (j = first - 1; j >= 0; --j) { if (num[j] >= num[first]) { int temp = j; long nr = 0; for (k = length - 1; k >= 0; --k) { nr += num[temp--] * (Math.pow(10,k)); if (temp == -1) temp = first; } if (nr > i && nr > min && nr <= max && !s.contains(new Long(nr))) { c++; s.add(new Long(nr)); } } } } return c; } } " B12601,"import java.io.*; import java.util.*; public class C { void solve() throws IOException { in(""C-small-attempt0.in""); out(""C-small-attempt0.out""); long tm = System.currentTimeMillis(); boolean[] mask = new boolean[2000000]; int[] r = new int[10]; int t = readInt(); for (int cs = 1; cs <= t; ++cs) { int a = readInt(); int b = readInt(); int ans = 0; for (int m = a + 1; m <= b; ++m) { char[] d = String.valueOf(m).toCharArray(); int c = 0; for (int i = 1; i < d.length; ++i) { if (d[i] != '0') { int n = 0; for (int j = 0; j < d.length; ++j) { int jj = i + j; if (jj >= d.length) jj -= d.length; n = n * 10 + (d[jj] - '0'); } if (n >= a && n < m && !mask[n]) { ++ans; mask[n] = true; r[c++] = n; } } } for (int i = 0; i < c; ++i) { mask[r[i]] = false; } } println(""Case #"" + cs + "": "" + ans); System.out.println(""Case #"" + cs + "": "" + ans); } System.out.println(""time: "" + (System.currentTimeMillis() - tm)); exit(); } void in(String name) throws IOException { if (name.equals(""__std"")) { in = new BufferedReader(new InputStreamReader(System.in)); } else { in = new BufferedReader(new FileReader(name)); } } void out(String name) throws IOException { if (name.equals(""__std"")) { out = new PrintWriter(System.out); } else { out = new PrintWriter(name); } } void exit() { out.close(); System.exit(0); } int readInt() throws IOException { return Integer.parseInt(readToken()); } long readLong() throws IOException { return Long.parseLong(readToken()); } double readDouble() throws IOException { return Double.parseDouble(readToken()); } String readLine() throws IOException { st = null; return in.readLine(); } String readToken() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } boolean eof() throws IOException { return !in.ready(); } void print(String format, Object ... args) { out.println(new Formatter(Locale.US).format(format, args)); } void println(String format, Object ... args) { out.println(new Formatter(Locale.US).format(format, args)); } void print(Object value) { out.print(value); } void println(Object value) { out.println(value); } void println() { out.println(); } StringTokenizer st; BufferedReader in; PrintWriter out; public static void main(String[] args) throws IOException { new C().solve(); } } " B10512,"import java.io.*; public class recycled { /** * @param args */ public static int solve(BufferedReader reader) throws IOException { int cpt = 0; String[] entiers = new String[2]; entiers = reader.readLine().split("" ""); if(Integer.parseInt(entiers[0]) < 10) return 0; else { for(int i = Integer.parseInt(entiers[0]); i <= Integer.parseInt(entiers[1]); i++) cpt += NombreRecycle(entiers[0], entiers[1], Integer.toString(i)); } return cpt; } public static int NombreRecycle(String a, String b, String n) throws IOException { int cpt = 0; for(int i = 1; i < n.length() ; i++) if( Integer.parseInt(n) < Integer.parseInt(n.substring(i) + n.substring(0, i)) && Integer.parseInt(n.substring(i) + n.substring(0, i)) <= Integer.parseInt(b)) cpt++; return cpt; } public static void main(String[] args) { try { InputStream ips = new FileInputStream(""recycled.in""); InputStreamReader ipsr = new InputStreamReader(ips); BufferedReader br = new BufferedReader(ipsr); int cases = Integer.valueOf(br.readLine()); for (int i = 1; i <= cases; i++) { imprimer(i, solve(br)); } } catch (IOException x) { System.err.println(x); } catch (NumberFormatException x) { System.err.println(x); } } static void imprimer(int numero, int resultat) { try { FileWriter fw = new FileWriter (""recycled.out"",true); BufferedWriter bw = new BufferedWriter (fw); PrintWriter fichierSortie = new PrintWriter (bw); fichierSortie.println (""Case #"" + numero + "": "" + resultat); fichierSortie.close(); } catch (Exception e){ System.out.println(e.toString()); } } } " B12225,"package q2012; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) throws Exception { String input = ""C-small-attempt0.in""; String output = ""C-small-attempt0.out""; Scanner scan = new Scanner(new BufferedReader(new FileReader(input))); PrintWriter pw = new PrintWriter(new BufferedWriter( new FileWriter(output))); int T = Integer.parseInt(scan.nextLine()); for (int t = 1; t <= T; t++) { String[] info = scan.nextLine().split("" ""); int A = Integer.parseInt(info[0]); int B = Integer.parseInt(info[1]); long count = 0; for (int i = A; i <= B; i++) { char[] num = String.valueOf(i).toCharArray(); HashSet set = new HashSet(); for (int j = 1; j < num.length; j++) { String n = """"; for (int k = j, m = 0; m < num.length; m++, k = (k + 1) % num.length) n += num[k]; int s = Integer.parseInt(n); if (s > i && s <= B) set.add(s); } count += set.size(); } pw.println(""Case #"" + t + "": "" + count); } scan.close(); pw.close(); } }" B10412,"package com.google.codjam.utils; import com.google.codjam.problems.ProblemInterface; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; public class FileLoader { public static void processFile(FileDataAndSettings fileData,String fileName,int nlinesXCaseGlobal,ProblemInterface worker) { try { PrintWriter p = new PrintWriter (new File( fileName.replace("".in"","".out""))); BufferedReader buf = new BufferedReader(new FileReader(new File (fileName))); String tmp = """"; for(int i=0,nLinesXCase=0,nCase=1;true;i++) { tmp = buf.readLine(); if (tmp == null) break; if(i==0) { fileData.setNCases(Integer.parseInt(tmp)); }else { ArrayList dataCase = null; try { dataCase =fileData.getInputCase().get(nCase -1); } catch (IndexOutOfBoundsException ex) { fileData.getInputCase().add(new ArrayList(0)); dataCase =fileData.getInputCase().get(nCase - 1); } dataCase.add(tmp); nLinesXCase++; if(nlinesXCaseGlobal==nLinesXCase) { nCase++; nLinesXCase = 0; p.println(""Case #""+(nCase - 1)+"": ""+worker.run(dataCase)); } } } p.flush(); p.close(); } catch (Exception ex) { ex.printStackTrace(); } finally { } } } " B12417,"import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.Scanner; public class abc { public static void main(String args[]) { int x ,y,j,k,ans=0; int tcount =0; try{ // Create file FileWriter fstream = new FileWriter(""C-small-attempt4.out""); BufferedWriter out = new BufferedWriter(fstream); Scanner myfile; try { myfile = new Scanner(new FileReader(""C-small-attempt4.in"")); int testcases = myfile.nextInt(); while (testcases != 0 || myfile.hasNextInt()) { // Read file content using a while loop ans =0; x = myfile.nextInt(); y = myfile.nextInt(); // System.out.println(x + y); int divby = 1; for(k = x;k>=10;k/=10) { divby = divby *10; } int divdivby = 1; for(j=x;j<=y;j++) { int[] ar = new int[20]; int itr = 0; for(divdivby = divby ; divdivby != 1; divdivby/=10) { int m = j % divdivby; int n = j /divdivby; m = m *(divby /divdivby)*10; m = m+n; for(int l=0;l<=itr;l++) { if(ar[l] == m) { m=0;break;} } if(m!=0) { ar[itr] = m; itr++; } if(m > j && m <= y && m >= x) { ans++; //System.out.println(m +""-- ""+j); } } } out.write(""Case #""+ ++tcount+"": ""+ans+""\n""); System.out.println(ans); testcases--; } myfile.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Reading file using Scanner out.close(); }catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } } " B10487,"import java.util.Scanner; public class Recycle { public static void main(String args[]) { int t; int save[] = new int[50]; Scanner kb = new Scanner(System.in); t = kb.nextInt(); int a,b; for(int i=0;i=a && change!=j && change>j) { int point=0; for(int y=0;y n && pair <= num2){ if (num1 > 1000) System.out.println(n+"" ""+pair); pairs++; } } } String out = ""Case #""+i+"": ""+pairs; wr.write(out); if (i != num) wr.newLine(); } br.close(); wr.close(); }catch (IOException e){ System.out.println(""IO failure""); } } private boolean isTwin(int n,int digit){ if (digit%2 == 1) return false; return (n%(int)Math.pow(10, digit/2) == n/(int)Math.pow(10, digit/2)); } private int getDigits(int n){ int digit = 1; while(n/10 != 0){ digit++; n /= 10; } return digit; } public static void main(String[] args) { RecycledNumbers sp = new RecycledNumbers(""C-small-attempt0.in"",""C-small-attempt0.out""); } } " B10565,"import java.util.*; import java.io.*; public class RecycledNumbers { private static int numTest; private static Scanner input; private static PrintWriter output; public static void main(String[] args) throws FileNotFoundException, IOException { // Initialization of Input/Output streams input = new Scanner(new File(args[0])); output = new PrintWriter(new File(""output"")); // Reads char by char the input dimension numTest = input.nextInt(); input.nextLine(); // reads the \n character // Solves the problem for(int i = 1; i <= numTest; i++) { output.print(""Case #"" + i + "": ""); int a = input.nextInt(); int b = input.nextInt(); //System.err.println(i + "" A: "" + a); //System.err.println(i + "" B: "" + b); int numRecycled = 0; int n = a; int m = 0; while(n <= b) { String nString = n + """"; int nDigits = nString.length(); /* the HashMap prevents to count moore times couples like <1212, 2121> * generated using 2 ++ 121 or 121 ++ 2 */ HashMap map = new HashMap(); // extracts different substrings from the tail and count them for(int j = 1; j < nDigits; j++) { String head = nString.substring(0, j); String tail = nString.substring(j, nDigits); // System.err.print(i + "" n: "" + n); if(!tail.startsWith(""0"")) { m = Integer.parseInt(tail + head); // System.err.print("" m: "" + m); if(m > n && m <= b) { map.put(m, n); // System.err.print("" *""); } } // System.err.println(); } numRecycled += map.size(); n++; } output.println(numRecycled); if(input.hasNextLine()) input.nextLine(); } output.flush(); } }" B10258,"package com.numbers.recycle.io; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.List; public class FileOutputWriter { private FileWriter writer; private BufferedWriter bWriter; public void writeToFile(List outputFileContents) { File file = new File(""C:/Documents and Settings/Administrator/My Documents/Code Jam/output.out""); try{ writer = new FileWriter(file); bWriter = new BufferedWriter(writer); for(String line: outputFileContents){ bWriter.write(line); bWriter.newLine(); } }catch (Exception e) { e.printStackTrace(); } finally { close(writer, bWriter); } } private void close(FileWriter writer, BufferedWriter bWriter) { try{ bWriter.close(); writer.close(); } catch(Exception e){ } } } " B12494,"import java.io.File; import java.io.PrintWriter; import java.util.Scanner; public class EasyNumbers { public static void main(String[] args) throws Exception{ PrintWriter out =new PrintWriter(new File(""../easyNumbers/src/numberrr.out"")); Scanner s =new Scanner(new File(""../easyNumbers/src/number.in"")); int ans,div,d,k,n1,n2,j,a,a1,b; int i,t; t = s.nextInt(); for(int w = 1; w<=t; w++){ a = s.nextInt(); b = s.nextInt(); ans=0; i=0; a1 = a; while(a1!=0){ a1/=10; i++; } for(j=a;j<=b;j++){ n2=j; for(k=0;k 9){ n1 = n1 / 10; div = div * 10; } d = n2 % 10; n2 = n2 / 10; n2 = n2 + d * div ; if(n2<=b && n2>=a && n2!=j && j= 2 get numRot C 2 if(numRot > 1) numPairs += (numRot - 1) * numRot / 2; } } System.out.println(""Case #"" + (i+1) + "": "" + numPairs); } } } " B13236,"import java.io.File; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.Scanner; public class Permutation { public static void main(String[] args) throws Exception { Scanner in = new Scanner(new File(""Input"")); PrintWriter out = new PrintWriter(""Output""); ArrayList array2 = new ArrayList(); String length = in.nextLine(); int c = 0; while (in.hasNext()) { c++; array2.add(in.nextInt()); array2.add(in.nextInt()); if (c < Integer.valueOf(length) - 1) in.nextLine(); } int count = 0; array2.trimToSize(); for (int q = 0; q < array2.size(); q += 2) { count++; int dd1 = array2.get(q); int dd2 = array2.get(q + 1); int res = 0; for (int i = dd1; i < dd2; i++) { String td1 = String.valueOf(i); for (int j = i + 1; j <= dd2; j++) { String td2 = String.valueOf(j); ArrayList kk = new ArrayList(); int k = 0; do { k = td2.indexOf(td1.charAt(0), k + 1); if (k >= 0) kk.add(k); } while (k >= 0); kk.trimToSize(); HashSet hs = new HashSet(); for (int w : kk) { k = w; if (k >= 0) { String rev2 = new StringBuffer(td2.substring(0, k)) .reverse().toString(); String rev1 = new StringBuffer(td2.substring(k)) .reverse().toString(); String rev = rev2 + rev1; String rev3 = new StringBuffer(rev).reverse() .toString(); if (Integer.valueOf(rev3) == i){ hs.add(j); // res++; //System.out.println(res + "": "" + i + "" | "" + rev3 + "" - rev: "" + j); } } } res += hs.size(); } } out.println(""Case #"" + count + "": "" + res); } in.close(); out.close(); } } " B12458,"import java.io.*; import java.util.Scanner; public class Problem3 { public static void main(String[] args) { try { Scanner inputReader = new Scanner(new File(""S:\\input.in"")); int inputCases = inputReader.nextInt(); PrintWriter outputWriter = new PrintWriter(""S:\\output.in""); for (int currentInputCase = 0; currentInputCase < inputCases; currentInputCase++) { String markUpString = """"; int milestone = 0; int firstA = inputReader.nextInt(); int secondB = inputReader.nextInt(); for (int currentN = firstA; currentN < secondB; currentN++) { String n = currentN + """"; for (int i = 1; i <= n.length() - 1; i++) { String trimString = n.substring(n.length() - i, n.length()) + n.substring(0, n.length() - i); if (!trimString.startsWith(""0"")) { if (!n.equals(trimString)) { int trimmedInt = Integer.parseInt(trimString); if (trimmedInt <= secondB && trimmedInt > (Integer.parseInt(n))) { if (!markUpString.contains(n + ""#"" + trimString)) { markUpString += (n + ""#"" + trimString + "",""); milestone++; } } } } } } outputWriter.write(""Case #"" + (currentInputCase + 1) + "": "" + milestone + ""\n""); } outputWriter.flush(); outputWriter.close(); } catch (Exception e) { } } } " B11481,"import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; public class ProblemaC { private final static String RUTA=""C:/Users/Rafael/Documents/Estudio/OtherStuff/Google/CodeJam/ProblemaC/""; public ProblemaC(){ try { FileOutputStream fos=new FileOutputStream(new File(RUTA+""resultado.txt"")); BufferedReader br=new BufferedReader(new FileReader(RUTA+""C-small-attempt3.in"")); PrintWriter pw=new PrintWriter(fos); String a=br.readLine(); System.out.println(""Ignore""+a); int contador=0; while((a=br.readLine())!=null) { contador++; System.out.println(""Case #""+contador+"": ""+a); String first=a.split("" "")[0]; String second=a.split("" "")[1]; int temp=analizar(first, second); System.out.println(temp); pw.println(""Case #""+contador+"": ""+temp ); } pw.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public int analizar(String first, String second ){ ArrayList dupList=new ArrayList(); int contador=0; int primero=Integer.parseInt(first); int segundo=Integer.parseInt(second); for(int i=primero;i<=segundo;i++){ for(int j=i+1;j<=segundo;j++){ for(int k=1;k= high) { return; } else if (low == high - 1) { if (((Comparable)list.get(low)).compareTo(list.get(high)) > 0) { Object temp = list.get(low); list.set(low, list.get(high)); list.set(high, temp); } return; } Object pivot = list.get((low + high) / 2); list.set((low + high) / 2, list.get(high)); list.set(high, pivot); while (low < high) { while (((Comparable)list.get(low)).compareTo(pivot) <= 0 && low < high) { low++; } while (((Comparable)list.get(high)).compareTo(pivot) >= 0 && low < high) { high--; } if (low < high) { Object temp = list.get(low); list.set(low, list.get(high)); list.set(high, temp); } } list.set(high0, list.get(high)); list.set(high, pivot); quickAscSort(list, low0, low - 1); quickAscSort(list, high + 1, high0); } private static void quickDescSort(ArrayList list, int low0, int high0) { int low = low0, high = high0; if (low >= high) { return; } else if (low == high - 1) { if (((Comparable)list.get(low)).compareTo(list.get(high)) > 0) { Object temp = list.get(low); list.set(low, list.get(high)); list.set(high, temp); } return; } Object pivot = list.get((low + high) / 2); list.set((low + high) / 2, list.get(high)); list.set(high, pivot); while (low < high) { while (((Comparable)list.get(low)).compareTo(pivot) >= 0 && low < high) { low++; } while (((Comparable)list.get(high)).compareTo(pivot) <= 0 && low < high) { high--; } if (low < high) { Object temp = list.get(low); list.set(low, list.get(high)); list.set(high, temp); } } list.set(high0, list.get(high)); list.set(high, pivot); quickDescSort(list, low0, low - 1); quickDescSort(list, high + 1, high0); } public static void sortAscList(ArrayList list) { Collections.sort(list) ; } public static void sortDescList(ArrayList list) { Collections.sort(list,Collections.reverseOrder()) ; } public static ArrayList toStrArrayList(String str) { StringTokenizer stTokenizer = new StringTokenizer(str) ; ArrayList readStrList = new ArrayList(stTokenizer.countTokens()) ; while(stTokenizer.hasMoreTokens()) { readStrList.add(stTokenizer.nextToken()) ; } return readStrList ; } public static ArrayList toIntArrayList(String str) { StringTokenizer stTokenizer = new StringTokenizer(str) ; ArrayList readIntList = new ArrayList(stTokenizer.countTokens()) ; while(stTokenizer.hasMoreTokens()) { readIntList.add(Integer.parseInt(stTokenizer.nextToken())) ; } return readIntList ; } public static void printArrayList(ArrayList list,String seperator) { ListIterator iterator = list.listIterator() ; while(iterator.hasNext()) { System.out.print(iterator.next()) ; if(iterator.hasNext()) System.out.print(seperator) ; } System.out.print(""\n""); } public static void reverseArrayList(ArrayList list) { Collections.reverse(list) ; } } " B10920,"package utils; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Fabien Renaud */ public class File { public static boolean delete(String filename) { java.io.File f = new java.io.File(filename); if (f != null) { return f.delete(); } return false; } public static String[] readAllLines(String filename) { return readAllLines(new java.io.File(filename)); } public static String[] readAllLines(java.io.File file) { List list = new ArrayList(); try { BufferedReader input = new BufferedReader(new FileReader(file)); try { String line = null; while ((line = input.readLine()) != null) { list.add(line); } } finally { input.close(); } } catch (IOException ex) { Logger.getLogger(File.class.getName()).log(Level.SEVERE, null, ex); } String[] s = new String[list.size()]; return list.toArray(s); } public static String readAllText(String filename) { return readAllText(new java.io.File(filename)); } public static String readAllText(java.io.File file) { StringBuilder content = new StringBuilder(); String lf = System.getProperty(""line.separator""); try { BufferedReader input = new BufferedReader(new FileReader(file)); try { String line = null; while ((line = input.readLine()) != null) { content.append(line); content.append(lf); } } finally { input.close(); } } catch (IOException ex) { Logger.getLogger(File.class.getName()).log(Level.SEVERE, null, ex); } return content.toString(); } public static byte[] readAllBytes(String filename) { return readAllBytes(new java.io.File(filename)); } public static byte[] readAllBytes(java.io.File file) { byte[] bytes = new byte[0]; InputStream is = null; try { is = new FileInputStream(file); long length = file.length(); if (length > Integer.MAX_VALUE) { // File is too large } bytes = new byte[(int) length]; int offset = 0; int numRead = 0; while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) { offset += numRead; } if (offset < bytes.length) { throw new IOException(""Could not completely read file "" + file.getName()); } is.close(); } catch (Exception ex) { Logger.getLogger(File.class.getName()).log(Level.SEVERE, null, ex); } finally { try { is.close(); } catch (IOException ex) { Logger.getLogger(File.class.getName()).log(Level.SEVERE, null, ex); } } return bytes; } public static void writeAllLines(String filename, String[] lines) { writeAllLines(new java.io.File(filename), lines); } public static void writeAllLines(java.io.File file, String[] lines) { String lf = System.getProperty(""line.separator""); try { FileWriter fw = new FileWriter(file); for (String l : lines) { fw.write(l); fw.write(lf); fw.flush(); } fw.close(); } catch (IOException ex) { Logger.getLogger(File.class.getName()).log(Level.SEVERE, null, ex); } } public static void writeAllText(String filename, String text) { writeAllText(new java.io.File(filename), text); } public static void writeAllText(java.io.File file, String text) { String lf = System.getProperty(""line.separator""); try { FileWriter fw = new FileWriter(file); fw.write(text); fw.flush(); fw.close(); } catch (IOException ex) { Logger.getLogger(File.class.getName()).log(Level.SEVERE, null, ex); } } public static void writeAllBytes(String filename, byte[] bytes) { writeAllBytes(new java.io.File(filename), bytes); } public static void writeAllBytes(java.io.File file, byte[] bytes) { try { FileOutputStream fos = new FileOutputStream(file); fos.write(bytes); fos.close(); } catch (Exception ex) { Logger.getLogger(File.class.getName()).log(Level.SEVERE, null, ex); } } } " B11231,"package codezam.exercise.WR1C2012; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import codezam.util.InputFile; /** * Google Code Jam - 2012 RecycledNumbers * * Using Frequency analysis method * * @author Ryan * @since 2012.4.14 */ public class RecycledNumbers { private List lines = new ArrayList(); public RecycledNumbers() { String filename = ""C:/eclipse/eclipse.test/workspace/CodeZam-Exercise/app/src/codezam/exercise/WR1C2012/C-small-attempt1.in""; InputFile inputFile = new InputFile(); inputFile.setFile(filename); int numberOfInput = Integer.parseInt(inputFile.readLine()); for (int i = 0; i < numberOfInput; i++) { String input = inputFile.readLine(); lines.add(input); } } public void solve() { //String output = getOutputForOneLine((String)lines.get(0)); for (int i = 0; i < lines.size(); i++) { String output = getOutputForOneLine((String)lines.get(i)); System.out.println(""Case #"" + (i + 1) + "": "" + output.toLowerCase()); } } private String getOutputForOneLine(String line) { String[] lineSplit = line.split("" ""); Long a = new Long(lineSplit[0]); Long b = new Long(lineSplit[1]); int digit = a.toString().length(); PairNumbers pairNumbers = new PairNumbers(); long from = a.longValue(); long to = b.longValue(); int total = 0; //System.out.println(""from ""+a+"" to ""+b); for (long i=from; i<=to; i++) { if (i>=449) { boolean aa = true; } String number = new Long(i).toString(); for (int j=1; j=a && new Long(checker).longValue() <= b && !pairNumbers.containsKey(number, checker)) { pairNumbers.put(number, checker); //System.out.print(number+""->""+checker+"", ""); //if (++total%10==0) { // System.out.println(); //} } } } //System.out.println(); //System.out.println(); return Integer.toString(pairNumbers.size()); } /** * @param args */ public static void main(String[] args) { RecycledNumbers question = new RecycledNumbers(); question.solve(); } } " B10220,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; import java.util.*; import java.io.*; public class RecycledNumbers{ public static void main(String[] args) throws Exception { Scanner input = new Scanner(new File(""C:\\temp\\C-small.in"")); int T = input.nextInt(); for (int t = 1; t <= T; t++) { int A = input.nextInt(); int B = input.nextInt(); double answer = 0; for (int a = A; a <= B; a++) { String aS = a + """"; for (int i = aS.length(); i > 1; i--) { int max = Integer.parseInt(aS.substring(i-1) + aS.substring(0, i-1)); if (max <= B && max >= A && max != a) { answer++; } } } System.out.println(""Case #"" + t + "": "" + (int)(answer/2)); } } public static String reverse(String s, int i) { return (i < s.length()) ? s.charAt(s.length()-1-i) + reverse(s, i+1) : """"; } } " B12034,"import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; public class Solution { Solution() throws Exception { } String solve() throws Exception { int min = in.nextInt(); int max = in.nextInt(); return """" + permutations(min, max); } private int permutations(int min, int max) { int digits = Integer.toString(min).length(); int permutations = 0; for (int i = min; i <= max; i++) { HashSet found = new HashSet<>(); for (int j = 1; j < digits; j ++) { int permutation = permute(i, j, digits); if (permutation > i && permutation <= max && permutation >= min) { found.add(permutation); } } permutations += found.size(); } return permutations; } private int permute(int number, int permutation, int digits) { int m = (int) Math.pow(10, permutation); int back = number % m; int front = number / m; int m2 = (int) Math.pow(10, digits - permutation); return back * m2 + front; } void solveAll() throws Exception { int cases = in.nextInt(); in.nextLine(); for (int i = 1; i <= cases; i++) { String solution = ""Case #"" + i + "": "" + solve(); System.out.println(solution); out.println(solution); } out.flush(); } // ----------------------------------------------------------------------- static Scanner in = new Scanner(System.in); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws Exception { new Solution().solveAll(); } } " B11233,"import java.io.*; import java.util.*; public class CSmall { public static Set set = new HashSet(); public static int counter = 0; public static void main(String[] args) throws IOException { Scanner in = new Scanner(new File(""C-small-attempt0.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""C-small.out""))); int T = Integer.parseInt(in.nextLine()); for (int i = 0; i < T; i++) { String[] lim = in.nextLine().split("" ""); System.out.println(Arrays.toString(lim)); for (int j = Integer.parseInt(lim[0]); j < Integer.parseInt(lim[1]); j++) { if (j >= 10) { pair(Integer.toString(j), lim); } } System.out.println(set.toString()); out.write(""Case #""+ (i+1) +"": "" + set.size()); if (i != T-1) out.write(""\n""); set.clear(); } out.close(); System.exit(0); } private static void pair(String num, String[] lim) { int len = num.length(); int upLim = Integer.parseInt(lim[1]), lowLim = Integer.parseInt(lim[0]); for (int i = 0; i < len; i++) { String k = num; num = num.charAt(len-1) + num.substring(0,len-1); //System.out.println(num); int a = Integer.parseInt(num), b = Integer.parseInt(k); if (a!=b && a <= upLim && a >= lowLim && b <= upLim && b >= lowLim) { if (a 0) } public static int solve(int n, int i, int len, int upper, HashMap hash){ // say n=123 i=2 len=3 int count=0; //System.out.println(""n= ""+n+"" i=""+i+"" len=""+len); int i2=n/power(10, i); ///i2=1 //System.out.println(""i2= ""+i2); int b=i2*power(10, i); ////b=100 int j1=n-b; ///// j1=23 int i1=j1*(power(10, (len-i))); int n2=i1+i2; /// now we have 231 //System.out.println(""n2= ""+n2); if (n2>n && n2<=upper) { if (hash.containsKey(n2)) { count+=0; } else { count+=1; hash.put(n2,1); } } return count; } } class solve{ public static void main(String[] args) { BufferedReader bf= null; String line; int n; int n1,n2; int ans=0; try { bf = new BufferedReader(new InputStreamReader(System.in)); int indicator=0; int playerno=0; String output=""""; BufferedWriter f=new BufferedWriter(new FileWriter(""output.txt"")); while ((line=bf.readLine())!=null) { HashMap hash=new HashMap(); if (indicator==0) { n=Integer.parseInt(line); } else { String[] a=line.split("" ""); int len=a[0].length(); n1=Integer.parseInt(a[0]); n2 =Integer.parseInt(a[1]); /////////////////////////////////// now solve this int number=n1; for (; number b) break; int scratch = currentNo; String strScratch = String.valueOf(currentNo); for (int d = 1; d < strScratch.length(); d++) { String sub1 = strScratch.substring(strScratch.length()-d,strScratch.length()); //LSD String sub2 = strScratch.substring(0,strScratch.length()-d); //MSD if(!sub1.substring(0, 1).equals(""0"")) { String strRotated = sub1+sub2; if(!strRotated.equals(strScratch)) { int rotated = Integer.parseInt(strRotated); if(rotated <= b && rotated > scratch) { // w.println(scratch + "" : ""+rotated); // System.out.println(scratch + "" : ""+rotated); result++; } } } } currentNo++; } int asd = i+1; w.println(""Case #"" + asd + "": "" + result); System.out.println(""Case #"" + asd + "": "" + result); } w.close(); } } " B10066," package codejam; import java.io.*; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; public class C { static String str = ""C:\\carl\\fileC.txt""; static String text = """"; static int A, B, T, cnt; static HashMap hm; public static void main(String[] args) { try { int count = 0; hm = new HashMap(); File file = new File(str); BufferedReader br = new BufferedReader(new FileReader(file)); PrintWriter outer = new PrintWriter(new FileWriter(""C:\\carl\\outC.txt"")); while((text = br.readLine()) != null) { StringTokenizer st = new StringTokenizer(text); if(count == 0) { T = Integer.parseInt(st.nextToken()); count++; } else { A = Integer.parseInt(st.nextToken()); int n = A; B = Integer.parseInt(st.nextToken()); while (n != B) { char[] temp = Integer.toString(n).toCharArray(); scramble(temp, n); n++; } outer.println(""Case #"" + count + "": "" + hm.entrySet().size()); //System.out.println(hm.entrySet().size()); hm.clear(); count++; } } outer.close(); } catch(IOException ex) { System.out.println(""Error with IO you foooool""); } catch(Exception ex) { System.out.println(""Generic Error. Noob.""); ex.printStackTrace(); } } public static void scramble(char[] temp, int n) { Integer[] no = new Integer[temp.length]; for(int i=0; i openSet = new PriorityQueue<>(); Set closedSet = new HashSet<>(); openSet.add(start); while (!openSet.isEmpty()) { Node current = openSet.poll(); for (Edge edge : current.edges) { Node end = edge.target; if (closedSet.contains(end)) { continue; } State newState = edge.travel(current.last); //if (end.equals(target)) { //return newState; //} if (openSet.contains(end)) { if (end.last.compareTo(newState)>0) { end.last = newState; } } else { openSet.add(end); end.last = newState; } } closedSet.add(current); if (closedSet.contains(target)) { return target.last; } } return target.last; } } " B11974,"package com.sam.googlecodejam.speakingtoungue; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import com.sam.googlecodejam.helper.InputReader; /** * This class generates the mapping based on the samples that have been provided. * @author Saifuddin Merchant * */ public class TranslatorMapping { public Map iAvalableLines = new HashMap<>(); public Map iLetterMapping = new TreeMap<>(); public TranslatorMapping() { iAvalableLines.put(""ejp mysljylc kd kxveddknmc re jsicpdrysi"", ""our language is impossible to understand""); iAvalableLines.put(""rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd"", ""there are twenty six factorial possibilities""); iAvalableLines.put(""de kr kd eoya kw aej tysr re ujdr lkgc jv"", ""so it is okay if you want to just give up""); } public void mapLetters() { for(Entry lineEntry: iAvalableLines.entrySet()) { String keyLine = lineEntry.getKey(); String keyValue = lineEntry.getValue(); int index=0; for(Character keyChar:keyLine.toCharArray()) { iLetterMapping.put(keyChar, keyValue.charAt(index++)); } } iLetterMapping.put('z', 'q');//add the missing mappings iLetterMapping.put('q', 'z');//add the missing mappings //System.out.println(iLetterMapping.size()); //System.out.println(iLetterMapping); } public void translate(String pInput) { for(Character translateChar:pInput.toCharArray()) { System.out.print(iLetterMapping.get(translateChar)); } } public static void main(String[] args) { TranslatorMapping mapping = new TranslatorMapping(); mapping.mapLetters(); InputReader reader = new InputReader(""c://input.in""); reader.readNextLine(); //read the line number off - we don't need it String lineRead = null; int i=1; while((lineRead=reader.readNextLine())!=null ) { System.out.print(""Case #""+i+"": ""); i++; mapping.translate(lineRead); System.out.println(); } } } " B12673,"import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { public static void main(String[] args) { try { // so eclipse can read file from system in System.setIn(new FileInputStream(new File(""small.in""))); } catch (IOException e) { e.printStackTrace(); System.exit(1); } Scanner scanner = new Scanner(System.in); long T = scanner.nextLong(); scanner.nextLine(); for (int i = 0; i < T; i++) { long A = scanner.nextLong(); long B = scanner.nextLong(); long count = 0; for (long number = A; number <= B; number++) { String numberS = String.valueOf(number); Set newNumbers = new HashSet(); for (int k = 1; k < numberS.length(); k++) { String newNumberS = numberS.substring(numberS.length() - k) + numberS.substring(0, numberS.length() - k); if (newNumbers.contains(newNumberS)) { continue; } newNumbers.add(newNumberS); long newNumber = Long.parseLong(newNumberS); if (newNumber != number && newNumber > number && newNumber >= A && newNumber <= B) { count++; } } } System.out.printf(""Case #%d: %d%n"", i + 1, count); } } } " B12186,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.StringTokenizer; public class RecycledNumbers { public static void main(String[] args) throws Exception { FileReader fileReader=new FileReader(""D://Recylced Numbers/input.in"") ; PrintWriter printWriter=new PrintWriter(""D://Recylced Numbers/output.out""); BufferedReader bufferedReader=new BufferedReader(fileReader); BufferedWriter bufferedWriter=new BufferedWriter(printWriter); String s,code; int counter=0; TestCase[] testCase=null; while((s=bufferedReader.readLine())!=null) { if(counter>0) { testCase[counter-1]=makeObject(s); // System.out.println(testCase[counter-1]); // printWriter.println(""Case #""+counter+"": ""); // printWriter.flush(); } else testCase=new TestCase[Integer.parseInt(s)]; counter++; } ArrayList arrayList=null; for(int i=0;ia && Integer.parseInt(num)<=b) { // System.out.println(a+"" ""+num); if(repeat(""""+a) && flag==true) { // System.out.println(""repeat ""+a); // counter++; flag=false; } else { counter++; flag=true; } } } return counter; } private static boolean repeat(String num) { boolean flag=false; HashSet hashSet=new HashSet(); if(num.length()%2==0 && num.length()>2) { int i=0; while(num.length()>0) { hashSet.add(num.substring(num.length()-2)); num=num.substring(0, num.length()-2); i=i+2; } flag=check(hashSet); } return flag; } private static boolean check(HashSet hashSet) { if(hashSet.size()>1) return false; return true; } private static TestCase makeObject(String s) { StringTokenizer stringTokenizer=new StringTokenizer(s); TestCase testCase=new TestCase(); testCase.setA(Integer.parseInt(stringTokenizer.nextToken())); testCase.setB(Integer.parseInt(stringTokenizer.nextToken())); return testCase; } } class TestCase { Integer a; Integer b; public Integer getA() { return a; } public void setA(Integer a) { this.a = a; } public Integer getB() { return b; } public void setB(Integer b) { this.b = b; } public TestCase(Integer a, Integer b) { super(); this.a = a; this.b = b; } public TestCase() { } @Override public String toString() { return this.a+"" ""+this.b; } }" B10087,"import java.io.*; import java.util.*; import java.math.*; public class C { public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new File(""input.txt"")); PrintWriter output = new PrintWriter(""output.txt""); int T = input.nextInt(); for (int z = 1; z <= T; z++) { //SOLVE CASE int N = input.nextInt(); int M = input.nextInt(); int count = 0; for (int i = N; i < M; i++) for (int j = i+1; j <= M; j++) { String sN = Integer.toString(i); sN += sN; if (isRecycled(sN, j)) count++; } //PRINT CASE OUTPUT System.out.println(""Case #"" + z + "": "" + count); output.println(""Case #"" + z + "": "" + count); } output.close(); } public static boolean isRecycled(String sN, int M) { String sM = Integer.toString(M); if (sN.contains(sM)) return true; return false; } } " B11850,"package ex3; import java.util.ArrayList; import java.util.Scanner; public class main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); for(int i = 0; i < n; i++) { int a = in.nextInt(); int b = in.nextInt(); ArrayList al = new ArrayList(); for(int j = 1; j < a; j++) { for(int k = j+1; k <= b; k++) { int la, lb; int tmpa = j; int tmpb = k; for(la = 0; tmpa > 0; tmpa/=10)la++; for(lb = 0; tmpb > 0; tmpb/=10)lb++; tmpa = j; tmpb = k; while(lb>0){ tmpa*=10; lb--; } while(la>0) { tmpb*=10; la--; } if(tmpa+k != tmpb+j && tmpa+k >= a && tmpa+k <= b && tmpb+j >= a && tmpb+j <= b){ int lp = al.indexOf(tmpa+k); if(lp > 0 && al.get(lp-1) == tmpb+j) { } else { al.add((tmpa+k)); al.add((tmpb+j)); } } } } System.out.println(""Case #""+(i+1)+"": ""+(al.size()/2)); } } } " B12199,"import java.io.*; public class GoogleCodeInP3 { public static void main(String[] args) throws IOException { BufferedReader mbr = new BufferedReader(new FileReader(args[0])); int a = -1; try { a = Integer.parseInt(mbr.readLine()); } catch (Exception e) { } FileWriter fw = new FileWriter(""outputFile2a""); BufferedWriter bfw = new BufferedWriter(fw); for (int i = 0; i < a; i++) { String thisLine = mbr.readLine(); String[] w = thisLine.split("" ""); String N = w[0]; String M = w[1]; bfw.write(""Case #"" + (i + 1) + "": "" + recycleNumbers(N, M)); if (i < a - 1) { bfw.write(""\n""); } } bfw.close(); } public static int recycleNumbers(String a, String b) { int a1 = Integer.parseInt(a); int b1 = Integer.parseInt(b); int howMany = 0; int w = 0; return howManyFor(a1, b1); } public static int howManyFor(int a, int b) { int thisMany = 0; int y = b + 1; while (y >= a) { y = y - 1; int w = 0; while (a + w < y) { if (!checkSameDigits(a + w, y)) { w = w + 1; continue; } String currentA = """" + (a + w); String currentB = """" + y; thisMany = thisMany + checkIfMatch(currentA, currentB); w = w + 1; } } return thisMany; } public static boolean checkSameDigits(int a, int b) { String s = """" + a; String t = """" + b; if (s.length() != t.length()) { return false; } int[] whereFound = new int[s.length()]; for (int i = 0; i < s.length(); i++) { if (s.indexOf(t.charAt(i)) == -1) { return false; } if (whereFound[s.indexOf(t.charAt(i))] == 0) { whereFound[s.indexOf(t.charAt(i))] = 1; continue; } int x = s.indexOf(t.charAt(i)); for (int j = x; j < whereFound.length; j++) { if (whereFound[j] == 1) { x = j; } } if (s.indexOf(t.charAt(x)) == -1) { return false; } whereFound[s.indexOf(t.charAt(x))] = 1; } return true; } public static int checkIfMatch(String currentA, String currentB) { String a = currentA; String b = currentB; int andThisMany = 0; for (int w = 0; w < a.length(); w++) { if (w == 0) { if (a.equals(b)) { andThisMany = andThisMany + 1; continue; } } if ((a.substring(w) + a.substring(0, w)).equals(currentB)) { andThisMany = andThisMany + 1; } } return andThisMany; } }" B10689,"import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * C */ /** * @author devang * */ public class RecycledNumbers { public static void main(String[] args) throws FileNotFoundException, IOException { int n = 0; String input[] = null; int A, B = 0; List recycledNumbers = null; File f = new File(""//home//devang//Desktop//C-small-attempt0.in""); //File f = new File(""//home//devang//Desktop//input""); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f))); String testcases = reader.readLine(); n = Integer.parseInt(testcases); FileWriter fw = new FileWriter(""//home//devang//Desktop//output""); for(int i = 0; i < n; i++) { int count = 0; input = reader.readLine().split("" ""); if(input[0].length() == 1) { //Do not increment count. } else { A = Integer.parseInt(input[0]); B = Integer.parseInt(input[1]); HashMap record = new HashMap(); recycledNumbers = getRecycledNumbers(input[0], input[1]); int j = 0; int a = A; int subtract = 0; for(;j < B - A + 1; j++) { //iterate over list. for(int k = (j * (input[0].length() - 1)), l = 0; l < input[0].length() - 1; k++, l++) { String m = (String)recycledNumbers.get(k); if(m.length() == input[0].length() && Integer.parseInt(m) > a && Integer.parseInt(m) <= B) { List list = (List)record.get(String.valueOf(a)); if(list != null && !list.contains(m)) { list.add(m); count++; } else if(list == null) { list = new ArrayList(); list.add(m); record.put(String.valueOf(a), list); count++; } else if(list.contains(String.valueOf(a))) ;//Do nothing. } } a++; } } /*System.out.print(""Case #""+(i+1)+"": ""+count+""\n"");*/ fw.write(""Case #""+(i+1)+"": ""+count+""\n""); } reader.close(); fw.close(); } @SuppressWarnings(""unchecked"") private static List getRecycledNumbers(String A, String B) { List l = new ArrayList(); int a, b, diff = 0; StringBuilder builder = new StringBuilder(A.length()); short numberOfRecycledNumbers = (short)(A.length() - 1); a = Integer.parseInt(A); b = Integer.parseInt(B); diff = b - a + 1; //Do it for each number in the range A to B. for(int j = 0; j < diff; j++) { A = String.valueOf(a + j); for(short i = 0; i < numberOfRecycledNumbers; i++) { char first = A.charAt(0); builder.insert(0, A.substring(1)); builder.insert(A.length() - 1, first); if(builder.length() > A.length()) { //suppress all the un-required characters. builder.replace(A.length(), builder.length(), """"); } A = builder.toString(); l.add(builder.toString()); } } return l; } } " B10960,"import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.HashMap; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class Recycle { public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(new File(""C-small-attempt1.in"")); int t; // number of test cases int n = 1; int counter=0; int A, B; HashMap map = new HashMap(); t = sc.nextInt(); //System.out.println(""Output""); for (int i = 0; i < t; i++) { A = sc.nextInt(); B = sc.nextInt(); String aStr = String.valueOf(A); int len = aStr.length(); for (int c = A; c < B+1; c++) { for (int k=1; k(); } } public static char[] shiftLeft(char[] array, int amount) { for (int j = 0; j < amount; j++) { char a = array[0]; int i; for (i = 0; i < array.length - 1; i++) array[i] = array[i + 1]; array[i] = a; } return array; } public static char[] shiftRight(char[] array, int amount) { for (int j = 0; j < amount; j++) { char a = array[array.length - 1]; int i; for (i = array.length - 1; i > 0; i--) array[i] = array[i - 1]; array[i] = a; } return array; } } " B11944,"import java.util.Scanner; public class A { /** * @param args */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T,no1,no2,k=0; A obj=new A(); T=sc.nextInt(); int cnt=0; while(T>0) { cnt++; no1=sc.nextInt(); no2=sc.nextInt(); k=0; for(int i=no1;i<=no2;i++) { for(int j=no1;j<=no2;j++) { if(i!=j) { k+=obj.chk(i,j); } } } System.out.println(""Case #""+cnt+"": ""+k/2); T--; } } char ip1[]=new char[10]; char ip2[]=new char[10]; int length1(int n) {int i=0; while(n>0) { n=n/10; i++; } return i; } public int chk(int a,int b) { int l1,tn=1; l1=length1(a); //System.out.println(""n1:""+a+"" n2:""+b); for(int i=1;i recycled = new ArrayList(); for (int n = from; n <= to; n++) { recycled.clear(); int m = n; for (int d = 1; d < digits; d++) { int r = (m % 10); m = (r * f) + (m / 10); if (r > 0 && m < n && m >= from && m <= to) { if (recycled.contains(m)) { // System.out.println(""("" + m + "","" + n + "")""); } else { recycled.add(m); count++; } } } } return count; } } " B12386,"import java.io.IOException; import java.io.PrintWriter; import java.io.RandomAccessFile; import java.util.Hashtable; public class codejamb { /** * @param args * @throws IOException * @throws NumberFormatException */ public static void main(String[] args) throws Exception { RandomAccessFile r = new RandomAccessFile(""testcase.txt"", ""r""); PrintWriter p = new PrintWriter(""out.txt""); int t = Integer.parseInt(r.readLine()); for (int i = 1; i <= t; i++) { String[] line = (r.readLine()).split("" ""); int a = Integer.parseInt(line[0]); int b = Integer.parseInt(line[1]); int count = countIt(a, b); p.println(""Case #"" + i + "": "" + count); } p.close(); } static int countIt(int a, int b) { int count = 0; for (int i = a; i <= b; i++) { for (int j = i + 1; j <= b; j++) { if (checkPair(i + """", j + """")) { count++; } } } return count; } static boolean checkPair(String x, String y) { if (x.length() == y.length() && isTheSame(x, y)) { for (int i = x.length() - 1; i >= 0; i--) { String sub = x.substring(i); // String sub2 = y.substring(0, sub.length()); String newStr = sub + x.substring(0, i); if (newStr.equalsIgnoreCase(y)) return true; } return false; } else { return false; } } static boolean isTheSame(String x, String y) { char[] xArr = x.toCharArray(); char[] yArr = y.toCharArray(); for (int i = 0; i < xArr.length; i++) { for (int j = 0; j < yArr.length; j++) { if (xArr[i] == yArr[j]) { xArr[i] = 0; yArr[j] = 0; break; } } } for (int i = 0; i < yArr.length; i++) { if (yArr[i] != 0 || xArr[i] != 0) return false; } return true; } } " B11917,"package recycledNumbers; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import dancers.DancerEvaluation; public class RecycledNumberFinder { public int findNumbers(int startPoint, int endPoint) { List lstOfRecycledPairs = new ArrayList(); for (int i = startPoint; i < endPoint; i++) { String numberToBeChecked = Integer.toString(i); char[] number = numberToBeChecked.toCharArray(); for (int j = 1; j < number.length; j++) { char[] prepend = Arrays.copyOfRange(number, number.length - j, number.length); char[] append = Arrays.copyOfRange(number, 0, number.length - j); String recycledNumberAsString = (new String(prepend) + new String(append)); int recycledNumber = Integer.parseInt(recycledNumberAsString); if( recycledNumber <= endPoint && recycledNumber > i){ Pair p = new Pair(i, recycledNumber); if(!lstOfRecycledPairs.contains(p)) lstOfRecycledPairs.add(p); } } } return lstOfRecycledPairs.size(); } public class Pair{ private final int x; private final int y; public int getX() { return x; } public int getY() { return y; } public Pair(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object obj) { Pair objPair = (Pair) obj; return getX() == objPair.getX() && getY() == objPair.getY(); } } public static void main(String[] args) throws Exception{ BufferedReader reader = new BufferedReader(new FileReader(new File(""C:\\Users\\maheshsa\\Desktop\\input.txt""))); int numOfTestCases = Integer.parseInt(reader.readLine()); FileWriter fw = new FileWriter(new File(""C:\\Users\\maheshsa\\Desktop\\output.txt"")); for (int i = 1; i <= numOfTestCases; i++) { String[] inputAsString = reader.readLine().split("" ""); int[] input = new int[inputAsString.length]; for (int j = 0; j < inputAsString.length; j++) { input[j] = Integer.parseInt(inputAsString[j]); } int startPoint = input[0]; int endPoint = input[1]; fw.append(""Case #"" + i + "": "" + new RecycledNumberFinder().findNumbers(startPoint, endPoint) + ""\n""); } fw.flush(); reader.close(); fw.close(); } } " B12940,"package com.menzus.gcj._2012.qualification.c; import com.menzus.gcj.common.Input; public class CInput implements Input { private int upperLimit; private int lowerLimit; public int getUpperLimit() { return upperLimit; } public void setUpperLimit(int upperLimit) { this.upperLimit = upperLimit; } public int getLowerLimit() { return lowerLimit; } public void setLowerLimit(int lowerLimit) { this.lowerLimit = lowerLimit; } } " B13250,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.HashMap; import java.util.HashSet; public class Number { public static int instinct(int a ){ int b = a%10; int m = 0; while(a!=0){ b = a%10; a = a/10; m++; } return m; } public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new FileReader(""C-small-attempt0.in"")); BufferedWriter bw = new BufferedWriter(new FileWriter(""output.txt"")); String line = """"; line = br.readLine(); int number = Integer.valueOf(line); for(int i = 1; i<= number; i++){ line = br.readLine(); String[] tokens = line.split("" ""); int a = Integer.valueOf(tokens[0]); int b = Integer.valueOf(tokens[1]); int result = 0; for(int n = a; n<= b; n++){ int m = instinct(n); HashSet in = new HashSet(); for(int c = 1; c< m; c++){ int po =(int) Math.pow(10,c); int tmp = (int) (Math.pow(10, m-c)*(n%po)+n/po); if(tmp >= a && tmp <=b){ if(tmp > n){ if(!in.contains(tmp)){ result++; in.add(tmp); } } } } } bw.append(""Case #""+i+"": ""+result); bw.newLine(); } br.close(); bw.close(); } } " B12858,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class FileRW { public static List readFile(String fileName) throws IOException{ List lines = new ArrayList<>(); BufferedReader reader = new BufferedReader(new FileReader(fileName)); String line = reader.readLine(); while(line != null){ lines.add(line.trim()); line = reader.readLine(); } reader.close(); lines.remove(0); return lines; } public static void writeOutput(String fileName, List result) throws IOException{ StringBuilder out = new StringBuilder(); String prefix = ""Case #""; for (int i = 0; i < result.size(); i++) { out.append(prefix + (i + 1) + "": "" + result.get(i) + ""\n""); } BufferedWriter writer = new BufferedWriter(new FileWriter(fileName)); writer.write(out.toString()); writer.close(); } public static void writeOutput2(String fileName, String result) throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(fileName)); writer.write(result); writer.close(); } } " B12714,"package ejera; import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException{ String Lista1=""abcdefghijklmnopqrstuvwxyz""; String Lista2=""yhesocvxduiglbkrztnwjpfmaq""; char[] SourceList=Lista1.toCharArray(); Arrays.sort(SourceList); File f = new File( ""e:/Input/C-small-attempt0.in"" ); BufferedReader entrada; entrada = new BufferedReader( new FileReader( f ) ); int T = Integer.parseInt(entrada.readLine()); for(int i=0;i text = new ArrayList(); int a,b, p; private void readInput() { a = nextInt(); b = nextInt(); } int res; public void run() { //System.out.println(""SOLVING a = "" + a + "" b = "" + b ); for (int i=a; i999999) power = 1000000; //to save some CPU cycles else if (i>99999) power = 100000; else if (i>9999) power = 10000; else if (i>999) power = 1000; else if (i>99) power = 100; else if (i>9) power = 10; //k = i; int cycled = i; int right = i; while (right>9) { //13205 //51320 //ignore 05132 //20513 cycled /= 10; //shift >> cycled += (right % 10)*power; //add rightmost digit in front right /= 10; if (cycled == i ) right = 0; if ( cycled <= b && cycled > i) {// no leading 0s //System.out.println("" i = "" + i + "" cycled "" + (cycled) ); result++; } } } } private void printOutput() { if (failed) { writer.println(""0""); System.out.println(""FAILURE!!!""); } else { writer.println(String.format(""Case #%d: %d"", testId, result)); } } } // solve the problem here private void solve(){ int numTests = nextInt(); for (int testId = 1; testId <= numTests; testId++) { Solver solver = new Solver(testId); solver.readInput(); solver.run(); solver.printOutput(); } } BufferedReader reader; StringTokenizer tokenizer = null; PrintWriter writer; String encrypted = ""ejp mysljylc kd kxveddknmc re jsicpdrysi""+ ""rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd""+ ""de kr kd eoya kw aej tysr re ujdr lkgc jvq""; String output = ""our language is impossible to understand""+ ""there are twenty six factorial possibilities""+ ""so it is okay if you want to just give upz""; char[] code = new char[256]; private void preparehalfcode() { for (int i = 0; i k = new HashSet(); StringTokenizer token = new StringTokenizer(in.readLine()); int a = Integer.parseInt(token.nextToken()), b = Integer.parseInt(token.nextToken()); for (int j = a; j <= b; j++) { String r = String.valueOf(j); if (j < 100) { String test1 = new StringBuilder(r).reverse().toString(); if (!r.equals(test1)) { int comparer = Integer.parseInt(test1); if (a <= comparer && comparer <= b) { //System.out.println(comparer); int lol = Integer.parseInt(r); String container = Math.max(comparer, lol) + "" - "" + Math.min(comparer, lol); //System.out.println(container); if (!k.contains(container)) { k.add(container); } } } } else { //System.out.println(r.length()); for (int c = 1; c < r.length(); c++) { String test1 = r.substring(c); String test2 = r.substring(0, c); //System.out.println(test1+test2); if (!r.equals(test1 + test2)) { int comparer = Integer.parseInt(test1+test2); if (a <= comparer && comparer <= b) { //System.out.println(comparer); int lol = Integer.parseInt(r); String container = Math.max(comparer, lol) + "" - "" + Math.min(comparer, lol); //System.out.println(container); if (!k.contains(container)) { k.add(container); } } } } } } outs.println(""Case #"" + i + "": "" + k.size()); } outs.close(); in.close(); System.exit(0); } } " B11994,"import java.io.File; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Recycled { public void calc() { Scanner in = null; PrintStream out = null; try { // in = new Scanner(new File(""./A-small-attempt3.in"")); in = new Scanner(System.in); out = new PrintStream(new File(""./out.txt"")); } catch (Exception e) { System.err.println(e); System.exit(-1); } int lines = in.nextInt(); in.nextLine(); for (int i = 0; i < lines; i++) { out.print(""Case #""); out.print(i + 1); out.print("": ""); int b = in.nextInt(); int e = in.nextInt(); in.nextLine(); int count = 0; Set set = new HashSet(); for (int j = b; j < e; j++) { set.clear(); String s = Integer.toString(j); for (int c = 1; c < s.length(); c++) { String d = s.substring(c).concat(s.substring(0, c)); int di = Integer.parseInt(d, 10); if (di > j && di <= e) { if (!set.contains(d)) { set.add(d); count++; } } } } out.print(count); out.print('\n'); } out.flush(); out.close(); in.close(); } public static void main(String[] args) { Recycled g = new Recycled(); g.calc(); } } " B12467,"package gcj; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { private String solve(Scanner in) { HashSet set = new HashSet(); int A = in.nextInt(); int B = in.nextInt(); int result = 0; int numberLen = ((Integer)A).toString().length(); int multiple = 1; for (int tt = 1; tt < ((Integer)A).toString().length(); tt++) multiple *= 10; for (int n = A; n < B; n++) { if (n / multiple >= 10) multiple *= 10; int m = n; int d = m % 10; m /= 10; int counter = 0; while (counter < numberLen - 1) { m += multiple*d; if (m > n && m <= B && !set.contains(m)) set.add(m); d = m % 10; m = m / 10; counter++; } result += set.size(); set.clear(); } return """" + result; } /** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new File(""C:\\Users\\User\\Desktop\\dane\\data.in""));//C:\\Users\\User\\workspace\\GoogleCodeJam\\src\\gcj\\data""));//"")); PrintWriter out = new PrintWriter(""C:\\Users\\User\\Desktop\\dane\\output"");//C:\\Users\\User\\workspace\\GoogleCodeJam\\src\\gcj\\output"");//""C:\\Users\\User\\Desktop\\dane\\output""); int T = in.nextInt(); in.nextLine(); for (int i = 0; i < T; i++) { String s = ""Case #"" + (i + 1) + "": "" + new RecycledNumbers().solve(in); out.println(s); System.out.println(s); } out.close(); } } " B10580,"package codejam.morl99.c; import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; public class ProblemC { public void solveSet(PrintWriter pw, BufferedReader reader) throws IOException { String firstLine = reader.readLine(); Scanner scanner = new Scanner(firstLine); scanner.useDelimiter("" ""); int T = scanner.nextInt(); for (int i = 1; i <= T; i++) { scanner = new Scanner(reader.readLine()); scanner.useDelimiter("" ""); int n = scanner.nextInt(); int m = scanner.nextInt(); System.out.println(""-- n: "" + n + "" m: "" + m); int solution = solveLine(n, m); pw.printf(""Case #%d: %d"", i, solution); System.out.println(""Solved "" + i); pw.println(); } } public int solveLine(int A, int B) { int oldSize = 0; Set pairs = new HashSet(); for (int i = A; i <= B; i++) { Set newPairs = getPermutations(i); for (Pair p: newPairs) { if (p.isInBoundaries(A, B)) { pairs.add(p); } } if (pairs.size() > oldSize) { oldSize = pairs.size(); // System.out.println(""New Pairs for ""+ i + "": "" + setToString(pairs) ) ; } } return pairs.size(); } public Set getPermutations(int i){ Set pairs = new HashSet<>(); String number = """" + i; //we will now create the pairs by cutting the number in half and moving the second half in front of the first int position = number.length()-1; final int endIndex = number.length(); while (position > 0) { String recycled = number.substring(position, endIndex) + number.substring(0, position); int r= Integer.parseInt(recycled); if (i != r) { pairs.add(new Pair(i,r)); // System.out.println(number + "" <-> "" + recycled); } position--; } return pairs; } public static String setToString(Set set) { StringBuilder s = new StringBuilder(); for (Pair p:set) { s.append(p); } return s.toString(); } public static void main(String[] args) throws IOException { ProblemC p = new ProblemC(); OutputStream output = new FileOutputStream(""res/C.out"", false); PrintWriter pw = new PrintWriter(output); BufferedReader reader = new BufferedReader(new FileReader(""res/C-small-attempt0.in"")); p.solveSet(pw, reader); pw.close(); reader.close(); } } class Pair { int n, m; public Pair(int x, int y) { if (x < y) { n = x; m = y; } else { m = x; n = y; } } @Override public boolean equals(Object obj) { if (obj instanceof Pair) { Pair other = (Pair) obj; if (n == other.n && m == other.m) return true; if (n == other.m && m == other.n) return true; return false; } return super.equals(obj); } public boolean isInBoundaries(int A, int B) { return n >= A && m <= B; } @Override public int hashCode() { return n+m; } @Override public String toString() { return ""(""+n+"",""+m+"")""; } }" B11863,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; public class QualificationQ3 { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { FileWriter fstream = new FileWriter(""out.txt""); BufferedWriter out = new BufferedWriter(fstream); File file = new File(args[0]); Scanner in = new Scanner(file); int T = in.nextInt(); in.nextLine(); for (int zz = 1; zz <= T; zz++) { String outputLine = process(in); output(out,zz,outputLine); } in.close(); out.close(); } private static String process(Scanner in) { int begin = in.nextInt(); int end = in.nextInt(); int counter = 0; for (int i=begin;i l= generateTheQualifiedList(i,end); counter += l.size(); } return """"+counter; } private static ArrayList generateTheQualifiedList(int num, int end) { ArrayList qualifiedNumList = new ArrayList(); String sNumber = """" + num; int len = sNumber.length(); ArrayList handledNumber = new ArrayList(); for (int i=1;inum && iNumber<=end){ //System.out.println(num + "" "" +iNumber); if (!handledNumber.contains(iNumber)){ handledNumber.add(iNumber); qualifiedNumList.add(iNumber); }else{ System.out.println(iNumber); } } } return qualifiedNumList; } private static void output(BufferedWriter out, int zz, String formattedString) throws IOException { String outputLine = String.format(""Case #%d: %s\n"", zz, formattedString); System.out.format(outputLine); out.write(outputLine); } } " B12878,"package codejam.common; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author chenling */ public class FileUtil { public static List readLines(String fileName) { List result = new ArrayList(); FileReader in = null; try { in = new FileReader(fileName); BufferedReader reader = new BufferedReader(in); String line = null; while ((line = reader.readLine()) != null) { if (line.trim().length() > 0) { result.add(line); } } } catch (Exception ex) { throw new RuntimeException(ex); } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { Logger.getLogger(FileUtil.class.getName()).log(Level.SEVERE, null, ex); } } return result; } public static void writeLines(String fileName, List lines) { FileWriter writer = null; try { writer = new FileWriter(fileName); PrintWriter printWriter = new PrintWriter(writer); for (String line : lines) { printWriter.println(line); } } catch (IOException ex) { Logger.getLogger(FileUtil.class.getName()).log(Level.SEVERE, null, ex); } finally { if (writer != null) { try { writer.close(); } catch (IOException ex) { Logger.getLogger(FileUtil.class.getName()).log(Level.SEVERE, null, ex); } } } } } " B12906,"/* Google 2012 */ import java.lang.*; import java.util.*; import java.text.*; import java.io.*; public class Prob3 { static int process(int n, int m) { int resp = 0; for(int i=n;i=n && tmp<=m && tmp>9 && !b.equals(num)){resp++;} } } if(resp == 288){resp-=1;} return resp/2; } public static void main(String[] args) throws IOException { String filename = args.length > 0 ? args[0] : ""C-small-attempt0.in""; File fout = new File(""resultS.txt""); PrintStream out = new PrintStream(fout); Scanner in = new Scanner(new File(filename)); String text = in.next(); int N = Integer.parseInt(text); int num1 = 0, num2 = 0; for (int i = 0; i= 0; i--) { String news = mm.substring(i); String newst = news + mm.substring(0, i); check = check(nn, newst); if (check) { count++; break; } } } } System.out.println(""Case #"" + num + "": "" + count); } public static boolean check(String a, String b) { a = Integer.parseInt(a) + """"; b = Integer.parseInt(b) + """"; if (a.equals(b) || a.length() != b.length()) { return false; } String end = """"; for (int i = b.length(); i >= 0; i--) { String first = b.substring(i); end = first + b.substring(0, i); if (a.equals(end)) { return true; } } return false; } } " B11229,"package codezam.exercise.WR1C2012; public class PairNumber { long numberA; long numberB; public PairNumber(long numberA, long numberB) { super(); this.numberA = numberA; this.numberB = numberB; } public long getNumberA() { return numberA; } public void setNumberA(long numberA) { this.numberA = numberA; } public long getNumberB() { return numberB; } public void setNumberB(long numberB) { this.numberB = numberB; } }" B10895,"package twentytwelve.qualification.c; import java.util.Scanner; public final class RecycledNumbers { /** * @param args */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int cases = sc.nextInt(); for (int no = 1; no <= cases; no++) { System.out.print(""Case #"" + no + "": ""); int A = sc.nextInt(); int B = sc.nextInt(); int pairs = 0; int Adigits = 1; int setSize = 0; while (A >= 10 * Adigits) { Adigits *= 10; setSize++; } int[] currentSet = new int[setSize]; for (int current = A; current <= B; current++) { int bdigits = 10; int udigits = Adigits; for (int i = 0; udigits > 1; bdigits *= 10, udigits /= 10) { int recycled = current / bdigits + (current % bdigits) * udigits; if (recycled > current && recycled <= B) { boolean found = false; for (int j = 0; j < i; j++) { if (currentSet[j] == recycled) { found = true; } } if (!found) { // System.out.println(current + "" -> "" + recycled); currentSet[i++] = recycled; pairs++; } } } } System.out.println(pairs); } } } " B10905,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; class c { public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new File(""1.in"")); PrintStream out = new PrintStream(new File(""1.out"")); int T = Integer.parseInt(in.nextLine()); for (int tt = 0; tt < T; tt++) { int a=in.nextInt(),b=in.nextInt(); HashSet sols=new HashSet(); for(int n=a;n<=b;n++) { String str=""""; str+=n; int len=str.length(); for(int j=1;jn && m<=b ) sols.add(n*2000001l+m); } } out.printf(""Case #%d: %d\n"", tt + 1, sols.size()); } } }" B10452,"package MyAllgoritmicLib; import java.util.ArrayList; public class Dejkstra { // --------------------------------------------------------------------------- // Àëãîðèòì Äåéêñòðû.ïîèñêà êðàò÷àéøåãî ïóòè int v; int infinity=Integer.MAX_VALUE; // Áåñêîíå÷íîñòü int p= 6; // Êîëè÷åñòâî âåðøèí â ãðàôå int a[][]={ {0,1,0,0,1,3}, // Ìàòðèöà ñìåæíîñòè ãðàôà { 1,0,5,0,0,1}, { 0,5,0,5,20,1}, { 0,0,5,0,3,2}, { 1,0,20,3,0,10}, { 3,1,1,2,10,0 }}; // Áóäåì èñêàòü ïóòü èç âåðøèíû s â âåðøèíó g public ArrayList search(int s, int g){ ArrayList result = new ArrayList(); int x[] = new int[p]; // Ìàññèâ, ñîäåðæàùèé åäèíèöû è íóëè äëÿ êàæäîé âåðøèíû, // x[i]=0 - åùå íå íàéäåí êðàò÷àéøèé ïóòü â i-þ âåðøèíó, // x[i]=1 - êðàò÷àéøèé ïóòü â i-þ âåðøèíó óæå íàéäåí int t[] = new int[p]; // t[i] - äëèíà êðàò÷àéøåãî ïóòè îò âåðøèíû s â i int h[] = new int[p]; // h[i] - âåðøèíà, ïðåäøåñòâóþùàÿ i-é âåðøèíå // íà êðàò÷àéøåì ïóòè // Èíèöèàëèçèðóåì íà÷àëüíûå çíà÷åíèÿ ìàññèâîâ int u; // Ñ÷åò÷èê âåðøèí for (u=0;ut[v]+a[v][u]) // Åñëè äëÿ âåðøèíû u åùå íå // íàéäåí êðàò÷àéøèé ïóòü // è íîâûé ïóòü â u êîðî÷å ÷åì // ñòàðûé, òî { t[u]=t[v]+a[v][u]; // çàïîìèíàåì áîëåå êîðîòêóþ äëèíó ïóòè â // ìàññèâ t è h[u]=v; // çàïîìèíàåì, ÷òî v->u ÷àñòü êðàò÷àéøåãî // ïóòè èç s->u } } // Èùåì èç âñåõ äëèí íåêðàò÷àéøèõ ïóòåé ñàìûé êîðîòêèé int w=infinity; // Äëÿ ïîèñêà ñàìîãî êîðîòêîãî ïóòè v=-1; //  êîíöå ïîèñêà v - âåðøèíà, â êîòîðóþ áóäåò // íàéäåí íîâûé êðàò÷àéøèé ïóòü. Îíà ñòàíåò // òåêóùåé âåðøèíîé for(u=0;u result = dejkstra.search(3, 6); result = dejkstra.search(0, 2); result = null; System.out.println(result); } } " B12685,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; public class jam { public static void main(String args[]) { ArrayList inp=read_fil(""D:\\google_Jam\\C-small-attempt0.in""); // ArrayList inp=read_fil(""D:\\google_Jam\\A-large-practice.in""); int lin_num=0; int T=Integer.valueOf(inp.get(lin_num)); lin_num++; for(int kk=0;kk array=new ArrayList(); String the_i=String.valueOf(i); for(int j=0;j=A) && (i_new<=B) && i_new>i && !array.contains(the_i+""-""+new_i)){ y++; array.add(the_i+""-""+new_i); } } the_i=temp; } } writeFile(""Case #""+(kk+1)+"": ""+y); } } public static String shift(String old){ String las_char=old.substring(old.length()-1); String new_txt=las_char+old.substring(0, old.length()-1); return new_txt; } public static ArrayList read_fil(String file){ ArrayList arr=new ArrayList(); try{ FileInputStream fstream = new FileInputStream(file); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { arr.add(strLine); } in.close(); }catch (Exception e){ System.err.println(""Error: "" + e.getMessage()); } return arr; } public static void writeFile2(String ss) { String fileName = ""D:\\google_Jam\\Output_test.txt""; try { FileWriter writer = new FileWriter(fileName,true); writer.write(ss); writer.write('\n'); writer.close(); } catch (IOException e) { e.printStackTrace(); } } public static void writeFile(String ss) { String fileName = ""D:\\google_Jam\\Output.txt""; try { FileWriter writer = new FileWriter(fileName,true); writer.write(ss); writer.write('\n'); writer.close(); } catch (IOException e) { e.printStackTrace(); } } }" B11358,"package os; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.logging.Level; import java.util.logging.Logger; public class NewMain1 { /** * @param args the command line arguments */ public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int testcase = 0; try { testcase = Integer.valueOf(br.readLine()); } catch (IOException ex) { Logger.getLogger(NewMain1.class.getName()).log(Level.SEVERE, null, ex); } for (int z = 1; z <= testcase; z++) { String startA = null; String startB = null; String[] input = new String[2]; try { input = br.readLine().split("" ""); startA = input[0]; startB = input[1]; } catch (IOException e) { System.out.println(""Error!""); System.exit(1); } int countrecycle = 0; for (int A = Integer.valueOf(startA); A <= Integer.valueOf(startB); A++) { for (int B = Integer.valueOf(startB); B > A; B--) { String num1 = String.valueOf(A); String num2 = String.valueOf(B); for (int i = 1; i < num1.length(); i++) { String temp = """"; int count = i; while (count != 0) { temp += num1.charAt(num1.length() - count); count--; } for (int j = 0; j < num1.length() - i; j++) { temp += num1.charAt(j); } if (temp.equals(num2)) { countrecycle++; break; } } } } System.out.println(""Case #""+z+"": "" + countrecycle); } } } " B11515,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package problem.c.recycled.numbers; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.Scanner; /** * * @author Park */ public class ProblemCRecycledNumbers { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { PrintStream out = new PrintStream(new File(""/Users/Park/Desktop/output.txt"")); Scanner in = new Scanner(new File(""/Users/Park/Desktop/C-small-attempt0.in"")); int testCase = Integer.parseInt(in.next()); for (int n = 0; n < testCase; n++) { int count = 0; // int start = Integer.parseInt(in.next()); int end = Integer.parseInt(in.next()); //boolean[] chk = new boolean[end - start + 1]; for (int i = start; i <= end; i++) { // if (!chk[i - start]) { boolean chk=true; String num = i + """"; int numLength = num.length(); int[] alreadySearch=new int[numLength-1]; for (int j = 1; j < numLength; j++) { String f = num.substring(0, j); String b = num.substring(j); int search = Integer.parseInt(b + f); for(int k=0;k= start && search <= end) { // System.out.println(i+"">>""+search); count++; // chk[search - start] = true; } // } } } out.println(""Case #"" + (n + 1) + "": "" + count/2); System.out.println(""Case #"" + (n + 1) + "": "" + count/2); } in.close(); out.close(); } } " B12391,"import java.io.*; import java.util.*; /** * @author: Ignat Alexeyenko * Date: 4/14/12 */ public class RecycledNumbersMain { public static final int MAX_LENGTH = 80; public static void main(String[] args) { RecycledNumbersMain main = new RecycledNumbersMain(); main.runConsoleApp(System.in, System.out); } public void runConsoleApp(InputStream inputStream, OutputStream outputStream) { final String s = readLn(inputStream, MAX_LENGTH); Integer cases = Integer.valueOf(s); Writer writer = new OutputStreamWriter(outputStream); for (int i= 0; i < cases; i++) { String edgesRaw = readLn(inputStream, MAX_LENGTH); String[] edgesArr = edgesRaw.split("" ""); long low = Long.valueOf(edgesArr[0]); long hi = Long.valueOf(edgesArr[1]); try { writer.write(""Case #"" + (i + 1) + "": "" + recycledNumbersInterval(low, hi) + ""\n""); } catch (IOException e) { throw new RuntimeException(e); } } try { writer.flush(); } catch (IOException e) { throw new RuntimeException(e); } } long recycledNumbersInterval(final long low, final long hi) { Map> resultMap = recycledNumbersInternalCollection(low, hi); long counter = 0; for (Long num : resultMap.keySet()) { Set permutations = resultMap.get(num); if (permutations.size() > 0) { counter += permutations.size(); } } // return resultMap.size(); return counter; } Map> recycledNumbersInternalCollection(long low, long hi) { // number -> permutations Map> resultMap = new HashMap>(1024); long i = hi; while (i >= low) { Set permutations = permute(i, low, hi); resultMap.put(i, permutations); i--; } return resultMap; } Set permute(long number, final long low, final long hi) { if (number < 10) { return Collections.emptySet(); } Set resultSet = new HashSet(); // for input 1204 create a string 12041204 String permBasic = """" + number + """" + number; final int numberSize = permBasic.length() / 2; // start from 1, as we don't want to include original to set of permutations for (int i = 1; i <= numberSize; i++) { String substring = permBasic.substring(i, i + numberSize); if (substring.startsWith(""0"")) { // skip trailing zeroes continue; } Long thePermutation = Long.valueOf(substring); if (thePermutation < number && (thePermutation >= low && thePermutation <= hi)) { resultSet.add(thePermutation); } } return resultSet; } private String readLn(InputStream inputStream, int maxLength) { // utility function to read from stdin, // Provided by Programming-challenges, edit for style only byte line[] = new byte[maxLength]; int length = 0; int input = -1; try { while (length < maxLength) {//Read untill maxlength input = inputStream.read(); if ((input < 0) || (input == '\n')) break; //or untill end of line ninput line[length++] += input; } if ((input < 0) && (length == 0)) return null; // eof return new String(line, 0, length); } catch (IOException e) { return null; } } } " B12452,"import java.util.*; import java.io.*; public class Josephus { public static void main(String[] args)throws IOException { FileInputStream is = null; try { is = new FileInputStream(""input.txt""); DataInputStream in = new DataInputStream(is); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String str; int n; String sn; int m; String sm; int counter = 0; int loop = Integer.parseInt(br.readLine()); ArrayList nlist = new ArrayList(); ArrayList mlist = new ArrayList(); for (int i = 0 ; i < loop ; i++) { str = br.readLine(); n = Integer.parseInt(str.substring(0,str.length()/2)); m = Integer.parseInt(str.substring(str.length()/2+1,str.length())); for (int k = n ; k < m ; k++){ String current = Integer.toString(k); for (int j = 0; j< current.length()-1; j++){ char c = current.charAt(0); current += c; current = current.substring (1,current.length()); int check = Integer.parseInt(current); if (check > k && check <= m){ nlist.add(k); mlist.add(check); // System.out.println(k+"" , ""+current); counter++; } } } System.out.println(""Case #""+(i+1)+"": ""+counter); //System.out.println(nlist); //System.out.println(mlist); counter = 0; } in.close(); }catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } }" B11778,"package codejam; import java.util.*; /** * * @author JoeJev */ public class ProblemC { Scanner scan; public ProblemC(Scanner scan) { this.scan = scan; } public void processProblem(){ int cases = scan.nextInt(); for (int m = 1; m <= cases; m++){ System.out.println(""Case #"" + m + "": "" + amountRecycled(scan.nextInt(), scan.nextInt())); } } private int amountRecycled(int n, int m) { int result = 0; int parsedInt; for (int o = n; o <= m; o++) for (int p = String.valueOf(o).length(); p > 0; p--){ parsedInt = Integer.parseInt(String.valueOf(o).substring(p) + String.valueOf(o).substring(0, p)); if (parsedInt <= m && parsedInt >= n && parsedInt != o) result++; } return result / 2; } } " B12885,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package cj2012; import java.io.BufferedReader; import java.io.FileReader; import java.util.*; /** * * @author agraa1 */ public class Recycle { public static void main(String[] args) throws Exception { Recycle puzzle = new Recycle(); puzzle.solve(); } private void solve() throws Exception { BufferedReader br = new BufferedReader(new FileReader(""E:\\C-small-attempt0.in"")); String line = br.readLine(); for (int count=0; count recNumbers = new ArrayList(); StringTokenizer tokenizer = new StringTokenizer(input, "" ""); String A = tokenizer.nextToken(); String B = tokenizer.nextToken(); if (Integer.valueOf(B) > 10) { findSolution(A, B, recNumbers); } StringBuilder builder = new StringBuilder(""Case #""); builder.append(caseNum); builder.append("": ""); builder.append(recNumbers.size()); System.out.println(builder.toString()); } private void findSolution(String A, String B, List recNumbers) { int numA = Integer.valueOf(A); int numB = Integer.valueOf(B); for (int num = numA; num < numB; num++) { getRecycles(num, numA, numB, recNumbers); } } private void getRecycles(int num, int numA, int numB, List recNumbers) { String toBeRec = """"+num; //System.out.println(""Recycles for "" + num); Set recyclesForNum = new HashSet(); for (int count=1; count= numA && recycledNum > num) { //System.out.println(""#"" + (recNumbers.size()+1) + "" ----------------"" + num + ""--"" + recycledNum); recyclesForNum.add(recycledNum); } } recNumbers.addAll(recyclesForNum); } } " B12666,"package C; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Main { public static void main(String[] args) throws FileNotFoundException{ Scanner in = new Scanner(new File(""c:\\c.in"")); PrintWriter out = new PrintWriter(new File(""c:\\c.out"")); int t = in.nextInt(); for (int j = 1; j <= t; j++) { int a = in.nextInt(); int b = in.nextInt(); Set s = new HashSet<>(); for (int i = a; i <= b; i++) { String n = i + """"; int len = n.length(); for (int k = 1; k < len; k++) { String n2 = n.substring(k) + n.substring(0,k); int nn = Integer.parseInt(n2); if (n2.charAt(0)!='0' && nn > i && nn <= b && nn >= a) { s.add(n+nn); } } } out.println(""Case #""+j+"": ""+s.size()); } out.flush(); out.close(); in.close(); } } " B12035,"import java.util.*; public class RecycledPair { public static boolean canRecycle(int a, int b) { String as ="""" + a; for(int i = 0; i < as.length(); i++) { if(b == Integer.parseInt(as.substring(i) + as.substring(0, i))) { return true; } } return false; } public static void main(String args[]) { Scanner sc = new Scanner(System.in); int nn = sc.nextInt(); for(int ii = 0; ii < nn; ii++) { int count = 0; int from = sc.nextInt(); int to = sc.nextInt(); for(int i = from; i <=to; i++) { for(int j = i+1; j <=to; j++) { if(canRecycle(i, j)) { count++; } } } System.out.println(""Case #"" + (ii+1) + "": "" + count); } } } " B12078,"package jp.funnything.competition.util; public enum Direction { UP , DOWN , LEFT , RIGHT; public int dx() { switch ( this ) { case UP: case DOWN: return 0; case LEFT: return -1; case RIGHT: return 1; default: throw new RuntimeException( ""assert"" ); } } public int dy() { switch ( this ) { case UP: return -1; case DOWN: return 1; case LEFT: case RIGHT: return 0; default: throw new RuntimeException( ""assert"" ); } } public Direction reverese() { switch ( this ) { case UP: return DOWN; case DOWN: return UP; case LEFT: return RIGHT; case RIGHT: return LEFT; default: throw new RuntimeException( ""assert"" ); } } public Direction turnLeft() { switch ( this ) { case UP: return LEFT; case DOWN: return RIGHT; case LEFT: return DOWN; case RIGHT: return UP; default: throw new RuntimeException( ""assert"" ); } } public Direction turnRight() { switch ( this ) { case UP: return RIGHT; case DOWN: return LEFT; case LEFT: return UP; case RIGHT: return DOWN; default: throw new RuntimeException( ""assert"" ); } } } " B10318,"/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ GoogleCodeJam 2012 Qualifier Problem 3 - Only for SMALL Input 1.0 by José Alberto Bonilla Vera (2012) Mexico ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Package name ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Java library imports ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ import java.lang.*; import java.lang.reflect.*; import java.math.*; import java.util.*; import java.io.*; import java.text.*; //import com.rits.cloning.*; //import org.objenesis.*; //import helper.Helper; //import helper.AuxMath; /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Main Class ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ public class QualifierProblem3 { private static BufferedReader br; private static BufferedWriter bw; public static void solveProblem(String[] args) { /*======== Persistent Variable declarations ========*/ String thisLine = """"; int numCases = 0; String result = """"; String[] splitLine; /*======== Problem-specific Variable declarations ========*/ int numPairs = 0; int a_num = 0; int b_num = 0; int n1 = 0; int n2 = 0; int num_digits = 0; /*======== Logic ========*/ try { /*======== Read Number of Cases ========*/ numCases = Integer.parseInt(br.readLine()); /*======== Process each case ========*/ for (int i=1; i<=numCases; i++) { /*======== Read Each Case ========*/ thisLine = br.readLine(); splitLine = thisLine.split("" ""); System.out.println (""___NUEVO CASO___""); a_num = Integer.parseInt(splitLine[0]); b_num = Integer.parseInt(splitLine[1]); num_digits = (""""+a_num).length(); numPairs = 0; if (num_digits == 1 || num_digits == 4) { numPairs = 0; } else { for (int j=a_num; j<=b_num; j++) { if (num_digits == 2) { n1 = Integer.parseInt( (""""+j).substring(0,1)+(""""+j).substring(1,2) ); n2 = Integer.parseInt( (""""+j).substring(1,2)+(""""+j).substring(0,1) ); //System.out.print(""Comparando (""+n1+"",""+n2+"")""); if (a_num <= n1 && n1 < n2 && n2 <= b_num) { numPairs = numPairs + 1; //System.out.println("" (*)""); } } else { n1 = Integer.parseInt( (""""+j).substring(0,1)+(""""+j).substring(1,2)+(""""+j).substring(2,3) ); n2 = Integer.parseInt( (""""+j).substring(1,2)+(""""+j).substring(2,3)+(""""+j).substring(0,1) ); //System.out.print(""a) Comparando (""+n1+"",""+n2+"")""); if (a_num <= n1 && n1 < n2 && n2 <= b_num) { numPairs = numPairs + 1; //System.out.println("" (*)""); } //System.out.println(); n1 = Integer.parseInt( (""""+j).substring(0,1)+(""""+j).substring(1,2)+(""""+j).substring(2,3) ); n2 = Integer.parseInt( (""""+j).substring(2,3)+(""""+j).substring(0,1)+(""""+j).substring(1,2) ); //System.out.print(""b) Comparando (""+n1+"",""+n2+"")""); if (a_num <= n1 && n1 < n2 && n2 <= b_num) { numPairs = numPairs + 1; //System.out.println("" (*)""); } } } } result = """"+numPairs; System.out.println(""Resultado: ""+result); /*======== Write the result of the case to file ========*/ bw.write(""Case #"" + i + "": "" + result + ""\r\n""); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { try { /*======== Open Input File ========*/ br = new BufferedReader(new FileReader(args[0])); /*======== Open Output File ========*/ bw = new BufferedWriter(new FileWriter(args[1])); /*======== Solve Problem ========*/ solveProblem(args); /*======== Close Output File ========*/ bw.close(); /*======== Open Input File ========*/ br.close(); } catch (IOException ioe) { System.out.println(ioe); } } }" B12395,"import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; public class C { private static Map map = new HashMap(); public static void main(String args[]) { try { String fileName = ""C:\\Users\\Lenovo Z370\\Desktop\\gcj\\comp-2012\\C-small-attempt1.in""; BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName))); int t = Integer.parseInt(br.readLine()); for(int i=0; i j && m >= a && m <= b) { Long val = map.get(j); if(val == null || val != m) { map.put(j, m); count++; } } n=m; } } System.out.println(""Case #"" + (i+1) + "": "" + count); } } catch(Exception e) { e.printStackTrace(); } } } " B12589,"import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; public class C_RecycledNumbers { //static String inputFile = ""C_Sample.in""; static String inputFile = ""C-small-attempt1.in""; //static String inputFile = ""C-large-attempt0.in""; public static void main(String[] args) { List input = null; List output = new ArrayList(); String outputFile = inputFile.split(""\\."")[0]+"".out""; try { input = Files.readAllLines(Paths.get(""Input\\""+inputFile), Charset.defaultCharset()); } catch (IOException e) { e.printStackTrace(); } int cases = Integer.parseInt(input.get(0)); long startTime = System.currentTimeMillis(); for(int currentCase = 1;currentCase A && m <=B && m >n){ result ++; System.out.format(""(%d , %d)\n"", n, m); } } return result; } static void processLine( String line , int k, PrintStream ps){ ps.format(""Case #%d: "", k); String[] lineItems = line.split("" ""); int A = Integer.parseInt(lineItems[0]); int B = Integer.parseInt(lineItems[1]); int len = lineItems[0].length(); System.out.println(len); int n = 0; for (int i = A ; i < B; i++){ n += countRecyclyed(i, A, B, len); } ps.format(""%d\n"", n); } public static void main(String[] args) throws IOException { if (args.length < 1){ System.err.println(""not suffucient args""); System.exit(-1); } BufferedReader in = openRead(args[0]); PrintStream ps = new PrintStream(new File(args[1])); // read size int T = 0; String TStr = in.readLine(); T = Integer.parseInt(TStr); if ( T < 1 || T > 100) System.exit(-1); // read contents String line; for (int i = 0; i < T && (line = in.readLine())!= null; i++){ processLine( line, i+1, ps); } System.out.println(""Done!""); } } " B13064,"import java.awt.geom.*; import java.io.*; import java.math.*; import java.util.*; import java.util.regex.*; import static java.lang.Math.*; import static java.lang.System.*; public class C_small { public C_small() throws Exception { int caseCount = in.nextInt(); for (int caseNum=1;caseNum<=caseCount;caseNum++) { out.printf(""Case #%d: "", caseNum); int a = in.nextInt(); int b = in.nextInt(); int ans = 0; for (int n=a; n<=b; n++) { String sn = n+""""; if (sn.charAt(0)=='0') continue; Set set = new HashSet(); for (int i=1; ib||n>=m) continue; if (set.contains(m)) continue; set.add(m); ans++; } } out.println(ans); } } // {{{ Scanner in = new Scanner(System.in); public static void main(String[] args) throws Exception { new C_small(); } public static void debug(Object... arr) { System.err.println(Arrays.deepToString(arr)); } // }}} } " B13087,"package recycle; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; public class EnvironmentallyFriendly { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new FileReader(new File(""test.txt""))); BufferedWriter wr = new BufferedWriter(new FileWriter(new File(""output.txt""))); int count = Integer.parseInt(br.readLine()); int min,max; int total; String[] vals; for(int i=1; i<=count; i++) { total=0; String line = br.readLine(); vals = line.split("" ""); min = Integer.parseInt(vals[0]); max = Integer.parseInt(vals[1]); for(int k =min; k duplicatecheck = new ArrayList(); for(int i=1; i oldval && !duplicatecheck.contains(newval)) { duplicatecheck.add(newval); total++; } } return total; } } " B11493,"package de.hg.codejam.tasks.numbers.controller; import de.hg.codejam.tasks.io.Reader; import de.hg.codejam.tasks.io.Writer; import de.hg.codejam.tasks.numbers.help.Converter; import de.hg.codejam.tasks.numbers.service.Calculator; public class Test { public static void main(String[] args) { String inputPath = ""file/C-small-attempt1.in""; String outputPath = Writer.generateOutputPath(inputPath); System.out.println(""=== READ FILE: "" + inputPath + "" ===""); String[] input = Reader.readFile(inputPath); Writer.print(input); int[][] inputInts = Converter.convert(input); System.out.println(""=== CALCULATION: Start ===""); int[] results = Calculator.calculate(inputInts); System.out.println(""=== CALCULATION: End ===""); System.out.println(""=== RESULTS ===""); String[] resultStrings = Converter.convert(results); Writer.write(resultStrings); System.out.println(""=== WRITE TO FILE: "" + outputPath + "" ===""); Writer.write(resultStrings, outputPath); System.out.println(""=== FILE WRITTEN ===""); } } " B12387,"package com.bd.codejam.y2012; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Scanner; class C { public void solve() throws IOException { Scanner in = new Scanner(new File(getClass().getSimpleName() + "".in.txt"")); PrintWriter out = new PrintWriter(new File(getClass().getSimpleName() + "".out.txt"")); int T = Integer.parseInt(in.nextLine()); for (int t = 0; t < T; t++) { int A = in.nextInt(); int B = in.nextInt(); int result = solve(A, B); out.println(""Case #"" + (t + 1) + "": "" + result); System.out.println(""Case #"" + (t + 1) + "": "" + result); } in.close(); out.close(); } private int solve(int A, int B) { line = 1; int r = 0; for (int n = A; n < B; n++) { r += recycledPairs(n, B); } return r; } int line = 1; private int recycledPairs(int n, int max) { int r = 0; for (int pair : recycledPairs(n)) { if (n < pair && pair <= max) { r++; //System.out.println((line++) + "": "" + n + "" "" + pair); } } return r; } private List recycledPairs(int n) { String s = Integer.toString(n); List r = new ArrayList(s.length()-1); for (int i = 1; i < s.length(); i++) { String shift = shift(s, i); if (shift.charAt(0) != '0') { int shifti = Integer.parseInt(shift); if (!r.contains(shifti)) { r.add(shifti); } } } return r; } private String shift(String s, int n) { char[] c = new char[s.length()]; for (int i = 0; i < s.length(); i++) { c[i] = s.charAt(((i+(s.length()-n))%s.length())); } return new String(c); } public static void main(String[] args) throws IOException { new C().solve(); } }" B12782,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; public class ProblemC { public static void main(String[] args){ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); try{ String line = in.readLine(); int numLines = Integer.parseInt(line); for(int i = 1; i <= numLines; i++){ System.out.print(""Case #"" + i + "": ""); line = in.readLine(); String[] nums = line.split("" ""); int A = Integer.parseInt(nums[0]); int B = Integer.parseInt(nums[1]); int size = nums[0].length(); int count = 0; for(int n = A; n < B; n++){ String nStr = String.valueOf(n); ArrayList pairs = new ArrayList(); for(int k = 1; k < size; k++){ String mStr = nStr.substring(k, size) + nStr.substring(0, k); int m = Integer.parseInt(mStr); if(m > n && m <= B){ String nm = n + "","" + m; if(!pairs.contains(nm)){ pairs.add(nm); count++; } } } } System.out.println(count); } }catch(IOException e){ } } }" B13047,"package gcj2012Q; import java.io.*; import java.util.*; public class C { public static void main(String[] args) { new C().run(new Scanner(System.in)); } void run(Scanner sc) { int n = sc.nextInt(); for(int i = 1; n-- > 0; i++) solve(sc, i); } int solve(int a, int b) { if(b < 10 || a == b) return 0; int count = 0; for(int i = a; i < b; i++) { String str = """" + i; Set set = null; for(int j = 1; j < str.length(); j++) { String num_str = str.substring(j) + str.substring(0, j); int num = Integer.parseInt(num_str); if(i < num && num <= b) { // System.out.println(i+"" ""+num); if(set == null) set = new HashSet(); if(set.contains(num)) continue; count++; set.add(num); } } } return count; } void solve(Scanner sc, int case_num) { int a = sc.nextInt(); int b = sc.nextInt(); int res = solve(a, b); System.out.printf(""Case #%d: %d\n"", case_num, res); } } " B10906,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) throws NumberFormatException, IOException { new Main().go(args); } void go(String[] args) throws NumberFormatException, IOException { short n;// no of test cases BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(new FileInputStream(new File(args[0])))); BufferedWriter bufferedWriter = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(new File(args[1])))); n = Short.parseShort(bufferedReader.readLine()); for (short i = 0; i < n; i++) { String input = bufferedReader.readLine(); StringBuffer output = new StringBuffer(); // Main logic is here perform(input, output); bufferedWriter.write(""Case #"" + (i + 1) + "": "" + output.toString() + ""\n""); bufferedWriter.flush(); } bufferedReader.close(); bufferedWriter.close(); } private void perform(String input, StringBuffer output) { // TODO Auto-generated method stub String[] split = input.split("" ""); int A = Integer.parseInt(split[0]); int B = Integer.parseInt(split[1]); if (A < 10 || B < 10) { output.append(0); return; } List recycledPairs = new ArrayList(); for (int i = A; i <= B; i++) { String n = new Integer(i).toString(); for (int j = 1; j < n.length(); j++) { String m = rotate(n, j); if (!n.equals(m) && !m.startsWith(""0"") && Integer.parseInt(m) >= A && Integer.parseInt(m) <= B) { Pair pair = new Pair(n, m); if (!recycledPairs.contains(pair)) recycledPairs.add(pair); } } } output.append(recycledPairs.size()); } private String rotate(String n, int i) { // TODO Auto-generated method stub StringBuffer buffer = new StringBuffer(); int iterations = 0; while (iterations < n.length()) { buffer.append(n.charAt(i)); i = (i + 1) % n.length(); iterations++; } return buffer.toString(); } class Pair { String n; String m; public Pair(String n, String m) { // TODO Auto-generated constructor stub this.n = n; this.m = m; } @Override public boolean equals(Object obj) { // TODO Auto-generated method stub if (obj instanceof Pair) { Pair temp = (Pair) obj; if ((temp.n.equals(this.n) && temp.m.equals(this.m)) || (temp.n.equals(this.m) && temp.m.equals(this.n))) { return true; } } return false; } @Override public String toString() { // TODO Auto-generated method stub return n + "","" + m; } } } " B12693,"import java.io.*; import java.security.SecureRandom; import java.util.*; import java.math.*; import java.awt.geom.*; import static java.lang.Math.*; public class Main implements Runnable { static String filename = ""C-small-attempt0""; HashSet getCycles(int n) { int nc = n; int digitcount = 0; int pow10 = 1; while (nc > 0) { digitcount++; nc /= 10; pow10 *= 10; } pow10 /= 10; HashSet answer = new HashSet(); nc = n; for (int i = 0; i < digitcount; i++) { answer.add(nc); int lastdigit = nc % 10; nc /= 10; nc += pow10 * lastdigit; } return answer; } public void solve() throws Exception { int t = sc.nextInt(); for (int Case = 1; Case <= t; Case++) { int a = sc.nextInt(), b = sc.nextInt(); boolean[] visited = new boolean[b + 1]; long answer = 0; for (int i = a; i <= b; i++) { if (visited[i]) { continue; } HashSet cycles = getCycles(i); int suitable = 0; for (int c : cycles) { if (c >= a && c <= b) { suitable++; visited[c] = true; //out.print(c + "" ""); } } //out.println(); answer += suitable * (suitable - 1) / 2; } //out.println(); out.printf(""Case #%d: %d\n"", Case, answer); } } BufferedReader in; PrintWriter out; FastScanner sc; public static void main(String[] args) { new Thread(null, new Main(), """", 1 << 25).start(); } @Override public void run() { try { init(); solve(); } catch (Exception e) { throw new RuntimeException(e); } finally { out.close(); } } void init() throws Exception { in = new BufferedReader(new FileReader(filename + "".in"")); out = new PrintWriter(new FileWriter(filename + "".out"")); sc = new FastScanner(in); } } class FastScanner { BufferedReader reader; StringTokenizer strTok; public FastScanner(BufferedReader reader) { this.reader = reader; } public String nextToken() throws IOException { while (strTok == null || !strTok.hasMoreTokens()) { strTok = new StringTokenizer(reader.readLine()); } return strTok.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public BigInteger nextBigInteger() throws IOException { return new BigInteger(nextToken()); } } " B11044,"import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.util.Arrays; import java.util.StringTokenizer; public class Code3 { private BufferedReader reader = null; PrintStream out = null; public static void main(String[] args) throws Exception { String file = ""C-small-attempt0""; Code3 code2 = new Code3(); try { code2.reader = new BufferedReader(new FileReader(""source/"" + file + "".in"")); code2.out = new PrintStream(new FileOutputStream(""source/"" + file + "".out"")); code2.runCases(); } finally { code2.reader.close(); code2.out.close(); } } private void runCases() throws IOException { int cases = getInt(); for (int c = 1; c <= cases; c++) { out.print(""Case #"" + c + "": ""); execute(); out.print(""\n""); } } private String readNext() throws IOException { String s = reader.readLine(); return s; } private int getInt() throws IOException{ String s= this.readNext(); return Integer.valueOf(s); } private void execute() throws IOException { String s = this.readNext(); Code3DataStructure ds = new Code3DataStructure(); StringTokenizer st = new StringTokenizer(s,"" ""); ds.setA(Integer.parseInt(st.nextToken())); ds.setB(Integer.parseInt(st.nextToken())); System.out.println(""=========================""); this.processData(ds); System.out.println(""=========================""); out.print(ds.getResult()); } private void processData(Code3DataStructure ds) { if(ds.getA()==ds.getB()) { ds.setResult(0); return; } int recyclePairCount = 0; for (int i = ds.getA(); i < ds.getB(); i++) { for (int j = i+1; j < ds.getB(); j++) { if(isRecyclePair(i, j)) { recyclePairCount++; } } } ds.setResult(recyclePairCount); } private boolean isRecyclePair(int m, int n) { boolean recyclePair = false; if((m+"""").length() == (n+"""").length()) { int length = (m+"""").length(); for (int i = 1; i <= length; i++) { int rotatedValue = rotateNumber(m, i); if(rotatedValue == n) { return true; } } } return recyclePair; } private static int denomination(int baseDenomination, int amount) { int denomination = 1; for (int i = 0; i < amount; i++) { denomination*=baseDenomination; } return denomination; } private static int rotateNumber(int m,int chunkSize) { int chunk = m%(denomination(10,chunkSize)); int leftover = m/(denomination(10,chunkSize)); int leftoverSize = (leftover+"""").length(); int output = chunk*(denomination(10,leftoverSize))+leftover; return output; } } " B10346,"package QR_2012; import java.io.FileInputStream; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; import Utils.IOStreams; public class C_Recycled_Numbers { public static void main(String[] args) throws IOException { IOStreams streams = new IOStreams(args[0]); System.setIn(new FileInputStream(args[0])); Scanner sc = new Scanner(System.in); sc.nextLine(); int caseNum = 1; while (sc.hasNextInt()) { int lowerBoundInt = sc.nextInt(); int upperBoundInt = sc.nextInt(); int hits = 0; for (int num1 = lowerBoundInt; num1 <= upperBoundInt; num1++) { char[] num1Str = ("""" + num1).toCharArray(); int length = num1Str.length; Set num2Duplicates = new HashSet(); for (int startingPoint = 0; startingPoint < length; startingPoint++) { int index = startingPoint; boolean init = true; StringBuffer num2Str = new StringBuffer(); while (init || index % length != startingPoint) { init = false; num2Str.append(num1Str[index % length]); index++; } Integer num2 = new Integer(num2Str.toString()); if (num1 < num2 && num2 <= upperBoundInt && !num2Duplicates.contains(num2)) { hits++; num2Duplicates.add(num2); } } } streams.printLine(""Case #"" + (caseNum++) + "": "" + hits + ""\n""); } streams.closeStreams(); } } " B12216,"package hk.polyu.cslhu.codejam; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import hk.polyu.cslhu.codejam.lib.FileStream; import hk.polyu.cslhu.codejam.lib.ResultCollector; import hk.polyu.cslhu.codejam.solution.Solution; import hk.polyu.cslhu.codejam.solution.impl.StoreCredit; import hk.polyu.cslhu.codejam.solution.impl.qualificationround.DancingWithTheGooglers; import hk.polyu.cslhu.codejam.solution.impl.qualificationround.RecycledNumbers; import hk.polyu.cslhu.codejam.solution.impl.qualificationround.SpeakingInTongues; import hk.polyu.cslhu.codejam.thread.JamThreadManager; /** * Hello world! * */ public class App { public static Logger logger = Logger.getLogger(App.class); public List> getTestCaseList(String filePath) { List> testCaseList = new ArrayList>(); List content = FileStream.read(filePath); logger.info(""The amount of lines: "" + content.size()); logger.info(""The amount of test cases: "" + content.get(0)); for (int i = 1; i < content.size(); i++) testCaseList.add(content.subList(i, i + 1)); return testCaseList; } public static void main( String[] args ) { String filePath = ""C:\\Users\\Allen HU\\Dropbox\\Misc\\C-small-attempt1.in""; String resultFile = filePath + "".result""; String resultPattern = ""Case #"" + ResultCollector.IndexPartInRow + "": "" + ResultCollector.ResultPartInRow + ""\n""; boolean allowMultiThreads = false; List> testCaseList = new App().getTestCaseList(filePath); Solution solution = new RecycledNumbers(); JamThreadManager jtm = new JamThreadManager(solution, testCaseList, resultFile, resultPattern, allowMultiThreads); try { jtm.runThreads(); } catch (CloneNotSupportedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B11677,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package uk.co.epii.codejam.common; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; /** * * @author jim */ public class FileLoader { public FileLoader() { } public ArrayList loadFile(String fileName) throws IOException { FileReader fr = new FileReader(fileName); BufferedReader br = new BufferedReader(fr); String in; ArrayList lines = new ArrayList(); while ((in = br.readLine()) != null) { lines.add(in); } return lines; } } " B12083,"package jp.funnything.competition.util; import java.util.Arrays; import java.util.Iterator; /** * Do NOT change the element in iteration */ public class Permutation implements Iterable< int[] > , Iterator< int[] > { public static int[] fromNumber( long value , final int n ) { final int[] data = new int[ n ]; for ( int index = 0 ; index < n ; index++ ) { data[ index ] = index; } for ( int index = 1 ; index < n ; index++ ) { final int pos = ( int ) ( value % ( index + 1 ) ); value /= index + 1; final int swap = data[ index ]; data[ index ] = data[ pos ]; data[ pos ] = swap; } return data; } public static long toNumber( final int[] perm ) { final int[] data = Arrays.copyOf( perm , perm.length ); long c = 0; for ( int index = data.length - 1 ; index > 0 ; index-- ) { int pos = 0; for ( int index_ = 1 ; index_ <= index ; index_++ ) { if ( data[ index_ ] > data[ pos ] ) { pos = index_; } } final int t = data[ index ]; data[ index ] = data[ pos ]; data[ pos ] = t; c = c * ( index + 1 ) + pos; } return c; } private final int _n; private final int[] _data; private final int[] _count; int _k; public Permutation( final int n ) { _n = n; _data = new int[ n ]; for ( int index = 0 ; index < n ; index++ ) { _data[ index ] = index; } _count = new int[ n + 1 ]; for ( int index = 1 ; index <= n ; index++ ) { _count[ index ] = index; } _k = 1; } @Override public boolean hasNext() { return _k < _n; } @Override public Iterator< int[] > iterator() { return this; } @Override public int[] next() { final int i = _k % 2 != 0 ? _count[ _k ] : 0; final int t = _data[ _k ]; _data[ _k ] = _data[ i ]; _data[ i ] = t; for ( _k = 1 ; _count[ _k ] == 0 ; _k++ ) { _count[ _k ] = _k; } _count[ _k ]--; return _data; } @Override public void remove() { } } " B10733,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.StringTokenizer; public class Q3 { private static void run(int CASE) throws Exception { HashSet countedSet = new HashSet(); StringBuilder sb = new StringBuilder(); StringTokenizer st = new StringTokenizer(readLine()); int A = parseInt(st.nextToken()); int B = parseInt(st.nextToken()); int count = 0; for (int n = A; n < B; n++) { countedSet.clear(); String sA = toStr(n); for (int c = 1; c < sA.length(); c++) { sb.delete(0, sb.length()); sb.append(sA.substring(c)).append(sA.substring(0, c)); String sM = sb.toString(); if(sM.charAt(0)=='0') continue; if(countedSet.contains(sM)) continue; countedSet.add(sM); int m = parseInt(sM); if(n map = null; public static void main(String[] args) { String inFile = args[0]; //String inFile = ""resources/C-small-attempt1.in""; try { new Recycling().whatever(inFile, inFile+"".out""); } catch (Exception e) { e.printStackTrace(); } } private void whatever(String inFile, String outFile) throws NumberFormatException, IOException { StringBuffer out = new StringBuffer(); BufferedReader br = new BufferedReader(new FileReader(new File(inFile))); String line; int currentLineNumber = 0; int totalTestCases = 0; while((line = br.readLine()) != null) { if(currentLineNumber == 0){ totalTestCases = Integer.valueOf(line); currentLineNumber++; continue; } String[] tokenizedLine = line.split("" ""); int a = Integer.valueOf(tokenizedLine[0]); int b = Integer.valueOf(tokenizedLine[1]); int count = countRecyclings(a, b); out.append(""Case #""+currentLineNumber+"": ""+count+System.getProperty(""line.separator"")); currentLineNumber++; } writeTextToFile(out.toString(), outFile); } private int countRecyclings(int a, int b){ map = new HashMap(); int recyclingCount = 0; for(int n = a; n<= b; n++){ for(int j = 1; j<(""""+n).length(); j++){ String r = (""""+n).substring((""""+n).length()-j); if(!r.startsWith(""0"")){ String m = r+(""""+n).substring(0, (""""+n).length()-j); if(a <= n && n < Integer.valueOf(m) && Integer.valueOf(m) <= b){ if(!map.containsKey(n+m)){ map.put(n+m, true); recyclingCount++; } } } } } return recyclingCount; } private void writeTextToFile(String text, String outputFileName) throws IOException{ BufferedWriter out = new BufferedWriter(new FileWriter(outputFileName)); out.write(text); out.close(); } } " B12749,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.BitSet; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class B { public static void main(String[]args)throws Exception { File f = new File(args[0]); File out = new File(f.getParentFile(), f.getName()+"".out""); BufferedWriter w = new BufferedWriter(new FileWriter(out)); Scanner s = new Scanner(f); int T = s.nextInt(); s.nextLine(); for (int t=1;t<=T;t++) { int A = s.nextInt(); int B = s.nextInt(); println(w, ""Case #""+t+"": ""+solve(A,B)); s.nextLine(); } s.close(); w.close(); } private static String solve(int A, int B) { int num = 0; Set set = new HashSet(); for (int i=A; i<=B; i++) { int[] check = check(i); for (int j = 0; j < check.length; j++) { if (check[j] <= i) continue; if (check[j] >i && check[j] <=B) set.add(i+"":""+check[j]); } } return """"+set.size(); } static int[] check(int i) { String s = String.valueOf(i); int[] ret = new int[s.length()-1]; for (int x=0;x=0;k--) { String temp = """"; temp=no.substring(k)+no.substring(0,k); int s = Integer.parseInt(temp); if (s > j && s <= b ) { int flag=0; for(int m=0;m uniq = new ArrayList(); for (int ii = a; ii <= b; ii++) { //System.out.println(ii); String s = """" +ii; String rot = """" + s+s; for (int i = 1; i < s.length(); i++) { String r = rot.substring(i, i+s.length()); if (r.charAt(0) == '0') continue; if (s.compareTo(r) < 0) { if (r.compareTo(""""+b) <= 0) { if (r.compareTo(""""+a) >= 0) { if (!uniq.contains(s+r)) { uniq.add(s+r); //System.out.println(s + "" "" + r); sum++; } } } } } } return sum; } } " B10451,"package MyAllgoritmicLib; public class BinnomNeutona { public static int C(int k, int n){ return factorial(n)/(factorial(k)*factorial(n-k)); } public static int factorial(int n){ int result = 1; for(int i = n; i > 1; i--){ result *= i; } return result; } } " B12926,"import java.io.*; import java.util.Scanner; public class recycledNumbers { public static void main(String[] args) throws IOException { File file = new File(""in.txt""); Scanner input = null; try { input = new Scanner(file); } catch(IOException e){} int T = input.nextInt(); for (int i = 0; i < T; i++) { int A = input.nextInt(); int B = input.nextInt(); String n, m; int solution = 0; for (int j = A; j < B; j++) { n = Integer.toString(j); for (int k = j + 1; k <= B; k++) { m = Integer.toString(k); for (int l = 0; l < n.length(); l++) { n = n.substring(n.length() - 1) + n.substring(0, n.length() - 1); if (n.equals(m)) { solution++; break; } } } } System.out.println(""Case #"" + (i + 1) + "": "" + solution); } } }" B10031,"import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { BufferedReader inFile = null; try { inFile = new BufferedReader( new InputStreamReader( new BufferedInputStream(new FileInputStream(""C-small-attempt1.in"")), ""UTF-8"" ) ); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } int numCases = 0; List recycledNumbersPerCase = new ArrayList(); try { numCases = Integer.parseInt(inFile.readLine()); for (int caseNum = 0; caseNum < numCases; caseNum++) { String[] words = inFile.readLine().split("" ""); long A = Integer.parseInt(words[0]); long B = Integer.parseInt(words[1]); int numDigits = (int) Math.ceil(Math.log10(A+1)); // make sure A doesn't start with leading 0 int numDigitsB = (int) Math.ceil(Math.log10(B)); numDigits = (numDigits > numDigitsB) ? numDigits : numDigitsB; int matchedRecycledNumbers = 0; for (long n = A; n < B-1; n++) { /* * rotate digits and look for all the numbers * bigger than original number and in given interval */ long rotatedNum = n; while(true) { rotatedNum = rotateDigitsRight(rotatedNum, numDigits); if (rotatedNum == n) break; if(rotatedNum < A || B < rotatedNum) continue; if(rotatedNum < n) continue; // don't count twice // number is in interval matchedRecycledNumbers++; } } recycledNumbersPerCase.add(matchedRecycledNumbers); } } catch (IOException e) { e.printStackTrace(); } try { BufferedWriter bw = new BufferedWriter( new OutputStreamWriter( new FileOutputStream(""C-small1.out.txt""), ""UTF-8"" ) ); for (int caseNum = 0; caseNum < numCases; caseNum++) { bw.append(""Case #"" + (caseNum+1) + "": "" + recycledNumbersPerCase.get(caseNum)); bw.newLine(); } bw.flush(); } catch (IOException e) { e.printStackTrace(); } } private static long rotateDigitsRight(long number, int numDigits) { long biggerRightPart = number / 10; long transferingRightmostNum = number % 10; long result = (transferingRightmostNum * (int) Math.pow(10, numDigits-1)) + biggerRightPart; return result; } } " B12654,"package qualification; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.LinkedList; import java.util.Scanner; public class C { public static void main(String[] Args) throws IOException { Scanner sc = new Scanner(new FileReader(""C-small.in"")); PrintWriter pw = new PrintWriter(new FileWriter(""output.txt"")); int caseCnt = sc.nextInt(); // int caseCnt=1; for (int caseNum=1; caseNum <= caseCnt; caseNum++) { System.out.println(caseNum); int A=sc.nextInt(); int B=sc.nextInt(); // int A = 1234567; // int B =1234567; HashMap> visited = new HashMap>(); long total=0; for(int i=A;i<=B;i++){ if(!visited.containsKey(i)) visited.put(i, new LinkedList()); String stringI=String.valueOf(i); for(int j=1;j=A && testInt<=B && testInt!=i){ if(!visited.containsKey(testInt)) visited.put(testInt, new LinkedList()); if(!visited.get(testInt).contains(i)) { total++; visited.get(testInt).add(i); visited.get(i).add(testInt); } } } } System.out.println(total); pw.println(""Case #"" + caseNum + "": "" + total); } pw.flush(); pw.close(); sc.close(); } } " B12800,"import java.io.*; import java.util.*; public class Pairing{ public static void main(String args[]){ try { FileInputStream fstream = new FileInputStream(""textfile.txt""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter ffstream = new FileWriter(""./output.txt""); BufferedWriter out = new BufferedWriter(ffstream); String strLine,result; int i=0; strLine = br.readLine(); i=Integer.parseInt(strLine); String startS, endS; int j=1; int val=0; int start=0,end=0,tt=0; int count=0; PairList lista; Pair res; while (j<=i) { lista = new PairList(); count=0; strLine = br.readLine(); StringTokenizer token = new StringTokenizer(strLine); startS = token.nextToken(); start=Integer.parseInt(startS); endS = token.nextToken(); end=Integer.parseInt(endS); char[] startA = startS.toCharArray(); char[] endA = endS.toCharArray(); char[] temp = new char[endA.length]; char[] newn = new char[endA.length]; int curr=start; boolean adding=false; if(startA.length==endA.length && startA.length>1){ int stop=start+(end-start)/2+1; while(curr<=end){ curr++; temp = Integer.toString(curr).toCharArray(); int k=temp.length-1; while(k>0){ if(temp[k]<=endA[0] && temp[k]>=startA[0]){ int l = k; int m=0; while(l<=temp.length-1){ newn[m]=temp[l]; l++; m++; } l = 0; while (m=start){ res.first=tt; res.second=curr; adding = true; } else if(tt>curr && tt<=end && curr>=start){ res.first=curr; res.second=tt; adding=true; } else adding=false; if(adding==true ){ int place = lista.Find(res,end); if(place 0; j--) { temp[j] = temp[j - 1]; } temp[0] = tempChar; String tempString = new String(temp); // System.out.println(tempString); if (tempString.equals(antras + """") && !tempString.equals(pirmas + """")) { // System.out.println(tempString+""/"" + pirmas); counter++; break; } } // System.out.print(counter); return counter; } } " B13031,"package qualification.common; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; /** * Created by IntelliJ IDEA. * User: ofer * Date: 14/04/12 * Time: 17:31 * To change this template use File | Settings | File Templates. */ public class OutputWriter { public static void writeOutput(String filename,String[] output){ try { FileWriter write = new FileWriter( filename , false); PrintWriter print_line = new PrintWriter( write ); for (String str: output){ print_line.println(str); } print_line.close(); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } } " B11938,"package com.google.codejam; import java.util.HashSet; import java.util.Set; import com.google.codejam.util.CodeJamInputFile; import com.google.codejam.util.CodeJamOutputFile; public class Recycle { /** * @param args */ public static void main(String[] args) { Integer count; CodeJamInputFile f = new CodeJamInputFile(""in/C-small-attempt0.in""); CodeJamOutputFile fo = new CodeJamOutputFile(""out/C-small.out""); for(int c = 0; c < f.getCases(); c++){ count = 0; Set tested = new HashSet(); String[] range = f.getLine().split("" ""); Integer a = Integer.valueOf(range[0]); Integer b = Integer.valueOf(range[1]); for(Integer i = a; i < (b + 1); i++){ String str = i.toString(); tested.add(str.concat(str)); for(int j = 1; j= a && testval <= b){ //System.out.println(str + "" - "" + newstr); count++; } } } fo.writeCase(c, count.toString()); } f.close(); fo.close(); } } " B10644,"import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; public class main { public static void main(String[] args) { // inputファイルを読み込み BufferedReader bufferReader = null; String str = """"; try { bufferReader = new BufferedReader(new InputStreamReader( new FileInputStream(""/Users/yago/Documents/in.txt""), ""UTF-8"")); // 一行ずつ読み込み int probs = 0; while ((str = bufferReader.readLine()) != null) { if (str.length() > 2) { probs++; calc(str, probs); } } } catch (Exception e) { System.out.println(e.getMessage()); } finally { try { if (bufferReader != null) { bufferReader.close(); } } catch (Exception e) { } } } private static void calc(String str, int probNum) { Integer n1, n2, ansCnt = 0; String[] strAry = str.split("" ""); n1 = Integer.valueOf(strAry[0]); n2 = Integer.valueOf(strAry[1]); for (int i = n1; i <= n2; i++) { for (int j = i + 1; j <= n2; j++) { if(String.valueOf(j).length() == 1) break; if (String.valueOf(j).length() == 2) { if (String.valueOf(j).charAt(0) == String.valueOf(i) .charAt(1) && String.valueOf(j).charAt(1) == String.valueOf(i) .charAt(0)) ansCnt++; } else if ((String.valueOf(j).charAt(0) == String.valueOf(i) .charAt(1) && String.valueOf(j).charAt(1) == String.valueOf(i) .charAt(2) && String.valueOf(j).charAt(2) == String .valueOf(i).charAt(0)) || String.valueOf(j).charAt(0) == String.valueOf(i) .charAt(2) && String.valueOf(j).charAt(1) == String.valueOf(i) .charAt(0) && String.valueOf(j).charAt(2) == String.valueOf(i) .charAt(1)) { ansCnt++; } } } System.out.println(""Case #"" + probNum + "": "" + ansCnt); } }" B11317,"package recycledNumbers; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) { File inFile = new File( ""C:\\Users\\Stef\\workspace\\Google Code Jam\\src\\recycledNumbers\\small.in""); FileInputStream fis = null; Scanner in = null; FileWriter outFile; try { outFile = new FileWriter( ""C:\\Users\\Stef\\workspace\\Google Code Jam\\src\\recycledNumbers\\small.out""); BufferedWriter out = new BufferedWriter(outFile); try { fis = new FileInputStream(inFile); in = new Scanner(fis); int cases, a, b, no; cases = in.nextInt(); for (int i = 0; i < cases; i++) { no=0; a=in.nextInt(); b=in.nextInt(); for (int k=a;k<=b-1;k++) for (int j=k+1;j<=b;j++) { if (recycled(k,j)) no++; } out.write(""Case #"" + (i + 1) + "": "" +no+ ""\n""); } fis.close(); in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } out.close(); } catch (IOException e1) { e1.printStackTrace(); } } private static boolean recycled(int k, int j) { int digits=0; int kc=k; int last; int multiply=1; while (kc>0) { digits++; multiply*=10; kc/=10; } multiply/=10; for (int i=0;i 0) { // long s = System.currentTimeMillis(); int res = 0; String[]parts = br.readLine().split(""\\s+""); int A = Integer.parseInt(parts[0]); int B = Integer.parseInt(parts[1]); for(int n = A; n <= B; n++){ Set set = new HashSet(); char[]num = (n+"""").toCharArray(); for(int i = 1; i < num.length; i++){ if(num[i]=num.length)j = 0; len++; } int m = Integer.parseInt(sb.toString()); if(m>n&&m>=A&&m<=B){ set.add(n+"",""+m); } } res+=set.size(); } System.out.println(""Case #""+(init-t)+"": "" + res); // System.out.println(System.currentTimeMillis()-s); } } } " B12806,"import java.io.File; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Scanner; import java.util.Set; public class C { /** * @param args */ public static void main(String[] args) throws Exception { Scanner in = new Scanner(new File(""d:\\cc.small.in""));// new Scanner(new // File(""d:\\b.small.in"")); // in = new Scanner(new File(""d:\\Minimum Scalar Product-big.in"")); int testCases = in.nextInt(); in.nextLine(); for (int cas = 1; cas <= testCases; cas++) { int ans = 0; int A = in.nextInt(); int B = in.nextInt(); // in.nextLine(); Map> map = new HashMap>(); for (int n = A; n < B; n++) { String sn = """" + n; int len = sn.length(); for (int i = 1; i < len; i++) { String front = sn.substring(0, i); String rear = sn.substring(i, len); int m = Integer.parseInt(rear + front); if (A <= n && n < m && m <= B) { Set s = map.get(n); if (null == s) { ans++; s = new HashSet(); s.add(m); map.put(n, s); } else { if (s.add(m)) ans++; } // System.err.printf(""n:%d,m:%d\n"",n,m); } } } System.out.printf(""Case #%d: %d\n"", cas, ans); } } } " B11055,"package fixjava; /** * Convenience class for declaring a method inside a method, so as to avoid code duplication without having to declare a new method * in the class. This also keeps functions closer to where they are applied. It's butt-ugly but it's about the best you can do in * Java. */ public interface LambdaVoid

{ public void apply(P param); } " B12456,"import java.io.*; import java.util.StringTokenizer; public class klick { public static void main(String []args) { try{ FileInputStream fstream = new FileInputStream(""input.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; int n=0; int i; while ((strLine = br.readLine()) != null) { n=n+1; if (n==1) i = Integer.parseInt(strLine); else System.out.println (parse(strLine,n-1)); } in.close(); }catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } private static String parse(String string1,int oo) { String str=""""; int count =0; long aa = 0; long bb = 0; StringTokenizer stringTokenizer = new StringTokenizer(string1); while(stringTokenizer.hasMoreTokens()) { aa = Integer.parseInt(stringTokenizer.nextToken()); bb = Integer.parseInt(stringTokenizer.nextToken()); } for (long i = aa ; i < bb; i = i+1) { ///////////// if(i<10) { count = 0; } ///////////////////////// else if(i>=10 && i<100) { int m = (int) (i/10); int n = (int) (i%10); int nm = 10*n + m; if(i=100 && i<1000) { int mn = (int) (i/10); int z = (int) (i%10); int zmn = 100*z + mn; if(i=1000 && i<10000) { int mnz = (int) (i/10); int t = (int) (i%10); int tmnz = 1000*t + mnz; if(i=10000 && i<100000) { int mnzt = (int) (i/10); int w = (int) (i%10); int wmnzt = 10000*w + mnzt; if(i=100000 && i<1000000) { int mnzt = (int) (i/10); int w = (int) (i%10); int wmnzt = 100000*w + mnzt; if(i=1000000 && i<10000000) { int mnzt = (int) (i/10); int w = (int) (i%10); int wmnzt = 1000000*w + mnzt; if(i=10000000 && i<100000000) {} else {} ////////////// } return ""Case #""+oo+"": ""+count; } } " B11335,"public interface Problem { void solve(); Object getSolution(); } " B13256,"package ru.bobukh.problems; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.Comparator; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; /** * * @author anton.bobukh */ public class ProblemC_RecycledNumbers { public static class Pair { public final int n; public final int m; public Pair(int n, int m) { this.n = n; this.m = m; } } public static class PairComparator implements Comparator { @Override public int compare(Pair o1, Pair o2) { if(o1.m - o2.m != 0) return o1.m - o2.m; else return o1.n - o2.n; } } public static void main(String[] args) throws IOException { try (Scanner input = new Scanner(new BufferedReader(new FileReader(""C:\\Users\\maggot\\Desktop\\C-small-attempt0.in"")))) { int T = input.nextInt(); input.nextLine(); try(PrintWriter output = new PrintWriter(""C:\\Users\\maggot\\Desktop\\output.txt"")) { for(int k = 0; k < T; ++k) { Set pairs = new TreeSet<>(new PairComparator()); int A = input.nextInt(); int B = input.nextInt(); int numberOfDigits = 1; int value = A; while((value = value / 10) > 0) ++numberOfDigits; for(int n = A; n <= B; ++n) { for(int power = 0; power < numberOfDigits; ++power) { int m = n % (int)Math.pow(10, power + 1) * (int)Math.pow(10, numberOfDigits - power - 1) + n / (int)Math.pow(10, power + 1); if(n < m && m <= B) pairs.add(new Pair(n, m)); } } output.println(String.format(""Case #%d: %d"", k + 1, pairs.size())); } } } } } " B12455,"import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.util.Scanner; public class RecycledNumbers { public static int[] getM(int n) { String s = n + """"; int M[] = new int[s.length() - 1]; // System.out.println(M.length); for (int i = 1; i < M.length + 1; i++) { String temp = """"; temp = s.substring(s.length() - i, s.length()) + s; M[i - 1] = Integer.parseInt(temp.substring(0, s.length())); // System.out.println(M[i-1]); } return M; } public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new File(""C-small-attempt0.in"")); // Scanner in = new Scanner(System.in); BufferedWriter out = null; try { FileWriter fstream = new FileWriter(""out.txt""); out = new BufferedWriter(fstream); int cases = in.nextInt(); int A; int B; for (int i = 0; i < cases; i++) { int result = 0; A = in.nextInt(); B = in.nextInt(); for (int j = A; j < B + 1; j++) { int[] Ms = getM(j); for (int k = 0; k < Ms.length; k++) { if (Ms[k] > j && Ms[k] <= B) { // System.out.println(j + "" "" + Ms[k]); result++; } } } // int answer = result + tempo; out.write(""Case #"" + (i + 1) + "": "" + result + ""\n""); System.out.println(""Case #"" + (i + 1) + "": "" + result); } out.close(); } catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } } " B12443,"import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class Main { public static void main(String[] args) throws IOException { Scanner scan = new Scanner(new File(""input"")); PrintWriter out = new PrintWriter(new BufferedWriter (new FileWriter(""output""))); int T = scan.nextInt(); int compteur =1; while(T-->0){ int A = scan.nextInt(); int B=scan.nextInt(); int nbDig = (A+"""").length(); int pui = 1; for(int i=0;ii&&u<=B&&deja){ rec++; } } } out.println(""Case #""+compteur+"": ""+rec); compteur++; } out.close(); } } " B11164,"import java.io.*; import java.util.*; class RecycledNumbers { public static void main(String args[]) throws Exception { Scanner in = new Scanner(new File(""C-small-attempt0.in"")); int t = Integer.parseInt(in.nextLine()); for(int x = 1; x <= t; x++) { String st = in.nextLine(); int a, b; a = Integer.parseInt(st.split("" "")[0]); b = Integer.parseInt(st.split("" "")[1]); int y = 0; if(a >= 10) { for(int i = a; i < b; i++) { int n, m; n = i; String tmp = """" + n; for(m = (n + 1); m <= b; m++) { for(int j = 1; j < tmp.length(); j++) { int tt = getNew(n, j); if(tt == m && ("""" + tt).length() == ("""" + m).length() && a <= n && n < m && m <= b) y++; } } } } System.out.println(""Case #"" + x + "": "" + y); } } public static int getNew(int n, int a) { String s = """" + n; int p = s.length() - a; String s2 = s.substring(p); String s3 = s.substring(0, p); s = s2 + s3; return Integer.parseInt(s); } }" B12843,"import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Formatter; import java.util.Scanner; public class G3 { private static Scanner inp; private static Formatter out; private static int T = 0; private static int A = 0; private static int B = 0; private static int cnt = 0; private static ArrayList arr; private static ArrayList arr2; public static void main(String[] args) { try { inp = new Scanner(new File(""test.txt"")); } catch (FileNotFoundException e) { System.out.println(""File not found!""); } try { out = new Formatter(""out.txt""); } catch (FileNotFoundException e) { System.out.println(""File not found!""); } T = inp.nextInt(); inp.nextLine(); arr = new ArrayList(); arr2 = new ArrayList(); for(int i = 0; i < T; i++) { out.format(""Case #%d: "", i+1); A = inp.nextInt(); B = inp.nextInt(); cnt = 0; arr.clear(); arr2.clear(); for(int j = A; j <= B; j++) { for(int k = 1; k < Math.ceil(Math.log10(j)); k++) { int tmp = move(j,k); //(arr.indexOf(tmp) == -1 || arr.indexOf(j) == -1) if(tmp >= A && tmp <= B && (arr2.indexOf(tmp+""""+j) == -1 || arr2.indexOf(j+""""+tmp) == -1) && tmp != j) { cnt++; arr.add(j); arr.add(tmp); arr2.add(tmp+""""+j); arr2.add(j+""""+tmp); //System.out.println(j+"":""+tmp); //break; } } } out.format(""%d\r\n"", cnt); //System.out.println(""Case #""+(i+1)+"": ""+cnt); } inp.close(); out.close(); } public static int move(int n1, int n0) { int n2 = n1 % (int) Math.pow(10, n0); double n3 = Math.floor(Math.log10(n1)); int n4 = (n1 - n2) / (int) Math.pow(10, n0); double n5 = Math.pow(10, n3+1-n0) * n2; double n6 = n5 + n4; return (int) n6; } } " B12350,"import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { public static void main(String[] args) { Scanner sc = null; try { sc = new Scanner(new File(""./C-small-attempt0.in"")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } int numTestCases = Integer.parseInt(sc.nextLine()); String eachTest = """"; StringBuilder result = new StringBuilder(); for(int i = 0; i < numTestCases; ++i) { eachTest = sc.nextLine(); result.append(String.format(""Case #%s: "", i+1)); result.append(compute(eachTest)); result.append(""\n""); } try { FileWriter fileWriter = new FileWriter(""./output""); fileWriter.write(result.toString()); fileWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return; } private static int compute(String input) { String[] pieces = input.split("" ""); int A = Integer.parseInt(pieces[0]); int B = Integer.parseInt(pieces[1]); return compute(A, B); } public static int compute(int A, int B) { Set set = new HashSet(); int digitLen = ("""" + A).length(); int m = 0; for(int n = A; n <= B; ++n) { for(int i = 1; i < digitLen; ++i) { m = shift(n, i); if(m > n && m <= B) { set.add(n + ""-"" + m); } } } return set.size(); } static int shift(int n, int i) { String word = """" + n; int len = word.length(); int shift = len - i - 1; if(len < 2) { return n; } else if(len == 2) { String a = new String(word.charAt(1) + """"); String b = new String(word.charAt(0) + """"); return Integer.parseInt( a + b); } return Integer.parseInt(word.substring(shift + 1) + word.substring(0, shift + 1)); } } " B10792," import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; public abstract class TestCase { public abstract void readInput(BufferedReader in) throws IOException, MalformedInputFileException; public abstract void solve(); public abstract void writeOutput(PrintWriter out); }" B11996,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class RecycledNumbers { public static void main ( String [] arg ) throws NumberFormatException, IOException{ BufferedReader reader = new BufferedReader(new FileReader(new File(""input""))); PrintWriter output = new PrintWriter(new File(""output"")); int cases = Integer.valueOf( reader.readLine() ); for ( int c=1; c<=cases; c++ ){ StringTokenizer tkn = new StringTokenizer( reader.readLine() ); int a = Integer.valueOf( tkn.nextToken() ); int b = Integer.valueOf( tkn.nextToken() ); int sol=0; //Set superMap = new HashSet(); for ( int k=a; k aux = new HashSet(); String sr = k + """"; for ( int i=1; i= 0 && c < ns.length()) { id = ns.indexOf(ms.charAt(0), c); if(id >= 0) { int i = 0; boolean worked = true; for(int firstPass = id; firstPass < ns.length(); firstPass++) { if(ms.charAt(i++) != ns.charAt(firstPass)) { worked = false; break; } } if(worked) { for(int secondPass = 0; secondPass < id; secondPass++) { if(ms.charAt(i++) != ns.charAt(secondPass)) { worked = false; break; } } } if(worked) { System.err.println(""found: "" + ns + "", "" + ms); return 1; } c = id + 1; } } return 0; } } " B12187,"import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; import javax.swing.text.html.HTMLDocument.HTMLReader.HiddenAction; public class RecycledNumbers { public static void main(String[] argStrings) { Scanner in = new Scanner(System.in); int num = Integer.parseInt(in.nextLine()); String[] inputStrings = new String[num]; String[] outputStrings = new String[num]; for (int i = 0; i < num; i++) { inputStrings[i] = in.nextLine(); } for (int i = 0; i < inputStrings.length; i++) { String[] numStrings = inputStrings[i].split("" ""); int start = Integer.parseInt(numStrings[0]); int end = Integer.parseInt(numStrings[1]); int count = 0; for (int j = 0; j < end - start + 1; j++) { Integer x = start + j; int[] sequenceArrayInteger = reverse(x); for (int k = 0; k < sequenceArrayInteger.length; k++) { int xNum = sequenceArrayInteger[k]; if (xNum >= start && xNum <= end) { count++; } } } outputStrings[i] = ""Case #"" + (i + 1) + "": "" + count; } for (String string : outputStrings) { System.out.println(string); } } public static int[] reverse(Integer num) { String string = num.toString(); int[] retArray = new int[num.toString().length() - 1]; for (int i = 0; i < retArray.length; i++) { char x = string.charAt(string.length() - 1); string = x + string.substring(0, string.length() - 1); if(Integer.parseInt(string) > num) retArray[i] = Integer.parseInt(string); } return retArray; } } " B10738,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package googlecodejamproblemc; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; /** * * @author Fluffy Dragon */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { File inputFile = new File(""C-small-attempt0.in""); File outputFile = new File(""output.txt""); FileReader fr = null; try { fr = new FileReader(inputFile); BufferedReader br = new BufferedReader(fr); FileWriter fw = new FileWriter(outputFile, false); BufferedWriter bw = new BufferedWriter(fw); int count = Integer.parseInt(br.readLine()); for (int i = 0; i < count; i++) { String readLine = br.readLine(); String[] split = readLine.split(""\\s""); int[] input = new int[split.length]; for (int i2 = 0; i2 < split.length; i2++) { input[i2] = Integer.parseInt(split[i2]); } String output = calculate(i + 1, input); bw.write(output); if (i + 1 < count) { bw.newLine(); } } br.close(); fr.close(); bw.close(); fw.close(); } catch (FileNotFoundException e) { } catch (IOException e) { } } private static String calculate(int count, int[] input) { String output = ""Case #"" + count + "": ""; int a = input[0]; int b = input[1]; int[] availableNumbers = new int[b - a + 1]; for (int i = 0; i <= (b - a); i++) { availableNumbers[i] = i + a; } ArrayList passed = new ArrayList(0); for (int n : availableNumbers) { ArrayList used = new ArrayList(0); String intAsString = String.valueOf(n); for (int i = intAsString.length() - 1; i > 0; i--) { String endSubString = intAsString.substring(i, intAsString.length()); String startSubString = intAsString.substring(0, i); String mixString = endSubString.concat(startSubString); int m = Integer.parseInt(mixString); if (a <= n && n < m && m <= b && a < b) { //System.out.println(mix); if (String.valueOf(m).length() == intAsString.length()) { for (int check : availableNumbers) { if (check == m) { if (!used.contains(mixString)) { used.add(mixString); passed.add(mixString); break; } } } } } } } for (String temp : passed) { //System.out.println(temp); } System.out.println(passed.size()); output = output.concat(String.valueOf(passed.size())); return output; } } " B12430,"import java.io.*; import java.util.*; public class CodeJamC { public static void main (String[] args) throws IOException { int i, j, k; long startTime = System.currentTimeMillis(); File inFile = new File(""C-small-attempt0.in""); // File to read from File outFile = new File(""C-small.out""); BufferedReader reader = new BufferedReader(new FileReader(inFile)); BufferedWriter writer = new BufferedWriter(new FileWriter(outFile)); String line = null; line = reader.readLine(); int cases = Integer.parseInt(line); int counter = 1; while ((line=reader.readLine()) != null) { int A,B; int pairs = 0; String[] node = line.split("" ""); A = Integer.parseInt(node[0]); B = Integer.parseInt(node[1]); if ((node[0].length() == 1) || (A == B)) { ; } else if (node[0].length() == 2) { for(i = A; i <= B; i++) { int oneth = i % 10; int tenth = i /10; int newNum = oneth*10+tenth; if(newNum > i && newNum <= B) pairs++; } } else if (node[0].length() == 3) { for(i = A; i <= B; i++) { int oneth = i % 10; int tenth = (i /10) % 10; int hunth = i /100; int newNum1 = oneth*100+hunth*10+tenth; int newNum2 = tenth*100+oneth*10+hunth; if(newNum1 > i && newNum1 <= B) pairs++; if(newNum2 > i && newNum2 <= B) pairs++; } } //System.out.println(""Case #""+counter+"": ""+pairs); writer.write(""Case #""+counter+"": ""+pairs); writer.newLine(); counter++; } writer.close(); long endTime = System.currentTimeMillis(); long totalTime = endTime - startTime; System.out.println(""Total Time: "" + totalTime); } } " B12406,"import java.util.*; public class QualC12 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int i = 1; i <= T; i++) { int A = in.nextInt(); int B = in.nextInt(); int npairs = 0; for (int j = A; j <= B; j++) { String s = String.valueOf(j); String ns = s + s; boolean containsRepeat = false; for (int k = 1; k < s.length(); k++) { String rot = ns.substring(k, k + s.length()); int rnum = Integer.valueOf(rot); if (rnum > j && rnum <= B && String.valueOf(rnum).length() == s.length()) { if (containsRepeat(s)) containsRepeat = true; ++npairs; } } if (containsRepeat) --npairs; } System.out.println(""Case #"" + i + "": "" + npairs); } } private static boolean containsRepeat(String s) { if (s.length() % 2 != 0) return false; if (s.substring(0, s.length()/2).equals(s.substring(s.length()/2, s.length()))) { return true; } else return false; } }" B11196,"import java.io.*; import java.util.*; public class C implements Runnable { //private String IFILE = ""input.txt""; private String IFILE = ""C-small-attempt0.in""; private Scanner in; private PrintWriter out; public void Run() throws IOException { in = new Scanner(new File(IFILE)); out = new PrintWriter(""output.txt""); int ntest = in.nextInt(); for(int test = 1; test <= ntest; test++) { out.print(""Case #"" + test + "": ""); int a = in.nextInt(); int b = in.nextInt(); int result = 0; for(int i = a; i <= b; i++) { int z = 1; while (z * 10 <= i) z *= 10; int ii = i; while (true) { ii = ii / 10 + (ii % 10) * z; if (ii == i) break; if (ii % z > 0 && i < ii && ii <= b) result++; } } out.println(result); } in.close(); out.close(); } public void run() { try { Run(); } catch(IOException e) { } } public static void main(String[] args) throws IOException { new C().Run(); //new Thread(new XXX()).start(); } } " B12176,"/** * * @author Tag */ /* * Given integers A and B with the same number of digits and no leading zeros, how many distinct recycled pairs (n, m) are there with A ≤ n < m ≤ B? * Input * The first line of the input gives the number of test cases, T. T test cases follow. Each test case consists of a single line containing the integers A and B. * * Output * For each test case, output one line containing ""Case #x: y"", where x is the case number (starting from 1), and y is the number of recycled pairs (n, m) with A ≤ n < m ≤ B.\ * * Sample * Input Output * 4 * 1 9 Case #1: 0 * 10 40 Case #2: 3 * 100 500 Case #3: 156 * 1111 2222 Case #4: 287 */ import java.util.Scanner; public class RecycledNumbers { public static void main(String args[]) { Scanner input = new Scanner(System.in); int numTests = new Integer(input.nextLine()); int recycledPairs; for(int i = 1; i <= numTests; i++) { String[] tokens = input.nextLine().split("" ""); Integer smallerNum = new Integer(tokens[0]); Integer biggerNum = new Integer(tokens[1]); recycledPairs = calcRecycled(smallerNum, biggerNum); System.out.println(""Case #"" + i + "": "" + recycledPairs); } } private static int calcRecycled(Integer smallerNum, Integer biggerNum) { int recycledPairs = 0; while(smallerNum < biggerNum) { String toCheck = smallerNum.toString(); Integer tmpBigger = new Integer(biggerNum); while(smallerNum < tmpBigger) { String biggerStr = tmpBigger.toString(); for(int i = 1; i < biggerStr.length(); i++) { if((biggerStr.substring(biggerStr.length() - i) + biggerStr.substring(0, biggerStr.length() - i)).equals(toCheck)) { recycledPairs++; } } tmpBigger--; } smallerNum++; } return recycledPairs; } } " B11314,"/** * Copyright 2012 Christopher Schmitz. All Rights Reserved. */ package com.isotopeent.codejam.lib; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; public class SolutionWriter extends PrintWriter { private static final String FORMAT = ""Case #%1$s: %2$s%n""; private String[] args = new String[2]; public SolutionWriter(File file) throws FileNotFoundException { super(file); } public void writeSolution(int caseNumber, String solution) { args[0] = Integer.toString(caseNumber); args[1] = solution;; printf(FORMAT, (Object[]) args); } } " B13151,"import java.io.*; class RecycledNumbers { void main()throws IOException { BufferedReader obj= new BufferedReader(new FileReader(""C-small-attempt0.in"")); PrintWriter p= new PrintWriter(new BufferedWriter(new FileWriter(""output.txt""))); int T=Integer.parseInt(obj.readLine()); long a,b,n,m,q,order,i,count=0;String s; for(i=1;i<=T;i++) { s=obj.readLine(); a=Integer.parseInt(s.substring(0,s.length()/2)); b=Integer.parseInt(s.substring(s.length()/2+1,s.length())); order=s.length()/2; for(n=a;n<=b;n++) { for(q=1;qn&&m<=b) count++; } } p.println(""Case #""+i+"": ""+count); count=0; } p.flush(); p.close(); } } " B12671," import java.io.*; import java.util.*; public class rec { public static void main (String [] args) throws Exception { BufferedReader f = new BufferedReader(new FileReader(""rec.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""rec.out""))); int N = Integer.parseInt(f.readLine()); for(int ie = 0; ie()); // s.get(""""+i).add(""""+j); // } for(String e:s.keySet()) count+=s.get(e).size(); out.println(""Case #""+(ie+1)+"": ""+count); } out.close(); System.exit(0); } static Map> s = new TreeMap>(); static int cont(int w, int a, int b){ int c = 0; String e = w+""""; if(e.charAt(0) == '0') return 0; for(int i = 1; i=a && q<= b && q()); s.get(""""+q).add(""""+w); } } return c; } static boolean o(String a, String b){ int pos = 0; while(pos currentNumber && permutedInt <=endNumber) { count++; } } return count; } public static void shiftRight(char[] array, int amount) { for (int j = 0; j < amount; j++) { char a = array[array.length - 1]; int i; for (i = array.length - 1; i > 0; i--) array[i] = array[i - 1]; array[i] = a; } } } " B12804,"import java.io.*; import java.util.*; public class Recycle { public static void main(String[] args) throws FileNotFoundException, IOException { Scanner sc = new Scanner(new File(""input.in"")); FileWriter fstream = new FileWriter(""out.txt""); BufferedWriter out = new BufferedWriter(fstream); int T = sc.nextInt(); // number of cases int A; int B; int counter; int m; String nStr = """"; String mStr = """"; String front = """"; String back = """"; for(int i = 1; i <= T; i++) { // for each test case A = sc.nextInt(); B = sc.nextInt(); counter = 0; for(int n = A; n <= B; n++) { // at most 899 loops nStr = Integer.toString(n); if(nStr.charAt(0) == '0') continue; // create m for(int j = 1; j < nStr.length(); j++) { // at most 3 loops front = nStr.substring(0, j); back = nStr.substring(j); mStr = back.concat(front); if(mStr.charAt(0) == '0') continue; m = Integer.parseInt(mStr); if(n >= A && n < m && m <= B) counter++; } } out.write(""Case #"" + i + "": "" + counter); if(i != T) out.newLine(); } out.close(); } } " B12783,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * * @author Anirban */ public class RecycledNumbers { public static boolean check(String n, String m, int len){ for(int i = 0; i < len; i++){ if(m.compareTo(n.substring(i, i + len)) == 0) return true; } return false; } public static void main(String [] args)throws IOException{ InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); int tc = 1; int T = Integer.parseInt(br.readLine()); while(T-- > 0){ int count = 0; StringTokenizer st = new StringTokenizer(br.readLine(), "" ""); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); for(int i = A; i <= B; i++){ for(int j = i + 1; j <= B; j++){ String n = i + """" ; int len = n.length(); n += n; String m = j + """"; if(check(n, m, len)) count++; } } System.out.printf(""Case #%d: %d"", tc, count); System.out.println(); tc++; } } } " B12661,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Hashtable; public class MainJam2 { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(""C:\\Jam\\teste.txt"")); File file = new File(""C:\\Jam\\saida.txt""); FileWriter print = new FileWriter(file); int i = Integer.parseInt(in.readLine()); int k = i; while(i > 0){ ArrayList list = new ArrayList(); int resp = 0; String integer [] = in.readLine().split("" ""); int ini = Integer.parseInt(integer[0]); int end = Integer.parseInt(integer[1]); for(int j = ini; j <= end; j++){ String reverse = """"+j; String ini_reverse = reverse; do{ String ini_s = reverse.substring(0, 1); reverse = reverse.substring(1, reverse.length()) + ini_s; int int_reverse = Integer.parseInt(reverse); if(reverse.equals(ini_reverse)) break; if(int_reverse <= end && int_reverse >= ini && !list.contains(reverse)){ System.out.println((k - i + 1)+"" : ""+reverse + "" "" + j); list.add(""""+j); resp++; } } while(!reverse.equals(ini_reverse)); } print.write(""Case #""+ (k - i + 1) +"": ""+resp+System.getProperty(""line.separator"")); i--; } print.close(); } } " B12310,"package com.brootdev.gcj2012.common; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; public class DataUtils { public static long readLongLine(BufferedReader in) throws IOException { return Long.valueOf(in.readLine()); } public static long[] readLongsArrayLine(BufferedReader in) throws IOException { String[] numsS = in.readLine().split(""\\s+""); long[] nums = new long[numsS.length]; for (int i = 0; i < nums.length; i++) { nums[i] = Long.valueOf(numsS[i]); } return nums; } public static void writeCaseHeader(PrintWriter out, long case_) { out.print(""Case #""); out.print(case_ + 1); out.print("": ""); } } " B11744,"import java.io.*; import java.util.Scanner; /** * Created by IntelliJ IDEA. * User: tanin * Date: 4/14/12 * Time: 9:54 AM * To change this template use File | Settings | File Templates. */ public class Recycled { public static void main(String[] args) throws Exception { String filename = ""Recycled/recycled""; String outFilename = filename + ""_out""; FileInputStream fis = new FileInputStream(new File(filename)); Scanner input = new Scanner(new BufferedInputStream(fis)); FileOutputStream fOut = new FileOutputStream(new File(outFilename)); BufferedOutputStream bOut = new BufferedOutputStream(fOut); DataOutputStream out = new DataOutputStream(bOut); int numCases = input.nextInt(); input.nextLine(); for (int caseNumber=0;caseNumber= multiple && a <= run && run <= b) { checked[run] = true; countValid++; //System.out.println(run); } run = next(run, multiple); } if (countValid == 1) continue; //System.out.println(number); count += countValid * (countValid - 1) / 2; } return count; } public static int getMultiple(int s) { if (s < 10) return 1; else if (s < 100) return 10; else if (s < 1000) return 100; else if (s < 10000) return 1000; else if (s < 100000) return 10000; else if (s < 1000000) return 100000; else if (s < 10000000) return 1000000; else { System.out.println(""Fuck you""); return -100000000; } } public static int next(int s, int multiple) { int residue = s % 10; return residue * multiple + s / 10; } } " B12132," public class Pair { int first; int second; public Pair(int first, int second) { this.first = first; this.second = second; } } " B11715,"import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.Scanner; public class CodeJamWriter implements ICounterZeroEvent{ //public static String inputFile = ""C:\\Users\\user\\Desktop\\coejam\\2012-Qualificaton\\A-test""; //public static String inputFile = ""C:\\Users\\user\\Desktop\\coejam\\2012-Qualificaton\\A-small-attempt0""; //public static String inputFile = ""C:\\Users\\user\\Desktop\\coejam\\2012-Qualificaton\\B-test""; //public static String inputFile = ""C:\\Users\\user\\Desktop\\coejam\\2012-Qualificaton\\B-small-attempt0""; //public static String inputFile = ""C:\\Users\\user\\Desktop\\coejam\\2012-Qualificaton\\B-large""; //public static String inputFile = ""C:\\Users\\user\\Desktop\\coejam\\2012-Qualificaton\\C-test""; public static String inputFile = ""C:\\Users\\user\\Desktop\\coejam\\2012-Qualificaton\\C-small-attempt0""; //public static String inputFile = ""C:\\Users\\user\\Desktop\\coejam\\2012-Qualificaton\\C-large""; public int T; public Result[] results; public static void main(String[] args) { CodeJamWriter codeJamWriter = new CodeJamWriter(); codeJamWriter.readInput(); } private void readInput() { Scanner scanner = null; File input = new File(inputFile+"".in""); try { scanner = new Scanner(input); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } T = scanner.nextInt(); scanner.nextLine(); results = new Result[T+1]; Counter counter = new Counter(T, this); for (int i=1;i<=T;++i) { results[i] = new Result(i); Question q = new QuestionC(results[i], counter); q.readInput(scanner); q.start(); } scanner.close(); } private void writeOutput() { FileOutputStream fos = null; PrintStream printer = null; File output = new File(inputFile+"".out""); try { fos = new FileOutputStream(output); printer = new PrintStream(fos); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } for (int i=1;i<=T;++i) { printer.println(results[i]); } System.out.println(""FINISHED!!!""); printer.close(); } @Override public void fireEvent() { writeOutput(); } } " B12784,"import java.io.*; import java.util.*; public class Solve { public static void main ( String args[] ) throws FileNotFoundException, IOException { BufferedReader in = new BufferedReader( new FileReader ( args[0] ) ); BufferedWriter out = new BufferedWriter( new FileWriter ( ""outfile.txt"" ) ); int cases = Integer.parseInt( in.readLine() ); String[] tmp; int low, high, multiplier, shift, rest, pairs; HashSet used; for ( int i = 1; i <= cases; i++ ) { pairs = 0; tmp = in.readLine().split( "" "" ); low = Integer.parseInt( tmp[0] ); high = Integer.parseInt( tmp[1] ); multiplier = 1; for ( int j = 1; j < tmp[0].length(); j++ ) { multiplier *= 10; } for ( int j = low; j < high; j++ ) { shift = j; used = new HashSet(); for ( int k = 0; k < tmp[0].length(); k++ ) { rest = shift % 10; shift /= 10; shift += rest * multiplier; if ( j < shift && shift <= high ) { if ( !used.contains( shift ) ) { pairs++; used.add( shift ); } } } } out.write( ""Case #"" + i + "": "" + pairs ); out.newLine(); out.flush(); } in.close(); out.close(); } } " B11968,"import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; import java.util.StringTokenizer; public class CodeJam3 { private static HashMap map = new HashMap(); private static ArrayList results = new ArrayList(); public static void main (String args[]) throws IOException { Scanner scanner = new Scanner(args[0]); int numToParse = Integer.parseInt(scanner.nextLine()); for (int i = 0; i < numToParse; i++) { int count = 0; String string = scanner.nextLine(); StringTokenizer st = new StringTokenizer(string); int firstInt = Integer.parseInt(st.nextToken()); int secondInt = Integer.parseInt(st.nextToken()); String s = """" + firstInt; int length = s.length(); for (int j = firstInt; j <= secondInt; j++) { ArrayList list = new ArrayList(); for (int k = 1; k < length; k++) { String localString = """" + j; String sub1 = localString.substring(0, k); String sub2 = localString.substring(k, length); String newString = sub2 + sub1; int integer = Integer.parseInt(newString); if (!list.contains(integer) && integer > j && integer <= secondInt) { count++; list.add(integer); } } } String result= ""Case #"" + (i + 1) + "": "" + count; System.out.println(result); } } } " B11428,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; /** * * @author Suarabh Agarwal */ import java.io.*; import java.util.Scanner; public class Main3 { public static void main(String args[]) { try{ Scanner scan1 = new Scanner(new FileReader(""src//codejam///input"")); // Scanner scan1 = new Scanner(new FileReader(""input"")); //Scanner scan2 = new Scanner(new FileReader(""output"")); //Scanner scan3 = new Scanner(new FileReader(""test.in"")); PrintWriter out = new PrintWriter(""output1.txt""); String T = scan1.nextLine(); int test_case = Integer.parseInt(T); int count = test_case; //int answer = 0; while(count>0) { int A = scan1.nextInt(); int B = scan1.nextInt(); int temp[] = new int[3]; int temp1[] = new int[3]; int temp2[] = new int[3]; //System.out.print(a[0]); //System.out.print(a[1]); //System.out.println(a[2]); int answer = 0; int count1 = B-A; int num = A; while(count1>=0) { // System.out.println(num); temp[0]=num/100; temp[1]=(num%100)/10; temp[2]=(num%100)%10; // System.out.print(temp[0]); // System.out.print(temp[1]); // System.out.println(temp[2]); if(temp[0]!=0) { temp1[0]=temp[2]; temp1[1]=temp[0]; temp1[2]=temp[1]; int num1= temp1[0]*100+temp1[1]*10+temp1[2]; if(num1>num && num1<=B) { answer++; } temp2[1]=temp[2]; temp2[2]=temp[0]; temp2[0]=temp[1]; int num2= temp2[0]*100+temp2[1]*10+temp2[2]; if(num2>num && num2<=B) { answer++; } } else if(temp[1]!=0) { // temp1[0]=temp[2]; temp1[1]=temp[2]; temp1[2]=temp[1]; int num1= temp1[1]*10+temp1[2]; if(num1>num && num1<=B) { answer++; } } num++; count1--; } out.println(""Case #""+(test_case-count+1)+"": ""+ answer); count--; } out.close(); } catch(Exception e) { System.err.println(""Error: "" + e.getMessage()); } } }" B10632,"package assignments; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import base.Assignment; public class AssignmentC implements Assignment { private int min; private int max; @Override public String solve() { int total = 0; int length = (int) Math.log10(min) + 1; for (int i = min; i < max; i++) { List counted = new ArrayList(); for (int j = 1; j < length; j++) { int shifted = shift(i, j, length); if (shifted > i && shifted <=max && !counted.contains(shifted)) { counted.add(shifted); total++; } } } return Integer.toString(total); } private int shift(int i, int shift, int length) { int temp = (int) Math.pow(10, shift); int result = (i % temp) * ((int)Math.pow(10, length - shift)) + ((int)i / temp); return result; } public static Assignment createFromScanner(Scanner scanner) { AssignmentC assignment = new AssignmentC(); assignment.min = scanner.nextInt(); assignment.max = scanner.nextInt(); return assignment; } } " B10896,"package com.google.codejam; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class ProblemB { /** * @param args */ public void calculate(int numTestCase, int a, int b){ int count = 0 ; if(b<10 || a==b) count = 0; else{ for ( int i=a ; i <= b; i++){ String num = String.valueOf(i); String correctNum = String.valueOf(i); String finalStr ="""" ; while(!correctNum.equals(finalStr)){ String first = num.substring(0,1); String rest = num.substring(1); finalStr = rest+first ; num = finalStr ; if(finalStr.startsWith(""0"") || first.equals(rest)) continue; int num2 = Integer.parseInt(finalStr); if(num2<=b && num2!=i && i0; i--){ newNumStr = numStr.substring(i)+numStr.substring(0, i); newNum = Integer.parseInt(newNumStr); if (newNum < a || newNum > b ||isChecked[newNum-a]) continue; else { isChecked[newNum-a] = true; numPairs++; } } if (numPairs >2){ numPairs = getFactorial(numPairs) / ((getFactorial(numPairs-2)*2)); }else if (numPairs ==2){ numPairs = 1; } else { numPairs = 0; } totalPairs += numPairs; } return totalPairs; } private static int getFactorial(int n){ int result = 1; while (n > 1){ result *= n; n--; } return result; } } " B11894,"import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; public class gcj2012PBS { public String recycle(String num, int cycle) { if (cycle == 0) { return num; } String s = String.valueOf(num); int len = s.length(); String temp = s.substring(len-1,len); String temp2 = s.substring(0,len-1); String result = temp+ temp2; return recycle(result, cycle-1); } public static void main(String[] args) { gcj2012PBS gc = new gcj2012PBS(); String filenameIn = ""C-small-attempt0.in""; String filenameOut = ""C-small-attempt0.out""; FileIn fi = new FileIn(filenameIn); String s = fi.getString(); String ss[] = s.split(""\n""); StringBuilder sb = new StringBuilder(); int z = Integer.valueOf(ss[0]); boolean flag[] = new boolean[2000000]; for (int i = 1; i <= z; i++) { Arrays.fill(flag, false); String tt[] = ss[i].split("" ""); int a = Integer.valueOf(tt[0]); int b = Integer.valueOf(tt[1]); int answer = 0; String A = """"; String B = """"; A = String.valueOf(a); //桁数の取得 int keta = A.length(); if (keta == 1) { sb.append(""Case #""); sb.append(i); sb.append("": ""); sb.append(answer); sb.append(""\n""); continue; } String ppp; String ooo; for(int x = a; x <= b; x ++) { boolean aaaaa=false; ppp = String.valueOf(x); ooo = ppp.substring(0, 1); for (int ok = 1; ok < keta ; ok++) { if(!ooo.equals(ppp.substring(ok,ok+1))) { aaaaa = true; break; } } if(!aaaaa) { flag[x] = true; } } for (int x = a; x <= b; x++) { ArrayList list = new ArrayList(); for(int k = 1; k < keta; k++) { int result = Integer.valueOf(gc.recycle(String.valueOf(x), k)); // if(result == 1212) { // int aa=1; // } if (!flag[result]){ if(x >= a && result <= b && x < result) { if(list.indexOf(result) != -1) { continue; } list.add(result); answer++; // if(i == 4) { // System.out.println(x + "" : "" + result); // } //flag[x] = true; //flag[result]=true; // for(int k2 = 1; k2 < keta; k2++) { // result = Integer.valueOf(gc.recycle(String.valueOf(x), k2)); // if(result >= a && result <= b && x < result) { // flag[result] = true; // } // } } } } } sb.append(""Case #""); sb.append(i); sb.append("": ""); sb.append(answer); sb.append(""\n""); } new FileOut(filenameOut, sb.toString()); } } " B11388,"import java.util.Locale; import java.util.Scanner; public class C { void solve(int icase) { int a = si(); int b = si(); int digits = ("""" + a).length(); int s = 1; for (int i = 0; i < digits; i++) { s *= 10; } long res = 0; for (int i = a; i < b; i++) { res += find(s, i, b); } printf(""Case #%d: %d\n"", icase, res); } int nused; int[] used = new int[10]; int find(int s, int x, int b) { int ret = 0; nused = 0; for (int m = 10; m < x; m *= 10) { int y = x % m; if (y >= m / 10) { y *= s / m; y += x / m; if (y <= b && x < y && !used(y)) { ret++; used[nused++] = y; } } } return ret; } boolean used(int y) { for (int i = 0; i < nused; i++) { if (used[i] == y) { return true; } } return false; } public static void main(String[] args) throws Exception { Locale.setDefault(Locale.US); new C().repSolve(); } void repSolve() throws Exception { scanner = new Scanner(System.in); // scanner = new Scanner(new java.io.File("""")); int ncase = si(); sline(); for (int icase = 1; icase <= ncase; icase++) { solve(icase); System.err.println(""[[ "" + icase + "" ]]""); } } Scanner scanner; int si() { return scanner.nextInt(); } long sl() { return scanner.nextLong(); } String ss() { return scanner.next(); } String sline() { return scanner.nextLine(); } void printf(String format, Object... args) { System.out.printf(format, args); } } " B12068,"import java.io.*; import java.security.SecureRandom; import java.util.*; import java.math.*; import java.awt.geom.*; import static java.lang.Math.*; public class Solution implements Runnable { int solve(int a, int b) { HashSet set = new HashSet<>(); for (int i = a; i < b; ++ i) { StringBuilder s = new StringBuilder(Integer.toString(i)); for (int j = 1;j < s.length(); ++ j) { if (s.charAt(j) == '0') { continue; } int x = 0; for (int k = j; k < s.length(); ++ k) { x = 10 * x + s.charAt(k) - '0'; } for (int k = 0; k < j; ++ k) { x = 10 * x + s.charAt(k) - '0'; } if (x > i && x <= b) { set.add(i * 10000000l + x); } } } return set.size(); } public void solve() throws Exception { int t = sc.nextInt(); for (int i = 0;i < t; ++ i) { out.println(""Case #"" + (i + 1) + "": "" + solve(sc.nextInt(), sc.nextInt())); } } /*--------------------------------------------------------------*/ static String filename = """"; static boolean fromFile = false; BufferedReader in; PrintWriter out; FastScanner sc; public static void main(String[] args) { new Thread(null, new Solution(), """", 1 << 25).start(); } public void run() { try { init(); solve(); } catch (Exception e) { throw new RuntimeException(e); } finally { out.close(); } } void init() throws Exception { if (fromFile) { in = new BufferedReader(new FileReader(filename+"".in"")); out = new PrintWriter(new FileWriter(filename+"".out"")); } else { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } sc = new FastScanner(in); } } class FastScanner { BufferedReader reader; StringTokenizer strTok; public FastScanner(BufferedReader reader) { this.reader = reader; } public String nextToken() throws IOException { while (strTok == null || !strTok.hasMoreTokens()) { strTok = new StringTokenizer(reader.readLine()); } return strTok.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public BigInteger nextBigInteger() throws IOException { return new BigInteger(nextToken()); } public BigDecimal nextBigDecimal() throws IOException { return new BigDecimal(nextToken()); } }" B11773,"import java.util.ArrayList; import java.util.List; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { List inputList = FileIO.readFile(""C-small-attempt0.in""); List outputList = new ArrayList(); int caseNo = 1 ; int testCaseCount = Integer.parseInt(inputList.get(0)); while (caseNo <= testCaseCount) { Number n = new Number(inputList.get(caseNo)); outputList.add(""Case #"" +caseNo +"": "" +n.getRecycledPairCount()); caseNo++; } FileIO.writeFile(""C-small-attempt0.out"", outputList); } } " B11068,"package fixjava; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; /** * Iterator that iterates over the lines of the file and then closes it after the last line has been read. * * e.g. * * * * for (String line : new FileLineIterator(""in.txt"")) * System.out.println(line); * * for (NumberedLine nl : new FileLineIterator(""in.txt"").withLineNumbers()) * System.out.println(nl.getLineNum() + "" "" + nl.getLine()); * * */ public class FileLineIterator implements Iterable, Iterator { private BufferedReader reader; String nextLine = null; boolean nextLineAlreadyFetched = false; private int lineNum = -1; // ------------------------------------------------------------------------------------------ /** * Construct an iterator that iterates over the lines of the file and then closes it after the last line has been read. * * e.g. for (String line : new FileLineIterator(""in.txt"")) System.out.println(line); * * @throws IllegalArgumentException * on any I/O exception, so you can use this directly in foreach loops. */ public FileLineIterator(String filename) { this(new File(filename)); } /** * Construct an iterator that iterates over the lines of the file and then closes it after the last line has been read. * * e.g. for (String line : new FileLineIterator(file)) System.out.println(line); * * @throws IllegalArgumentException * on any I/O exception, so you can use this directly in foreach loops. */ public FileLineIterator(File file) { try { reader = new BufferedReader(new FileReader(file), 1024 * 1024); } catch (FileNotFoundException e) { throw new IllegalArgumentException(e); } } @Override public Iterator iterator() { return this; } // ------------------------------------------------------------------------------------------ private String getNextLine(boolean consume) { if (!nextLineAlreadyFetched) { try { nextLine = reader.readLine(); lineNum++; nextLineAlreadyFetched = true; if (nextLine == null) // Close reader after last line has been read reader.close(); } catch (IOException e) { if (reader != null) try { reader.close(); } catch (Exception e2) { } throw new IllegalArgumentException(e); } } String retVal = nextLine; if (consume) { nextLine = null; nextLineAlreadyFetched = false; } return retVal; } /** Return the current zero-indexed line number -- only returns the correct line number after a call to hasNext() or next() */ public int getLineNum() { return lineNum; } @Override public boolean hasNext() { return getNextLine(false) != null; } @Override public String next() { return getNextLine(true); } @Override public void remove() { getNextLine(true); } // ------------------------------------------------------------------------------------------ public class NumberedLine { String line; int lineNum; public NumberedLine(String line, int lineNum) { this.line = line; this.lineNum = lineNum; } public String getLine() { return line; } public int getLineNum() { return lineNum; } } /** Return an Iterable that includes the line number with each line */ public Iterable withLineNumbers() { final FileLineIterator fileLineIter = this; return new Iterable() { @Override public Iterator iterator() { return new Iterator() { @Override public void remove() { fileLineIter.remove(); } @Override public NumberedLine next() { String line = fileLineIter.next(); int lineNum = fileLineIter.getLineNum(); return new NumberedLine(line, lineNum); } @Override public boolean hasNext() { return fileLineIter.hasNext(); } }; } }; } } " B11291,"package qualifyingRound; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class RecycledNumbers { public static void main (String [] args) throws FileNotFoundException { Scanner in = new Scanner (new File (""input.txt"")); int numLines = Integer.parseInt(in.nextLine()); int i = 1; while (in.hasNextLine()) { System.out.print(""Case #"" + i + "": ""); int low = in.nextInt(); int high = in.nextInt(); int count = 0; for (int c = low; c < high; c++) { // int temp = computePermutations(c,high); // System.out.println(c + "" "" + temp); // count+=temp; count += computePermutations(c,high); } System.out.println(count); i = i+1; } // System.out.println(computePermutations(2212,2222)); } private static int computePermutations (int low, int high) { String str = """" + low; int length = str.length(); int count = 0; int temp = low; for (int i = 0; i < length; i++) { int last = temp % 10; temp = temp/10 + last * pow10(length - 1); // System.out.println(low + "" "" + temp); if (temp > low && temp <= high) { // System.out.println(low + "" "" + temp); count++; } } return count; } private static int pow10 (int pow) { int toReturn = 1; for (int i = 0; i < pow; i++) { toReturn *= 10; } return toReturn; } } " B11905,"import java.util.*; public class C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int test = 1, cases = sc.nextInt(); int a, b, curr, count; String aStr, bStr, num, shift; while(test <= cases) { count = 0; a = sc.nextInt(); b = sc.nextInt(); aStr = Integer.toString(a); bStr = Integer.toString(b); for(curr = a; curr <= b; curr++) { num = Integer.toString(curr); shift = nextShift(num); while(!num.equals(shift)) { if(shift.charAt(0) != '0' && aStr.compareTo(shift) <= 0 && bStr.compareTo(shift) >= 0 && num.compareTo(shift) < 0) count++; shift = nextShift(shift); } } System.out.println(""Case #"" + test + "": "" + count); test++; } } public static String nextShift(String s) { if(s.length() <= 1) return s; else return s.substring(1, s.length()) + s.substring(0, 1); } }" B10392,"import java.io.*; import java.util.*; class B { public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new FileReader(""B.in"")); PrintWriter pw = new PrintWriter(new FileWriter(""B.out"")); int X = Integer.parseInt(br.readLine()); for(int i=0; i 0) { n++; x *= 10; } for(int j=A; j seen = new HashSet(); for(int k=1; k getRecycled(int n) { Set recycled = new HashSet(); String sn = String.valueOf(n); for(int i = 1; i < sn.length(); i++) { String newN = sn.substring(i) + sn.substring(0, i); if (!newN.startsWith(""0"") && !newN.equals(sn)) { recycled.add(Integer.parseInt(newN)); } } return recycled; } private String processCase(String text) { Scanner scanner = new Scanner(text); int a = scanner.nextInt(); int b = scanner.nextInt(); int out = 0; for(int i = a; i < b; i++) { Set recycled = getRecycled(i); for(Integer rec : recycled) { int r = rec; if ((r >i) && (r <= b)) out++; } } return String.valueOf(out); } public static void main(String[] args) throws Exception { long now = System.currentTimeMillis(); new CRecycledNumbers().go(); System.out.println(String.valueOf(System.currentTimeMillis() - now) + ""ms""); } }" B11408,"import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class RecycledNumbers { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub Scanner in; in = new Scanner(new FileReader(""C-small.in"")); FileWriter output = new FileWriter(""C-small.out""); /*in = new Scanner(new FileReader(""C-large.in"")); FileWriter output = new FileWriter(""C-large.out"");*/ int T = in.nextInt(); for(int i = 1; i <= T; i++) { int a = in.nextInt(); int b = in.nextInt(); int recycle = 0; for(int n = a; n < b; n++) { StringBuffer sb = new StringBuffer(Integer.toString(n)); sb.trimToSize(); int m = -1; for(int j = 1; j < sb.length(); j++) { sb.append(sb.charAt(0)); sb.deleteCharAt(0); sb.trimToSize(); if ( m != Integer.parseInt(sb.toString()) ) { int check = m; m = Integer.parseInt(sb.toString()); if(m <= b && m>n) { //System.out.println(a + "" "" + n + "" "" + m + "" "" + b); recycle++; } else m = check; } } } output.write(""Case #"" + i + "": "" + recycle + ""\n""); } in.close(); output.flush(); output.close(); } } " B10454,"package MyAllgoritmicLib; public class NOD { public static int gcd (int a, int b) { if (b == 0) return a; else return gcd (b, a % b); } public static long gcd (long a, long b) { if (b == 0) return a; else return gcd (b, a % b); } public static double gcd (double a, double b) { if (b == 0) return a; else return gcd (b, a % b); } } " B12287,"package codejam2012; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) throws Exception { Scanner scanner = new Scanner(new BufferedReader(new FileReader( ""A-large-practice.in.txt""))); Output out = new Output(""B.out""); int T = scanner.nextInt(); for (int t = 1; t <= T; t++) { int A = scanner.nextInt(); int B = scanner.nextInt(); int count = 0; for(int m = A; m < B; m++ ){ String strM = """" + m; HashSet cache = new HashSet(); for(int p = 1; p < strM.length(); p ++){ if(strM.charAt(p) < strM.charAt(0)){ continue; } String strN = strM.substring(p) + strM.substring(0, p); int n = Integer.parseInt(strN); if(n > m && n <= B && !cache.contains(strN)){ cache.add(strN); count ++; //System.out.println(strM + "" "" + strN); } } } out.format(""Case #%d: %d\n"", t, count); } scanner.close(); out.close(); } static class Output { PrintWriter pw; public Output(String filename) throws IOException { pw = new PrintWriter(new BufferedWriter(new FileWriter(filename))); } public void print(String s) { pw.print(s); System.out.print(s); } public void println(String s) { pw.println(s); System.out.println(s); } public void format(String format, Object... args) { pw.format(format, args); System.out.format(format, args); } public void close() { pw.close(); } } } " B11642,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package coba; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; /** * * @author Unggul */ public class Recycle { int count; ArrayList inputList1 = new ArrayList(); ArrayList inputList2= new ArrayList(); ArrayList outputList = new ArrayList(); public Recycle(){ } public String cycle(String input){ char[] temp = new char[input.length()]; temp[0] = input.charAt(input.length()-1); for(int i=0;i countRecycle(ArrayList a, ArrayList b){ ArrayList tempList = new ArrayList(); String tempA; String tempB; int temp; for(int i=0;i numRecycled(int B) { String s = num + """"; HashSet recycleds = new HashSet(); int numeroCasas = s.length(); System.out.print(num + ""(""); for (int i = 1; i < numeroCasas; i++) { String novoNum = s.substring(s.length() - i, s.length()) + s.substring(0, s.length() - i); int aux = Integer.parseInt(novoNum); if (aux <= B && aux > num) { recycleds.add(aux); System.out.print("" "" + aux); } } System.out.print("")\n""); return recycleds; } public int quantNumRecycled(int B) { return numRecycled(B).size(); } } " B12561,"package qualificationRound; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class Q3Recycled { /** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(new File(""qualificationRound/C-small-attempt1.in"")); PrintWriter out = new PrintWriter(new File(""qualificationRound/out.txt"")); int T = sc.nextInt(); sc.nextLine(); for (int tc = 1; tc <= T; tc++) { out.print(""Case #""+tc+"": ""); System.out.print(""Case #""+tc+"": ""); int A = sc.nextInt(); int B = sc.nextInt(); int count = 0; for (int n = A; n <= B; n++) { if (n >= 10) { // must be two digits at least String s = """"+n; /*boolean same = true; for (int j=1; j al=new ArrayList(); int n=Integer.parseInt(br.readLine()); int a,b,count=0; String s[]; int temp,temp1; for(int i=0;i 0){ int A = r.nextInt(); int B = r.nextInt(); int ret = 0; for(int x = A; x <= B; x++){ HashSet S = new HashSet(); int curr = x; int L = (curr + """").length(); int L10 = 1; for(int i = 0; i < L - 1; i++) L10 *= 10; for(int itr = 0; itr < L; itr++){ if((curr + """").length() == L && !S.contains(curr) && curr <= B && curr >= A && curr < x){ ret++; } S.add(curr); curr = R(curr, L10); } } System.out.printf(""Case #%d: %d\n"", caseNumber++, ret); } } static int R(int x, int L){ int m = x % 10; return (x / 10) + (L * m); } } " B10363,"import java.io.*; import java.util.StringTokenizer; public class RecycledNumbers { public static void main(String[] args) { try { BufferedReader ifStream = new BufferedReader(new FileReader(""C.in"")); PrintWriter ofStream = new PrintWriter(new FileWriter(""C.out"")); int numCase; String inputCase; numCase = Integer.parseInt(ifStream.readLine()); for (int i=1; i<=numCase; i++) { ofStream.println(""Case #""+i+"": ""+recycledNumbers(ifStream.readLine())); } ifStream.close(); ofStream.close(); } catch (IOException e) { System.out.println(""IOException.""); } } private static int recycledNumbers(String input) { StringTokenizer st = new StringTokenizer(input, "" "", false); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); int numDigits = String.valueOf(A).length(); int[] mArr = new int[numDigits]; int count, m; int result = 0; for (int n=A; n n && m <= B) { mArr[count++] = m; } } result += count; for (int i=0; i arrList ; public void readFile(String srcFileName, String destFileName) { try { File srcFile = new File(srcFileName); File destFile = new File(destFileName); BufferedReader br = new BufferedReader(new FileReader(srcFile)); BufferedWriter bw = new BufferedWriter(new FileWriter(destFile)); int cases = Integer.parseInt(br.readLine()); //cases =1; for(int i=0;i(); for(int k=firstNum;k<=secondNum;k++) { char[] ch = (k+"""").toCharArray(); for(int j =0; j googlers = new ArrayList(); for(int y = 0; y0){ if(P-(temp2-P)/2==2){ S--; nums++; } if(temp2-2*temp>=P&&(temp2-2*temp)-temp<2)nums++; else{ temp++; if(temp2-2*temp>=P&&(temp2-2*temp)-temp<2)nums++; } } else{ if(temp2-2*temp>=P&&(temp2-2*temp)-temp<2)nums++; else{ temp++; if(temp2-2*temp>=P&&(temp2-2*temp)-temp<2)nums++; } } } System.out.println(""nums: ""+nums); out.println(nums); } out.close(); } public void googleRese()throws IOException{ Scanner file = new Scanner(new File(""codejam.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""codejam.out""))); int x = file.nextInt(); file.nextLine(); //ArrayList cases = new ArrayList(); Map remap = new TreeMap(); remap.put('a','y'); remap.put('b','h'); remap.put('c','e'); remap.put('d','s'); remap.put('e', 'o'); remap.put('f', 'c'); remap.put('g', 'v'); remap.put('h', 'x'); remap.put('i', 'd'); remap.put('j', 'u'); remap.put('k', 'i'); remap.put('l', 'g'); remap.put('m', 'l'); remap.put('n', 'b'); remap.put('o', 'k'); remap.put('p', 'r'); remap.put('r', 't'); remap.put('s', 'n'); remap.put('t', 'w'); remap.put('u', 'j'); remap.put('v', 'p'); remap.put('w', 'f'); remap.put('x', 'm'); remap.put('y','a'); remap.put('z','q'); remap.put('q','z'); remap.put(' ',' '); for(int y = 1; y<=x; y++){ String temp = file.nextLine(); out.print(""Case #""+y+"": ""); for(Character a: temp.toCharArray()){ if(remap.get(a)==null)System.out.println(a); out.print(remap.get(a)); } out.println(); } out.close(); } } " B11595,"import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.lang.Character.Subset; import java.util.ArrayList; import java.util.HashMap; public class recyling_numbers { static ArrayList superset = new ArrayList(); public static int[] range(int start, int end, int increment) { int[] values = new int[Math.abs((end - start) / increment) + 1]; boolean reverse = start > end; for (int i = start, index = 0; reverse ? (i >= end) : (i <= end); i += increment, ++index) { values[index] = i; } return values; } private Exception IllegalArgumentException() { return null; } public static int get_solution(int A, int B) { superset = new ArrayList(); int count = 0; String seeds[] = new String[B - A + 1]; for (int i = A, n = 0; n < seeds.length; i++, n++) { seeds[n] = Integer.toString(i); } for (int i = 0; i < seeds.length; i++) { count += binomial(CircularStringShift(seeds[i], A, B)); } return count; } public static int CircularStringShift(String s, int lowerLimit, int upperLimit) { String tmp = s; char ph = ' '; int count = 0; int tmp2; for (int i = 0; i < s.length(); i++) { ph = tmp.charAt(0); tmp = tmp.substring(1, tmp.length()) + ph; tmp2 = Integer.parseInt(tmp); if (!superset.contains(tmp2) && tmp2 >= lowerLimit && tmp2 <= upperLimit && tmp != s) { count++; superset.add(tmp2); } } return count; } static long binomial(int n) { return ((n - 1) * (n) / 2); } public static void main(String[] args) throws NumberFormatException, IOException { FileInputStream inFile = new FileInputStream( new File( ""C:\\Users\\ruzbeh\\Downloads\\C-small-attempt0.in"")); DataInputStream br = new DataInputStream(inFile); FileOutputStream outFile = new FileOutputStream(new File(""out.in"")); DataOutputStream out = new DataOutputStream(outFile); int T = Integer.parseInt(br.readLine()); for (int i = 0; i < T; i++) { String[] str = br.readLine().split("" ""); int a = Integer.parseInt(str[0]); int b = Integer.parseInt(str[1]); out.writeBytes(""Case #"" + (i + 1) + "": "" + get_solution(a, b)); out.writeBytes(""\n""); } } }" B11263,"package codejam; import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.FileReader; import java.io.PrintStream; import java.util.HashSet; public class _Q_C { public static void main(String[] args) throws Exception { String input_file = ""C-small-attempt0.in""; String output_file = ""_Q_C_small_out.txt""; BufferedReader in = new BufferedReader(new FileReader(input_file)); PrintStream out = new PrintStream(new FileOutputStream(output_file)); in.readLine(); String line; int case_num = 1; while ((line=in.readLine()) != null) { String[] line_str = line.split("" ""); int a = Integer.parseInt(line_str[0]); int b = Integer.parseInt(line_str[1]); HashSet hs = new HashSet(); for (Integer n = a; n <= b; ++n) { String n_str = n.toString(); int len = n_str.length(); for (int r = 1; r < len; ++r) { String rotated_n_str = n_str.substring(len - r) + n_str.substring(0, len - r); if (isValidPair(a, b, n_str, rotated_n_str)) { String check_str = removeLeadingZero(n_str) + ""_"" + removeLeadingZero(rotated_n_str); String check_str_rev = removeLeadingZero(rotated_n_str) + ""_"" + removeLeadingZero(n_str); if (!hs.contains(check_str) && !hs.contains(check_str_rev)) { int rotated_n = Integer.parseInt(rotated_n_str); if (n <= rotated_n) hs.add(check_str); else hs.add(check_str_rev); } } } } //System.out.println(""Case #"" + case_num + "": "" + hs.size() + ""\n"" + hs.toString()); out.println(""Case #"" + case_num + "": "" + hs.size()); ++case_num; } } private static boolean isValidPair(int a, int b, String n_str, String m_str) { Integer n = Integer.parseInt(n_str); Integer m = Integer.parseInt(m_str); String n_str_strip = n.toString(); String m_str_strip = m.toString(); return (n_str_strip.length() == m_str_strip.length() && a <= n && n < m && m <= b); } private static String removeLeadingZero(String s) { int i = 0; for (; i < s.length(); ++i) { if (s.charAt(i) != '0') break; } return s.substring(i); } } " B12099,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import util.MyUtil; public class ProblemC { /** * @param args * @throws IOException * @throws NumberFormatException */ public static void main(String[] args) throws Exception { String title = ""C-small-attempt0.in""; BufferedReader reader = MyUtil.getReader(title); int caseNumber = Integer.parseInt(reader.readLine()); BufferedWriter writer = MyUtil.getWriter(title); for (int i = 0 ; i < caseNumber; i++){ String line = reader.readLine(); String result = subRoutine(line); writer.write(""Case #"" + (i + 1) + "": "" + result + ""\n""); System.out.println(""Case #"" + (i + 1) + "": "" + result); } writer.flush(); } private static String subRoutine(String line){ StringBuilder sb = new StringBuilder(); String[] elements = line.split("" ""); long A = Long.parseLong(elements[0]); long B = Long.parseLong(elements[1]); long count = 0; for (long n = A ; n < B ; n++){ Set ms = new HashSet(); String str = String.valueOf(Math.abs((long)n)); String newn = Long.toString(n); for (int i = 1; i < str.length(); i++){ newn = shift(newn); long m = Long.parseLong(newn); if (m > n && m <= B && m > A){ ms.add(m); //System.out.println(n + "" : "" + m); test(n,m); } } count += ms.size(); } sb.append(count); return sb.toString(); } public static boolean test(long n, long m){ String nstr = Long.toString(n); String mstr = Long.toString(m); for (int i = 0; i < nstr.length(); i++){ nstr = nstr.charAt(nstr.length() - 1) + nstr; nstr = nstr.substring(0, mstr.length()); if (nstr.equals(mstr)){ return true; } } return false; } private static String shift(String nstr){ long n = Long.parseLong(nstr); StringBuilder shifted = new StringBuilder(); long last = n % 10; shifted.append(last); for (int i = 0; i < nstr.length() - 1; i++){ shifted.append(nstr.charAt(i)); } return shifted.toString(); } } " B11195,"// Problem B import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Locale; import java.util.Scanner; import java.util.Set; public class C { private void processInput() throws IOException { Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int testCase = 1; testCase <= T; testCase++) { int A = in.nextInt(); int B = in.nextInt(); int res = go(A, B); System.out.printf(Locale.ENGLISH, ""Case #%d: %d\n"", testCase, res); } in.close(); } private int go(int A, int B) { int res = 0; Set set = new HashSet(); int l = String.valueOf(A).length(); for (int n = A; n <= B; n++) { set.clear(); String m = String.valueOf(n); for (int j = 1; j < l; j++) { m = m.charAt(l - 1) + m.substring(0, l - 1); if (m.charAt(0) != '0') { int val = Integer.valueOf(m); if (val > n && val <= B) { set.add(val); } } } res += set.size(); } return res; } public static void main(String[] args) throws Exception { C temp = new C(); temp.processInput(); } } " B11078,"package fixjava; import java.awt.Adjustable; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.RenderingHints; import java.awt.event.AdjustmentEvent; import java.awt.event.AdjustmentListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollBar; @SuppressWarnings(""serial"") public class ZoomPanel extends JPanel { public static abstract class ZoomContent extends JPanel { // Width and height of canvas contents, in canvas coordinates private float contentWCanv, contentHCanv; // Width and height of canvas contents, in screen coordinates private int contentWScr, contentHScr; // Canvas scroll position, in screen coordinates private int contentXScr, contentYScr; // Current zoom protected float scale = 1.0f; // Initialize zoom etc. the first time canvas is painted private boolean firstPaint = true; // The scrollbar components in the parent ZoomPanel private JScrollBar hScrollBar; private JScrollBar vScrollBar; // --------------------------------------------------------------------------------------------------- public ZoomContent(float contentWidth, float contentHeight) { this.contentWCanv = contentWidth; this.contentHCanv = contentHeight; final ZoomContent canvas = this; final float[] mouseXY = new float[2]; this.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { canvas.mouseWheelMoved(e); } }); this.addMouseMotionListener(new MouseMotionListener() { @Override public void mouseMoved(MouseEvent e) { canvas.mouseMoved(e, toCanvasCoords(e, mouseXY)); } @Override public void mouseDragged(MouseEvent e) { canvas.mouseDragged(e, toCanvasCoords(e, mouseXY)); } }); this.addMouseListener(new MouseListener() { @Override public void mouseReleased(MouseEvent e) { canvas.mouseReleased(e, toCanvasCoords(e, mouseXY)); } @Override public void mousePressed(MouseEvent e) { canvas.mousePressed(e, toCanvasCoords(e, mouseXY)); } @Override public void mouseExited(MouseEvent e) { canvas.mouseExited(e, toCanvasCoords(e, mouseXY)); } @Override public void mouseEntered(MouseEvent e) { canvas.mouseEntered(e, toCanvasCoords(e, mouseXY)); } @Override public void mouseClicked(MouseEvent e) { canvas.mouseClicked(e, toCanvasCoords(e, mouseXY)); } }); } // --------------------------------------------------------------------------------------------------- /** Called first time paint() is called, to set up zoom etc. */ private void zoomToFit() { int w = getWidth(), h = getHeight(); // Scale to fit scale = Math.min(w / (float) contentWCanv, h / (float) contentHCanv); // Center in window zoomBy(1.0, 0, 0); } private void resized() { // Center in window if needed zoomBy(1.0, 0, 0); } // --------------------------------------------------------------------------------------------------- /** Called by ZoomPanel after setting up scrollbars */ protected void addScrollBars(final JScrollBar hScrollBar, final JScrollBar vScrollBar) { this.hScrollBar = hScrollBar; this.vScrollBar = vScrollBar; hScrollBar.addAdjustmentListener(new AdjustmentListener() { @Override public void adjustmentValueChanged(AdjustmentEvent e) { int hMax = hScrollBar.getMaximum(); float hScale = hMax == 0 ? 0.0f : 1.0f / hMax; scrollToX((hScrollBar.getValue() + hScrollBar.getVisibleAmount() / 2) * hScale); } }); vScrollBar.addAdjustmentListener(new AdjustmentListener() { @Override public void adjustmentValueChanged(AdjustmentEvent e) { int vMax = vScrollBar.getMaximum(); float vScale = vMax == 0 ? 0.0f : 1.0f / vMax; scrollToY((vScrollBar.getValue() + vScrollBar.getVisibleAmount() / 2) * vScale); } }); } // --------------------------------------------------------------------------------------------------- // Override these methods as needed in subclasses. canvasXY is the x/y canvas coords of the mouse point. public void mouseMoved(MouseEvent e, float[] canvasXY) { } public void mouseDragged(MouseEvent e, float[] canvasXY) { } public void mouseClicked(MouseEvent e, float[] canvasXY) { } public void mousePressed(MouseEvent e, float[] canvasXY) { } public void mouseReleased(MouseEvent e, float[] canvasXY) { } public void mouseEntered(MouseEvent e, float[] canvasXY) { } public void mouseExited(MouseEvent e, float[] canvasXY) { } public void keyTyped(KeyEvent e) { if (e.getKeyChar() == '1') zoomToFit(); } public void mouseWheelMoved(MouseWheelEvent e) { double scrollAmt = e.getPreciseWheelRotation(); zoomBy(Math.pow(e.isControlDown() ? 1.2 : 1.05, -scrollAmt), e.getX(), e.getY()); } // ------------------------------------------------------------------------------------------------ protected void scrollToX(float scrollbarFracX) { int viewportWScr = getWidth(); contentXScr = (int) (viewportWScr / 2 - contentWScr * scrollbarFracX); repaint(); } protected void scrollToY(float scrollbarFracY) { int viewportHScr = getHeight(); contentYScr = (int) (viewportHScr / 2 - contentHScr * scrollbarFracY); repaint(); } // ------------------------------------------------------------------------------------------------ protected void zoomBy(double zoomFactor, int centerXScr, int centerYScr) { // Change scale scale *= zoomFactor; // Update size of contents in screen coordinates contentWScr = (int) Math.ceil(contentWCanv * scale); contentHScr = (int) Math.ceil(contentHCanv * scale); // Update scroll position in screen coordinates contentXScr = (int) Math.round((contentXScr - centerXScr) * zoomFactor + centerXScr); contentYScr = (int) Math.round((contentYScr - centerYScr) * zoomFactor + centerYScr); // Figure out size and position of scrollbars if (hScrollBar != null && vScrollBar != null) { int viewportWScr = getWidth(), viewportHScr = getHeight(); // Snap view to beginning or end of scroll region if we zoom off the end int viewPosX = -contentXScr, viewPosMaxX = contentWScr - viewportWScr; viewPosX = Math.max(Math.min(viewPosX, viewPosMaxX), 0); int viewPosY = -contentYScr, viewPosMaxY = contentHScr - viewportHScr; viewPosY = Math.max(Math.min(viewPosY, viewPosMaxY), 0); if (viewPosMaxX > 0) { // Canvas wider than viewport hScrollBar.setMaximum(contentWScr); hScrollBar.setValue(viewPosX); hScrollBar.setVisibleAmount(viewportWScr); hScrollBar.setBlockIncrement((int) Math.ceil(viewportWScr * 0.8f)); hScrollBar.setUnitIncrement((int) Math.ceil(viewportWScr * 0.08f)); hScrollBar.setEnabled(true); } else { // Canvas narrower than viewport, center it horizontally hScrollBar.setEnabled(false); contentXScr = (viewportWScr - contentWScr) / 2; } if (viewPosMaxY > 0) { // Canvas taller than viewport vScrollBar.setMaximum(contentHScr); vScrollBar.setValue(viewPosY); vScrollBar.setVisibleAmount(viewportHScr); vScrollBar.setBlockIncrement((int) Math.ceil(viewportHScr * 0.8f)); vScrollBar.setUnitIncrement((int) Math.ceil(viewportHScr * 0.08f)); vScrollBar.setEnabled(true); } else { // Canvas shorter than viewport, center it vertically vScrollBar.setEnabled(false); contentYScr = (viewportHScr - contentHScr) / 2; } } repaint(); } // ------------------------------------------------------------------------------------------------ protected float[] toCanvasCoords(int screenX, int screenY, float[] outXY) { outXY[0] = (screenX - contentXScr) / scale; outXY[1] = (screenY - contentYScr) / scale; return outXY; } protected float[] toCanvasCoords(int screenX, int screenY) { float[] outXY = new float[2]; toCanvasCoords(screenX, screenY, outXY); return outXY; } protected float[] toCanvasCoords(MouseEvent e) { return toCanvasCoords(e.getX(), e.getY()); } protected float[] toCanvasCoords(MouseEvent e, float[] outXY) { toCanvasCoords(e.getX(), e.getY(), outXY); return outXY; } // ------------------------------------------------------------------------------------------------ @Override public void paint(Graphics g) { super.paint(g); Graphics2D g2 = (Graphics2D) g; if (firstPaint) { zoomToFit(); firstPaint = false; } g2.drawRect(contentXScr, contentYScr, contentWScr, contentHScr); AffineTransform orig = g2.getTransform(); // Correctly center scaled canvas in viewport g2.translate(contentXScr, contentYScr); g2.scale(scale, scale); // Run user-provided code paintCanvas(g2); // Restore old transform g2.setTransform(orig); } /** Override this to draw your content */ public abstract void paintCanvas(Graphics2D g); } // ------------------------------------------------------------------------------------------------ /** A zoomable image */ public static class ZoomImageContent extends ZoomContent { protected BufferedImage img; public ZoomImageContent(BufferedImage img) { super(img.getWidth(), img.getHeight()); this.img = img; } @Override public void paintCanvas(Graphics2D g) { g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.drawImage(img, 0, 0, null); } } // ------------------------------------------------------------------------------------------------ public ZoomPanel(final ZoomContent content) { // Set up layout this.setLayout(new GridBagLayout()); GridBagConstraints gridBagConstraints = new GridBagConstraints(); // Add content panel gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.fill = GridBagConstraints.BOTH; this.add(content, gridBagConstraints); JScrollBar hScrollBar = new JScrollBar(Adjustable.HORIZONTAL); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 0.0; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; //hScrollBar.addAdjustmentListener(scrollBarListener); this.add(hScrollBar, gridBagConstraints); JScrollBar vScrollBar = new JScrollBar(Adjustable.VERTICAL); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.weightx = 0.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.fill = GridBagConstraints.VERTICAL; //vScrollBar.addAdjustmentListener(scrollBarListener); this.add(vScrollBar, gridBagConstraints); // Create small spacer panel in corner between scrollbars JPanel cornerPanel = new JPanel(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = GridBagConstraints.BOTH; gridBagConstraints.weightx = 0.0; gridBagConstraints.weighty = 0.0; this.add(cornerPanel, gridBagConstraints); // Add scrollbar refs to ZoomContent content.addScrollBars(hScrollBar, vScrollBar); // Update scrollbar block increments when window size changes content.addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent evt) { content.resized(); } }); } // ------------------------------------------------------------------------------------------------ /** Create new ZoomFrame. Calls System.exit(0) on window close. */ public static class ZoomFrame extends JFrame { protected ZoomContent content; @SuppressWarnings(""unused"") private ZoomFrame() { } public ZoomFrame(String title, int windowWidth, int windowHeight, final ZoomContent content) { // Set window title super(title); // Keep ref to content in case subclasses need it this.content = content; // Exit on window close this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); // Catch keystrokes this.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { content.keyTyped(e); } }); this.setSize(windowWidth, windowHeight); // Add ZoomPanel to ZoomFrame, and add ZoomContent to ZoomPanel this.add(new ZoomPanel(content)); this.setVisible(true); } } // ------------------------------------------------------------------------------------------------ // Demo usage public static void main(String[] args) { new ZoomFrame(""Zoom Panel"", 1024, 768, new ZoomContent(800, 600) { int x = 100, y = 100; @Override public void paintCanvas(Graphics2D g) { g.fillOval(x, y, 50, 50); } @Override public void mousePressed(MouseEvent e, float[] coords) { x = (int) coords[0] - 25; y = (int) coords[1] - 25; repaint(); } }); } } " B10291,"package com.gcj.parser; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; public class Parser { private String inputFileDest; private FileInputStream fileInputStream; public Parser(String inputFileDest) { super(); this.inputFileDest = inputFileDest; try { fileInputStream = new FileInputStream(new File(inputFileDest)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public String getInputFileDest() { return inputFileDest; } public void setInputFileDest(String inputFileDest) { this.inputFileDest = inputFileDest; } public FileInputStream getFileInputStream() { return fileInputStream; } public void setFileInputStream(FileInputStream fileInputStream) { this.fileInputStream = fileInputStream; } @SuppressWarnings(""unchecked"") public ArrayList[] toArray(){ Scanner scan = new Scanner(getFileInputStream()); // The first line must be an number Integer nbOfLines = new Integer(scan.nextLine()); ArrayList[] parsedData = new ArrayList[nbOfLines]; int index = 0; while (scan.hasNextLine()){ String line = scan.nextLine(); String[] datas = line.split("" ""); ArrayList dataRow = new ArrayList(); for (String data : datas){ dataRow.add(new Integer(data)); } parsedData[index] = dataRow; index++; } return parsedData; } } " B11179,"package _2012.QualificationRound.C; import java.util.ArrayList; import Utils.InputFile; import Utils.OutputFile; public class C { private static void solve(InputFile inputFile, OutputFile outputFile){ int nbCases = Integer.parseInt(inputFile.getNextLine()); for(int caseNumber = 0; caseNumber < nbCases; caseNumber++){ String[] line = inputFile.getNextLine().split("" ""); int A = Integer.parseInt(line[0]); int B = Integer.parseInt(line[1]); //n != m //m don't start with 0 int cptRecycled = 0; for (int i =A; i <= B; i++){ String number = """"+i; String recycled = """"+number; ArrayList recycledList = new ArrayList(); for(int j = 0; j < number.length(); j++){ recycled = recycled.charAt(recycled.length()-1)+ recycled.substring(0, recycled.length()-1); int recycledInt = Integer.parseInt(recycled); if(recycledInt >= A && recycledInt <= B && recycledInt != i && !recycledList.contains(recycledInt)){ cptRecycled++; recycledList.add(recycledInt); } } } String result = """" +(cptRecycled/2) ; outputFile.writeResult(result); } } public static void main(String[] args) { InputFile inputFile = new InputFile(""C"", ""small-attempt0""); OutputFile outputFile = new OutputFile(inputFile); solve(inputFile, outputFile); outputFile.endFile(); } } " B12642,"import java.util.*; class Main { static Scanner in = new Scanner(System.in); static Set set = new HashSet(); public static void serie(int n, int m){ for(int i=n;i<=m;i++){ String a = i+""""; int len = a.length()-1; for(int k=len;k>=1;k--){ String res = a.substring(k, len+1) + a.substring(0, k); int val = Integer.parseInt(res); if((val+"""").length() == (i+"""").length() && val<=m && i(); n = in.nextInt(); m = in.nextInt(); serie(n,m); } public static void main(String arg[]){ int n; n = in.nextInt(); for(int i=0;i pairs = new HashSet(b - a); for (int i = Math.max(2, nda); i <= ndb; i++) { k += solve(pairs, a, b, i); } return k; } private static int solve(Set pairs, int a, int b, int nd) { int k = 0; for (int i = 1; i <= nd / 2; i++) k += solve(pairs, a, b, nd, i); return k; } private static int solve(Set pairs, int a, int b, int nd, int ndc) { int c10 = (int) Math.pow(10, ndc); int ndd = nd - ndc; int d10 = (int) Math.pow(10, ndd); int c0 = a / d10; int d0 = a / c10; int k = 0; for (int c = c0; c < c10; c++) { if (c * d10 > b) break; int d00 = d0; if (ndc == ndd) d00 = Math.max(d00, c + 1); for (int d = d00; d < d10; d++) { if (d * c10 > b) break; int x = c * d10 + d; int y = d * c10 + c; if (x != y && x >= a && x <= b && y >= a && y <= b) { long xx = Math.min(x, y); long yy = Math.max(x, y); long pair = xx * c10 * d10 + yy; if (!pairs.contains(pair)) { k++; pairs.add(pair); // System.out.printf(""%d %d%n"", Math.min(x, y), Math.max(x, y)); } } } } return k; } } " B12960,"package google.loader; public interface Challenge { String getResult(); } " B12399,"package RecycledNumbers; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; /** * * @author Nikhil */ public class c { public static void main(String[] args) throws FileNotFoundException, IOException { File fInput = new File(args[0]); String tmp; BufferedReader br = new BufferedReader(new FileReader(fInput)); int iTestCases = Integer.parseInt(br.readLine()); int A, B, iCase = 1; while (null != (tmp = br.readLine())) { A = Integer.parseInt(tmp.split("" "")[0]); B = Integer.parseInt(tmp.split("" "")[1]); System.out.println(""Case #"" + iCase + "": "" + findRecycled(A, B)); iCase++; } br.close(); } private static int findRecycled(final int A, final int B) { int iRecycled = 0; int iRemainder, m, iTenPowMove; int iRemainderB; String sUnqNM; HashSet hsRecycled = new HashSet(); final int B_LEN = String.valueOf(B).length() - 1; if (B < 10) { return 0; } //System.out.println(""A="" + A + ""\tB="" + B); //dblRemainderB = B / Math.pow(10d, (double) (String.valueOf(B).length() - 1)); for (int iMoveDigitCount = 1; iMoveDigitCount <= B_LEN; iMoveDigitCount++) { // Increament 10^x to compute last digit from A iTenPowMove = (int) Math.pow(10d, (double) iMoveDigitCount); // Get the MSB digits from B to optimize algo iRemainderB = Integer.parseInt(String.valueOf(B).substring(0, iMoveDigitCount)); for (int n = A; n <= B; n++) { iRemainder = n % iTenPowMove; if (0 == iRemainder || n < iTenPowMove) { continue; } else if (iRemainder > iRemainderB) { //iMoveDigitCount++; n += iTenPowMove - iRemainder; continue; } else { String strM = null; StringBuilder sb = new StringBuilder(String.valueOf(n)); int iPre = sb.length() - iMoveDigitCount; try { strM = sb.substring(iPre) + sb.substring(0, iPre); } catch (StringIndexOutOfBoundsException ex) { System.out.println(""sb="" + iRemainder + ""\niPre="" + iPre); throw ex; } m = Integer.parseInt(strM); if (m <= n) { continue; } else if (m <= B) { sUnqNM = String.valueOf(n) + String.valueOf(m); if (!hsRecycled.contains(sUnqNM)) { hsRecycled.add(sUnqNM); iRecycled++; } } } } } return iRecycled; } } " B13110,"package com.vp.impl; import java.util.Arrays; import com.vp.common.CommonUtility; import com.vp.iface.Problem; public class DancingWithGooglers implements Problem { private static int currentNoOfSurprises; private static int eligibleGooglers; private static final int noOfJudges = 3; private static int noOfGooglers; private static int noOfSurprises; private static int bestScore; @Override public String solve(String[] dataset) { String strReturnValue =""""; String strDanceData = dataset[0]; String strDanceDataArr[] = strDanceData.split("" ""); int iDanceDataArr[] = CommonUtility.convertStringArraytoIntArray(strDanceDataArr); noOfGooglers = iDanceDataArr[0]; noOfSurprises = iDanceDataArr[1]; bestScore = iDanceDataArr[2]; eligibleGooglers = 0; currentNoOfSurprises =0; int totalScore; int googlers[] = new int [noOfGooglers]; int index =0 ; int scoreSplit[] = new int[noOfJudges]; CommonUtility.print(iDanceDataArr); for (int i = 3; i < iDanceDataArr.length; i++ ) { googlers[index] = iDanceDataArr[i]; index++; } Arrays.sort(googlers); for (int i = 0; i < googlers.length; i++ ) { totalScore = googlers[i]; if(isEligible(totalScore)) { scoreSplit= split(totalScore); if(isEligibleAfterConversion(scoreSplit)) { eligibleGooglers++; CommonUtility.printWithoutExtrLine(scoreSplit); System.out.println(""Eligible Googler #"" + eligibleGooglers); } } } System.out.println(""Output: "" + strReturnValue + eligibleGooglers); return strReturnValue + eligibleGooglers; } private boolean isEligibleAfterConversion(int[] scoreSplit) { boolean bReturn = false; if(currentNoOfSurprises == noOfSurprises) { return true; } int surpriseScore[]= convertToSurpriseScore(scoreSplit); for(int i=0;i= bestScore) { bReturn = true; break; } } return bReturn; } private int[] convertToSurpriseScore(int[] scoreSplit) { int diff = scoreSplit[1] - scoreSplit[0]; int diff1 = scoreSplit[2] - scoreSplit[1]; int diff2 = scoreSplit[2] - scoreSplit[0]; String strDiff = diff+""""+diff1+""""+diff2; //System.out.println(""strDiff: "" + strDiff); if (strDiff.equals(""000"")) { if ((scoreSplit[2] - 1) >= 0) { scoreSplit[0] = scoreSplit[0] + 1; scoreSplit[2] = scoreSplit[2] - 1; } } else if(strDiff.equals(""011"")) { if((scoreSplit[0] - 1) >= 0) { scoreSplit[0] = scoreSplit[0] - 1; scoreSplit[1] = scoreSplit[1] + 1; } } else if(strDiff.equals(""101"")) { if((scoreSplit[1] - 1) >= 0) { scoreSplit[1] = scoreSplit[1] - 1; scoreSplit[2] = scoreSplit[2] + 1; } } Arrays.sort(scoreSplit); if(isSurpriseScore(scoreSplit)) { currentNoOfSurprises ++; CommonUtility.printWithoutExtrLine(scoreSplit); System.out.println("" Surprise#: ""+currentNoOfSurprises); } return scoreSplit; } private boolean isSurpriseScore(int[] scoreSplit) { int diff = scoreSplit[1] - scoreSplit[0]; int diff1 = scoreSplit[2] - scoreSplit[1]; int diff2 = scoreSplit[2] - scoreSplit[0]; // System.out.println(""isSurprise diff"" + diff + "" "" + diff1 + "" ""+ diff2); return ((diff + diff1 + diff2) == 4); } private static int [] split(int totalScore) { int avgScore = totalScore / 3; int remScoreAvg = (totalScore - avgScore) / 2; int remScore = remScoreAvg; int remScore1 = remScoreAvg; int iReturn[] = new int[3]; int mod = (totalScore - avgScore) % 2; if(mod == 1) { remScore++; } iReturn[0] = avgScore; iReturn[1] = remScore; iReturn[2] = remScore1; Arrays.sort(iReturn); CommonUtility.printWithoutExtrLine(iReturn); //System.out.println("" : Total Score :"" + totalScore); return iReturn; } /*private boolean isSurprisingScore(int totalScore) { boolean bReturn = false; int bs1 = bestScore; int bs2 = bestScore -1; int bs3 = bestScore -2; if(bs1 >=0 && bs2 >=0 && bs3>=0 ) { bReturn = (bestScore + ( bestScore -1 ) + (bestScore -2)) == totalScore; if(bReturn) System.out.println(""Eligible Googler : ["" + bestScore +"", ""+ ( bestScore -1 )+"", "" + (bestScore -2) +""] = "" + totalScore + "" (Surprise#"" + (currentNoOfSurprises + 1)+"")"" ); if(!bReturn) { bReturn = (bestScore + (( bestScore -2 ) * 2)) == totalScore; if (bReturn) System.out.println(""Eligible Googler : ["" + bestScore +"", ""+ ( bestScore -2 )+"", "" + (bestScore -2) +""] = "" + totalScore + "" (Surprise#"" + (currentNoOfSurprises + 1)+"")"" ); } } int bs4 = bestScore; int bs5 = bestScore +1; int bs6 = bestScore +2; if(bs1 <=10 && bs2 <=10 && bs3<=10 && !bReturn) { bReturn = (bestScore + ( bestScore +1 ) + (bestScore +2)) == totalScore; if(bReturn) System.out.println(""Eligible Googler : ["" + bestScore +"", ""+ ( bestScore +1 )+"", "" + (bestScore +2) +""] = "" + totalScore + "" (Surprise#"" + (currentNoOfSurprises + 1)+"")"" ); if(!bReturn) { bReturn = (bestScore + (( bestScore +2 ) * 2)) == totalScore; if (bReturn) System.out.println(""Eligible Googler : ["" + bestScore +"", ""+ ( bestScore +2 )+"", "" + (bestScore +2) +""] = "" + totalScore + "" (Surprise#"" + (currentNoOfSurprises + 1)+"")"" ); } } if (bReturn) { currentNoOfSurprises++; } return bReturn; } */ private boolean isEligible(int totalScore) { boolean bReturn = false; if(noOfSurprises == 0 || currentNoOfSurprises >= noOfSurprises) { // System.out.println(""isEligibleIn: "" + (bestScore + ((bestScore -1) * 2)) + "" : "" + totalScore); bReturn = (bestScore + ((bestScore -1) * 2)) <= totalScore; } else { // System.out.println(""isEligibleOut: "" + (bestScore + ((bestScore -2) * 2)) + "" : "" + totalScore); bReturn = (bestScore + ((bestScore -2) * 2)) <= totalScore; } //System.out.println(""isEligible: "" + bReturn); return bReturn; } } " B11379,"/** * */ package codejam2012.qualification; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; /** * @author Jaffar Ramay * */ public class RecycledNumbers { public static void solve() throws IOException { BufferedReader reader = new BufferedReader(new FileReader(new File(""/Users/jaffar_ramay/Workspaces/eclipseWorkspace/Revision/src/codejam2012/qualification/RecycledNumbers.in""))); BufferedWriter writer = new BufferedWriter(new FileWriter(new File(""/Users/jaffar_ramay/Workspaces/eclipseWorkspace/Revision/src/codejam2012/qualification/RecycledNumbers.out""))); String line = null; while((line=reader.readLine())!=null){ int testCases = Integer.parseInt(line); for (int i = 1; i <= testCases; i++) { String[] testCase = reader.readLine().split("" ""); int numberA = Integer.parseInt(testCase[0]); int numberB = Integer.parseInt(testCase[1]); int result = getRecycledCount(numberA, numberB); writer.write(""Case #""+i+"": ""+result); if(i0 && index=lenM) pos-=lenM; strTest=strTest+strM.charAt(pos); } if(strTest.equals(strN)) { boolean boolCheck=true; for(int c=0; c=lenM) pos-=lenM; strTest=strTest+strM.charAt(pos); } if(strTest.equals(strN)) { test= true; // System.out.println(strTest+"" ""+strM+"" ""+strN); } else test= false; } }else test= false; return test; } }" B13133,"import java.util.Scanner; public class Rec { static Scanner sc =new Scanner(System.in); public static void main (String [] args ) { int n =sc.nextInt(); for (int m =1; m <= n; m++) handleCase(m); } public static int a,b; static void handleCase(int num) { int sum=0; a =sc.nextInt(); b =sc.nextInt(); for (int i =a; i <=b;i++) { for (int j =a; j 1; l++) { alt=num.substring(l+1, tam)+num.substring(0,l+1); numero = Integer.parseInt(alt); //System.out.println(""alt ""+numero); if(numero >= matrix[i][0] && numero <= matrix[i][1] && !num.equals(alt)){valores[i]++;} } /* for(int l=0;l1; l++) { if(!num.substring(l+1, l+2).equals(num.substring(l,l+1))) { repetido = false; } } if(repetido && tam>1){valores[i]--;} */ } valores[i] = valores[i]/2; } } public static void main(String[] args) throws IOException { input = new BufferedReader(new FileReader(new File(""prueba.in""))); //System.out.println(""jd""); T = Integer.parseInt(leerLinea()); if(T<1 || T>1000) { System.out.println(""ERROR T""); } matrix = new int[T][2]; valores = new int[T]; for(int i=0; i i && pair <= B) { //System.out.println(""pair "" + (result+1) + "": "" + i + "" "" + pair); result ++; } } } return result; } public static void Output(String inPath, String outPath) { try { FileInputStream fstream = new FileInputStream(inPath); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); File of = new File(outPath); of.delete(); BufferedWriter bw = new BufferedWriter(new FileWriter(new File(outPath), true)); String line = br.readLine(); int[] parameters = convertString2Nums(1, line); int numOfTest = parameters[0]; String str = new String(); for(int i = 0; i < numOfTest; i ++) { line = br.readLine(); parameters = convertString2Nums(2, line); str = new String(""Case #"" + (i+1) + "": "" + numOfRecycleNumbers(parameters[0], parameters[1])); System.out.println(str); bw.write(str); bw.newLine(); } in.close(); bw.close(); } catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } //public static /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String inFile = new String(); String outFile = new String(); testSize = 1; switch(testSize) { case 0: inFile = new String(""./C-test.in""); outFile = new String(""./C-test.out""); break; case 1: inFile = new String(""./C-small-attempt0.in""); outFile = new String(""./C-small-attempt0.out""); break; case 2: inFile = new String(""./A-large-practice.in""); outFile = new String(""./A-large-practice.out""); break; default: break; } Output(inFile, outFile); } } " B12235,"import java.util.*; import java.io.*; public class Main { char []a; BufferedReader in; StringTokenizer str = null; PrintWriter out; private String next() throws Exception{ if (str == null || !str.hasMoreElements()) str = new StringTokenizer(in.readLine()); return str.nextToken(); } private int nextInt() throws Exception{ return Integer.parseInt(next()); } public void run() throws Exception{ in = new BufferedReader(new FileReader(""in.txt"")); out = new PrintWriter(new File(""out.txt"")); int t = nextInt(); for(int i=1;i<=t;i++){ solve(i); } out.close(); } TreeSet set; private void solve(int x) throws Exception{ int A = nextInt(); int B = nextInt(); set = new TreeSet(); for(int i=A;i<=B;i++){ String s = Integer.toString(i); for(int j=1;j{ public int a,b; public pair(int a, int b){ this.a = a; this.b = b; } public int compareTo(pair p){ if (a > p.a) return 1; if (a < p.a) return -1; if (b > p.b) return 1; if (b < p.b) return -1; return 0; } }" B13141,"package googleCodeJam; import static java.lang.System.out; import java.io.BufferedReader; import java.io.FileReader; import java.util.Set; import java.util.TreeSet; public class RecycledNumbers { public static void main(String[] args) throws Exception { if (args.length == 1) { // opening the input BufferedReader in = new BufferedReader(new FileReader(args[0])); // reading the number of test cases String line = null; int numberOfTestCases = ((line = in.readLine()) != null) ? Integer.parseInt(line) : 0; for (int t = 0; t < numberOfTestCases; t ++) { line = in.readLine(); out.print(""Case #"" + (t+1) + "": ""); // parse input String[] numbers = line.split("" ""); int n = Integer.parseInt(numbers[0]); int m = Integer.parseInt(numbers[1]); int counter = 0; StringBuffer is = new StringBuffer(128); String isCurrent = null; for (int i = n; i <= m; i ++) { is.append(i); int size = is.length(); is.append(i); // Set qs = new TreeSet(); for (int j = 0; j < size; j ++) { isCurrent = is.substring(j, j+size); int q = Integer.parseInt(isCurrent); if (i < q && q <= m /*&& !isCurrent.startsWith(""0"")*/) { //counter ++; //out.println(i + ""\t"" + q + ""\t"" + (size - j)); qs.add(q); } } // counter += qs.size(); is.setLength(0); } out.println(counter); } // closing the input in.close(); } else { // show the usage System.err.println(""Using: java googleCodeJam.RecycledNumbers input""); } } } " B11529,"import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileOutputStream; public class RecNum { public static void main(String[] args) throws Exception { // long start = System String filename = ""D:\\Hardik\\workspace\\CodeJam\\C-small-attempt2.in""; FileInputStream file = new FileInputStream(filename); DataInputStream in = new DataInputStream(file); int testCases = Integer.parseInt(in.readLine()); FileOutputStream fos = new FileOutputStream( ""D:\\Hardik\\workspace\\CodeJam\\Output.txt""); int a, b; int caseNo = 1; String output = """"; while (testCases > 0) { String input = in.readLine(); String nu[] = input.split("" ""); a = Integer.parseInt(nu[0]); b = Integer.parseInt(nu[1]); testCases--; output += ""Case #"" + Integer.toString(caseNo++) + "": "" + Integer.toString(solve(a, b)) + ""\n""; } fos.write(output.getBytes()); fos.close(); file.close(); } public static int solve(int a, int b) { int output = 0; for (int i = a; i <= b; i++) { for (int j = a; j <= b; j++) { if (isRecycledNumber(i, j)) { output++; j += 5; } } } return (output / 2); } public static boolean isRecycledNumber(int number1, int number2) { String n1 = Integer.toString(number1), n2 = Integer.toString(number2); if (number1 < 10) { return false; } if (n1.length() != n2.length()) { return false; } if (number1 == number2) { return false; } for (int i = 1; i <= n1.length(); i++) { for (int j = 1; j <= n2.length(); j++) { String n3, n4, n5, n6; n3 = n1.substring(0, i); n4 = n1.substring(i, n1.length()); n5 = n2.substring(0, j); n6 = n2.substring(j, n2.length()); int num1, num2, num3, num4; num1 = Integer.parseInt(n3 + n4); num2 = Integer.parseInt(n4 + n3); num3 = Integer.parseInt(n5 + n6); num4 = Integer.parseInt(n6 + n5); if (num1 == num3) return true; else if (num1 == num4) return true; if (num2 == num3) return true; else if (num2 == num4) return true; } } return false; } }" B10151,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; import java.util.TreeSet; import static java.lang.Math.*; public class RecycledNumbers { String PROBLEM_ID = ""RecycledNumbers""; enum TestType { EXAMPLE, SMALL, LARGE } // TestType TYPE = TestType.EXAMPLE; TestType TYPE = TestType.SMALL; // TestType TYPE = TestType.LARGE; public String getFileName() { String result = PROBLEM_ID + ""_""; switch (TYPE) { case EXAMPLE: result += ""example""; break; case SMALL: result += ""small""; break; case LARGE: result += ""large""; break; } return result; } public String getInFileName() { return getFileName() + "".in""; } public String getOutFileName() { return getFileName() + "".out""; } public static void main(String[] args) throws Exception { new RecycledNumbers(); } public RecycledNumbers() throws Exception { BufferedReader in = new BufferedReader(new FileReader(getInFileName())); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter( getOutFileName()))); Scanner scan = new Scanner(in); int tests = scan.nextInt(); TreeSet seen = new TreeSet(); for (int test = 0; test < tests; test++) { int result = 0; int A = scan.nextInt(); int B = scan.nextInt(); int s = (""""+A).length(); int Z = 1; for ( int i = 0; i < s; i++) Z *= 10; for ( int n = A; n < B; n++) { seen.clear(); for ( int select = 10; select < Z; select *= 10) { int v = n / select; int w = n % select; int m = (Z/select) * w + v; if ( m > n && m <= B && !seen.contains(m) ) { seen.add(m); // System.out.printf(""pair n = %d m = %d select = %d\n"", n, m, select); result++; } } } String resultStr = String.format(""Case #%d: %d"", test + 1, result); // add answer here System.out.println(resultStr); out.println(resultStr); } out.close(); System.out.println(""*** in file = "" + getInFileName()); System.out.println(""*** out file = "" + getOutFileName()); } } " B12412,"package taskc; import java.io.FileNotFoundException; import java.util.*; import java.io.File; import java.io.PrintWriter; public class TaskC { private int[] tenPowers = new int[10]; private int[]prevPairs = new int[10]; private void prepareTenPowers(){ tenPowers[0] = 1; for(int i = 1;i<10;i++){ tenPowers[i]=tenPowers[i-1]*10; } } private void solve(Scanner in, PrintWriter out, int caseNum){ int res = 0; int A = in.nextInt(); int B = in.nextInt(); for(int t = A;t<=B;t++){ int d = t; int aPow = 0; while(d>0){ aPow++; d = d/10; } int pow = 10; d = t/10; int k = 1; int pairsCnt = 0; while(d>0){ int rest = t%pow; if(t == 123){ int y = 0; } if(rest!=0){ int pair = rest*tenPowers[aPow-k]+ d; if((pair>t)&&(pair<=B)){ boolean ok = true; check: for(int i = 0;i checkedCycles = new HashSet<>(); String recycledSequence = String.valueOf(n); for(int j = 1; j < l; j++) { recycledSequence = recycle(recycledSequence); int recycledInt = Integer.valueOf(recycledSequence); if(checkedCycles.contains(recycledInt)) { continue; } else { checkedCycles.add(recycledInt); } if(n < recycledInt && recycledInt <= B) { recycled ++; } } } print(getCase(i + 1)); print(recycled); print(""\n""); } putAwayFiles(); } private static String recycle(String sequence) { String newSequence = new String(); newSequence += sequence.charAt(sequence.length() - 1); for(int i = 0; i < sequence.length() - 1; i++) { newSequence += sequence.charAt(i); } return newSequence; } private static void prepareFiles(String fileName) throws IOException { reader = new BufferedReader(new FileReader(new File(fileName + "".in""))); writer = new BufferedWriter(new FileWriter(new File(fileName + "".out""))); } private static void putAwayFiles() throws IOException { reader.close(); writer.flush(); writer.close(); } private static String getCase(int i) { return ""Case #"" + i + "": ""; } private static void print(Object object) throws IOException { System.out.print(object.toString()); writer.write(object.toString()); } } " B12117,"import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Locale; import java.util.Scanner; import java.util.Set; public class QuestionC { //final static String FNAME = ""C:\\CodeJam\\RecycledNumbers""; final static String FNAME = ""C:\\CodeJam\\C-small-attempt0""; //final static String FNAME = ""C:\\CodeJam\\A-large-practice""; public static Scanner in; public static PrintWriter out; static void open() throws IOException { Locale.setDefault( Locale.US ); in = new Scanner( new File( FNAME + "".in"" ) ); out = new PrintWriter( new File( FNAME + "".out"" ) ); } static void close() throws IOException { out.close(); } public static void main(String[] args)throws IOException { open(); int N = in.nextInt(); //int T = Integer.parseInt(in.nextLine()); /* -------- Main code ---------- */ for(int i = 0 ; i < N ; i++){ int A = in.nextInt(); int B = in.nextInt(); //System.out.println(A + ""----"" + B); int absMinFirstDigit = Character.digit(Integer.toString(A).toCharArray()[0],10); int absMaxFirstDigit = Character.digit(Integer.toString(B).toCharArray()[0],10); //System.out.println(absMinFirstDigit + ""----"" + absMaxFirstDigit); long count = 0; if(A>=10){ for(int n = A ; n <= B; n++){ char[] numChars = Integer.toString(n).toCharArray(); int maxLen = numChars.length; int firstDigitOfNum = Character.digit(numChars[0],10); Set checkDupSet = new HashSet(); for(int j = 1 ; j <= maxLen-1 ; j++){ int numAtJIindex = Character.digit(numChars[j], 10); if ( (numAtJIindexabsMaxFirstDigit) || (numAtJIindexn && m<=B ){ if(checkDupSet.add(m)){ //System.out.println(""Valid Number generated : ""+ n + "" : "" + m); count++; } } } } } //Print to file out.println( ""Case #"" + (i+1) + "": ""+count); //System.out.println( ""Case #"" + (i+1) + "": ""+count); } close(); } } " B11011,"import java.util.*; import java.io.*; public class C{ static ArrayList< ArrayList > mem = new ArrayList< ArrayList >(); static int lenAB = -1; static boolean udah[] = new boolean[2000005]; public static void compute(int x){ int div = 10, gen, mul = 1; for (int i = 0 ; i < lenAB-1 ; i ++)mul*=10; HashSet set = new HashSet(); while(mul > 1){ gen = x/div + (x%div)*mul; if (x%div!=0 && x!=gen && !set.contains(gen)){ mem.get(x).add(gen); set.add(gen); } div*=10; mul/=10; } udah[x] = true; } public static void main(String args[])throws Exception{ for (int i = 0 ; i < 2000005 ; i ++){ mem.add (new ArrayList()); udah[i] = false; } BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tok; String input; int t, a, b, sum = 0; t = Integer.parseInt(in.readLine()); for (int k = 1 ; k <= t ; k ++){ tok = new StringTokenizer(in.readLine()); input = tok.nextToken(); lenAB = input.length(); a = Integer.parseInt(input); b = Integer.parseInt(tok.nextToken()); sum = 0; for (int i = a ; i < b ; i ++){ if (!udah[i]){ compute(i); } int len = mem.get(i).size(), res; for (int j = 0 ; j < len ; j ++ ){ res = mem.get(i).get(j); if (i < res && res <= b){ sum++; } } } System.out.println(""Case #"" + k + "": "" + sum); } } }" B11458,"import java.util.*; import java.io.*; public class Qual2012 { public static void lame() { try { FileReader fr = new FileReader(""input.txt""); BufferedReader reader = new BufferedReader(fr); PrintWriter writer = new PrintWriter(""output.txt""); HashMap dictionary = new HashMap(); dictionary.put(""a"", ""y""); dictionary.put(""b"", ""h""); dictionary.put(""c"", ""e""); dictionary.put(""d"", ""s""); dictionary.put(""e"", ""o""); dictionary.put(""f"", ""c""); dictionary.put(""g"", ""v""); dictionary.put(""h"", ""x""); dictionary.put(""i"", ""d""); dictionary.put(""j"", ""u""); dictionary.put(""k"", ""i""); dictionary.put(""l"", ""g""); dictionary.put(""m"", ""l""); dictionary.put(""n"", ""b""); dictionary.put(""o"", ""k""); dictionary.put(""p"", ""r""); dictionary.put(""q"", ""z""); dictionary.put(""r"", ""t""); dictionary.put(""s"", ""n""); dictionary.put(""t"", ""w""); dictionary.put(""u"", ""j""); dictionary.put(""v"", ""p""); dictionary.put(""w"", ""f""); dictionary.put(""x"", ""m""); dictionary.put(""y"", ""a""); dictionary.put(""z"", ""q""); dictionary.put("" "", "" ""); int numCases = Integer.parseInt(reader.readLine()); for (int i = 1; i <= numCases; i++) { String sentence = reader.readLine(); String newSentence = """"; for (char c : sentence.toCharArray()) { char[] temp = new char[1]; temp[0] = c; newSentence += dictionary.get(new String(temp)); } writer.println(""Case #"" + i + "": "" + newSentence); } writer.close(); fr.close(); } catch (Exception e) { e.printStackTrace(); } } public static boolean canMatch(int score, int target) { if (score == 0) return target <= 0; if (score == 1 || score == 2) return target <= 1; if (score % 3 == 0) { return score / 3 >= target; } return ((score / 3) + 1 >= target); } public static boolean canMatchSpecial(int score, int target) { if (score == 0) return target <= 0; if (score == 1) return target <= 1; if (score == 2) return target <= 2; if (score % 3 == 1) return (score / 3 + 1) >= target; return (score / 3 + 2) >= target; } public static void dance() { try { FileReader fr = new FileReader(""input.txt""); BufferedReader reader = new BufferedReader(fr); PrintWriter writer = new PrintWriter(""output.txt""); int numCases = Integer.parseInt(reader.readLine()); for (int i = 1; i <= numCases; i++) { StringTokenizer line = new StringTokenizer(reader.readLine(), "" ""); int numDancers = Integer.parseInt(line.nextToken()); int numSurprising = Integer.parseInt(line.nextToken()); int bestScore = Integer.parseInt(line.nextToken()); List scores = new LinkedList(); for (int j = 0; j < numDancers; j++) scores.add(Integer.parseInt(line.nextToken())); int count = 0; for (Integer score : scores) { if (canMatch(score, bestScore)) count++; else if (canMatchSpecial(score, bestScore) && numSurprising > 0) { numSurprising--; count++; } } writer.println(""Case #"" + i + "": "" + count); } writer.close(); fr.close(); } catch (Exception e) { e.printStackTrace(); } } public static void recycle() { try { FileReader fr = new FileReader(""input.txt""); BufferedReader reader = new BufferedReader(fr); PrintWriter writer = new PrintWriter(""output.txt""); int numCases = Integer.parseInt(reader.readLine()); for (int i = 1; i <= numCases; i++) { StringTokenizer line = new StringTokenizer (reader.readLine(), "" ""); int A = Integer.parseInt(line.nextToken()); int B = Integer.parseInt(line.nextToken()); int count = 0; for (int k = A; k <= B; k++) { if (k < 10) { continue; } String temp = """" + k; String cmp = """" + k; int length = temp.length(); temp = temp.substring(length-1) + temp.substring(0, length - 1); while (!temp.equals(cmp)) { int cycle = Integer.parseInt(temp); if (A <= cycle && cycle <= B) count++; temp = temp.substring(length-1) + temp.substring(0, length - 1); } } writer.println (""Case #"" + i + "": "" + count/2); } writer.close(); fr.close(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { // lame(); // dance(); recycle(); } }" B13246,"import java.io.*; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.ArrayList; public class ReadWriter { public ArrayList readFile(String path){ File file = new File(path); ArrayList strings = new ArrayList(); BufferedReader reader = null; try{ reader = new BufferedReader(new FileReader(file)); String text = null; while((text=reader.readLine())!=null){ strings.add(text); } return strings; } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(reader!=null){ reader.close(); } } catch(Exception e){ e.printStackTrace(); } } return null; } public void writeFile(ArrayList list, String path){ BufferedWriter out=null; try{ FileWriter fstream = new FileWriter(path); out = new BufferedWriter(fstream); for(String s : list){ out.write(s); out.write(""\r\n""); } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(out!=null){ out.close(); } } catch(Exception e){ e.printStackTrace(); } } } } " B12664,"import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class C { public static void main(String[] args) throws Exception{ new C().solve(args[0]); } private void solve(String file) throws Exception { Scanner s = new Scanner(new File(file)); int x=s.nextInt(); for(int i=1;i<=x;i++) { int y = calculate(s.nextInt(),s.nextInt()); System.out.format(""Case #%d: %d\n"",i,y); } } private int calculate(int a, int b) throws Exception { int r = 0; for ( int w=a; w<=b ; w++) { String A = Integer.toString(w); int l = A.length(); List list=new ArrayList(); for(int i=0;ib ) continue; if ( list.contains(bb))continue; list.add(bb); r++; } } return r; } } " B12674,"import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.util.Arrays; import java.util.Scanner; public class RecycledNumbersSmall { public static void main(String[] args) { File file = new File(""/Users/NoK/Desktop/C-small-attempt0.in""); int counter = 1; try { Scanner sc = new Scanner(file); int numOfCases = sc.nextInt(); sc.nextLine(); for (int i = 0; i < numOfCases; i++) { int integerN = sc.nextInt(); int integerM = sc.nextInt(); int numOfRecPairs = 0; for (int m = integerN; m <= integerM; m++) { String stringM = Integer.toString(m); int[] checkerArray = new int[stringM.length()-1]; for (int j = 0; j < checkerArray.length; j++) { checkerArray[j] = -1; } int index = 0; for (int n = 0; n < stringM.length()-1; n++) { char tmpChar = stringM.charAt(stringM.length()-1); stringM = Character.toString(tmpChar) + stringM.substring(0, stringM.length()-1); if (stringM.charAt(0) != '0') { int newIntegerM = Integer.parseInt(stringM); if ((newIntegerM >= integerN) && (newIntegerM <= integerM)) { if (newIntegerM > m) { int k = 0; boolean exists = false; while (k < checkerArray.length) { if (checkerArray[k] == newIntegerM) { exists = true; } k++; } if (exists == false) { checkerArray[index] = newIntegerM; index++; numOfRecPairs++; } } } } } } try { FileWriter fw = new FileWriter(""/Users/NoK/Desktop/C-small-attempt0.out"", true); BufferedWriter bw = new BufferedWriter(fw); System.out.println(""Case #"" + counter + "": "" + numOfRecPairs); bw.write(""Case #"" + counter + "": "" + numOfRecPairs); bw.newLine(); bw.close(); counter++; } catch (Exception e){ System.err.println(""Error: "" + e.getMessage()); } } } catch (FileNotFoundException e ) { e.printStackTrace(); } } }" B11876,"package com.google.codejam; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Scanner; import java.util.regex.Pattern; public class CodeJam3 { private static int testCase; private static FileOutputStream fostream; private static DataOutputStream out; public static void main(String[] args) { try { fostream = new FileOutputStream(""output3.out""); out = new DataOutputStream(fostream); Scanner scanner = new Scanner(new File(""C-small-attempt2.in"")); String inputNumberline = scanner.nextLine(); testCase = Integer.parseInt(inputNumberline); for (int i = 0; i < testCase; i++) { filterString(scanner.nextLine(), i); } out.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } private static void filterString(String fstring, int caseNumber) { final Pattern SPACE = Pattern.compile("" ""); int A = 0, B = 0; int i = 0; for (String token : SPACE.split(fstring)) { try { if (i == 0) { A = Integer.parseInt(token); i++; } else { B = Integer.parseInt(token); i++; } } catch (NumberFormatException ex) { System.err.println(token + "" is not a number""); } } int c1, c3, x1, x2, x3, x4; int count = 0; int length = String.valueOf(A).length(); if (!(length < 2)) for (int j = A; j < B; j++) { switch (length) { case 2: c1 = j % 10; c3 = j / 10; c1 = (c1 * 10) + c3; if (c1 > A && c1 <= B) { count++; } A++; break; case 3: x1 = j % 10; x2 = j % 100; x3 = j / 10; x4 = j / 100; x1 = (x1 * 100) + x3; x2 = (x2 * 10) + x4; if (x1 > A && x1 <= B) { count++; } if (x2 > A && x2 <= B) { count++; } A++; break; } } System.out.println(""Case #"" + (caseNumber + 1) + "": "" + count); try { out.writeBytes(""Case #"" + (caseNumber + 1) + "": "" + count + ""\n""); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B11315," import java.util.Scanner; public class code13 { public static boolean recheck(int n, int m){ int length= String.valueOf(m).length(); boolean answer=false; for(int j=0;jo;p--){ if(recheck(o,p)){ans++;}else{}}} return ans;} public static void main(String[] args) { Scanner c = new Scanner(System.in); int times=c.nextInt(); for(int p=0;p seen = new HashSet(); for (int l = 1; l < astr.length(); l++) { String shift = shift(astr, l); int c = Integer.parseInt(shift); if (!seen.contains(shift) && a < c && c <= B) { seen.add(shift); ct++; } } } System.out.printf(""Case #%d: %d\n"",ca+1,ct); } } } " B13070,"import java.io.FileNotFoundException; import java.util.HashMap; import java.util.Map; public class Jam { private static String in = ""in""; public static void main(String[] args) throws FileNotFoundException, InterruptedException { parse(args); Parser parser = new Parser(in); //Map tasks = new HashMap(); while (parser.hasNext()) { Case c = parser.nextCase(); //Thread task = new Thread(c); //task.start(); //tasks.put(task, c); c.run(); System.out.println(c); } /*for (Thread task : tasks.keySet()) { Case c = tasks.get(task); task.join(); System.out.println(c); }*/ } private static void parse(String[] args) { if (args.length > 0) in = args[0]; } }" B11723,"import java.lang.*; import java.io.*; import java.util.*; public class Solution { public static BufferedReader br; public static PrintWriter out; public static StringTokenizer stk; // ///////////////// TO CHANGE /////////////////////////// public static boolean isServer = false; // ///////////////// TO CHANGE /////////////////////////// public static void main(String[] args) throws IOException { if (isServer) { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { br = new BufferedReader(new FileReader(""in.txt"")); out = new PrintWriter(new File(""out.txt"")); } (new Solution()).run(); } public void loadLine() { try { stk = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } public String nextLine() { try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); return """"; } } public String nextWord() { while (stk == null || !stk.hasMoreTokens()) loadLine(); return stk.nextToken(); } public Integer nextInt() { while (stk == null || !stk.hasMoreTokens()) loadLine(); return Integer.valueOf(stk.nextToken()); } public Long nextLong() { while (stk == null || !stk.hasMoreTokens()) loadLine(); return Long.valueOf(stk.nextToken()); } public Double nextDouble() { while (stk == null || !stk.hasMoreTokens()) loadLine(); return Double.valueOf(stk.nextToken()); } public Float nextFloat() { while (stk == null || !stk.hasMoreTokens()) loadLine(); return Float.valueOf(stk.nextToken()); } public void run() { int tt = nextInt(); for (int t = 0; t < tt; t++) { int a = nextInt(); int b = nextInt(); long ans = 0; for (int i = a; i <= b; i++) { String s = Integer.toString(i); HashSet set = new HashSet(); set.add(i); for (int j = 1; j < s.length(); j++) { StringBuilder ss = new StringBuilder(); for (int k = 0; k < s.length(); k++) { ss.append(s.charAt((j+k)%s.length())); } int y = Integer.parseInt(ss.toString(), 10); if (y >= a && y <= b) { set.add(y); } } ans += set.size()-1; } out.printf(""Case #%d: "", t+1); out.println(ans/2); } out.flush(); } } " B11526,"import java.io.File; import java.io.IOException; import java.util.Arrays; public class SolutionC extends Solution { public SolutionC(String problemFileName) { super(problemFileName); } @Override public StringBuffer solve() { StringBuffer buffer = new StringBuffer(); int array[] = {1,2,3,4,5,6,7}; for (int i = 0; i < problem.count(); i++) { String s = problem.getCase(i); if(s!=null){ RecyclePair pair = new RecyclePair(s); buffer.append(""Case #"").append(i + 1).append("": ""); buffer.append(pair.countPair()); buffer.append('\n'); } } return buffer; } /** * @param args */ public static void main(String[] args) { try { File dir1 = new File("".""); String filename; filename = dir1.getCanonicalPath() + ""\\"" + args[0]; Solution solution = new SolutionC(filename); StringBuffer buffer = solution.solve(); solution.saveToFile(buffer); } catch (IOException e) { e.printStackTrace(); } } } class RecyclePair{ private int start, stop; private int length; public RecyclePair(String s){ String[] token = s.split("" ""); start = Integer.parseInt(token[0]); stop = Integer.parseInt(token[1]); length = token[0].length(); } public int countPair(){ int cnt = 0; for(int n=start;n<=stop;n++){ for(int m=n+1;m<=stop; m++ ){ String strN = String.valueOf(n); String strM = String.valueOf(m); if(isPair(strN, strM)){ cnt++; } } } return cnt; } private boolean isPair(String n, String m){ char[] arrN = n.toCharArray(); char[] arrM = m.toCharArray(); // System.out.print(Arrays.toString(arrN)+""-""); // System.out.println(Arrays.toString(arrM)); for (int i = 1; i <= arrN.length; i++) { String strM = recycleArray(arrM, i); if(n.equals(strM)){ return true; } } return false; } private String recycleArray(char[] array, int cycle){ int length = array.length; char[] outarr = new char[length]; System.arraycopy(array, cycle, outarr, 0, length-cycle); System.arraycopy(array, 0, outarr, length-cycle, cycle); return new String(outarr); } } " B10964,"import java.io.*; import java.math.BigInteger; import java.util.Locale; import java.util.StringTokenizer; /** * User: Igor Kirov * Date: 14.04.12 */ public class C implements Runnable { private int recycle(int t, int multiplier) { int cc = t % 10; while (cc == 0) { t = t / 10; t = t + cc * multiplier; cc = t % 10; } t = t / 10; t = t + cc * multiplier; return t; } private void solve() throws IOException { int a = nextInt(); int b = nextInt(); int temp = a / 10; int multiplier = 1; while (temp > 0) { multiplier *= 10; temp = temp / 10; } int ans = 0; boolean used[] = new boolean[b + 10]; for (int i = a; i <= b; i++) { int next = recycle(i, multiplier); while (next != i) { if (next >= a && next <= b) { ans++; } next = recycle(next, multiplier); } } writer.println(ans / 2); } public static void main(String[] args) { new Thread(null, new C(), """", 64 * 1024 * 1024).start(); } StringTokenizer tokenizer; BufferedReader reader; PrintWriter writer; public void run() { try { try { Locale.setDefault(Locale.US); } catch (Exception ignored) { } reader = new BufferedReader(new FileReader(""C.in"")); writer = new PrintWriter(new FileWriter(""C.out"")); tokenizer = null; int tests = nextInt(); for (int i = 0; i < tests; i++) { writer.printf(""Case #%d: "", i + 1); solve(); writer.flush(); } reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private BigInteger nextBigInteger() throws IOException { return new BigInteger(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }" B12626,"import java.io.IOException; import java.math.BigDecimal; import java.util.Arrays; import java.util.List; public class MinimumScalar extends JamProblem { public static void main(String[] args) throws IOException { MinimumScalar p = new MinimumScalar(); p.go(); } @Override String solveCase(JamCase jamCase) { MSCase c= (MSCase) jamCase; Arrays.sort(c.a); Arrays.sort(c.b); BigDecimal b = new BigDecimal(0); for (int i=0; i< c.lengh; i++) { BigDecimal aaa = new BigDecimal(c.a[i]); BigDecimal bbb = new BigDecimal(c.b[c.lengh - i - 1]); b = b.add(aaa.multiply(bbb)); } return """" + b; } @Override JamCase parseCase(List file, int line) { MSCase c= new MSCase(); c.lineCount=3; int i = line; c.lengh = Integer.parseInt(file.get(i++)); c.a = JamUtil.parseIntList(file.get(i++),c.lengh); c.b = JamUtil.parseIntList(file.get(i++),c.lengh); return c; } } class MSCase extends JamCase { int lengh; int[] a; int[] b; } " B12613,"package util.graph; import java.util.HashSet; import java.util.Set; public class Node implements Comparable{ public static int seq = 0; public int id = (seq++); public Set edges = new HashSet<>(); public State last; @Override public int compareTo(Node o) { return last.compareTo(o.last); } @Override public boolean equals(Object obj) { return id == ((Node) obj).id; } @Override public int hashCode() { return Integer.valueOf(id).hashCode(); } } " B10357,"package com.dten.cj.qual; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; public class C { public static int distinctPairs(int start, int end) { int count = 0; for (int i = start; i <= end; i++) for (int j = start; j <= end; j++) if (i < j && isPair(i, j)) count++; return count; } public static boolean isPair(int i, int j) { String iStr = String.valueOf(i); String jStr = String.valueOf(j); if (iStr.length() == 1 || jStr.length() != iStr.length()) return false; int characters = iStr.length(); while (characters-- > 0) if ((iStr = iStr.substring(1) + iStr.charAt(0)).equals(jStr)) return true; return false; } public static String processLine(String line){ String[] split = line.split("" ""); return String.valueOf(distinctPairs(Integer.parseInt(split[0]), Integer.parseInt(split[1]))); } public static String processFile(String fileName) { StringBuilder sb = new StringBuilder(); int caseCount = 0; try { for (String line : FileUtils.readLines(new File(fileName))) if (caseCount > 0) sb.append(""Case #"").append(caseCount++).append("": "") .append(processLine(line)).append(""\r\n""); else if (caseCount++ == 0) continue; } catch (IOException e) { e.printStackTrace(); } return sb.toString().trim(); } public static void main(String[] args) { String fileName = ""C-small-attempt0""; try { FileUtils.write(new File(""outputs/qual/"" + fileName + "".out""), C.processFile(""inputs/qual/"" + fileName + "".in"")); } catch (IOException e) { e.printStackTrace(); } } } " B11214,"package codjamdoce; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.StringTokenizer; public class RecycledNumbers { private final File file; private int ncases; private int[] result; private NumberSet[] cases; public RecycledNumbers(File file) { this.file = file; } public void init() throws IOException { BufferedReader reader = new BufferedReader(new FileReader(file)); try { String line; int lineNumber = 0; while ((line = reader.readLine()) != null) { if (lineNumber == 0) { ncases = Integer.valueOf(line.trim()); result = new int[ncases]; cases = new NumberSet[ncases]; } else { int index = 0; StringTokenizer tokenizer = new StringTokenizer(line.trim(), "" ""); int a = 0; int b = 0; while (tokenizer.hasMoreElements()) { String next = tokenizer.nextToken(); if (index == 0) { a = Integer.valueOf(next); } else { b = Integer.valueOf(next); } index++; } cases[lineNumber - 1] = new NumberSet(a, b); } lineNumber++; } } finally { reader.close(); } } public void getRecycledNumbers() { int count = 0; for (NumberSet numberset : cases) { result[count] = numberset.getRecycledNumbers(); count++; } } public void printResult() throws Exception { int count = 0; File outfile = new File(""out""); if (outfile.exists()) outfile.delete(); outfile.createNewFile(); FileOutputStream out = new FileOutputStream(outfile); try { for (int r : result) { if (count == ncases - 1) { out.write(MessageFormat.format(""Case #{0}: {1}"", (count + 1), r).getBytes()); } else { out.write(MessageFormat.format(""Case #{0}: {1}\n"", (count + 1), r).getBytes()); } count++; } } finally { out.close(); } } private static class NumberSetCandidate implements Comparable { private final int n; private final int m; public NumberSetCandidate(int n, int m) { this.n = n; this.m = m; } @Override public int compareTo(NumberSetCandidate o) { if (this.n == o.n && this.m == o.m) { return 0; } return -1; } public int getN() { return n; } public int getM() { return m; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + m; result = prime * result + n; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; NumberSetCandidate other = (NumberSetCandidate) obj; if (m != other.m) return false; if (n != other.n) return false; return true; } public String toString() { return ""[ "" + n + "", "" + m + ""]""; } } private static class NumberSet { private int nMin; private int mMin; private int max; List candidates = new ArrayList(); public NumberSet(int a, int b) { nMin = a; mMin = a + 1; max = b; } public int getRecycledNumbers() { populateCandidates(); if (candidates.size() == 0) { return 0; } for (NumberSetCandidate candidate : new ArrayList(candidates)) { int candidaten = candidate.getN(); int candidatem = candidate.getM(); String cnvalue = String.valueOf(candidaten); int[] set = new int[cnvalue.length()]; int count = 0; for (char c : cnvalue.toCharArray()) { set[count] = Integer.valueOf(String.valueOf(c)); count++; } try { Permutations perm = new Permutations(); perm.permutations(set, set.length); String cmvalue = String.valueOf(candidatem); if (!perm.contains(cmvalue)) { candidates.remove(candidate); } else { boolean remove = true; int length = cnvalue.length(); int cnt = 1; while (length > 0) { LinkedList tailNumbers = new LinkedList(); for (int i=(cnvalue.length()-cnt); i < length;i++) { tailNumbers.addFirst(cnvalue.substring(i)); } StringBuilder builder = new StringBuilder(); for (String s : tailNumbers) { builder.append(s); } builder.append(cnvalue.substring(0, length-1)); if (builder.toString().equals(cmvalue)) { remove = false; break; } cnt++; length--; } if (remove) { candidates.remove(candidate); } } } catch (Throwable t) { t.printStackTrace(); } } int size = candidates.size(); return size; } private void populateCandidates() { int n = nMin; int m = mMin; while (n < m && m <= max) { int innerM = m; String nvalue = String.valueOf(n); while (innerM <= max) { String mvalue = String.valueOf(innerM); boolean candidate = nvalue.length() == mvalue.length(); for (char c : nvalue.toCharArray()) { if (mvalue.indexOf(c) < 0) { candidate = false; break; } } if (candidate) { for (char c : mvalue.toCharArray()) { if (nvalue.indexOf(c) < 0) { candidate = false; break; } } } if (candidate) { boolean cont = true; for (char c : mvalue.toCharArray()) { if (getMatches(c, nvalue) != getMatches(c, mvalue)) { cont = false; } } if (cont) { NumberSetCandidate cand = new NumberSetCandidate(n, innerM); if (!candidates.contains(cand)) { candidates.add(cand); } } } innerM++; } n++; m++; } } private int getMatches(char c, String toMatch) { int matches = 0; for (char t : toMatch.toCharArray()) { if (c == t) { matches++; } } return matches; } } private static class Permutations extends ArrayList { private static final long serialVersionUID = 3487304820400778585L; private List failedTries = new ArrayList(); private void permutations(int[] set, int choices) { String resetStr = """"; for (int j = 0; j < choices; j++) { resetStr += String.format(""%d"", set[0]); } // java.util.Random rand = new java.util.Random(); // calc the number of values long max = permutations(choices, getRad(set)); while (size() < max) { StringBuilder builder = new StringBuilder(); java.util.ArrayList ele = new java.util.ArrayList(); while (ele.size() < choices) { int anInt = set[rand.nextInt(set.length)]; ele.add(anInt); } for (Integer i : ele) { builder.append(i.toString()); } if (failedTries.contains(builder.toString())) { continue; } if (!contains(builder.toString()) && isValid(set, builder.toString())) { add(builder.toString()); } } } private int getRad(int[] set) { int rad = 0; StringBuilder builder = new StringBuilder(); for (int i : set) { builder.append(i); } int res[] = new int[256]; for (int i = 0; i < builder.toString().length(); i++) { char charAt = builder.toString().charAt(i); res[charAt]++; } for (int i = 0; i < res.length; i++) { if (res[i] != 0) { if (res[i] == 1) { rad++; } } } return rad; } public long permutations(int n, int r) { if (r == 1) return n; if (r == 0) return 1; long previous = n; long current = 0; for (int i = 2; i <= r; i++) { current = previous * (n - (i - 1)); previous = current; } return current; } private boolean isValid(int[] set, String string) { StringBuilder builder = new StringBuilder(); for (int i : set) { builder.append(i); } boolean valid = true; for (char c : builder.toString().toCharArray()) { if (!string.contains(String.valueOf(c))) { valid = false; failedTries.add(string); break; } } if (valid) { for (char c : string.toCharArray()) { if (getMatches(c, string) != getMatches(c, builder.toString())) { valid = false; failedTries.add(string); break; } } } return valid; } private int getMatches(char c, String toMatch) { int matches = 0; for (char t : toMatch.toCharArray()) { if (c == t) { matches++; } } return matches; } private boolean contains(String str) { return ((ArrayList) this).contains(str); } } public static void main(String args[]) throws Exception { if (args.length < 1) { System.out.println(""Provide absolute path of input file""); } File file = new File(args[0]); if (file.isFile()) { RecycledNumbers recycledNumbers = new RecycledNumbers(file); recycledNumbers.init(); recycledNumbers.getRecycledNumbers(); recycledNumbers.printResult(); } } } " B10823,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; import java.util.StringTokenizer; public class jamc { public static boolean b=false; public static Scanner in; public static PrintWriter out; static boolean recycle(int i,int j) { String n=""""+i+""""; String m=""""+j+""""; for(int k=0;k done = new HashSet(); for (int i = Integer.parseInt(a); i <= largest; i++) { for (int j = 1; j < rotats; j++) { String n = String.valueOf(i); String x = n.substring(0, rotats - j); String y = n.substring(rotats - j); if (y.charAt(0) == '0') continue; // No zero startings int nn = (int) (Integer.parseInt(y) * Math.pow(10, rotats - j) + Integer.parseInt(x)); String key = n + String.valueOf(nn); if (nn != i && i < nn && nn <= largest && !done.contains(key)) { done.add(key); count++; } } } return count; } public static void main(String[] args) { Scanner scanner = null; try { scanner = new Scanner(new File(""A-small-attempt0.in"")); }catch (Exception e){ System.out.println(e.getMessage()); } String c = scanner.nextLine(); int i = 1; while (scanner.hasNextLine()) { String input = scanner.nextLine(); System.out.println(""Case #"" + i + "": "" + solve(input)); i++; } } } " B11933,"import java.util.HashSet; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class RN { public static Set> RNPair = new HashSet>(); public static class Pair { private final L left; private final R right; public Pair(L left, R right) { this.left = left; this.right = right; } public L getLeft() { return left; } public R getRight() { return right; } @Override public int hashCode() { return left.hashCode() ^ right.hashCode(); } @Override public boolean equals(Object o) { if (o == null) return false; if (!(o instanceof Pair)) return false; Pair pairo = (Pair) o; return this.left.equals(pairo.getLeft()) && this.right.equals(pairo.getRight()); } } public static void main(String[] args) { Scanner scnr = new Scanner(System.in); int T = scnr.nextInt(); for (int t = 1; t <= T; t++) { RNPair.removeAll(RNPair); Integer first = scnr.nextInt(); Integer last = scnr.nextInt(); int ans = 0; for (int i = first; i < last; i++) { ans += check(first, last, i); } //ans /= 2; System.out.println(""Case #"" + t + "": "" +RNPair.size()); } } public static int check(Integer start, Integer end, Integer num) { String numStr = num.toString(); int l = numStr.length(); int count = 0; for (int i = 0; i < l - 1; i++) { String rotStr = numStr.substring(l - i - 1) + numStr.substring(0, l - i - 1); int rotStrNum = Integer.parseInt(rotStr); if (rotStrNum < start || rotStrNum > end) continue; if (rotStrNum <= num) continue; if (num.toString().length() != Integer.toString(rotStrNum).length()) continue; if ((start <= num) && (num < rotStrNum) && (rotStrNum <= end)) { count++; Pair p = new Pair(num, rotStrNum); RNPair.add(p); //System.out.println(num + "" "" + rotStrNum); } } return count; } } " B11260,"import java.io.File; import java.util.*; public class ProblemC { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new File(""C:\\C-small-attempt0.in"")); //Scanner sc = new Scanner(System.in); int cases = Integer.parseInt(sc.nextLine().trim()); for(int i = 0; i < cases; i++){ int a = sc.nextInt(); int b = sc.nextInt(); System.out.println(""Case #"" + (i + 1) + "": "" + solve(a,b)); } } private static int solve(int a, int b) { int [][]vis = new int[b + 1][b + 1]; int count = 0; for(int i = a; i <= b; i++){ int []arr = getPair(i); for(int j : arr){ if((j >= a) && (j <= b) && (i != j) && vis[i][j] != 1){ vis[i][j] = 1; vis[j][i] = 1; //System.out.println(i + "" "" + j); count++; } } } return count; } private static int[] getPair(int i) { int []ret = new int[]{}; String str = String.valueOf(i); if(str.endsWith(""0"")){ } else if(i < 10){ } else if (i < 100){ int a1 = i %10; int a2 = i/10; int a3 = a1*10 + a2; ret = new int[]{a3}; } else if (i <= 1000){ int a1 = i % 10; int a2 = ((i - a1)/10) % 10; int a3 = i/100; int a4 = a1*100 + a3*10 + a2; int a5 = a2*100 + a1*10 + a3; ret = new int[]{a4,a5}; } return ret; } } " B12546,"import java.io.File; import java.lang.StringBuilder; import java.util.Scanner; import java.io.FileWriter; public class RN { public static void main(String[] args) throws Exception{ File input = new File(""C-small-attempt1.in""); File output = new File(""output.out""); FileWriter fw = new FileWriter(output); Scanner s = new Scanner(input); int numloops = s.nextInt(); StringBuilder sb = new StringBuilder(); for(int n=0; n i && rotval <= hi ){//&& rotstr.length() == strnum.length()){ numrepeats++; //System.out.println(strnum + "" "" + rotstr); } if(rotval == i) ;//break; //already had a repeating number } } sb.append(numrepeats + ""\n""); //fw.append(numrepeats + ""\n""); } fw.write(sb.toString()); fw.close(); } } " B13242,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; public class CodeJam { public ReadWriteTextFile rw = new ReadWriteTextFile(); public int countDigits(int number) { int numberOfDigits = 0; while (number > 0) { number = number / 10; numberOfDigits++; } return numberOfDigits; } public int multiplyIndex(int count) { int multiplyIndex = 1; for (int i = 1;i < count;i++) { multiplyIndex *= 10; } return multiplyIndex; } public boolean isRecycled(int firstNumber, int secondNumber) { int firstLength = countDigits(firstNumber); int secondLength = countDigits(secondNumber); if (firstLength != secondLength) { return false; } int multiplyingIndex = multiplyIndex(firstLength); for (int i = 1; i < firstLength; i++) { secondNumber = secondNumber / 10 + (secondNumber % 10) * multiplyingIndex; if (firstNumber == secondNumber) { return true; } } return false; } public static void main(String[] args) { CodeJam codeJam = new CodeJam(); int sampleSize = codeJam.rw.readIntLine(); for (int i = 0; i < sampleSize; i++) { int c = 0; int firstNumber = codeJam.rw.readInt(); int secondNumber = codeJam.rw.readInt(); int recycledNumberCount = 0; for (; firstNumber < secondNumber; firstNumber++) { int currentFirstPair = firstNumber; for (int j = 1; currentFirstPair + j <= secondNumber; j++) { if (codeJam.isRecycled(currentFirstPair, currentFirstPair + j)) recycledNumberCount++; } } codeJam.rw.writeNextLine(recycledNumberCount); } codeJam.rw.close(); } } " B11657,"package googleCodeJam; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Map map = new HashMap(); int i; //System.out.println(""size of map: "" + map.size()); try{ FileInputStream fstream = new FileInputStream(""/Users/mkay/Documents/input_31.txt""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; int input1, input2; String str1, str2; int count = 0,j,m,n,num; while ((strLine = br.readLine()) != null) { //System.out.println (strLine); if(count != 0 ) { map = new HashMap(); input1 = Integer.parseInt(strLine.split("" "")[0]); input2 = Integer.parseInt(strLine.split("" "")[1]); num=0; ArrayList arr; for(i=input1;i= input1 && j<= input2 && j <= 99 && j > i){ num++; } }else{ j=i/10+(i%10)*100; //if(i==112) // System.out.println(""first one : "" + j); if(j>= input1 && j<= input2 && j!=i && j >= 100 && j>i){ if(i= input1 && j<= input2 && j>= 100 && j > i){ if(i implements CodeJamConstants { private final CodeJamWindow window = new CodeJamWindow(); private final CodeJamMainPanel mainPanel = new CodeJamMainPanel(); private final StatusListener statusListener = mainPanel; protected abstract AbstractCodeJamProblemSolver getTaskSolver(); protected abstract String getAssignmentName(); public void start() { if (!DEFAULT_CODE_JAM_DIRECTORY.exists()) { DEFAULT_CODE_JAM_DIRECTORY.mkdirs(); } window.setAssignmentName(getAssignmentName()); window.setContentPane(mainPanel); window.setEnabled(true); window.setVisible(true); final JFileChooser fileChooser = mainPanel.getFileChooser(); fileChooser.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals(JFileChooser.CANCEL_SELECTION)) { System.exit(0); return; } File inputFile = fileChooser.getSelectedFile(); String inputFilename = inputFile.getAbsolutePath(); int suffixIndex = inputFilename.lastIndexOf("".in""); String neutralFilenamePart = inputFilename.substring(0, suffixIndex); String outputFilename = neutralFilenamePart + "".out""; File outputFile = new File(outputFilename); System.out.println(""Input: "" + inputFilename + "", exists: "" + inputFile.exists()); System.out.println(""Output: "" + outputFilename + "", exists: "" + outputFile.exists()); if (outputFile.exists()) { outputFile.delete(); } try { outputFile.createNewFile(); } catch (IOException ioexception) { ioexception.printStackTrace(); } if ((null != inputFile) && (inputFile.exists())) { AbstractCodeJamProblemSolver taskSolver = getTaskSolver(); taskSolver.addStatusListener(statusListener); taskSolver.solveInputFile(inputFile, outputFile); } } }); } } " B10957,"import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; public class ProblemC { public static void main(String[] args) throws Exception { Scanner in = new Scanner(// // System.in new FileInputStream(""c-small.in"") // new FileInputStream(""b-large.in"") ); PrintStream out = new PrintStream( // // System.out new FileOutputStream(""c-small.out"") // new FileOutputStream(""b-large.out"") ); int T = in.nextInt(); for (int i = 1; i <= T; i++) { int A = in.nextInt(); int B = in.nextInt(); int res = 0; for (int x = A; x < B; x++) { res += cycle(x, A, B); } out.println(""Case #"" + i + "": "" + res); } } private static int cycle(int n, int A, int B) { int m = n; int digits = (int) Math.log10(n) + 1; if (digits == 1) return 0; int mul = 1; for (int i = 1; i < digits; i++) mul *= 10; int ret = 0; HashSet used = new HashSet(); for (int i = 0; i < digits; i++) { m = (m / 10) + (m % 10) * mul; if (m > n && m != n && m <= B && !used.contains(m)) { ret++; used.add(m); } } return ret; } } " B11431,"import java.io.*; import java.util.*; class p3 { public static void main(String s[]) { int startingnum; int endingnum; int totalcases; int pairs; try{ File f = new File(""C-small-attempt0.in""); File o = new File(""Output.out""); String strLine=null; int first=1; BufferedReader br = new BufferedReader(new FileReader(f)); PrintWriter out = new PrintWriter(new FileWriter(o)); strLine = br.readLine(); totalcases=Integer.parseInt(strLine); for(int i=0; i arl = new ArrayList(); for(currentnum = startingnum; currentnum <= endingnum; currentnum++) { // System.out.println(); String curr=currentnum+""""; String rotatednum=null; try{ for(int i=0; istartingnum && ( Integer.parseInt(rotatednum) )i && k<=n2) { count[t]++; //System.out.println(count[t]); } } } t++; /*System.out.println(""n1:""+n1); System.out.println(""n2:""+n2);*/ } //System.out.println(""t=""+t); for(int i=0;i0){ output.newLine(); } String content = ""Case #""+(i+1)+"": ""+contents[i]; output.write( content ); System.out.println(content); } } finally{ output.close(); } } catch (IOException e) { e.printStackTrace(); } } } " B11874,"package qualification_2012; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; public class PC { static Scanner sc = new Scanner(System.in); static PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args) { int n = sc.nextInt(); for (int i = 1; i <= n; i++) { int a = sc.nextInt(); int b = sc.nextInt(); pw.println(""Case #"" + i + "": "" + calculate(a, b)); } pw.flush(); } static long calculate(int a, int b) { long result = 0; for (int j = a; j < b; j++) { result += count(j, b); } return result; } static int count(int n, int max) { String str = n + """"; int m = str.length(); int result = 0; ArrayList store = new ArrayList(); for (int i = 1; i < m; i++) { int b1 = (int) Math.pow(10, i); int b2 = (int) Math.pow(10, m - i); int x = (n % b1) * b2 + n / b1; if (x > n && x <= max && !store.contains(x)) { store.add(x); result++; } } // if (result > 0) // pw.println(n + "" "" + result); return result; } } " B11816,"/** * Google CodeJam 2012 * Qualification round - Problem C * Recycled Numbers * * Solved by Üllar Soon */ package eu.positivew.codejam.recycled; import java.io.BufferedReader; import java.io.IOException; import eu.positivew.codejam.framework.CodeJamInputCase; import eu.positivew.codejam.framework.CodeJamInputParser; /** * Recycled Numbers input parser class. * * @author Üllar Soon */ public class RecycledNumbersParser implements CodeJamInputParser { @Override public CodeJamInputCase readCase(BufferedReader input) { CodeJamInputCase inCase; try { String line = input.readLine(); String[] args = line.split("" ""); Integer[] abArr = new Integer[args.length]; for(int i = 0; i < args.length; i++) { try { abArr[i] = Integer.parseInt(args[i]); } catch(NumberFormatException ex) { System.err.println(""Badly formatted test case data!""); } } inCase = new RecycledNumbersCase(abArr); return inCase; } catch (IOException e) { System.err.println(""Failed to read test case data!""); return null; } } } " B10377,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; class RecycledNumber { /** * @param args * @throws IOException * @throws NumberFormatException */ public static void main(String[] args) throws NumberFormatException, IOException { // TODO Auto-generated method stub FileInputStream fstream = new FileInputStream(""C:\\input.txt""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); int cases = Integer.parseInt(br.readLine()); String mainOutput = """"; for (int c = 0; c < cases; c++) { StringTokenizer stringTokenizer = new StringTokenizer(br.readLine()); int a = Integer.parseInt(stringTokenizer.nextToken()); int b = Integer.parseInt(stringTokenizer.nextToken()); int finalCount = 0; int arr[] = new int[b * 2]; int arr2[] = new int[b * 2]; for (int n = a; n < b; n++) { int TEN = 10; int count = Integer.toString(n).length(); for (int i = 1; i < count; i++) { int m = (int) ((n % Math.pow(TEN, i)) * Math.pow(TEN, count - i)) + (int) (n / Math.pow(TEN, i)); if (a <= n && n < m && m <= b) { // System.out.println(n + "" "" + m); arr[finalCount] = m; arr2[finalCount++] = n; } } } int count = 0; for (int i = 1; i < finalCount; i++) { if ((arr2[i] == arr2[i + 1] && arr[i] == arr[i + 1]) || (arr2[i - 1] == arr2[i] && arr[i - 1] == arr[i])) { count++; } } mainOutput = mainOutput + ""Case #""+(c+1)+"": ""+(finalCount - (count / 2))+""\n""; } BufferedWriter bw = new BufferedWriter(new FileWriter(new File( ""C:\\output.txt""), true)); bw.write(mainOutput); bw.close(); in.close(); } } " B11982,"package recycledNumbers; import java.util.*; public class RecycledNumbers { public int countRecylcedNumbers(int x, int y ) { int count =0; int m=x+1; ArrayList> arrayList= new ArrayList>(); ArrayList list = new ArrayList(); for(int i=0;i(); for(int j=0;j=x) { flag = true; if(i==m) { System.out.println(i + "" "" + array[j]); count++; list.add(new Integer(array[j]).toString()); } else { ArrayList searchList= arrayList.get(array[j]); if(searchList!= null) { for(int k=0;k= a && !used[number1] && number1 != a) { used[a] = true; count++; } } else if(a >= 100) { char temp0 = start[0]; char temp1 = start[1]; char temp2 = start[2]; //one rotation start[2] = temp1; start[1] = temp0; start[0] = temp2; int number1 = Integer.parseInt(new String(start)); if(number1 <= b && number1 >= a && !used[number1] && number1 != a) { used[a] = true; count++; } start[2] = temp0; start[1] = temp2; start[0] = temp1; int number2 = Integer.parseInt(new String(start)); if(number2 <= b && number2 >= a && !used[number2] && number1 != number2 && number2 != a) { used[a] = true; count++; } } } System.out.println(""Case #"" + (i+1) + "": "" + count); } } } " B10145,"import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; /* * Google Code Jam 2012 * Qualification 2012 * raguenets@gmail.com * Usage : java RecycledNumbers inputFileName outputFileName */ public class RecycledNumbers { public static void main(String[] args) { int T = 0; int A = 0; int B = 0; if (args.length == 2) { String inputFilename = args[0]; File finput = new File(inputFilename); String outputFilename = args[1]; File foutput = new File(outputFilename); Scanner scanner = null; BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter(foutput)); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if (finput.exists()) { try { scanner = new Scanner(finput); // Reads first line : number of Tests if (scanner.hasNextInt()) { T = scanner.nextInt(); scanner.nextLine(); } for (int i = 0; i < T; i++) { // Read number of flies A = scanner.nextInt(); B = scanner.nextInt(); // Read fly positions bw.write(""Case #"" + (i + 1) + "": "" + numberOfRecycled(A,B) + ""\n""); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { bw.close(); if (scanner != null) { scanner.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } public static int numberOfRecycled(int A,int B) { if (B < 10) { return 0; } else if (B < 100) { int count = 0; for (int i=A; i < B;i++) { int tens = i/10; int units = i%10; if (units*10+tens <= B && units*10+tens > i) { count++; } } return count; } else if (B < 1000) { int count = 0; for (int i=A; i < B;i++) { int cents = i/100; int tens = (i-100*cents)/10; int units = i%10; // ABC // BCA // CAB if (units*100+cents*10+tens <= B && units*100+cents*10+tens >i) { count++; } if (tens*100+units*10+cents <= B && tens*100+units*10+cents > i) { count++; } } return count; } return 0; } } " B11743,"package gcj; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; import java.util.Iterator; public class Jam2012 { //-10^9 < Integer.MAX_VALUE (2^31) < 10^10 //-10^18 < Long.MAX_VALUE (2^63) < 10^20 public static void main(String[] args) throws NumberFormatException, IOException { Scanner sc = new Scanner(new FileReader(filename+"".in"")); String output; String outputfile = filename + "".out""; FileOutputStream Output = new FileOutputStream(outputfile); PrintStream file2 = new PrintStream(Output); boolean after25 = false; boolean after50 = false; boolean after75 = false; int T = sc.nextInt(); //int T = Integer.parseInt(sc.nextLine()); System.out.println(Calendar.getInstance().getTime()+"" - Started writing to: ""+outputfile); //getPrimesH(); for (int i = 0; i < T; i++) { //ArrayList orders = new ArrayList(); //ArrayList v2 = new ArrayList(); //ArrayList queryList = new ArrayList(); //StringTokenizer st = new StringTokenizer(br.readLine(),"" ""); int a = sc.nextInt(); int b = sc.nextInt(); output = solve(a,b); file2.println(""Case #"" + (i+1) + "": ""+output); if ((100*(i+1)/T >= 25) && (!after25)) { System.out.println(Calendar.getInstance().getTime()+"" - 25% done""); after25 = true; } else if ((100*(i+1)/T >= 50) && (!after50)) { System.out.println(Calendar.getInstance().getTime()+"" - 50% done""); after50 = true; } else if ((100*(i+1)/T >= 75) && (!after75)) { System.out.println(Calendar.getInstance().getTime()+"" - 75% done""); after75 = true; } } sc.close(); System.out.println(Calendar.getInstance().getTime()+"" - Finished writing to: ""+outputfile); } /* private static String solve(String nextLine) { char[] a = {'f','g','d','e','b','c','a','n','o','l','m','j','k','h','i','w','v','u','t','s','r','q','p','z','y','x'}; char[] b = {'c','v','s','o','h','e','y','b','k','g','l','u','i','x','d','f','p','j','w','n','t','z','r','q','a','m'}; HashMap lib = new HashMap(); for (int i = 0; i< a.length; i++) { if(!lib.containsKey(a[i])) { lib.put(a[i], b[i]); } } StringBuilder out = new StringBuilder(); for (int i = 0; i< nextLine.length(); i++) { if (nextLine.charAt(i) == ' ') {out.append(' ');} else { out.append(lib.get(nextLine.charAt(i)));} } return out.toString(); }*/ private static String solve(int a, int b) { int length = String.valueOf(b).length(); if (length == 1) { return ""0""; } HashSet found = null; long total = 0; for (int i = a; i < b; i++) { found = null; String s = String.valueOf(i); StringBuilder sb = new StringBuilder(); for (int j = 0; j < s.length(); j++) { sb.append(s.charAt((j+s.length()-1)%s.length())); } int shift = Integer.parseInt(sb.toString()); for (int j = 1; j < length; j++) { if (shift > i && shift <= b) { if (found == null) { found = new HashSet(); } if (!found.contains(shift)) { found.add(shift); //System.out.println(i+"",""+shift); total++; } } //s = String.valueOf(shift); sb = new StringBuilder(); for (int k = 0; k < s.length(); k++) { sb.append(s.charAt((k+s.length()-(1+j))%s.length())); } shift = Integer.parseInt(sb.toString()); } } return String.valueOf(total); } //static String size = ""sample""; //static String size = ""small""; //static String size = ""large""= static String filename = ""D:\\gcj\\2012\\Q\\C-small-attempt0""; } " B11499," import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; import java.util.Vector; public class C { /** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { Scanner scan = new Scanner(new File(""C-small-attempt0.in"")); PrintWriter out = new PrintWriter(new File(""out.txt"")); int cases = scan.nextInt(); for (int r = 1; r <= cases; r++) { int a = scan.nextInt(); int b = scan.nextInt(); Vector[] v = new Vector[b + 1]; for (int i = 0; i < v.length; i++) v[i] = new Vector(); long ret = 0; for (int n = a; n <= b; n++) { String sn = n + """"; for (int j = sn.length()-1; j > 0; j--) { String sm = sn.substring(j) + sn.substring(0, j); int m = Integer.parseInt(sm); sm = m + """"; if (sm.length() == sn.length() && m <= b && m > n) { if (!v[n].contains(m)) { v[n].add(m); v[m].add(n); ret++; } } } } out.println(""Case #"" + r + "": "" + ret); } out.close(); scan.close(); } } " B10523,"package gcj2012qr; import java.io.*; import java.util.*; import java.util.concurrent.*; import com.google.*; /** * @author Roman Kosenko */ public class RecycledNumbers extends SingleThreadSolution { public static void main(String[] args) throws Exception { solve(new SolutionFactory() { public Callable read(BufferedReader br) throws IOException { String[] ss = br.readLine().split("" ""); assert ss.length == 2; return new RecycledNumbers(Integer.parseInt(ss[0]), Integer.parseInt(ss[1])); } }, ""google/src/gcj2012qr/"" + ""C-small-attempt0.in""); } private final int a, b; public RecycledNumbers(int a, int b) { this.a = a; this.b = b; } public String call() throws Exception { int result = 0; for(int i = a; i < b; i++) { int p = 1; for(int t = i / 10; t != 0; p *= 10) t /= 10; for(int t = i;;) { t = t / 10 + p * (t % 10); if(t == i) break; if(t > i && t <= b) result++; } } return Integer.toString(result); } } " B10535,"import java.util.*; public class RecycledNum { private static int testCase; public static void main( String[] args ) { Scanner s = new Scanner( System.in ); RecycledNum r = new RecycledNum(); r.setTestCase(Integer.parseInt(s.nextLine())); for( int i = 0; i < testCase; i++ ) { int A = s.nextInt(); int B = s.nextInt(); s.nextLine(); if( B/A < 10) { System.out.println( ""Case #"" +(i+1) +"": "" + r.recycle( A, B ) ); } } } public RecycledNum() { this.testCase = 1; } public void setTestCase( int T ) { if( T>=1 && T<=50 ) this.testCase = T; } public int getTestCase() { return this.testCase; } public int recycle(int A, int B) { int n = 0; double j = A; int count = 0; while( j >= 1) { j = j/10; n = n + 1; } for( int i = A; i <= B; i++ ) { //System.out.println(""original ""+ i); char[] array = new char[n]; String numstri = i + """"; for( int m = 0; m < n; m++) { array[m]=numstri.charAt(m); } int[] pair = new int[n]; for( int q = 0; q< pair.length; q++) { pair[q] = 0; } int count2 = 0; for ( int k = 0 ; k < n-1; k++ ) { String str = """"; String rts = """"; for( int p = 0; p < n - k-1; p++ ) { str = str + array[p]; ///System.out.println( str ); } for( int p = n-k-1; p < n; p++) { rts = rts + array[p]; //System.out.println(rts ); } String stri = rts + str; // System.out.println( stri); int num = Integer.parseInt(stri); boolean check = true; if( num <= B && num >= A && num != i ) { for( int q = 0; q < pair.length;q++ ) { if(pair[q] == num ){ check = false; } } if( check ) { count++; count2++; // System.out.println(count); pair[count2-1] = num; //System.out.println( num +"" ""); } } } } return count/2; } }" B10021,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; public class InputReader { private BufferedReader br = null; public InputReader(String fileName) { try { br = new BufferedReader(new FileReader(fileName)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public ArrayList loadLines() { ArrayList lines = new ArrayList(); String[] arrLines = null; String tmp = null; try { while ((tmp = br.readLine()) != null) { lines.add(tmp); } br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return lines; } } " B11465,"import java.io.PrintWriter; import java.util.Scanner; public class Codejam { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner inFile = null; PrintWriter outFile = null; inFile = FileUtils.ScannerOpen(""zin""); outFile = FileUtils.PrintWriterOpen(""zout""); int numberOfTestCase=0; //get the number of test cases if(inFile.hasNext()){ String s=inFile.nextLine(); try{ numberOfTestCase=Integer.parseInt(s); }catch(Exception e){ } } //for each test case get the input for(int i=0;i set = new HashSet(); private static void isRecycled(int i) { String s = i + """"; LinkedList l = new LinkedList(); for (int j = 0; j < s.length(); j++) { l.add(s.charAt(j) + """"); } for (int j = 0; j < s.length(); j++) { String zs = listToString(l); if (debug) { System.out.println(zs); } int z = Integer.parseInt(zs); if ((z >= a) && (z <= b) && (z > i)) { set.add(""{"" + i + "","" + z + ""}""); } l.add(l.getFirst()); l.removeFirst(); } } private static String listToString(List l) { return l.toString().replace(""["", """").replace(""]"", """").replace("" "", """") .replace("","", """"); } public static void main(String[] in) throws IOException { String fileName = ""C-small-attempt0.in""; URL file = Recycle.class.getResource(fileName); String path = file.getFile(); BufferedReader reader = new BufferedReader(new FileReader(path)); File fileOut = new File(fileName + "".out""); fileOut.createNewFile(); BufferedWriter writer = new BufferedWriter(new FileWriter(fileOut)); int numOfCases = Integer.parseInt(reader.readLine()); for (int t = 0; t < numOfCases; t++) { String line = reader.readLine(); String outputLine = ""Case #"" + (t + 1) + "": "" + result(line); System.out.println(outputLine); writer.write(outputLine + System.getProperty(""line.separator"")); } reader.close(); writer.close(); } private static int result(String line) { String[] params = line.split(""\\s""); a = Integer.parseInt(params[0]); b = Integer.parseInt(params[1]); set.clear(); for (int i = a; i <= b; i++) { isRecycled(i); } return set.size(); } } " B13000,"package mgg.problems; import java.util.ArrayList; import java.util.List; import mgg.utils.CombinatoryUtils; import mgg.utils.FileUtil; import mgg.utils.StringUtils; import mgg.utils.Triplet; /** * @author manolo * @date 14/04/12 */ public class ProblemB { public final static String EXAMPLE_IN = ""B-example.in""; public final static String EXAMPLE_OUT = ""B-example.out""; public final static String B_SMALL_IN = ""B-small-practice.in""; public final static String B_SMALL_OUT = ""B-small-practice.out""; public final static String B_LARGE_IN = ""B-large-practice.in""; public final static String B_LARGE_OUT = ""B-large-practice.out""; public final static String delim = "" ""; public static String solve(FileUtil util) { String line = util.getLine(); List listOfArgs = StringUtils.stringWithIntegersToList(line, delim); //System.out.println(""\tArgs = "" + listOfArgs); int googlers = listOfArgs.get(0); System.out.println(""\tGooglers = "" + googlers); int surprisingScores = listOfArgs.get(1); System.out.println(""\tSurprising scores = "" + surprisingScores); int leastScore = listOfArgs.get(2); System.out.println(""\tMinimum = "" + leastScore); List listOfScores = listOfArgs.subList(3, listOfArgs.size()); System.out.println(""\tScores = "" + listOfScores); List listOfTriplets; List> listOfListOfTriplets = new ArrayList>(); for(int score : listOfScores){ listOfListOfTriplets.add(CombinatoryUtils.possibleTriplets(score)); } System.out.println(""\tPossible triplets: "" + listOfListOfTriplets); List> scenarios = calculateScenarios(listOfListOfTriplets, surprisingScores); System.out.println(""\tPossible scenarios: "" + scenarios); return null; } private static List> calculateScenarios( List> listOfListOfTriplets, int surprisingScores) { return null; } } " B10826,"package com.skidson.codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class RecycledNumbers { private static final File inFile = new File(""input""); private static final File outFile = new File(""output""); public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(inFile)); BufferedWriter out = new BufferedWriter(new FileWriter(outFile)); int numTests = Integer.parseInt(in.readLine()); for (int x = 0; x < numTests; x++) { String[] params = in.readLine().split("" ""); final int A = Integer.parseInt(params[0]); final int B = Integer.parseInt(params[1]); int y = 0; for (int n = A; n < B; n++) { for (int m = B; m > n; m--) { String left = String.valueOf(n); for (int i = 1; i < left.length(); i++) { int pivot = left.length()-i; int temp = Integer.parseInt(left.substring(pivot) + left.substring(0, pivot)); // Repeating patterns will give us duplicate pairs, e.g. n = 1212 if (temp == n) break; if (temp == m) y++; } } } out.write(""Case #"" + (x+1) + "": "" + y + ""\n""); } out.flush(); out.close(); } } " B11305,"/** * Copyright 2012 Christopher Schmitz. All Rights Reserved. */ package com.isotopeent.codejam.lib.converters; import com.isotopeent.codejam.lib.InputConverter; public class MultiLineConverter implements InputConverter { private InputConverter[] converters; private int count; private Object[] input; private int lineNumber; public MultiLineConverter(InputConverter lineConverter, int count) { this.converters = new InputConverter[count]; this.count = count; for (int i = 0; i < count; i++) { converters[i] = lineConverter; } } public MultiLineConverter(InputConverter[] lineConverters) { this.converters = lineConverters; this.count = lineConverters.length; } @Override public boolean readLine(String data) { if (lineNumber == 0) { input = new Object[count]; } InputConverter converter = converters[lineNumber]; if (!converter.readLine(data)) { input[lineNumber++] = converter.generateObject(); } if (lineNumber >= input.length){ lineNumber = 0; } return lineNumber != 0; } @Override public Object[] generateObject() { return input; } } " B13260,"package com.eevoskos.codejam; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { private static final boolean DEBUG = false; public static void main(String... args) { RecycledNumbers instance = new RecycledNumbers(); try { BufferedReader c = new BufferedReader(new InputStreamReader(System.in)); // Number of test cases int T = Integer.valueOf(c.readLine()); System.out.println(); // Do, for each test case for (int i = 0; i < T; i++) { // Read input string String input = c.readLine(); // Process input String output = instance.solveCase(input); // Print the translated text System.out.println(""Case #"" + (i + 1) + "": "" + output); } } catch (Exception e) { e.printStackTrace(); } } Set allPairs = new HashSet(); Set countPairs = new HashSet(); private String solveCase(String input) { // Init variables countPairs = new HashSet(); String[] split = input.split("" ""); int A = Integer.valueOf(split[0]); int B = Integer.valueOf(split[1]); return getTotalRecycledPairs(A, B); } private String getTotalRecycledPairs(int a, int b) { int numOfPairs = 0; for (int i = a; i <= b; i++) { numOfPairs += countRecycledPairs(i, a, b); } return String.valueOf(numOfPairs); } private int countRecycledPairs(int num, int a, int b) { int count = 0; Set pairs = getAllPairs(num); for (Pair p : pairs) { if (p.isIncludedIn(a, b) && p.isRecycled()) { if (!countPairs.contains(p)) { countPairs.add(p); count++; if (DEBUG) { System.out.println(p + "": counts!""); } } else { if (DEBUG) { System.out.println(p + "": already count""); } } } else { if (DEBUG) { System.out.println(p + "": does not count""); } } } return count; } private Set getAllPairs(int num) { HashSet pairs = new HashSet(); String s = String.valueOf(num); for (int i = 0; i < s.length(); i++) { String s1 = s.substring(0, i); String s2 = s.substring(i); pairs.add(new Pair(Integer.valueOf(s1 + s2), Integer.valueOf(s2 + s1))); } return pairs; } class Pair { int n, m; Pair(int n, int m) { this.n = Math.min(n, m); this.m = Math.max(n, m); } @Override public String toString() { return ""("" + n + "", "" + m + "")""; } boolean isRecycled() { String N = String.valueOf(n); String M = String.valueOf(m); if (N.length() != M.length()) { return false; } for (int i = 0; i < N.length(); i++) { String n1 = N.substring(0, i); String n2 = N.substring(i); if ((n2 + n1).matches(M)) { return true; } } return false; } boolean isIncludedIn(int a, int b) { return a <= n && n < m && m <= b; } @Override public boolean equals(Object another) { if (another == null) return false; if (!(another instanceof Pair)) return false; return (this.m == ((Pair) another).m && this.n == ((Pair) another).n) || (this.m == ((Pair) another).n && this.n == ((Pair) another).m); } @Override public int hashCode() { return String.valueOf(n).hashCode() + String.valueOf(m).hashCode(); } } } " B10310,"import java.io.BufferedReader; import java.io.FileReader; public class C { private static final String head = ""Case #""; public static void main(String[] args) { try{ FileReader f = new FileReader(args[0]); BufferedReader b = new BufferedReader(f); String s; boolean ff = false; int c = 0; while((s = b.readLine())!=null){ if (!ff){ff=true;continue;} else { c++; System.out.println(head + c + "": "" + C.getI(s)); } } } catch (Exception e) { e.printStackTrace(); } finally { } } private static int getI(final String line) { //System.out.print(""TEST:""+line); int r = 0; int a,b; String[] sp = line.split("" ""); a = Integer.valueOf(sp[0]); b = Integer.valueOf(sp[1]); //if (b < 10) return 0; //else if (a == b) return 0; //else { //if (a <= 10) {a = 11;} for (int x = a; x <= b; x++) { for (int y = 0; y < String.valueOf(x).length(); y++) { if (y != 0) { int re = C.getRR(x, y); if (re <= 11 || re >= x) {continue;} else { if (re >= a && re <= b) { //System.out.println(""X:""+x+""T""+re); r++; } } } } } //} return r; } private static Integer getRR(final int v, final int o) { StringBuilder sb = new StringBuilder(); String str = String.valueOf(v); sb.append(str.substring(o)); sb.append(str.substring(0, o)); return Integer.valueOf(sb.toString()); } } " B10014,"package googlejam3; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; public class Main3 { static HashMap pairsMap = new HashMap(); protected static String resolveTestCase(String line) { String [] tokens = line.split("" ""); int A = Integer.parseInt(tokens[0]); int B = Integer.parseInt(tokens[1]); int pairs = 0; pairsMap.clear(); for ( int n = A; n <= B; n++ ) { String test = Integer.toString(n); for ( int j = 1; j < test.length(); j++ ) { String test2 = test.substring(j, test.length()) + test.substring(0, j); int m = Integer.parseInt(test2); if ( test2.charAt(0) != '0' && n < m && m <= B && pairsMap.get(test+test2) == null) { System.out.println(""N = "" + n + "" M = "" + m ); pairs++; pairsMap.put(test+test2, """"); } } } return """" + pairs; } public static void main (String [] args) throws IOException { String inputFile = args[0]; File f = new File(inputFile); FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr); File f2 = new File(inputFile + "".out""); FileWriter fw = new FileWriter(f2); String line = br.readLine(); int count = Integer.parseInt(line); // resolve test cases int testcase = 1; for(int tests = 0; tests < count; tests++) { line = br.readLine(); System.out.println(line); String output = ""Case #""+testcase+"": ""; output += resolveTestCase(line); System.out.println(output+""\n""); fw.write(output+""\r\n""); testcase++; } fw.close(); } } " B10806,"package com.googlecodejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; /* Main function goes here */ public class RecycledNumbersProblemC { public static void main(String[] args) { try { BufferedReader bfreader = new BufferedReader(new FileReader(""E:\\workspace\\TopCoder\\src\\com\\googlecodejam\\C-small-attempt0.in"")); BufferedWriter bfrwriter = new BufferedWriter(new FileWriter(""E:\\workspace\\TopCoder\\src\\com\\googlecodejam\\output.txt"")); int n = Integer.parseInt(bfreader.readLine()); String out = """"; for (int i = 0; i < n; i++) { String s = bfreader.readLine(); out += ""Case #"" + (i + 1) + "": "" + getRecycledPair(s) + ""\n""; } System.out.println(out); bfrwriter.write(out); bfreader.close(); bfrwriter.close(); } catch (IOException e) { e.printStackTrace(); } } /* Main function goes here */ public static String getRecycledPair(String s) { int iMinNumber = Integer.parseInt(s.split("" "")[0]); int iMaxNumber = Integer.parseInt(s.split("" "")[1]); int iLength; Integer iNoRecycledNo = 1; Integer iNoOfRecycledPairs = 0; ArrayList alInputNos = new ArrayList(); for (int i = iMinNumber; i <= iMaxNumber; i++) { alInputNos.add(i); } for (int number : alInputNos) { StringBuffer sNumber = new StringBuffer(Integer.toString(number)); iLength = sNumber.length(); ArrayList alRecycledPairs = new ArrayList(); for (int i = 1; i < sNumber.length(); i++) { StringBuffer recNum = new StringBuffer(); recNum.append(sNumber.substring(i, sNumber.length())); recNum.append(sNumber.substring(0, i)); int irecNumber = Integer.parseInt(recNum.toString()); String sTempNum = Integer.toString(irecNumber); if (iLength == sTempNum.length()) { if ((!(alRecycledPairs.contains(irecNumber))) && irecNumber <= iMaxNumber && irecNumber >= iMinNumber && !(irecNumber == number) && (alInputNos.contains(irecNumber))) { alRecycledPairs.add(irecNumber); iNoOfRecycledPairs = iNoRecycledNo / 2; iNoRecycledNo++; } } } } return Integer.toString(iNoOfRecycledPairs); } } " B11103,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; /** * @author Mark Devine * */ public class C { static final boolean DEBUG = false; static Scanner in; static PrintStream out; public static void main(String[] args) throws FileNotFoundException { if (DEBUG) { in = new Scanner(new File(""t"")); out = System.out; } else { in = new Scanner(new File(C.class.getName() + "".in"")); out = new PrintStream(C.class.getName() + "".out""); } int T = i(); for (int i = 0; i < T; i++) { pl(f(""Case #%d: %s"", i + 1, solve())); } out.close(); in.close(); System.out.println(""Done""); } static String solve() { HashSet done = new HashSet(); int A = i(); int B = i(); int pairs = 0; for (int n = A; n < B; n++) { String num = Integer.toString(n); for (int i = 1; i < num.length(); i++) { num = num.substring(1, num.length()) + num.charAt(0); int test = Integer.parseInt(num); if (test >= A && test <= B && n < test) { String map = n + "":"" + test; if (!done.contains(map)) { done.add(map); pairs++; } } } } return pairs + """"; } static void p(String x) { out.print(x); } static void pl(String x) { out.println(x); } static String f(String format, Object... args) { return String.format(format, args); } static int i() { return in.nextInt(); } static long l() { return in.nextLong(); } static String s(String pattern) { return in.next(pattern); } static String li() { return in.nextLine(); } }" B12824,"import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; import java.util.TreeMap; class Recycled { public static void main(String args[]) throws IOException{ Scanner in = new Scanner(new File(""recycle.txt"")); PrintWriter fw = new PrintWriter(new FileWriter(new File(""recycle.out""))); TreeMap > map = new TreeMap >(); for(int i = 1; i <= 2000000; i++){ ArrayList arr = new ArrayList(); String it = """" + i; for(int k = 0; k < it.length(); k++){ int temp = Integer.parseInt(it.substring(k + 1, it.length()) + it.substring(0, k+1)); if(temp > i){ boolean add = true; for(int ad = 0; ad < arr.size(); ad++){ if(temp==arr.get(ad)) add = false; } if(add) arr.add(temp); } } Collections.sort(arr); map.put(i, arr); } int cases = in.nextInt(); for(int c = 1; c <= cases; c++){ int A = in.nextInt(); int B = in.nextInt(); int pass = 0; for(int a = A; a < B; a++){ if(map.get(a)==null) continue; ArrayList list = map.get(a); for(int l = 0; l < list.size(); l++){ if(list.get(l) <= B) pass++; else break; } } String out = ""Case #"" + c + "": "" + pass; fw.println(out); } fw.close(); } } " B12861,"package google.codejam; import java.util.HashMap; public class RecycledNumberSolver implements GoogleSolver { @Override public String solve(String str) { String [] numbers = str.split("" ""); int min = Integer.parseInt(numbers[0]); int max = Integer.parseInt(numbers[1]); int digits = numbers[0].length(); System.out.println(""min:""+min + "" max:""+ max); HashMap map = new HashMap(); int count = 0; for(int i=min; i<=max ; i++){ for(int move=1 ; movei && testNum>=min && testNum<=max){ //System.out.println(""(""+temp + "" , "" + testNum+ "")""); if(map.get(i)==null || map.get(i)!=testNum){ map.put(i, testNum); count++; } } } map.clear(); } return count+""""; } } " B12404,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.HashSet; public class Prob1C { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new FileReader(""C-small-attempt0.in"")); PrintWriter pw = new PrintWriter(new FileWriter(""output.txt"")); int t = Integer.parseInt(br.readLine()); for(int x = 1; x <= t; x++) { int res = 0; String[] strs = br.readLine().split("" ""); int a = Integer.parseInt(strs[0]); int b = Integer.parseInt(strs[1]); if(a < 10 && b == 2000000) { pw.println(""Case #"" + x + "": 2498454""); continue; } for(int i = a; i <= b; i++) { HashSet set = new HashSet(); String as = """" + i; for(int j = 1; j < as.length(); j++) { String ns = as.substring(j) + as.substring(0, j); int nn = Integer.parseInt(ns); if(nn > i && nn <= b) { set.add(ns); } } res += set.size(); } pw.println(""Case #"" + x + "": "" + res); } br.close(); pw.close(); } } " B11635,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author 3mara */ public class Main { /** * @param args the command line arguments */ static int testCases = 0; static int a = 0, b = 0; static int numDigits; static HashMap> table = new HashMap>(); public static void read() { try { int index = 1; BufferedReader br = new BufferedReader(new FileReader(""C-small-attempt0.in"")); int result = 0; testCases = Integer.parseInt(br.readLine()); while (index <= testCases) { String array = (br.readLine()); a = Integer.parseInt((array.split("" ""))[0]); b = Integer.parseInt((array.split("" ""))[1]); numDigits = (array.split("" "")[0]).length(); if (a == (b) || a < 9) { System.out.println(""Case #"" + index + "": 0""); } else { result = 0; table.clear(); String temp = """"; for (int i = a; i <= b; i++) { for (int j = numDigits - 1; j >= 1; j--) { temp = i + """"; int tempint = Integer.parseInt(temp.substring(j) + temp.substring(0, j)); if ((tempint <= b) && tempint > i) { if (table.get(i) != null && !table.get(i).containsKey(tempint)) { // System.out.println(temp + ""===="" + temp.substring(j) + temp.substring(0, j)); result++; } else if (table.get(i) == null) { table.put(i, new HashMap()); table.get(i).put(tempint, 1); result++; } } } } System.out.println(""Case #"" + index + "": "" + result); } index++; } } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } public static void main(String[] args) { // try { // BufferedReader br = new BufferedReader(new FileReader(""a.txt"")); // String[] array = new String[288]; // String line = """"; // int i = 0; // while ((line = br.readLine()) != null) { // array[i] = line; // i++; // } // Arrays.sort(array); // for (int j = 0; j < 288; j++) { // System.out.println(array[j]); // } // // System.out.println(); // // System.out.println(); read(); // // System.out.println(); // } catch (IOException ex) { // Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); // } } } " B12376,"package google.codejam2012.awanish; import java.util.ArrayList; import java.util.Scanner; import java.util.StringTokenizer; public class RecycledNumbers { static long total = 0; /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner inputScan = new Scanner(System.in); int noOfCases = Integer.parseInt(inputScan.nextLine()); long start; long end; for (int i = 1; i <= noOfCases; i++) { total = 0; String startend = inputScan.nextLine(); StringTokenizer st = new StringTokenizer(startend, "" ""); start = Integer.parseInt(st.nextToken()); end = Integer.parseInt(st.nextToken()); for (long j = start; j <= end; j++) { checkPair(j, start, end); } System.out.println(""Case #"" + i + "": "" + total/2); } } private static void checkPair(long j, long start, long end) { ArrayList a = new ArrayList(); String tocheck = String.valueOf(j); a.add(tocheck); for (int c = 0; c < tocheck.length(); c++) { tocheck = rotate(tocheck); if (!a.contains(tocheck) && !tocheck.substring(0, 1).equals(""0"") && start <= Integer.parseInt(tocheck) && Integer.parseInt(tocheck) <= end) { a.add(tocheck); total++; } } } private static String rotate(String tocheck) { // TODO Auto-generated method stub return tocheck.substring(tocheck.length() - 1, tocheck.length()) + tocheck.substring(0, tocheck.length() - 1); } } " B12770,"public class ProblemC extends FileWrapper { private int A[] = null; private int B[] = null; private int digt[] = null; public ProblemC(String fileName) { this.processInput(fileName); this.calculate(); this.processOutput(OUTPUT); } @Override protected void processInput(String fileName) { try { this.openReadFile(fileName); this.caseNum = Integer.parseInt(this.readLine()); this.output = new String[this.caseNum]; this.A = new int[this.caseNum]; this.B = new int[this.caseNum]; this.digt = new int[this.caseNum]; for (int i = 0; i < this.caseNum; i++) { String elem[] = this.readLine().split("" ""); this.A[i] = Integer.parseInt(elem[0]); this.B[i] = Integer.parseInt(elem[1]); this.digt[i] = elem[0].length()-1; } this.closeReadFile(); } catch (Exception e) { } } @Override protected void calculate() { for (int i=0; ij && value<=B[i]) { total++; }else if (value==j) { break; } } } this.output[i] += total; } } public static void main(String argv[]) { if (argv.length > 0) { new ProblemC(argv[0]); } else { new ProblemC(""C-small-attempt0.in""); } } }" B11054,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class CodeJam { public static void main(String [] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int num = Integer.parseInt(br.readLine()); for(int ii=1;ii<=num;++ii) { StringTokenizer st = new StringTokenizer(br.readLine()); int begin = Integer.parseInt(st.nextToken()); int end = Integer.parseInt(st.nextToken()); int cnt=0; for(int i=begin; i<=end ; ++i) { int line = i; String orig = Integer.toString(line); String curr = orig; for(int j = 0; j= begin && intcurr <=end && intcurr > line) cnt++; } } System.out.println(""Case #""+ii+"": ""+cnt); } } } " B11918,"import java.io.IOException; import java.util.InputMismatchException; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.FileInputStream; import java.io.Writer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Egor Kulikov (egor@egork.net) */ public class Main { public static void main(String[] args) { InputStream inputStream; try { inputStream = new FileInputStream(""taskc.in""); } catch (IOException e) { throw new RuntimeException(e); } OutputStream outputStream; try { outputStream = new FileOutputStream(""taskc.out""); } catch (IOException e) { throw new RuntimeException(e); } InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { String a = in.readString(); String b = in.readString(); int answer = 0; for (int i = Integer.parseInt(a); i <= Integer.parseInt(b); i++) { String c = Integer.toString(i); String d = c; do { c = c.substring(c.length() - 1) + c.substring(0, c.length() - 1); if (c.compareTo(d) > 0 && c.compareTo(b) <= 0) answer++; } while (!c.equals(d)); } out.printLine(""Case #"" + testNumber + "":"", answer); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(outputStream); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } } " B12329,"package com.google.codejam; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class DancingWithGooglers { private int limit(long min, long max){ if (min>max) return 0; int count = 0; for (long i = min; i <= max; i++) { int loopCount = 1; long start = i; long rotation = i; do { rotation = rotate(start,loopCount); if ( rotation <= max && rotation > start) { // System.out.println(""pair numbers : "" + start + "","" + rotation); count+=1; } // else{ // System.out.println(""!!not pair numbers : "" + start + "","" + rotation); // } loopCount++; } while (loopCount<=Long.toString(start).length()); } return count; } // private long rotate(long x){ // if (x<9) { // return x; // } // long firstpart = x/10; // long secondpart = x%10; // double firstpartlen = (String.valueOf(firstpart)).length(); // int mul = (int) Math.pow(10, firstpartlen); // long fin = (secondpart * mul) + firstpart; // return fin; // } private long rotate(long x,int index){ if (x<9) { return x; } String s = Long.toString(x); String s1 = s.substring(0, s.length()-index); String s2 = s.substring(s.length()-index, s.length()); String s3 = s2+s1; return Long.parseLong(s3); } public static void main(String[] args) throws IOException{ BufferedReader in = new BufferedReader(new FileReader(""resources/googlecodejam/dancingwiththegooglers.txt"")); String strLine; int caseLine = 0; int lineCount = 0; DancingWithGooglers dancingWithGooglers = new DancingWithGooglers(); while ((strLine = in.readLine()) != null) { // Print the content on the console if (lineCount == 0) { lineCount+=1; continue; } caseLine += 1; long min = Long.parseLong(strLine.split("" "")[0]); long max = Long.parseLong(strLine.split("" "")[1]); System.out.println(""Case #"" + caseLine + "": "" + dancingWithGooglers.limit(min,max)); } } } " B11896,"import java.io.File; import java.io.FileWriter; import java.io.IOException; public class FileOut { /** * コンストラクタ. * @param filename 書き出すファイル名 * @param s 書き出す文字列 */ public FileOut(String filename, String s) { File f = new File(filename); FileWriter fw = null; try { fw = new FileWriter(f); fw.write(s); } catch (IOException e) { e.printStackTrace(); } finally { try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } } }" B11847,"package info.m3o.gcj2012.recyclednumber; import java.util.ArrayList; import java.util.List; public class RawInputLines_NotUsed { protected List rawInputLines; public List getRawInputLines() { if (rawInputLines == null) { rawInputLines = new ArrayList(); } return this.rawInputLines; } } " B11903,"import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; public class Run3 { private static class Pair { private String n; private String m; public Pair(String n, String m) { this.n = n; this.m = m; } public String getStringN() { return n; } public String getStringM() { return m; } public int getIntegerN() { return Integer.parseInt(n); } public int getIntegerM() { return Integer.parseInt(m); } @Override public boolean equals(Object obj) { Pair pair = (Pair)obj; if ((pair.getStringN().equals(this.n) && pair.getStringM().equals(this.m)) || (pair.getStringN().equals(this.m) && pair.getStringM().equals(this.n))) { return true; } else { return false; } } @Override public String toString() { return n+"" ""+m; } } public static void main(String[] args) { String path = ""files/C-small-attempt1.in""; int T = 0; ArrayList A = new ArrayList(); ArrayList B = new ArrayList(); ArrayList pairs = new ArrayList(); try { boolean isFirstLine = true; FileReader FR = new FileReader(path); BufferedReader BR = new BufferedReader(FR); String str = """"; while((str=BR.readLine())!=null) { if (isFirstLine) { T = Integer.parseInt(str); isFirstLine = false; } else { String[] temp = str.split("" ""); A.add(Integer.parseInt(temp[0])); B.add(Integer.parseInt(temp[1])); } } } catch (Exception e) { e.printStackTrace(); } for (int i = 0; i < T; i++) { pairs.clear(); int start = A.get(i); int end = B.get(i); for (int j = start; j <= end; j++) { String n = String.valueOf(j); String m = """"; for (int x = 1; x < n.length() ; x++) { m = moveDigital(n, x); if (start <= Integer.parseInt(n) && Integer.parseInt(n) < Integer.parseInt(m) && Integer.parseInt(m) <= end) { Pair pair = new Pair(n, m); if (!pairs.contains(pair)) { pairs.add(pair); } } } } System.out.println(""Case #""+(i+1)+"": ""+pairs.size()); } } static public String moveDigital(String number, int digitals) { return number.substring(number.length()-digitals, number.length())+number.substring(0, number.length()-digitals); } }" B12354,"import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Set; public class C { public static void main(String[] args) throws Throwable { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int numCases = Integer.parseInt(reader.readLine()); for (int c = 1; c <= numCases; c++) { System.out.println(""Case #"" + c + "": "" + solveCase(reader.readLine())); } } private static int solveCase(String line) { String[] tokens = line.split("" ""); int a = Integer.parseInt(tokens[0]); int b = Integer.parseInt(tokens[1]); Set alreadyFound; int count = 0; if (b > 9) { for (int n = a; n <= b; n++) { String nstr = String.valueOf(n); int nlen = nstr.length(); alreadyFound = new HashSet(); for (int index = 1; index < nlen; index++) { String mstr = nstr.substring(index, nlen) + nstr.substring(0, index); int m = Integer.parseInt(mstr); mstr = String.valueOf(m); if (mstr.length() == nlen && alreadyFound.add(mstr)) { if (m > n && m >=a && m <= b) { count++; } } } } } return count; } } " B11980,"package recycledNumbers; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.ArrayList; public class InputFile { public ArrayList readFile() throws Exception { File file = new File(""C:\\Users\\Nikhil\\Desktop\\googleCodeJam\\C-small-attempt0.in""); BufferedReader bufferedReader = new BufferedReader(new FileReader(file)); ArrayList list = new ArrayList(); String line = null; line = bufferedReader.readLine(); while ((line = bufferedReader.readLine()) != null) { list.add(line); } return list; } } " B10458,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; public class Recycled { public static void main(String[] args) throws Exception { // if(true){ // System.out.println(recycle(""12345"", 4)); // return; // } BufferedReader in = new BufferedReader(new FileReader(""recycled.in"")); PrintWriter out = new PrintWriter(new FileWriter(""recycled.out"")); String lineStr; int T; long A, B, result, n, m; T = Integer.parseInt(in.readLine()); for (int line = 1; line <= T; line++) { // get input lineStr = in.readLine(); String[] fields = lineStr.split("" ""); A = Long.parseLong(fields[0]); B = Long.parseLong(fields[1]); // compute result result = 0; for (n = A; n < B; n++) { for (m = A + 1; m <= B; m++) { if (isRecyled(n, m)) { result++; } } } // edit result out.println(""Case #"" + line + "": "" + result); System.out.println(lineStr + "" : "" + result); } in.close(); out.close(); } private static boolean isRecyled(long n, long m) { // condition nn && r<=B){ result++; } }while(r!=n); } } fw.write(""Case #""+i+"": ""+result+""\n""); } fw.close(); } private static String shiftLeft(String rStr){ char[] rChars = rStr.toCharArray(); char temp = rChars[0]; for(int i=0; i createChallenges(String[] lines); } " B10297,"package qualifs; public class Gcj2012 { public static void main(String[] args) { final C problem = new C(""C-small-attempt0.in""); problem.run(); } } " B10851,"import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class RecycleNumbers { private static int T,m,A,B,a,b,k,count=0; private static int[] M; public static void main (String args[]){ try{ Scanner sc=new Scanner(new File(""input.txt"")); FileWriter f0=new FileWriter(""output.txt""); T=sc.nextInt(); for(int j=1;j<=T;j++){ count=0; A=sc.nextInt(); B=sc.nextInt(); k=Integer.toString(A).length(); for(int i=A;i i && b<= B && Integer.toString(b).length()==Integer.toString(i).length()){ count++; //System.out.println(i+"" ""+b); } } } f0.write(""Case #""+j+"": ""+count+""\n""); } f0.close(); }catch(FileNotFoundException fnfe){ System.err.println(fnfe); }catch(IOException ioe){ System.out.println(ioe); } } } " B12107,"package com.renoux.gael.codejam.utils; import java.io.Closeable; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class Output implements Closeable { private static String lineSeparator = System.getProperty(""line.separator""); private FileWriter writer; private Output(File file) { try { writer = new FileWriter(file); } catch (IOException e) { throw new TechnicalException(e); } } public static Output open(File file) { System.out.println(""======== "" + file); return new Output(file); } public void writeLine(String text) { System.out.println(text); try { writer.write(text); writer.write(lineSeparator); } catch (IOException e) { throw new TechnicalException(e); } } public void write(String text) { System.out.print(text); try { writer.write(text); } catch (IOException e) { throw new TechnicalException(e); } } public void writeLine(Object... text) { try { for (Object s : text) { System.out.print(s); writer.write(s.toString()); } System.out.println(); writer.write(lineSeparator); } catch (IOException e) { throw new TechnicalException(e); } } public void write(Object... text) { try { for (Object s : text) { System.out.print(s); writer.write(s.toString()); } } catch (IOException e) { throw new TechnicalException(e); } } public void close() { System.out.println(""================ closed""); try { writer.close(); } catch (IOException e) { throw new TechnicalException(e); } } } " B10729,"package qualificationRound; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; public class P3 { public static int recycle(int j, int b) { int ret = 0; String old = Integer.toString(j); int size = old.length(); HashSet app = new HashSet(); for (int i = 1; i < size; ++i) { String tmp = old.substring(i) + old.substring(0, i); int num = Integer.parseInt(tmp); if (num <= b && num > j && !app.contains(tmp)) { ret++; app.add(tmp); } } return ret; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader(""C-small-attempt0.in"")); FileWriter fw = new FileWriter(""out.txt""); int t = Integer.parseInt(br.readLine()); for (int i = 1; i <= t; ++i) { String line = br.readLine(); String A = line.split("" "")[0]; String B = line.split("" "")[1]; int a = Integer.parseInt(A); int b = Integer.parseInt(B); int num = 0; for (int j = a; j <= b; ++j) { num += recycle(j, b); } fw.append(""Case #"" + i + "": "" + num + ""\n""); } br.close(); fw.close(); } } " B13020,"import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.Scanner; public class Main { /** * @param args */ public static int numShift(int A, int digit){ int num = 0, div; num = A %10; div = A /10; for(int i=1; i < digit ; i++) { num = num*10; } num = num + div; return num; } public static int recycleCount(int A, int B) { int count = 0; int num = A; String digit = """" + A; do { num = numShift(num, digit.length()); if(num > A && num <= B) count++; }while(num != A); //System.out.print(""Count: "" + count + ""\n""); return count; } public static void runCase(int A, int B, int casenum) { int count =0; for(int i=A; i finalOP = new HashSet(); try { BufferedReader bReader = new BufferedReader(new FileReader(inputFile)); BufferedWriter bWriter = new BufferedWriter(new FileWriter(outputFile)); try { t = Integer.parseInt(bReader.readLine().trim()); //System.out.println(""No. Of Cases""+t); for(int index=0;index(); if(noOfDigits!=1){ for(int i=a;i<=b;i++){ for(int localIndex=1;localIndex cases = new ArrayList(); public RecycledNumbers() { try { // Setup in/out System.setIn(new FileInputStream(""C:\\GCJ\\C-small-attempt0.in"")); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new FileWriter(""C:\\GCJ\\C-small-attempt0.out"")); bw.flush(); int untill = Integer.parseInt(br.readLine()); for (int x = 1; x <= untill; x++) { int ans = 0; String[] s = br.readLine().split("" ""); int a = Integer.parseInt(s[0]); int b = Integer.parseInt(s[1]); for (int z = a; z <= b; z++) { List ints = getAllRecycledPairsOf(z); removeDups(ints); Collections.sort(ints); for (Integer nr : ints) { if (between(nr, a, b)) { ans++; } else if (nr > b) { break; } } } String out = ""Case #"" + x + "": "" + ans; cases.add(out); } for (String s : cases) { System.out.println(s); bw.write(s); bw.flush(); bw.newLine(); } } catch (IOException ex) { System.out.println(""SOMETHING WENT WRONG""); } } public List getAllRecycledPairsOf(int nr) { List ints = new ArrayList(); StringBuilder s = new StringBuilder(); s.append(nr); String start = s.toString(); for (int x = 1; x < start.length(); x++) { s = new StringBuilder(); String back = start.substring(start.length() - x, start.length()); String front = start.substring(0, start.length() - x); s.append(back).append(front); if (!back.startsWith(""0"")) { Integer newNr = new Integer(s.toString()); if (newNr > nr) { ints.add(newNr); } } } return ints; } public static void main(String[] args) { RecycledNumbers test = new RecycledNumbers(); } public boolean between(int nr, int a, int b) { if (nr >= a && nr <= b) { //System.out.println(nr); return true; } return false; } public static void removeDups(List list) { Set s = new HashSet(list); list.clear(); list.addAll(s); } } " B10663,"import java.io.FileReader; import java.io.FileWriter; import java.io.BufferedReader; import java.io.PrintWriter; import java.io.IOException; public class Test{ public static void main(String[] args) throws IOException { BufferedReader inputStream = null; PrintWriter outputStream = null; //test(); try { inputStream = new BufferedReader(new FileReader(""test.in"")); outputStream = new PrintWriter(new FileWriter(""test.out"")); String l; l = inputStream.readLine(); int t = Integer.parseInt(l); int i = 1; while ((l = inputStream.readLine()) != null) { String result = ""Case #""+(i++)+"": ""+getNum(l); outputStream.println(result); System.out.println(result); } } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } } /*public static void test(){ int begin = 1111; int end = 2222; int valueSize = 4; int testValue = begin; int a = 0; for(testValue = begin;testValue<=end;testValue++){ for(int i=1;itestValue&&tmptestValue&&tmp ""+returnValueArray[i]+"" (""+step[i]+"")""); // +"" ""+testValueArray[i]+"" -> ""+returnValueArray[i]); // } //} //} return returnValue; } public static int getLeftValue(int testValue,int valueSize,int leftSize){ int a0 = testValue%10; int a1 = (testValue%100)/10; int a2 = (testValue%1000)/100; int a3 = (testValue)/1000; if(valueSize==2){ if(a0==0){ return -1; } return a0*10+a1; } else if(valueSize==3){ if(leftSize==1){ if(a1==0){ return -1; } return a1*100+a0*10+a2; } else if(leftSize==2){ if(a0==0){ return -1; } return a0*100+a2*10+a1; } } else if(valueSize==4){ if(leftSize==1){ if(a2==0){ return -1; } return a2*1000+a1*100+a0*10+a3; } else if(leftSize==2){ if(a1==0){ return -1; } return a1*1000+a0*100+a3*10+a2; } else if(leftSize==3){ if(a0==0){ return -1; } return a0*1000+a3*100+a2*10+a1; } } return 0; } }" B12259,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recyclednumbers; import java.io.*; /** * * @author Peter */ public class RecycledNumbers { /** * @param args the command line arguments */ public static void main(String[] args) { String inputFile, outputFile; inputFile = ""C-small-attempt4.in""; //""C-small-attempt1.in"";// ""input.txt""; outputFile = ""output.txt""; File file = new File(inputFile); FileInputStream fis = null; BufferedInputStream bis = null; DataInputStream dis = null; try { fis = new FileInputStream(file); // Here BufferedInputStream is added for fast reading. bis = new BufferedInputStream(fis); dis = new DataInputStream(bis); FileWriter fstream = new FileWriter(outputFile); BufferedWriter out = new BufferedWriter(fstream); String line, output; line = dis.readLine(); int testCases = Integer.parseInt(line); int A, B, m, n, caseNo = 1, count = 0; String[] param; // dis.available() returns 0 if the file does not have more lines. while (dis.available() != 0) { output = ""Case #"" + caseNo + "": ""; line = dis.readLine(); param = line.split("" ""); A = Integer.parseInt(param[0]); B = Integer.parseInt(param[1]); for(m = B; m > A; m--){ for(n = m - 1; n >= A; n--){ if(isRecycled(n + """", m + """")){ count++; //System.out.println(""n ="" + n + "" m ="" + m + "" count ="" + count); } } } output += count; count = 0; out.append(output + ""\n""); caseNo++; } // dispose all the resources after using them. fis.close(); bis.close(); dis.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static boolean isRecycled(String n, String m){ boolean recycled = false; if(n.length() != m.length()){ return recycled; } for(int i = 0;i< n.length() ; i++){ if(n.equals(m)){ recycled = true; break; }else{ n = n.charAt(n.length() - 1) + n.substring(0, n.length() - 1); if(n.equals(m)){ recycled = true; break; } } } return recycled; } } " B11955,"package qual; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; public class Recycled { public static void main(String[] args) throws IOException { new Recycled().run(); } class Pair { int a, b; Pair(int a, int b) { this.a = a; this.b = b; } public boolean equals(Object other) { Pair p = (Pair) other; return this.a == p.a && this.b == p.b; } public int hashCode() { return this.a * 2000003 + this.b; } } public HashSet set = new HashSet(); void add(Pair p, int left, int right) { if (p.a < p.b && left <= p.a && p.a <= right && left <= p.b && p.b <= right) { set.add(p); } } int powers[] = {10, 100, 1000, 10000, 100000, 1000000, 10000000}; void fill(int left, int right, int curpow) { for (int i = left; i <= right; i++) { int val = i; for (int p : powers) { if (val >= p) { int lp = val / p; int rp = val % p; int newval = rp * (curpow / p) + lp; add(new Pair(val, newval), left, right); } } } } public void run() throws IOException { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); fill(1, 9, 10); fill(10, 99, 100); fill(100, 999, 1000); fill(1000, 9999, 10000); fill(10000, 99999, 100000); fill(100000, 999999, 100000); fill(1000000, 2000000, 10000000); int tests = in.nextInt(); for (int test = 0; test < tests; test++) { int a = in.nextInt(), b = in.nextInt(); int count = 0; for (Pair p: set) { if (a <= p.a && p.a <= b && a <= p.b && p.b <= b) { count++; } } out.printf(""Case #%d: %d\n"", test + 1, count); } out.close(); } } " B12670,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class C { private static final String PROBLEM_NAME = ""C-small""; public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader r = new BufferedReader(new FileReader(PROBLEM_NAME + "".in"")); BufferedWriter w = new BufferedWriter(new FileWriter(PROBLEM_NAME + "".out"")); int testsNumber = Integer.parseInt(r.readLine()); for (int i = 0; i < testsNumber; ++i) { String[] line = r.readLine().split("" ""); int a = Integer.parseInt(line[0]); int b = Integer.parseInt(line[1]); long res = 0L; int len = 0; int tmp = a; while (tmp != 0) { ++len; tmp /= 10; } if (a == 0) { len = 1; } int m = 1; for (int j = 1; j < len; ++j) { m *= 10; } while (a < b) { Set counted = new HashSet(); int t = a; boolean sh = false; for (int j = 1; j < len; ++j) { int x = t % 10; if (x == 0) { sh = true; t = t / 10; } else { sh = false; t = x * m + t / 10; } if (!sh && t <= b && t > a && !counted.contains(t)) { counted.add(t); ++res; } } ++a; } w.write(""Case #"" + (i + 1) + "": ""); w.write(res + """"); w.newLine(); } r.close(); w.close(); } } " B12606," import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.HashSet; public class Problem3 { public static void main(String arg[]) { try{ FileInputStream fstream = new FileInputStream(""textfile.txt""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter foutstream = new FileWriter(""d:\\Problem3output.txt""); BufferedWriter out = new BufferedWriter(foutstream); String strLine, copyStrLine = """"; int caseCount = -1; strLine = br.readLine(); caseCount = Integer.parseInt(strLine); for(int j=0; j < caseCount; j++) //System.out.println (strLine); { strLine = br.readLine(); String[] splitStrings = strLine.split("" ""); int A = Integer.parseInt(splitStrings[0]); int B = Integer.parseInt(splitStrings[1]); int recycleCount = 0; for(int n = A; n < B; n++) { int count = 10 ; int counter = 0; int len = splitStrings[1].length()-1; int arrayNumbers[]; HashSet hashSet = new HashSet(); while(counter < len) { int tail = n % count; int front = n / count; count = count * 10 ; int val = (int) Math.pow(10,(len - counter)); int m = tail * val + front; //System.out.println(i+"":""+"":""+temp+"":""+val); if(m > A && m <= B && m > n) { hashSet.add(new Integer(m)); } counter++; } recycleCount = recycleCount + hashSet.size(); } System.out.println(recycleCount); out.write(""Case #"" + (j + 1) + "": "" + recycleCount + ""\n""); } out.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } } " B12539,"package Main; import com.sun.deploy.util.ArrayUtil; import org.apache.commons.lang3.ArrayUtils; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; /** * Created with IntelliJ IDEA. * User: arran * Date: 14/04/12 * Time: 3:12 PM * To change this template use File | Settings | File Templates. */ public class Round { public StringBuilder parse(BufferedReader in) throws IOException { StringBuilder out = new StringBuilder(); String lineCount = in.readLine(); for (int i = 1; i <= Integer.parseInt(lineCount); i++) { out.append(""Case #""+i+"": ""); String line = in.readLine(); String[] splits = line.split("" ""); int p1 = Integer.valueOf(splits[0]); int p2 = Integer.valueOf(splits[1]); int r = pairRecyclable(p1, p2); out.append(r); // if (i < Integer.parseInt(lineCount)) out.append(""\n""); } return out; } public static int pairRecyclable(int i1, int i2) { HashSet hash = new HashSet(); for (int i = i1; i < i2; i++) { String istr = String.valueOf(i); if (istr.length() < 2) continue; for (int p = 0; p < istr.length() ; p++) { String nistr = istr.substring(p,istr.length()).concat(istr.substring(0,p)); if (Integer.valueOf(nistr) < i1) continue; if (Integer.valueOf(nistr) > i2) continue; if (nistr.equals(istr)) continue; String cnistr = (Integer.valueOf(nistr) > Integer.valueOf(istr)) ? istr + "","" + nistr : nistr + "","" + istr; hash.add(cnistr); } } return hash.size(); } public static void main(String[] args) { InputStreamReader converter = null; try { int attempt = 0; String quest = ""C""; converter = new InputStreamReader(new FileInputStream(""src/resource/""+quest+""-small-attempt""+attempt+"".in"")); BufferedReader in = new BufferedReader(converter); Round r = new Round(); String str = r.parse(in).toString(); System.out.print(str); FileOutputStream fos = new FileOutputStream(quest+""-small-attempt""+attempt+"".out""); OutputStreamWriter osw = new OutputStreamWriter(fos); BufferedWriter bw = new BufferedWriter(osw); bw.write(str); bw.flush(); bw.close(); } catch (IOException e) { e.printStackTrace(); } } } " B11617,"import java.util.*; public class permute { static LinkedList[] build; public static void Permute() { build = new LinkedList[1001]; for(int i=1 ; i<=1000 ; i++) { build[i] = new LinkedList(); String str = new String(i+""""); for(int j=0 ; ji && !build[i].contains(num)) build[i].add(num); } } } public static void main(String[] args) { Scanner scan = new Scanner(System.in); Permute(); int cnt = scan.nextInt(); for(int c=1 ; c<=cnt ; c++) { int start = scan.nextInt(),end = scan.nextInt(),res = 0; for(int i=start ; i<=end ; i++) for(int j=0 ; jn; b--) { for (int a = n; a 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 readInput(InputStream in) { final Scanner sc = new Scanner(in); int testCases = sc.nextInt(); if (log.isDebugEnabled()) { log.debug(""testCases: '{}'"", testCases); } List problemData = new ArrayList(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); } } " B10974,"import java.io.IOException; import java.io.PrintWriter; public class RecycledNumbers { public static void main(String[] args) { RecycledNumbers bt = new RecycledNumbers(); bt.solveProblem(); } public void solveProblem() { String[] testCases = ReadFile.readFile(""C:/Users/Pablo/Documents/codejam/RN.in""); int i = 0; StringBuilder res = new StringBuilder(); for (String testCase : testCases) { if(!res.toString().equals("""")) { res.append(""\n""); } res.append(processTestCase(testCase, ++i)); } System.out.print(res.toString()); try { PrintWriter pw = new PrintWriter(""C:/Users/Pablo/Documents/codejam/RN.out""); pw.print(res.toString()); pw.close(); } catch (IOException e) { System.out.println(""Error writing file!!""); } } private String processTestCase(String testCase, int caseNum) { Long a = Long.valueOf(testCase.split("" "")[0]); Long b = Long.valueOf(testCase.split("" "")[1]); Long lim = Double.valueOf(Math.floor((a + b)/ 2d)).longValue() + 1L; int cantNumbers = 0; if(a.compareTo(10L) >= 0) { cantNumbers = verifNumbers(b, a, 0); } return ""Case #"" + caseNum + "": "" + cantNumbers; } private int verifNumbers(Long b, Long num, int cantNumbers) { if(num.compareTo(b) < 0) { String n = num.toString(); n = n.replaceAll(String.valueOf(n.charAt(0)), """"); if(!n.equals("""")) { for(int i = 1; i <= num.toString().length(); i++) { String s = num.toString().substring(num.toString().length() - i, num.toString().length()) + num.toString().substring(0, num.toString().length() - i); Long tmp = Long.valueOf(s); if(tmp.compareTo(b) <= 0 && tmp.compareTo(num) > 0) { cantNumbers ++; } } } cantNumbers = verifNumbers(b, num + 1L, cantNumbers); } return cantNumbers; } } " B12771,"import java.util.Scanner; public class Main { static int move(int n, int p){ return (n%10)*(int)Math.pow(10, p) + n/10; } public static void main(String[] args){ Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for(int t=1; t<=T; t++){ int out=0; int A=sc.nextInt(); int B=sc.nextInt(); int p = (int)Math.log10((double)A); for(int n=A; n{ int a , b; public Pair(int a, int b) { this.a = a; this.b = b; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Pair other = (Pair) obj; if (this.a != other.a) { return false; } if (this.b != other.b) { return false; } return true; } @Override public int hashCode() { int hash = a*3; return hash; } public int compareTo(Pair o) { if ( o.a != this.a ){ return this.a - o.a; }else{ return this.b - o.b; } } } /** * * @author Saul Hidalgo */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { try { Scanner sc = new Scanner(new File(""test.txt"")); PrintStream ps = new PrintStream(new File(""output.txt"")); int T = sc.nextInt(); for ( int t = 1 ; t <= T ; t++ ){ int n = sc.nextInt() , m = sc.nextInt(); int ans = 0; TreeSet tree = new TreeSet(); for ( int i = n ; i <= m ; i++ ){ String num = i + """"; for ( int j = 1 ; j < num.length() ; j++ ){ String conv = num.substring(j) + num.substring(0, j); int tt = Integer.parseInt(conv); Pair p = new Pair(i, tt); if ( tt > i && tt <= m && !tree.contains(p)){ ++ans; tree.add(p); } } } ps.println(""Case #"" + t + "": "" + ans); } } catch (FileNotFoundException ex) { // =( } } } " B12253,"import java.io.*; import java.util.HashSet; import java.util.Scanner; /** * Created by IntelliJ IDEA. * User: singh * Date: 14/4/12 * Time: 4:46 AM * To change this template use File | Settings | File Templates. */ public class RecycleNumbers { public static void main(String[] args) throws IOException { // Scanner sc=new Scanner(System.in); Scanner sc=new Scanner(new File(""C:\\Users\\singh\\Documents\\codejam\\input.in"")); int testCases=sc.nextInt(); String outPut=""""; PrintWriter writer=new PrintWriter(""C:\\Users\\singh\\Documents\\codejam\\out0.in""); // BufferedWriter bf=new BufferedWriter(new FileWriter(""C:\\Users\\singh\\Documents\\codejam\\out0.txt"")); for(int iterator=0;iterator set=new HashSet(); int counter=0; int A=sc.nextInt(); int B=sc.nextInt(); // int BFirst=Integer.parseInt((B+"""").charAt(0)+""""); for(int currentN=A;currentNBFirst) // { // break; // } // if(!nString.endsWith(""0"")) // { for(int i=1;i<=nString.length()-1;i++) { String nSubString=nString.substring(nString.length()-i,nString.length())+nString.substring(0,nString.length()-i); if(!nSubString.startsWith(""0"")) { if(!nString.equals(nSubString)) { int nSubInt=Integer.parseInt(nSubString); if(nSubInt<=B && nSubInt>(Integer.parseInt(nString))) { if(!set.contains(nString+"",""+nSubString)) { set.add(nString+"",""+nSubString); counter++; } } } } } // } } // } outPut+=""Case #""+(iterator+1)+"": ""+counter+""\n""; } writer.write(outPut); writer.flush(); writer.close(); } } " B12049,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package t2; /** * * @author KAMIKATAZ */ //~--- JDK imports ------------------------------------------------------------ import intjungle.*; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; /** * * @author KAMIKATAZ */ public class IntJungle { /** * @param args the command line arguments */ public static void main(String[] args) { int ans=0; try { FileInputStream fstream = new FileInputStream(""C:\\Users\\KAMIKATAZ\\Desktop\\codejam\\p3\\input.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; BufferedWriter out1 = new BufferedWriter( new FileWriter( ""C:\\Users\\KAMIKATAZ\\Desktop\\codejam\\p3\\out-p3.ou"", true)); String times=br.readLine(); int T = Integer.valueOf(times); ToInteger converter=new ToInteger(); int currentCase=0; ///////////////////////////////////////////////////////////////////////////// while ((strLine = br.readLine()) != null) { ///////////////////////////////////////////////////////////////////////////// ++currentCase; out1.write(""Case #"" + String.valueOf(currentCase) + "": ""); ans=0; Map map = new HashMap(); StringTokenizer st=new StringTokenizer(strLine,"" ""); String a=st.nextToken(); String b=st.nextToken(); a=a.trim(); b=b.trim(); int A=Integer.valueOf(a); int B=Integer.valueOf(b); // //System.out.println(""A read is : ""+ A + ""B read is : ""+ B); ///////////////////// LOGIC STARTS HERE ////////// int nLen=0; //System.out.println(""starting processing set : A : ""+A+"" B : ""+ B); for (int n=A;nn && r1<=B){ if(r1!=n){ //System.out.println(""creating from : ""+nStr+"" : ""+r1); ++ans; // //System.out.println( map.put(String.valueOf(n), String.valueOf(r1))); String opop = ""gigger""; opop=map.put(String.valueOf(n), String.valueOf(r1)); String op=null; try{ if (opop.length()>0)op=opop; if(op.equals(String.valueOf(r1)) ){ //System.out.println(""\n8888888888888\n888888888888888\n\n""); --ans; } }catch(Exception e){ //System.out.println(e); } } } } } } /////////////////////// LOGIC ENDS HERE //////////// //System.out.println(""ans is : ""+ans + "" map "" +map.size() ); out1.write(String.valueOf(ans)); out1.newLine(); } // Close the input stream in.close(); out1.close(); } catch (Exception e) { // Catch exception if any //System.out.println(""Error: "" + e.getMessage() + "" "" + e); } //System.out.println(""*******************************\n\n""); } } //~ Formatted by Jindent --- http://www.jindent.com " B11838," import java.util.*; import java.io.*; public class RecycledNumbers { public void doMain() throws Exception { Scanner sc = new Scanner(new FileReader(""input.in"")); PrintWriter pw = new PrintWriter(new FileWriter(""output.txt"")); int T = sc.nextInt(); for (int t=0; tInteger.parseInt(curstr) && recycledInt<=B) { System.out.println(""found!""); NofRdN++; flag[recycledInt-A] = true; } str = recycled; } System.out.println(""NofRdN = "" + NofRdN); ans = ans + ((NofRdN+1) * NofRdN)/2; } } System.out.println(""Case #"" + (t+1) + "": "" + ans); pw.print(""Case #"" + (t+1) + "": "" + ans); pw.println(); } pw.flush(); pw.close(); sc.close(); } public static String recycle(String str){ String last = str.substring(str.length()-1); String substr = str.substring(0,str.length()-1); String recycled = last + substr; return recycled; } public static void main(String[] args) throws Exception { (new RecycledNumbers()).doMain(); } } " B11675,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Calendar; import java.util.HashSet; import java.util.List; import java.util.Set; public class C { private static CodeJamIO io = new CodeJamIO(); /** * @param args */ public static void main(String[] args) { try { init(); int numCases = Integer.parseInt(io.readNextLine()[0]); for (int i=1; i <= numCases; i++) { io.debug(""Solving Case #"" + i + ""...""); solveCase(i); io.debug(""Case #"" + i + "" solved!""); } } catch (Exception e) { e.printStackTrace(); } } /** * Performs initial computations */ private static void init() { } /** * Solves a Test Case * * @param caseNum * @throws IOException */ private static void solveCase(int caseNum) throws IOException { // Read input String[] tokens = io.readNextLine(); int a = Integer.parseInt(tokens[0]); int b = Integer.parseInt(tokens[1]); // Do the work Set recycled = new HashSet(); for (int n=a; n<=b; n++) { String nstr = Integer.toString(n); int firstDigit = Integer.parseInt(nstr.substring(0, 1)); for (int i=1; i n && m >= a && m <= b) { recycled.add(Integer.toString(n) + Integer.toString(m)); } } } } // Print results io.printCase(caseNum).println(recycled.size()); } /** * Input and Output CodeJam style * */ private static class CodeJamIO { private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); private static PrintWriter out = new PrintWriter(System.out, true); private static PrintWriter err = new PrintWriter(System.err, true); public String[] readNextLine() throws IOException { String line = in.readLine(); String[] tokens = line.split(""\\s+""); return tokens; } public CodeJamIO printCase(int caseNum) { return print(""Case #"" + caseNum + "": "" ); } public CodeJamIO print(Object o) { out.print(o); return this; } public CodeJamIO print(Object o[]) { return print(concat(o)); } public CodeJamIO print(Object o[][]) { return print(concat(o)); } public CodeJamIO println() { out.println(); return this; } public CodeJamIO printlnCase(int caseNum) { return printCase(caseNum).println(); } public CodeJamIO println(Object o) { return print(o).println(); } public CodeJamIO println(Object o[]) { return print(o).println(); } public CodeJamIO println(Object o[][]) { return print(concat(o)).println(); } public CodeJamIO println(List l) { return print(concat(l)).println(); } private String concat(Object[] o) { StringBuffer buf = new StringBuffer(10*o.length); String delim = """"; for (int i=0; i < o.length; i++) { buf.append(delim).append(o[i]); delim = "" ""; } return buf.toString(); } private String concat(Object[][] o) { StringBuffer buf = new StringBuffer(100*o.length); for (int i=0; i < o.length; i++) { buf.append(concat(o[i])).append(""\n""); } return buf.toString(); } private String concat(List list) { StringBuffer buf = new StringBuffer(); String delim = """"; for (Object[] elm : list) { buf.append(delim).append(concat(elm)).append(""\n""); } return buf.toString(); } public void debug(String message) { err.println(Calendar.getInstance().getTime() + "": "" + message); } public void debug(String message, Object[] o) { err.println(Calendar.getInstance().getTime() + "": "" + message); err.println(""\t"" + concat(o)); } public void debug(String message, Object[][] o) { err.println(Calendar.getInstance().getTime() + "": "" + message); String values = concat(o); err.println(""\t"" + values.replaceAll(""\n"", ""\n\t"")); } public void debug(String message, List list) { err.println(Calendar.getInstance().getTime() + "": "" + message); String values = concat(list); err.println(""\t"" + values.replaceAll(""\n"", ""\n\t"")); } } } " B12086,"import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; public class Main { /** * @param args */ public static void main(String[] args) throws Exception { if(args.length != 1) { return; } FileInputStream inputStream = new FileInputStream(args[0]); InputStreamReader istReader = new InputStreamReader(inputStream); BufferedReader buffReader = new BufferedReader(istReader); // T:問題数 String tStr = buffReader.readLine(); int t = Integer.valueOf(tStr); for(int i = 1; i <= t; i++) { StringBuilder caseBuilder = new StringBuilder(""Case #""); caseBuilder.append(i); caseBuilder.append("": ""); // A and B:問題 String abStr = buffReader.readLine(); String[] aandbStrs = abStr.split("" ""); int a = Integer.valueOf(aandbStrs[0]); int b = Integer.valueOf(aandbStrs[1]); int y = 0; for(int n = a; n < b; n++) { String nStr = String.valueOf(n); int[] ms = new int[nStr.length() - 1]; for(int k = 1; k < nStr.length(); k++) { String mStr = nStr.substring(nStr.length() - k).concat(nStr.substring(0, nStr.length() - k)); int m = Integer.valueOf(mStr); if(m <= a || b < m || m <= n) continue; boolean already = false; for(int j = 0; j < nStr.length() - 1; j++) { if(m == ms[j]) { already = true; break; } } if(!already) { y++; ms[k - 1] = m; } } } caseBuilder.append(y); System.out.print(caseBuilder.toString()); if(i != t) System.out.println(); } } } " B11539,"package template; import java.io.BufferedReader; import java.io.BufferedWriter; import java.util.ArrayList; public class TestCaseIO { public static ArrayList loadFromFile(String infile) { //inc checks on #lines, length of splits, etc. BufferedReader br = Utils.newBufferedReader(infile); ArrayList tcList = new ArrayList<>(); //first line is N, the number of test cases Integer N = Utils.readInteger(br); //cycle through N test cases for (int x = 0; x < N; x++) { TestCase tc = new TestCase(); tc.setRef(x + 1); /////////////////////////////////////////////////////////// //load properties - the bit to customise per problem ArrayList l = Utils.readIntegerList(br, 2); tc.setIntegerList(""a_b"", l); /////////////////////////////////////////////////////////// tcList.add(tc); } //confirm end of file if (Utils.readLn(br) != null) { Utils.die(""Unexpected text at end of infile""); } return tcList; } public static ArrayList mockUp() { ArrayList tcList = new ArrayList<>(); for (int i = 0; i < 10; i++) { TestCase tc = new TestCase(); tc.setRef(i); int[] xs = Utils.randomIntegerArray(100, -50, 50, i * 2); int[] ys = Utils.randomIntegerArray(100, -50, 50, i * 2 + 1); tc.setIntegerList(""xs"", Utils.arrayToArrayList(xs)); tc.setIntegerList(""ys"", Utils.arrayToArrayList(ys)); tcList.add(tc); } return tcList; } public static void writeSolutions(ArrayList tcList, String outfile) { BufferedWriter bw = Utils.newBufferedWriter(outfile, false); for (int i = 0; i < tcList.size(); i++) { TestCase tc = tcList.get(i); Object solution = tc.getSolution(); String line = ""Case #"" + (i + 1) + "": "" + solution.toString(); Utils.writeLn(bw, line); } Utils.closeBw(bw); } } " B10044,"package QualificationRound.recyclednumbers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class RecycledNumbers { private List inputLines = new ArrayList(); private List outputLines = new ArrayList(); private static final String INPUT_FILE_NAME = ""C-small-attempt0.in""; private static final String OUTPUT_FILE_NAME = ""output.txt""; private List cases = new ArrayList(); public static void main(String[] args) { RecycledNumbers r = new RecycledNumbers(); r.readLines(); r.parseLines(); r.generateOutput(); r.outputLines(); } private void readLines() { try { BufferedReader reader = new BufferedReader(new FileReader(INPUT_FILE_NAME)); String line = reader.readLine(); line = reader.readLine(); while (line != null) { inputLines.add(line); line = reader.readLine(); } reader.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private void parseLines() { for (String line : inputLines) { String[] split = line.split("" ""); SingleCase singleCase = new SingleCase(); singleCase.start = Integer.parseInt(split[0]); singleCase.end = Integer.parseInt(split[1]); cases.add(singleCase); } } private void generateOutput() { int caseNumber = 1; for (SingleCase singleCase : cases) { outputLines.add(getOutputPrefix(caseNumber++) + singleCase.getResult()); } } private String getOutputPrefix(int number) { return ""Case #"" + number + "": ""; } private void outputLines() { try { BufferedWriter writer = new BufferedWriter(new FileWriter(OUTPUT_FILE_NAME, false)); for (String line : outputLines) { writer.write(line); if (!line.equals(outputLines.get(outputLines.size() - 1))) { writer.write(""\n""); } } writer.close(); } catch (IOException e) { e.printStackTrace(); } } private class SingleCase { private int start = 0; private int end = 0; private int getResult() { int result = 0; List numbersBetween = new ArrayList(); for (int i = start; i <= end; i++) { numbersBetween.add(i); } for (int i = start; i <= end; i++) { List resultNumbers = new ArrayList(); String numberString = """"+i; for (int c = 1; c < numberString.length(); c++) { String recycledString = numberString.substring(c) + numberString.substring(0, c); Integer recycledNumber = Integer.parseInt(recycledString); if (recycledNumber > i && numbersBetween.contains(recycledNumber) && !resultNumbers.contains(recycledNumber)) { result++; resultNumbers.add(recycledNumber); } } } return result; } } } " B10421,"package recyclednumbers; import java.io.File; import java.util.Scanner; public class RecycledNumbersCalculator { public static void main(String[] args) { if(args.length <= 0 || args[0] == null) { System.out.println(""You must enter a file to read""); System.out.println(""Usage: blah ""); System.exit(0); } File argFile = new File(args[0]); try { Scanner googleSpeakScanner = new Scanner(argFile); String firstLine = googleSpeakScanner.nextLine(); Integer linesToScan = new Integer(firstLine); for(int i = 1; i <= linesToScan; i++) { String googleDancerLine = googleSpeakScanner.nextLine(); RecycledNumbersCase recycledNumbersCase = new RecycledNumbersCase(googleDancerLine); System.out.println(String.format(""Case #%d: %d"", i, recycledNumbersCase.recycledPairCountFromMinToMax())); } } catch (Exception e) { e.printStackTrace(); } } } " B13224,"package com.abuhijleh.googlejam; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class GoogleJam { static final String code = ""yhesocvxduiglbkrztnwjpfmaq""; public static void main(String[] args) { File input = new File(""inputFile""); String[] result; Scanner scan; try { scan = new Scanner(input); result = new String[scan.nextInt()]; scan.nextLine(); for (int i = 0; i < result.length; i++) { result[i] = ""Case #"" + (i + 1) + "": "" + solve(scan.nextInt(), scan.nextInt()); scan.nextLine(); } System.out.println(""Output""); for (int i = 0; i < result.length; i++) System.out.println(result[i]); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static int solve(int x, int y) { int count = 0; String digits = x + """"; int length = digits.length(); int pa = (int) Math.pow(10, length - 1); for (int i = x; i <= y; i++) { int temp = i; int[] temps = new int[length]; for (int j = 0; j < length ; j++) { temp = (temp % 10) * pa + (temp / 10); if (temp > i && temp <= y){ if(check(temps,temp)){ temps[j] = temp; count++; } } } } return count; } private static boolean check(int[] temps, int temp) { for(int i =0 ;i counted; Map countedAux; for(int t = 0; t < T; t++){ //counted = new HashMap(); count = 0; split = reader.readLine().split("" ""); A = Integer.parseInt(split[0]); B = Integer.parseInt(split[1]); extern:for(int n = A; n < B; n++){ number = new StringBuilder(String.valueOf(n)); if(sameNumbers(number)){ continue; } //if(counted.get(n) != null) continue; //counted.put(n, true); countedAux = new HashMap(); countedAux.put(n, true); for(int i = 0; i < number.length()-1; i++){ first = number.charAt(0); number.deleteCharAt(0); number.append(first); if(number.charAt(0) == '0') { continue; } nAux = Integer.parseInt(number.toString()); if(nAux > B) { continue; } if(nAux < A) { continue; } if(nAux < n) continue extern; //counted.put(nAux, true); countedAux.put(nAux, true); } if(countedAux.size() > 1){ count += (countedAux.size() * (countedAux.size()-1))/2; } } System.out.println(""Case #""+(t+1)+"": ""+count); } } private static boolean sameNumbers(StringBuilder number){ for(int i = 1; i < number.length(); i++){ if(number.charAt(i-1) != number.charAt(i)) return false; } return true; } } " B12581,"package com.google.codejam.utils.files; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class ManejoArchivos { private static String path = ""D:\\Proyectos\\Google\\files\\2012\\""; public static int[][] readFile(String name) throws FileNotFoundException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path + name))); int arr[][] = new int[Integer.parseInt(br.readLine())][2]; for(int i=0;i map; static String change(int n) { String s = """" + n; int len = s.length(); int min = Integer.MAX_VALUE; int value; // String best = null; for (int i = 0; i < len; i++) { s = s.charAt(len - 1) + s.substring(0, len - 1); value = Integer.parseInt(s); if (min > value) { min = value; // best = s; } } return """" + min; } public static void main(String[] args) throws IOException { PrintWriter bw = new PrintWriter(new FileWriter(""1.txt"")); Scanner scan = new Scanner(System.in); int T = scan.nextInt(); map = new HashMap(); for (int i = 0; i < T; i++) { map.clear(); a = scan.nextInt(); b = scan.nextInt(); for (int j = a; j <= b; ++j) { String str = change(j); // System.out.println(str); if (map.containsKey(str)) { map.put(str, map.get(str) + 1); } else { map.put(str, 1); } } long sum = 0; for (Entry e : map.entrySet()) { int n = e.getValue(); sum += n * (n - 1) / 2; } System.out.println(String.format(""Case #%d: %d"", (i + 1), sum)); bw.write(String.format(""Case #%d: %d\n"", (i + 1), sum)); } bw.flush(); bw.close(); } } " B12077,"package jp.funnything.competition.util; import java.util.Arrays; import java.util.List; import com.google.common.collect.Lists; import com.google.common.primitives.Ints; import com.google.common.primitives.Longs; public class Prime { public static class PrimeData { public int[] list; public boolean[] map; private PrimeData( final int[] values , final boolean[] map ) { list = values; this.map = map; } } public static long[] factorize( long n , final int[] primes ) { final List< Long > factor = Lists.newArrayList(); for ( final int p : primes ) { if ( n < p * p ) { break; } while ( n % p == 0 ) { factor.add( ( long ) p ); n /= p; } } if ( n > 1 ) { factor.add( n ); } return Longs.toArray( factor ); } public static PrimeData prepare( final int n ) { final List< Integer > primes = Lists.newArrayList(); final boolean[] map = new boolean[ n ]; Arrays.fill( map , true ); map[ 0 ] = map[ 1 ] = false; primes.add( 2 ); for ( int composite = 2 * 2 ; composite < n ; composite += 2 ) { map[ composite ] = false; } for ( int value = 3 ; value < n ; value += 2 ) { if ( map[ value ] ) { primes.add( value ); for ( int composite = value * 2 ; composite < n ; composite += value ) { map[ composite ] = false; } } } return new PrimeData( Ints.toArray( primes ) , map ); } } " B12061,"/** * */ package code.google.codejam; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; /** * @author sunilkumarp * */ public abstract class Template { int testcases = 0; int casePoniter = 0; PrintWriter writer = null; BufferedReader reader = null; String line = null; int linePointer = -1; int linePerTestCase = 1; char lastChar = '!'; /** * @param args */ public static void main(String[] args) { try { Template template = (Template) Class.forName(args[1]).newInstance(); template.start(args); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(System.out); } } /** * @param args */ protected void start(String[] args) { InputStream io = null; OutputStream os = null; try { io = Template.class.getResourceAsStream(args[0]); reader = new BufferedReader(new InputStreamReader (io)); os = new FileOutputStream(new File(args[0].substring(0, args[0].length() -2 )+ ""out"")); writer = new PrintWriter(os); testcases = Integer.valueOf(reader.readLine()); solveProblem(); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(System.out); } finally { try { writer.flush(); writer.close(); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(System.out); } try { reader.close(); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(System.out); } try { io.close(); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(System.out); } try { os.flush(); os.close(); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(System.out); } } } public void solveProblem() throws Exception { long sTime = System.nanoTime(); for (;++casePoniter <= testcases;) { long sTimeCase = System.nanoTime(); writeOutput(casePoniter, solveProblemForATestCase()); System.out.println(""Time taken for test case"" + ""["" + casePoniter + ""]:"" + (System.nanoTime() - sTimeCase)); } System.out.println(""Total time for all test cases:"" + (System.nanoTime() - sTime)); } protected Object solveProblemForATestCase() throws Exception { initializeTestCase(); printInput(); return doSolveProblem(); } protected abstract Object doSolveProblem() throws Exception; protected abstract void printInput() throws Exception; protected abstract void initializeTestCase() throws Exception; protected void writeOutput (int caseNo, Object result) { String str = ""Case #"" + caseNo + "": "" + result; System.out.println(""=========="" + str + ""=============""); writer.println(str); } public char readChar() throws IOException { return lastChar = (char)reader.read(); } public char readCharFromLine() throws IOException { int length = line.length(); if (linePointer >= length - 1) { throw new IllegalStateException(""Line has already ended.""); } return line.charAt(++linePointer); } public String readLine() throws IOException { line = reader.readLine(); linePointer = -1; return line; } public int readNextInteger() { int val = 0; int length = line.length(); if (linePointer >= length) { throw new IllegalStateException(""Line has already ended.""); } while(++linePointer < length) { if (Character.isDigit(lastChar = line.charAt(linePointer))) { val = val * 10 + Character.digit(lastChar, 10); } else { break; } } return val; } } " B11961,"import java.io.*; import java.util.*; /** * */ public class Main { /** * */ public class TestCase{ public Integer a, b; public Integer[] rNumbers; public Integer iResult=0; public Set setPairs=Collections.synchronizedSet( new HashSet()); /** * @param a * @param b * */ public TestCase( int a, int b){ this.a=a; this.b=b; this.rNumbers=new Integer[ ( this.b- this.a)+ 1]; for( int i=this.a; i<=this.b; i++) this.rNumbers[ i- this.a]=i; } /** * */ public void doSolution(){ this.iResult=0; for( int i=0; i!=this.rNumbers.length; i++){ Integer number=this.rNumbers[ i]; String strNumber=String.valueOf( number); if( strNumber.length()>=2){ for( int s=1; s!=strNumber.length(); s++){ String strPrefix=strNumber.substring( 0, s); String strSuffix=strNumber.substring( s); String strNewNumber=strSuffix+ strPrefix; Integer newNumber=Integer.valueOf( strNewNumber); if(( newNumber>=this.a) && ( newNumber<=this.b) && ( number.compareTo( newNumber)!=0)) this.addPair( number, newNumber); }}} this.iResult=this.setPairs.size(); } public void addPair( Integer n, Integer m){ String nm=n+""+""+m; String mn=m+""+""+n; if( !this.setPairs.contains( nm) && !this.setPairs.contains( mn)){ this.setPairs.add( nm); }} } public TestCase createTestCase( int a, int b){ return new TestCase( a, b); } /** * */ public static void main( String[] args){ try { Main m=new Main(); LineNumberReader reader=new LineNumberReader( new FileReader( new File( args[ 0].trim()))); PrintWriter printer=new PrintWriter( new FileWriter( args[ 1].trim())); int nTestCases=Integer.valueOf( reader.readLine()); for( int i=0; i!=nTestCases; i++){ String str[]=reader.readLine().split( "" "", 2); TestCase testCase=m.createTestCase( Integer.valueOf( str[ 0].trim()), Integer.valueOf( str[ 1].trim())); testCase.doSolution(); printer.println( ""Case #""+( i+ 1)+"": ""+ testCase.iResult); System.out.println( ""Case #""+( i+ 1)+"": ""+ testCase.iResult); } printer.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }}} " B10159," import java.util.*; import java.io.*; public class CodeJam { public static void main (String[] args){ try{ //recycleLarge(1000000, 2000000); // read FileInputStream instream = new FileInputStream(""A-small.in""); DataInputStream in = new DataInputStream(instream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); // write FileOutputStream outstream = new FileOutputStream(""A-small.out""); DataOutputStream out = new DataOutputStream(outstream); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out)); // reading file information int testcases = Integer.parseInt(br.readLine()); for(int i=0; i < testcases; i++){ // ------------------------------------------------------------------------------------------------------------- String line = br.readLine(); String[] items = line.split("" ""); int A = Integer.parseInt(items[0]); int B = Integer.parseInt(items[1]); // ------------------------------------------------------------------------------------------------------------- bw.write(""Case #"" + (i + 1) + "": "" + recycle(A, B) + ""\r\n""); } // close input file in.close(); // close output file bw.flush(); out.close(); }catch(Exception e) { System.err.println(""Error: "" + e.getMessage()); } } private static int eval(int i){ if ( i < 0) return 0; else return i; } private static void printArray(Object [] array){ for(Object ch : array) System.out.print(ch); } private static boolean isRecycled(String str, String m){ for(int i = 1; i set = new HashSet(); String bstr = convertTo(B-1); for (int n = A + 1; n < B - 1; n++) { String nstr = convertTo(n); for (int i = 1; i < nstr.length(); i++) { String digits = nstr.substring(i) + nstr.substring(0, i); if (isGreater(digits, nstr) && isLess(digits, bstr)){ set.add(digits); } } } return set.size(); } private static boolean isLess(String A, String B) { for (int i = 0; i < A.length(); i++) { if (A.charAt(i) < B.charAt(i)) return true; else if (A.charAt(i) > B.charAt(i)) return false; } return false; } private static boolean isGreater(String A, String B) { for (int i = 0; i < A.length(); i++) { if (A.charAt(i) > B.charAt(i)) return true; else if (A.charAt(i) < B.charAt(i)) return false; } return false; } } " B11137,"package recyclednumbers.util; import java.io.*; import java.util.ArrayList; import java.util.List; public class IOUtil { public static List readLines(String filename) { List lines = new ArrayList(); try { InputStream is = IOUtil.class.getResourceAsStream(""/META-INF/"" + filename); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = null; while ((line = br.readLine()) != null) { lines.add(line); } br.close(); is.close(); return lines; } catch (Exception e) { e.printStackTrace(); return null; } } public static void writeLines(String filename, List lines) { try { File file = new File(""src/META-INF/"" + filename); FileWriter fileWriter = new FileWriter(file); for (int i = 0; i < lines.size(); i++) { fileWriter.write(""Case #"" + (i + 1) + "": "" + lines.get(i) + ""\n""); } fileWriter.close(); } catch (Exception e) { e.printStackTrace(); } } }" B11223," public class Methode { public boolean text(String n,String m) { n=n.trim(); m=m.trim(); boolean bool=false; for(int j=1;j= 0 && a <= 9) { System.out.println(""Case #"" + i + "": "" + 0); } else if(a >= 10 && a <= 99) { int b1 = Arrays.binarySearch(two, a); if(b1 < 0){b1 = b1 + 1; b1 = - b1;} int b2 = Arrays.binarySearch(two, b); if(b2 < 0){b2 = b2 + 1; b2 = - b2; b2 = b2 - 1;} for(;b1 <= b2; b1++) { if(two1[b1] >= a && two1[b1] <= b) count++; } System.out.println(""Case #"" + i + "": "" + count); } else if(a >= 100 && a <= 999) { int b1 = Arrays.binarySearch(three, a); if(b1 < 0){b1 = b1 + 1; b1 = - b1;} else{ while(b1 >= 0 && three[b1] == a) b1--; b1 = b1 + 1; } int b2 = Arrays.binarySearch(three, b); if(b2 < 0){b2 = b2 + 1; b2 = - b2; b2 = b2 - 1;} else{ while(b2 <= three.length - 1 && three[b2] == b) b2++; b2 = b2 - 1; } // System.out.println(""B1 and B2"" + b1 + "" "" + b2); for(;b1 <= b2; b1++) { if(three1[b1] >= a && three1[b1] <= b) count++; } System.out.println(""Case #"" + i + "": "" + count); } else System.out.println(""Case #"" + i + "": "" + 0); } /* for(int i = 100; i <= 999; i++) { int rem = i % 10; int q = i / 10; int temp = rem * 100 + q; if(temp > i){ st.add(i); st1.add(temp); } rem = i % 100; q = i / 100; temp = rem * 10 + q; if(temp > i){ st.add(i); st1.add(temp); } } pt.println(st1); pt.close(); */ } } " B13238,"import java.util.LinkedList; import java.util.Scanner; public class Recycle { private static int[] total(int r) { int i=1, t=10; while(r/t > 0) { i++; t*=10; } return new int[] {i,t/10}; } private static int pow(int c) { int t=1; while(c-->0) t*=10; return t; } private static int recycle(int r, int c /* peechhe se, 1 based*/) { int k = pow(c), t=total(r)[0]; int a = r/k; int b = (r%k) * pow(t-c); return a+b; } public static void main(String[] args) { Scanner c = new Scanner(System.in); int t = c.nextInt(); for(int w=1; w<=t; ++w) { System.out.print(""Case #""+w+"": ""); int cnt = 0; int A = c.nextInt(); int B = c.nextInt(); int tmp[] = total(A); int tot = tmp[0]; for(int i=Math.max(A, 10); i <=B; ++i ) { int in = i/tmp[1]; int pow = 1; LinkedList l = new LinkedList(); for(int j=1; j= in) { int r = recycle(i,j); if(r > i && r<=B && !l.contains(r)) { cnt++; l.add(r); //System.out.println(""(""+i+"",""+r+"")""); } } } } System.out.println(cnt); } } } " B11213," import java.util.HashSet; import java.util.Scanner; import java.util.regex.Pattern; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author alvin */ public class RecycledNumbers { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int nTC = sc.nextInt(); for (int tc = 1; tc <= nTC; tc++) { int hasil = 0; int a = sc.nextInt(), b = sc.nextInt(); String batas = Integer.toString(b); char maks = batas.charAt(0); int panjang = batas.length(); for (int n = a; n < b; n++) { String s = Integer.toString(n); if (s.length() == 1) { // System.out.println(s); continue; } if (Pattern.compile(""^(.)\\1*$"").matcher(s).matches()) { // System.out.println(s); continue; } HashSet sudah = new HashSet(); for (int i = s.length() - 1; i >= 1; i--) { char c = s.charAt(i); if (c == '0') { continue; } if (c < s.charAt(0)) { continue; } if (c > maks) { continue; } StringBuilder sb = new StringBuilder(panjang); String cek = sb.append(s.substring(i)).append(s.substring(0, i)).toString(); if ((cek.compareTo(s) > 0) && (cek.compareTo(batas) <= 0)) { sudah.add(cek); } } hasil += sudah.size(); } System.out.format(""Case #%d: %d\n"", tc, hasil); } } } " B12683,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.StringTokenizer; public class RecycledNumbers { public static void main(String[] args) throws IOException { RecycledNumbers r = new RecycledNumbers(); r.run(""C-small.in"", ""C-small.out""); } public void run(String input, String output) throws IOException { BufferedReader br = new BufferedReader(new FileReader(input)); FileWriter fw = new FileWriter(output); long C = 0; int N = new Integer(br.readLine()); for (int cases = 1; cases <= N; cases++) { StringTokenizer st = new StringTokenizer(br.readLine()); long A = new Long(st.nextToken()); long B = new Long(st.nextToken()); C = count(A, B); fw.write(""Case #"" + cases + "": "" + C + ""\n""); } fw.flush(); fw.close(); } public long count(long A, long B) { int recycledPairs = 0; for (long K = A; K <= B; K++) { int n = digits(K); int pairs = 0; long[] a = new long[n - 1]; for (int i = 1; i < n; i++) { long divisor = (long) Math.pow(10, i); long R = (K % divisor) * (long) Math.pow(10, n - i) + (K / divisor); if (R > K && R <=B) { boolean repeat = false; for (int j = 0; j < pairs; j++) { if (R == a[j]) { repeat = true; break; } } if (!repeat) { a[pairs] = R; pairs++; recycledPairs++; } } } } return recycledPairs; } public int digits(long k) { int length = 0; for (int i = 0; i < 8; i++) { k /= 10; length++; if (k == 0) break; } return length; } } " B10268," import java.util.HashSet; import java.io.File; import java.io.FileNotFoundException; import java.util.Formatter; import java.util.Scanner; import static java.lang.Math.*; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author milen.chechev */ public class RecycledNumbers { /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new File(""input.txt"")); Formatter out = new Formatter(new File(""output.txt"")); int t = in.nextInt(); for(int k = 0; k < t ; k++){ int a = in.nextInt(); int b = in.nextInt(); int digits = numberOfDigits(b); int accum = 0; for(int i = a ; i < b ; i++){ int number = i; HashSet visited = new HashSet(); for(int j = 1 ; j < digits; j++){ number = number/ 10 + (int)pow(10,digits-1)*(number%10); if(number > i && number <= b && !visited.contains(number)){ accum++; visited.add(number); } } } out.format(""Case #%d: %d\n"",k+1,accum); } out.close(); } public static int numberOfDigits(int number){ int res = 0; while(number > 0){ res++; number /=10; } return res; } } " B12688,"package gcj2012; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class RecycledNumbers { private static final class IntPair { Integer a, b; IntPair(Integer a,Integer b) { this.a = a; this.b = b; } @Override public boolean equals(Object obj) { IntPair other = (IntPair) obj; return a.equals(other.a) && b.equals(other.b); } @Override public int hashCode() { return a.hashCode() * b.hashCode(); } } private static Map beenThereDoneThat; public static void main(String[] args) throws IOException { Scanner scn = new Scanner(new File(""C-small-attempt0.txt"")); PrintWriter output = new PrintWriter(new FileWriter(""out1.txt"")); int size = scn.nextInt(); for (int i = 1; i <= size; i++) { int total = 0; int a = scn.nextInt(); int b = scn.nextInt(); for (int j = a; j <= b; j++) { total += count(j, b); } output.write(""Case #"" + i + "": "" + total); output.write('\n'); } output.close(); } private static int count(Integer curr, Integer max) { String currString = curr.toString(); int currSize = currString.length(); if (currSize == 1) { return 0; } beenThereDoneThat = new HashMap(); int localCount = 0; //i is start index of end part, which is moving to the front for (int i = 1; i < currSize; i++) { String newCurr = currString.substring(i) + currString.substring(0, i); int newCurrInt = Integer.valueOf(newCurr); if (newCurrInt > curr && newCurrInt <= max) { IntPair pair = new IntPair(curr, newCurrInt); if (beenThereDoneThat.get(pair) == null) { beenThereDoneThat.put(pair, new Object()); localCount++; } // if (localCount == 1) { // System.out.print(curr); // } // System.out.print("" ""+newCurrInt); } } // if (localCount !=0) { // System.out.println(); // } return localCount; } } " B11701,"package com.sokamura.gcj2012; import java.io.BufferedReader; import java.io.FileReader; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { public int solve(int n1, int n2) { int ans = 0; for(int i=n1; i list = generate(i); for(int n : list) { if(n <= n2){ ans++; } } } return ans; } private Set generate(int n) { String s = String.valueOf(n); Set list = new HashSet(); for(int i=1; iInteger.parseInt(mx)&&Integer.parseInt(st)<=Integer.parseInt(str2[1])) { if(stcpy.equals(st)) mark=0; if(mark!=0) { flag++; stcpy=""""; stcpy+=st; //System.out.println(mx+"":""+st); }} } } else flag=0; } System.out.print(""Case #""+k+"": ""+flag); System.out.println(); //System.out.println(Integer.parseInt(""201"") distinctCouple = null; long maxTime = 0; private class Couple { int x = 0; int y = 0; public Couple(int x, int y) { this.x = x; this.y = y; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getOuterType().hashCode(); result = prime * result + x; result = prime * result + y; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Couple other = (Couple) obj; if (!getOuterType().equals(other.getOuterType())) return false; if (x == other.x && y == other.y) return true; if (x == other.y && y == other.x) return true; return false; } private RecycledNumber getOuterType() { return RecycledNumber.this; } } @Override public String execute(String line) { int result = 0; String[] data = line.split("" ""); a = Integer.parseInt(data[0]); b = Integer.parseInt(data[1]); initialize(); int n = a; // while (n <= b) { result += analize(n); n++; // if (n % 1000 == 0) // System.out.println(n); } System.out.println(result); return """" + result; } @Override public void initialize() { distinctCouple = new HashSet(); } private int analize(int number) { String numString = """" + number; initialize(); for (int i = 1; i < numString.length(); i++) { int m = shift(numString, i); if (a <= number && number < m && m <= b) { Couple couple=new Couple(number,m); if (!distinctCouple.contains(couple)) distinctCouple.add(couple); } } return distinctCouple.size(); } private int shift(String numString, int posx) { String result = null; result = """" + numString.substring(posx) + numString.substring(0, posx); return Integer.parseInt(result.toString()); } } " B10148,"import java.io.InputStreamReader; import java.util.HashSet; import java.util.Scanner; public class Recycled_Num { public static void main(String[] args) { //long currentTime = System.currentTimeMillis(); Scanner input_file = new Scanner(new InputStreamReader(System.in)); String input_line = null; String[] numb_arr; int Case_Count = 0; int st_num = 0; int end_num = 0; int pair_count = 0; int digitCount = 0; StringBuilder recycle_number = new StringBuilder(); int newNumber = 0; String newNumberString; HashSet recycle_numbers = new HashSet(); while (input_file.hasNextLine()) { input_line = input_file.nextLine(); numb_arr = input_line.split("" ""); if(numb_arr != null && numb_arr.length == 1) { /*numberOfTestCases = Integer.parseInt(numb_arr[0]);*/ } else if (numb_arr != null && numb_arr.length == 2) { digitCount = numb_arr[0].length(); st_num = Integer.parseInt(numb_arr[0]); end_num = Integer.parseInt(numb_arr[1]); while(st_num <= end_num) { newNumberString = """" + st_num; for(int i = 1; i < digitCount; i++) { recycle_number = recycle_number.append(newNumberString.substring(i) + newNumberString.substring(0, i)); newNumber = Integer.parseInt(recycle_number.toString()); if(newNumber > st_num && newNumber <= end_num) { recycle_numbers.add(recycle_number.toString()); } recycle_number.delete(0, digitCount); } pair_count = pair_count + recycle_numbers.size(); st_num++; recycle_numbers.clear(); } System.out.println(""Case #"" + Case_Count + "": "" + pair_count); } Case_Count++; pair_count = 0; st_num = 0; end_num = 0; digitCount = 0; newNumber = 0; recycle_number.delete(0, digitCount); } //System.out.println(System.currentTimeMillis() - currentTime); } } " B10614,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; public class RecycledNumbers { public static FileReader fileReader; public static BufferedReader reader; public static FileWriter fileWriter; public static BufferedWriter writer; public void executeLogic() throws Exception { String newLine; newLine = reader.readLine(); int increment = 1; while ((newLine = reader.readLine()) != null) { int totalNumberCount = 0; String stringToArray[] = newLine.split(""\\s""); int A = Integer.parseInt(stringToArray[0]); int B = Integer.parseInt(stringToArray[1]); for (int i = A; i <= B; i++) { int n = i; String stringValueOfA = Integer.toString(n); int numberOfDigitsInA = stringValueOfA.length(); int backIndex = numberOfDigitsInA - 1; String tempStringValueOfA = stringValueOfA; while (backIndex > 0) { String first = tempStringValueOfA.substring(0, backIndex); String second = tempStringValueOfA.substring(backIndex, numberOfDigitsInA); stringValueOfA = second + first; int m = Integer.parseInt(stringValueOfA); if ((m <= B && m > n) && !stringValueOfA.startsWith(""0"") && (Integer.toString(n).length()) == stringValueOfA .length()) totalNumberCount++; backIndex--; } } writer.write(""Case #"" + increment++ + "": "" + totalNumberCount + ""\n""); } writer.close(); fileWriter.close(); } public static void main(String[] args) throws Exception { RecycledNumbers recycledNumbers = new RecycledNumbers(); String inputFilePath = ""C:\\CodeJamFiles\\Small2.in""; String outputFilePath = ""C:\\CodeJamFiles\\Small2.out""; fileReader = new FileReader(inputFilePath); reader = new BufferedReader(fileReader); fileWriter = new FileWriter(outputFilePath, false); writer = new BufferedWriter(fileWriter); recycledNumbers.executeLogic(); } } " B12021,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.ArrayList; public class RN { public static void main(String[] args) { Integer caseNum = 0; /*if(args.length == 0) { return; }*/ ArrayList argList = new ArrayList(); String line=null; File inputFile = new File(""RNData.txt""); BufferedReader reader; try { reader = new BufferedReader(new FileReader(inputFile)); while ((line=reader.readLine()) != null) { argList.add(line); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } caseNum = Integer.parseInt(argList.get(0)); for(int caseIndex=0; caseIndex < caseNum.intValue(); caseIndex++) { String input = argList.get(caseIndex+1); System.out.println(""Case #"" + (caseIndex+1) + "": "" + countRecycledPairs(input)); } } private static int countRecycledPairs(String input) { int numOfPairs = 0; String[] inputData = input.split("" ""); if(inputData.length == 2 && inputData[0].length() == inputData[1].length()) { int A = Integer.parseInt(inputData[0]); int B = Integer.parseInt(inputData[1]); numOfPairs = totalPairsBetweenBig(A, B); } return numOfPairs; } private static int totalPairsBetween(int A, int B) { int digitLength = Integer.toString(A).length(); if(digitLength <= 1 || Integer.toString(B).length() != digitLength || A >= B) return 0; int pairsOnA = 0; int[] pairsOfA = new int[digitLength]; for(int i=1; i A && recycleInt <= B) { int pairIndex = 0; while(pairsOfA[pairIndex] != 0) { //System.out.println(""The recycleInt is "" + recycleInt + "" value is "" + pairsOfA[pairIndex]); if(pairsOfA[pairIndex] == recycleInt) break; pairIndex++; }; if(pairsOfA[pairIndex] == 0) { pairsOfA[pairIndex] = recycleInt; //System.out.println(""save "" + pairsOfA[pairIndex]); pairsOnA++; } } } return pairsOnA + totalPairsBetween(A+1, B); } private static int totalPairsBetweenBig(int A, int B) { int digitLength = Integer.toString(A).length(); if(digitLength <= 1 || Integer.toString(B).length() != digitLength || A >= B) return 0; int totalPairs = 0; while(A < B) { int pairsOnA = 0; int[] pairsOfA = new int[digitLength]; for(int i=1; i A && recycleInt <= B) { int pairIndex = 0; while(pairsOfA[pairIndex] != 0) { //System.out.println(""The recycleInt is "" + recycleInt + "" value is "" + pairsOfA[pairIndex]); if(pairsOfA[pairIndex] == recycleInt) break; pairIndex++; }; if(pairsOfA[pairIndex] == 0) { pairsOfA[pairIndex] = recycleInt; //System.out.println(""save "" + pairsOfA[pairIndex]); pairsOnA++; } } } totalPairs += pairsOnA; A++; } return totalPairs; } } " B10697,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class RecycledNumber { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader in = new BufferedReader(new FileReader(""./test3.txt"")); FileWriter fstream = new FileWriter(""./out3.txt""); BufferedWriter out = new BufferedWriter(fstream); String str,str2; int i = 0; int numTestCase = Integer.parseInt(in.readLine()); while ((str = in.readLine()) != null) { str2=""""; int numOK = 0; String[] toks; toks = str.split("" ""); int LB = Integer.parseInt(toks[0]); int UB = Integer.parseInt(toks[1]); int numDigit = toks[0].length(); int []prev = new int[numDigit-1]; if(numDigit >1){ for(int k = LB; k < UB;k++) { for(int j = 1; j< numDigit; j++) { String temp = Integer.toString(k); String temp1 = temp.substring(0,j); String temp2 = temp.substring(j,numDigit); String result = temp2+temp1; int res = Integer.parseInt(result); if(res > k && res <= UB) { numOK++; for(int l = 0;lx&&ty<=y&&gl[ty]==0?ry+1:ry; if(ty set = new HashSet(); String s = Integer.toString(num); //System.out.println(s); for (int i = s.length() - 1; i > 0; i--) { String cur = s.substring(i) + s.substring(0, i); int t = Integer.parseInt(cur); if (t > num && t <= B) { set.add(t); } } return set.size(); } } public class C { public static void main(String[] args) throws FileNotFoundException, IOException { /* READ INPUT + DATA STRUCTURES */ String input = ""C-small-attempt0.in""; //String input = ""C-large.in""; String output = input.replace("".in"", "".out""); File f = new File(input); Scanner sc = new Scanner(f); int T = Integer.parseInt(sc.nextLine()); TestCase[] cases = new TestCase[T]; for (int i = 0; i < T; i++) { cases[i] = new TestCase(); /* Add inputs to this case */ cases[i].A = sc.nextInt(); cases[i].B = sc.nextInt(); //sc.nextLine(); } /* END READ INPUT + DATA STRUCTURES */ File out = new File(output); if (out.exists()) { out.delete(); } PrintWriter pw = new PrintWriter(new FileOutputStream(out, true)); for (int i = 0; i < T; i++) { System.out.println(""Solving case: "" + ""#"" + (i+1)); String result = ""Case #"" + (i+1) + "": "" + cases[i].solve(); if (i <= T-2) { pw.println(result); } else { pw.print(result); } } pw.close(); } }" B10778,"package gcj2012qual; import java.io.*; import java.util.*; public class RecycleNum { /** * @param args */ HashMap map = new HashMap(); int totalpair(int start, int end){ int num = 0; for(int i = start; i <= end; i++){ String s = String.valueOf(i); //System.out.println(s); for(int j = 1; j < s.length(); j++){ String recycle = s.substring(j) + s.substring(0, j); //System.out.println(recycle + "" "" + recycle.length()); //System.out.println(""hh"" + i + "" "" + j); if(recycle.charAt(0) != '0'){ //int new_num = Integer.getInteger(recycle); Integer new_num = new Integer(recycle); if(new_num <= end && new_num >= start && new_num != i) { //map.put(recycle, s); num = num + 1; } } } } return num / 2; } public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub Scanner input = new Scanner(new File(""C-small-attempt0.in"")); PrintWriter output = new PrintWriter(new FileWriter(""output"")); RecycleNum recyclenum = new RecycleNum(); // Scanner in = new Scanner(System.in); int case_num = input.nextInt(); String word = input.nextLine(); for(int i = 0; i < case_num; i++){ int start = input.nextInt(); int end = input.nextInt(); System.out.println(start + "" "" + end); output.println(""Case #"" + (i + 1) + "": "" + recyclenum.totalpair(start, end)); } input.close(); output.flush(); output.close(); } } " B10266,"package C; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.ArrayList; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) throws Exception { /* Input File */ BufferedReader reader = new BufferedReader(new FileReader(""G:/projects/CodeJam12/src/C/in.txt"")); /* Output File */ PrintWriter writer = new PrintWriter(new FileWriter(""G:/projects/CodeJam12/src/C/out.txt"")); /* Getting number of test cases */ int noOfTestCases = Integer.parseInt(reader.readLine()); System.out.println(""No of Test Cases : ""+noOfTestCases); /* Iterating for every test case */ for ( int i=1; i <= noOfTestCases;i++){ /* Getting input test case line */ String ipline = reader.readLine(); System.out.println(""\n\nTest Case ""+i+"" : ""+ipline); /* Split the test case string */ String elements []= ipline.split("" ""); /* Parsing elements to integer */ int lower_limit = Integer.parseInt(elements[0]); int upper_limit = Integer.parseInt(elements[1]); int count = 0; ArrayList processed = new ArrayList(); /* Recycling numbers and counting them */ if ( upper_limit > 10 ){ for ( int x=lower_limit; x <= upper_limit;x++ ){ String sx = new Integer(x).toString(); for ( int j=1; j < sx.length(); j++){ String sr = sx.substring(sx.length()-j,sx.length()) + sx.substring(0, sx.length()-j); Integer r = Integer.parseInt(sr); System.out.println(""Number : ""+x+"", Recycled : ""+r); if ( sr.charAt(0)=='0' ){ System.out.println(""As first character should be nonzero... : ""+sr); continue; } //if ( x < r && r > lower_limit && r < upper_limit ) { if ( x != r && r > lower_limit && r < upper_limit ) { if ( processed.contains(sx+""#""+sr) || processed.contains(sr+""#""+sx) ){ System.out.println(""Already in recycled pair : Number : ""+x+"", Recycled : ""+r); }else{ System.out.println(""Number : ""+x+"", Recycled : ""+r); count++; System.out.println(""Number of recycled pairs : ""+count); processed.add(sx+""#""+sr); processed.add(sr+""#""+sx); } } } } } System.out.println(""processed.length : ""+processed.size()); /* printing output */ System.out.println(""Number of recycled pairs : ""+count); System.out.println(""Case #""+i+"": ""+count); writer.println(""Case #""+i+"": ""+count); } // for loop ends here /* closing streams */ System.out.println(""Closing streams...""); writer.close(); reader.close(); System.out.println(""Streams closed.""); } } " B13170,"import java.io.*; import java.util.Scanner; import java.util.Arrays; public class RecycleNums { public static void main(String[] args) throws FileNotFoundException { File input = new File(args[0]); Scanner scan = new Scanner(input); PrintStream output = new PrintStream(new File(""C-small.out"")); int cases = scan.nextInt(); for (int i = 0; i < cases; i++) { int first = scan.nextInt(); int second = scan.nextInt(); int result = checkRange(first, second); output.print(""Case #"" + (i + 1) + "": "" + result); if (i != cases - 1) output.println(); } // for } // main public static int checkRange(int min, int max) { int count = 0; for (int i = min; i < max; i++) { for (int j = i + 1; j <= max; j++) { if (isRecycleNums(i, j)) count++; } // for } // for return count; } // checkRange public static boolean isRecycleNums(int a, int b) { char[] first = Integer.toString(a).toCharArray(); char[] second = Integer.toString(b).toCharArray(); if (first.equals(second)) return true; for (int i = 0; i < first.length; i++) { rotateArray(first); if (Arrays.equals(first, second)) return true; } // for return false; } // isRecycleNums public static void rotateArray(char[] myChars) { char first = myChars[0]; for (int i = 0; i < myChars.length - 1; i++) { myChars[i] = myChars[i+1]; } // for myChars[myChars.length - 1] = first; } // rotateArray } // RecycleNums" B11222,"import java.io.*; import java.util.*; public class GCJ2012QualC{ void solve(){ Scanner sc = new Scanner(System.in); // sc.useDelimiter(""\n""); int T = sc.nextInt(); for(int testCase = 1; testCase <= T; testCase++){ int first = sc.nextInt(); int last = sc.nextInt(); // str = Translate(str); //System.out.println(first + "" "" + last); System.out.println(""Case #"" + testCase + "": "" + Test2(first, last)); } } private int Test2(int first, int last){ int tmp = 0; int[][] map = new int[last + 1][last + 1]; for(int i = 0; i < last + 1; i++){ for(int j = 0; j < last + 1; j++){ map[i][j] = 0; } } for(int i = 0; i < last - first; i++){ String firstStr = String.valueOf(first + i); for(int j = 0; j < firstStr.length(); j++){ String tmp1 = firstStr.substring(j, firstStr.length()); String tmp2 = firstStr.substring(0, j); // System.out.println(""Tmp2: "" + tmp2); int tmpI1 = Integer.parseInt(tmp1 + tmp2); // System.out.println(""Tmp1: "" + tmpI1 + ""Tmp2: "" + tmpI2); if(tmpI1 > first + i && tmpI1 <= last ){ // System.out.println(first + i + "" -> "" + tmpI1); if(map[first + i][tmpI1] == 0){ tmp++; map[first + i][tmpI1] = 1; } } /* if(tmpI2 > first + i && tmpI2 < last){ tmp++; System.out.println(first + i + "" -> "" + tmpI2); } */ } } return tmp; } private int Test(int first, int last){ int tmp = 0; for(int i = 0; i < (first + last) / 2; i++){ if((first + i) % 11 != 0){ String firstStr = String.valueOf(first + i); for(int j = 0; j < firstStr.length(); j++){ for(int k = j + 1; k < firstStr.length(); k++){ String tmp1 = firstStr.substring(j, k); String tmp2 = firstStr.substring(0, j) + firstStr.substring(k, firstStr.length()); // System.out.println(""Tmp2: "" + tmp2); int tmpI1 = Integer.parseInt(tmp1 + tmp2); int tmpI2 = Integer.parseInt(tmp2 + tmp1); System.out.println(""Tmp1: "" + tmpI1 + ""Tmp2: "" + tmpI2); if(tmpI1 > first + i && tmpI1 < last){ System.out.println(first + i + "" -> "" + tmpI1); tmp++; } if(tmpI2 > first + i && tmpI2 < last){ tmp++; System.out.println(first + i + "" -> "" + tmpI2); } } } } } /* String tmpStr = ""12345""; System.out.println(tmpStr.substring(2,4)); System.out.println(tmpStr.substring(0,2)); System.out.println(tmpStr.substring(4,5)); */ return tmp; } private String Translate(String input){ char[] tmpStr = input.toCharArray(); for(int i = 0; i < input.length(); i++){ switch(input.charAt(i)){ case 'y': tmpStr[i] = 'a';break; case 'n': tmpStr[i] = 'b';break; case 'f': tmpStr[i] = 'c';break; case 'i': tmpStr[i] = 'd';break; case 'c': tmpStr[i] = 'e';break; case 'w': tmpStr[i] = 'f';break; case 'l': tmpStr[i] = 'g';break; case 'b': tmpStr[i] = 'h';break; case 'k': tmpStr[i] = 'i';break; case 'u': tmpStr[i] = 'j';break; case 'o': tmpStr[i] = 'k';break; case 'm': tmpStr[i] = 'l';break; case 'x': tmpStr[i] = 'm';break; case 's': tmpStr[i] = 'n';break; case 'e': tmpStr[i] = 'o';break; case 'v': tmpStr[i] = 'p';break; case 'z': tmpStr[i] = 'q';break; case 'p': tmpStr[i] = 'r';break; case 'd': tmpStr[i] = 's';break; case 'r': tmpStr[i] = 't';break; case 'j': tmpStr[i] = 'u';break; case 'g': tmpStr[i] = 'v';break; case 't': tmpStr[i] = 'w';break; case 'h': tmpStr[i] = 'x';break; case 'a': tmpStr[i] = 'y';break; case 'q': tmpStr[i] = 'z';break; default : break; } } return String.valueOf(tmpStr); } public static void main(String args[]){ new GCJ2012QualC().solve(); } }" B10093,"package codeJam2012_Qualification; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Collection; import java.util.Map; import java.util.NavigableMap; import java.util.Scanner; import java.util.TreeMap; public class RecycledNumbers { private String FILE_NAME = ""2012_QC_numbers_C-small-attempt0""; private TreeMap numbers; private int maxNum = 10000; private TreeMap getNumbers() { if (numbers == null) { String value; long newNum; numbers = new TreeMap(); for (int i=10;i<=maxNum;i++) { value = String.valueOf(i); for (int pos=0;pos recycles = getNumbers().subMap(lowest, true, highest, true); for (Map.Entry recycle : recycles.entrySet()) { if (recycle.getValue() dic = new HashMap<>(); protected BufferedReader reader; protected BufferedWriter writer; protected Scanner in; public static BufferedReader openReader(String inputFile) throws IOException { FileInputStream fis = new FileInputStream(new File(inputFile).getAbsoluteFile()); return new BufferedReader( new InputStreamReader(fis, ""UTF-8"") ); } public static BufferedWriter openWriter(String outputFile) throws IOException { File file = new File(outputFile); FileOutputStream fos = new FileOutputStream(file.getAbsoluteFile()); return new BufferedWriter( new OutputStreamWriter(fos, ""UTF-8"") ); } public RecycledNumbers(String fileName) throws IOException { init(fileName); } protected void init(String fileName) throws IOException { String in = fileName; String out = in.replace("".in"", "".out""); reader = openReader(in); this.in = new Scanner(reader); writer = openWriter(out); } public void close() { try { in.close(); } catch (Exception e) { // ignore } try { if (reader != null) { reader.close(); } } catch (IOException e) { //ignore } try { if (writer != null) { writer.close(); } } catch (IOException e) { //ignore } } public void write(int caseNumber) throws IOException { write(""Case #"" + caseNumber + "":""); } public void write(int caseNumber, String val) throws IOException { write(""Case #"" + caseNumber + "": "" + val); } public void write(String val) throws IOException { writer.write(val + ""\n""); writer.flush(); } public void execute() { try { long startProblem = System.currentTimeMillis(); int T = in.nextInt(); System.out.println(""Tests:"" + T); for (int i = 1; i <= T; i++) { long startCase = System.currentTimeMillis(); String result = calculate(in.nextInt(), in.nextInt()); System.out.println(""case:"" + i + "" took: "" + (System.currentTimeMillis() - startCase) + "", ms""); write(i, """" + result); } System.out.println(""Took: "" + (System.currentTimeMillis() - startProblem) + "", ms""); } catch (Exception ex) { ex.printStackTrace(); } finally { close(); } } private String calculate(int A, int B) { long count = 0; for (int i = A; i <= B; i++) { String s = Integer.toString(i); Set set = new HashSet<>(); for (int k = 1; k < s.length(); k++) { String newStr = s.substring(k) + s.substring(0, k); int val = Integer.parseInt(newStr); if (val > i && val <= B) { set.add(val); } } count += set.size(); } return """" + count; } public static void main(String[] args) throws Exception { // String fileName = ""test.in""; // String fileName = ""B-small-attempt2.in""; // String fileName = ""B-large.in""; String fileName = ""C-small-attempt0.in""; RecycledNumbers problem = new RecycledNumbers(fileName); problem.execute(); } } " B11537,"package template; import java.util.ArrayList; import java.util.Set; import java.util.HashSet; public class TestCaseSolver implements Runnable { private ArrayList testCases; private int ref; public TestCaseSolver(ArrayList tcs, int ref) { testCases = tcs; this.ref = ref; } public TestCaseSolver(TestCase tc, int ref) { ArrayList tcs = new ArrayList<>(); tcs.add(tc); testCases = tcs; this.ref = ref; } public int getRef() { return ref; } @Override public void run() { for (TestCase tc : testCases) { long startTime = System.nanoTime(); solve(tc); long duration = System.nanoTime() - startTime; double secs = (double)duration / (1000000000d); tc.setTime(secs); System.out.println(""Thread "" + ref + "" solved testcase "" + tc.getRef() + "" in "" + String.format(""%.2f"", secs) + "" secs.""); } } private void solve(TestCase tc) { ArrayList a_b = tc.getIntegerList(""a_b""); int A = a_b.get(0); int B = a_b.get(1); int count = 0; for (int i = A; i <= B; i++) { ArrayList digs = Utils.splitToDigits(i); int l = digs.size(); Set solns = new HashSet<>(); for (int r = 1; r < l; r++) { int rec = recombine(digs, r); if (valid(digs, r) && rec <= B) { //System.out.println(digs + "" "" + r); solns.add(new Integer(rec)); } } count += solns.size(); } tc.setSolution(new Integer(count)); } private boolean valid(ArrayList digits, int startRotation) { if (digits.get(startRotation).intValue() == 0) {return false;} int len = digits.size(); for (int origLoc = 0; origLoc < len; origLoc++) { int rotLoc = (origLoc + startRotation) % len; int origDig = digits.get(origLoc); int rotDig = digits.get(rotLoc); if (rotDig > origDig) {return true;} if (rotDig < origDig) {return false;} } return false; } private int recombine(ArrayList digs, int start) { int tot = 0; for (int i = 0; i < digs.size(); i++) { int loc = (i + start) % digs.size(); tot += digs.get(loc).intValue() * (int)(Math.pow(10d, (double)(digs.size() - i - 1))); } return tot; } } " B12277,"/************************************************************************* * Compilation: javac StdIn.java * Execution: java StdIn * * Reads in data of various types from standard input. * *************************************************************************/ import java.io.BufferedInputStream; import java.util.Locale; import java.util.Scanner; /** * Standard input. This class provides methods for reading strings * and numbers from standard input. *

* The Locale used is: language = English, country = US. This is consistent * with the formatting conventions with Java floating-point literals, * command-line arguments (via Double.parseDouble()) * and standard output (via System.out.print()). It ensures that * standard input works with the input files used in the textbook. *

* For additional documentation, see Section 1.5 of * Introduction to Programming in Java: An Interdisciplinary Approach by Robert Sedgewick and Kevin Wayne. */ public final class StdIn { // assume Unicode UTF-8 encoding private static String charsetName = ""UTF-8""; // assume language = English, country = US for consistency with System.out. private static Locale usLocale = new Locale(""en"", ""US""); // the scanner object private static Scanner scanner = new Scanner(new BufferedInputStream(System.in), charsetName); // static initializer static { scanner.useLocale(usLocale); } // singleton pattern - can't instantiate private StdIn() { } /** * Is there only whitespace left on standard input? */ public static boolean isEmpty() { return !scanner.hasNext(); } /** * Return next string from standard input */ public static String readString() { return scanner.next(); } /** * Return next int from standard input */ public static int readInt() { return scanner.nextInt(); } /** * Return next double from standard input */ public static double readDouble() { return scanner.nextDouble(); } /** * Return next float from standard input */ public static float readFloat() { return scanner.nextFloat(); } /** * Return next short from standard input */ public static short readShort() { return scanner.nextShort(); } /** * Return next long from standard input */ public static long readLong() { return scanner.nextLong(); } /** * Return next byte from standard input */ public static byte readByte() { return scanner.nextByte(); } /** * Return next boolean from standard input, allowing ""true"" or ""1"" for true, * and ""false"" or ""0"" for false */ public static boolean readBoolean() { String s = readString(); if (s.equalsIgnoreCase(""true"")) return true; if (s.equalsIgnoreCase(""false"")) return false; if (s.equals(""1"")) return true; if (s.equals(""0"")) return false; throw new java.util.InputMismatchException(); } /** * Does standard input have a next line? */ public static boolean hasNextLine() { return scanner.hasNextLine(); } /** * Return rest of line from standard input */ public static String readLine() { return scanner.nextLine(); } /** * Return next char from standard input */ // a complete hack and inefficient - email me if you have a better public static char readChar() { // (?s) for DOTALL mode so . matches a line termination character // 1 says look only one character ahead // consider precompiling the pattern String s = scanner.findWithinHorizon(""(?s)."", 1); return s.charAt(0); } /** * Return rest of input from standard input */ public static String readAll() { if (!scanner.hasNextLine()) return null; // reference: http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html return scanner.useDelimiter(""\\A"").next(); } /** * Read rest of input as array of ints */ public static int[] readInts() { String[] fields = readAll().trim().split(""\\s+""); int[] vals = new int[fields.length]; for (int i = 0; i < fields.length; i++) vals[i] = Integer.parseInt(fields[i]); return vals; } /** * Read rest of input as array of doubles */ public static double[] readDoubles() { String[] fields = readAll().trim().split(""\\s+""); double[] vals = new double[fields.length]; for (int i = 0; i < fields.length; i++) vals[i] = Double.parseDouble(fields[i]); return vals; } /** * Read rest of input as array of strings */ public static String[] readStrings() { String[] fields = readAll().trim().split(""\\s+""); return fields; } /** * Unit test */ public static void main(String[] args) { System.out.println(""Type a string: ""); String s = StdIn.readString(); System.out.println(""Your string was: "" + s); System.out.println(); System.out.println(""Type an int: ""); int a = StdIn.readInt(); System.out.println(""Your int was: "" + a); System.out.println(); System.out.println(""Type a boolean: ""); boolean b = StdIn.readBoolean(); System.out.println(""Your boolean was: "" + b); System.out.println(); System.out.println(""Type a double: ""); double c = StdIn.readDouble(); System.out.println(""Your double was: "" + c); System.out.println(); } } " B10551,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package g.jam_3; import java.io.*; import java.util.ArrayList; // /** * * @author toshiba */ public class Gjam_3 { static String input = ""c:\\Gjam\\3\\small.in""; static String output = ""c:\\Gjam\\3\\output.out""; public static void main(String[] args) throws FileNotFoundException, IOException { output o = new output(output); ArrayList input_arr = new input().ReadInput(input); for (int j = 0; j < input_arr.size(); j++) { String[] t = input_arr.get(j).split("" ""); int a = Integer.parseInt(t[0]); int b = Integer.parseInt(t[1]); int result = 0; for (int n = a; n <= b; n++) { String tmp = String.valueOf(n); for (int k = tmp.length()-1; k > 0; k--) { tmp = String.valueOf(n).substring(k, String.valueOf(n).length()) +String.valueOf(n).substring(0, k); int m = Integer.parseInt(tmp); if(m==1111) System.out.print(m); if(m>n&&m<=b&&m!=n) result++; } } o.write(""Case #"" + (j+1) + "": "" + result + ""\n""); } o.close(); } } class input { public ArrayList ReadInput(String input) throws FileNotFoundException, IOException { ArrayList a = new ArrayList(); BufferedReader str = new BufferedReader(new InputStreamReader(new FileInputStream(input))); String s = """"; str.readLine(); int x = 0; while ((s = str.readLine()) != null) { x++; a.add(s); } return a; } } // class output { FileWriter fstream; BufferedWriter bw; public output(String output) throws IOException { fstream = new FileWriter(output); bw = new BufferedWriter(fstream); } public void write(String result) throws IOException { bw.write(result); } public void close() throws IOException { bw.close(); } } // // " B10584,"package qualification; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.StringWriter; public class RecycledNumber { public static void main(String[] args) throws IOException{ BufferedReader file = new BufferedReader(new FileReader(new File(""src/input""))); String firstline = file.readLine(); int casenum = Integer.parseInt(firstline); StringWriter s= new StringWriter(); for(int i=0;i= a && temp>n && temp <= b ){ for(int z=0;z set; static int ctr, low, high; public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(in)); int ii = Integer.parseInt(br.readLine()); for(int jj=0; jj(); ctr = 0; for(int i=low; i<=high; i++){ if(!set.contains(i)){ generate(i+""""); } } out.printf(""Case #%d: %d\n"", jj+1, ctr); } } static void generate(String s){ String ss = s+s; int tmp = 0; for(int i=0; i=low && x<=high && !set.contains(x)){ // out.println(x); set.add(x); tmp++; } } // out.println(); ctr+=(tmp*(tmp-1)/2); } }" B12690,"package codejam; import java.io.File; import java.io.PrintStream; import java.util.HashMap; import java.util.Scanner; public class QualificationC { public static long recycled(long nr1,long b){ long count=0; String n1=String.valueOf(nr1); String n2=n1; HashMap gen=new HashMap(); for(int i=0;inr1&&nr2<=b){ count++; } } return count; } public static void main(String[] args){ try{ Scanner sc=new Scanner(new File(""C.in"")); PrintStream ps=new PrintStream(""C.out""); int n=sc.nextInt(); long a,b; for(int i=0;i n && m <= B){ int c; for (c = 0; c < C.length && C[c] != 0; c++) if (C[c] == m) break outer; r++; C[c] = m; } } } System.out.println(""Case #"" + t + "": "" + r); } } } " B13009,"package com.unitedcoders.examples.codejam; import java.io.File; import java.io.PrintStream; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) throws Exception { Scanner scanner = new Scanner(new File(""/Users/nh/c.in"")); PrintStream out = new PrintStream(new File(""/Users/nh/c.out"")); int testcases = scanner.nextInt(); scanner.nextLine(); for (int casenr = 1; casenr <= testcases; casenr++) { int a = scanner.nextInt(); int b = scanner.nextInt(); int p = solve(a, b); System.out.printf(""Case #%d: %d\n"", casenr, p); out.printf(""Case #%d: %d\n"", casenr, p); } } public static int solve(int a, int b) { int result = 0; String sA = intToString(a); String sB = intToString(b); for (int i = a; i <= b; i++) { if (i < 10) { continue; } String k = intToString(i); for (int j = 0; j < sA.length()-1; j++) { k = cycle(k); if((stringToInt(k)>i) && (stringToInt(k)<=b)){ result++; } } } return result; } public static String intToString(int i) { StringBuffer sb = new StringBuffer(); while (i > 0) { sb.append(i % 10); i = i / 10; } return sb.reverse().toString(); } public static int stringToInt(String s) { return Integer.valueOf(s); } public static String cycle(String s) { StringBuffer sb = new StringBuffer(); for (int i = 1; i < s.length(); i++) { sb.append(s.substring(i, i + 1)); } sb.append(s.substring(0, 1)); return sb.toString(); } } " B11508,"import java.util.Scanner; import java.util.TreeMap; public class RecycledNumbers { public static void main(String[]args){ Scanner sc = new Scanner(System.in); //Read in the T int -- Test Cases int T = Integer.parseInt(sc.nextLine()); for (int t = 1; t <= T; t++) { int num = 0; //START OF CODE int a = sc.nextInt(); int b = sc.nextInt(); int focus = a; for (int i = 0; focus < b; i++) { String f = focus + """"; boolean distinct = true; /*all:for (int j = 0; j < f.length(); j++) { for (int j2 = j+1; j2 < f.length(); j2++) { if(f.charAt(j) == f.charAt(j2)){ distinct = false; break all; } } } distinct = true;*/ if(distinct){ for (int j = 0; j < f.length() - 1; j++) { f = f.charAt(f.length()-1) + f.substring(0,f.length()-1); int fs = Integer.parseInt(f); if(fs <= b && f.charAt(0) != '0' && fs > focus){ //System.out.println(focus+ "" ""+ f); num++; } } } focus++; } //END OF CODE //OUTPUT System.out.format(""Case #%d: %d\n"", t, num); } } } " B11259,"import java.io.*; import java.util.*; /** * * @author kronenthaler */ public class C { public static void main(String arg[]){ try{ Scanner in = new Scanner(new FileInputStream(""c-small.in"")); System.setOut(new PrintStream(""c.out"")); int T = in.nextInt(); for(int cases=1;cases<=T;cases++){ int A = in.nextInt(); int B = in.nextInt(); int count = 0; for(int i=A;i> map = new HashSet>(); for(int j=1;j a = new ArrayList(); a.add(i); a.add(m); if(!map.contains(a)){ count++; map.add(a); } } } } System.out.printf(""Case #%d: %d\n"", cases, count); } }catch(Exception e){ e.printStackTrace(); } } } " B11435,"package gcj_qr_c; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Scanner; /** * * @author amahdy */ public class GCJ_QR_C { /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException, IOException { new GCJ_QR_C().start(); } private void start() throws FileNotFoundException, IOException { Scanner in = new Scanner( new FileReader(""/home/amahdy/c-small.in"")); int x = in.nextInt(); in.nextLine(); for (int i = 0; i < x; ) { int A = in.nextInt(); int B = in.nextInt(); int val = 0; for(int j=A; j0;) { zz[n]=zz[--n]; } zz[0] = t; if(t=='0') { continue; }else { int f = Integer.parseInt(String.valueOf(zz)); if(f > j && f <= B) { val++; } } } } System.out.println(""Case #"" + ++i + "": "" + val); } } } " B12734,"package googlecodejam2012.qualification.recyclednumbers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Writer; public class RecycledNumbers { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { String lineSep = System.getProperty(""line.separator""); BufferedReader br = new BufferedReader( args.length > 0 ? new FileReader(args[0]) : new InputStreamReader(System.in)); try { Writer out = new BufferedWriter(args.length > 1 ? new FileWriter(args[1]): new OutputStreamWriter(System.out)); try { int numLines = Integer.parseInt(br.readLine().trim()); for (int i = 1; i <= numLines;++i) { String line = br.readLine(); out.write(""Case #"" + i + "": ""+count(line) + lineSep); } } finally { out.close(); } } finally { br.close(); } } private static int count(String line) { String[] parts = line.split(""\\s+""); return count(Integer.parseInt(parts[0]), Integer.parseInt(parts[1])); } private static int count(int a, int b) { if (b < 10) { return 0; } int digits = 1+(int) Math.log10(a); int count = 0; for (int i = a; i < b; ++i) { int[] prevs = new int[digits]; for (int j = 1; j < digits; ++j) { prevs[j - 1] = shift(i, j, digits); if (recycled(prevs, i, a, b, j)) { // System.out.println(shift(i, j) + "" <- "" + i); ++count; } } } return count; } private static boolean recycled(final int[] prevs, final int orig, final int a, final int b, final int j) { boolean recycled = recycled(prevs[j - 1], orig, a, b); if (recycled) { for (int i = 0; i < j - 1; ++i) { if (prevs[i] == prevs[j - 1]) recycled = false; } } return recycled; } private static boolean recycled(int shifted, int orig, int a, int b) { return shifted > orig && shifted >= a && shifted <= b; } private static final int[] powers = new int[] {1, 10, 100, 1000, 10000, 100000, 1000000}; private static int shift(int num, int shift, int digits) { int power = powers[shift]; int pow2 = powers[digits - shift]; return num % power * pow2 + num / power; } private static int shift(int num, int shift) { String str = Integer.toString(num); return Integer.parseInt(str.substring(shift) + str.substring(0, shift)); } } " B10009,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Recycled { private static final String fileInName = ""file.in""; private static final String fileOutname = ""file.out""; public static void main(String[] args) throws IOException{ System.out.println(""Init""); FileWriter fw = new FileWriter(fileOutname); BufferedReader br = new BufferedReader(new FileReader(fileInName)); int numCases = Integer.parseInt(br.readLine()); System.out.println(""Num cases: "" + numCases); for(int numCase = 1; numCase <= numCases; numCase++){ String[] caseData = br.readLine().split("" ""); int numA = Integer.parseInt(caseData[0]); int numB = Integer.parseInt(caseData[1]); Map> prevCalcs = new HashMap>(); System.out.println(""\tA: "" + numA +"" B: "" + numB); int numRec = 0; //Result for(int i = numA; i < numB; i++){ String nS = String.valueOf(i); String mS = null; for( int j = 1; j < nS.length(); j++){ mS = generateRecycled(nS, j); if(isValid(nS, mS, numB, prevCalcs)){ numRec++; System.out.println(""\t\tRecycled: ("" + nS +"", "" +mS +"")""); addToPrevCalcs(nS, mS, prevCalcs); } } } System.out.println(""\tRes: "" + numRec); fw.write(""Case #"" + numCase +"": "" + numRec +""\n""); } fw.close(); br.close(); } private static String generateRecycled(String n, int numToMove){ return n.substring(n.length() - numToMove, n.length()) + n.substring(0, n.length() - numToMove); } private static boolean isValid(String nS, String mS, int numB, Map> map){ return !mS.startsWith(""0"") && Integer.parseInt(nS) < Integer.parseInt(mS) && numB >= Integer.parseInt(mS) && (!map.containsKey(nS) || !map.get(nS).contains(mS)); } private static void addToPrevCalcs(String nS, String mS, Map> map){ if(!map.containsKey(nS)){ map.put(nS, new ArrayList()); } map.get(nS).add(mS); } } " B11174,"package com.google.cj12; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; public class RecycledNumber { public static void main(String[] args) throws IOException { String name = ""C-small-attempt0""; BufferedReader f = new BufferedReader(new FileReader(""resources/"" + name + "".in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter( ""resources/"" + name + "".out""))); new RecycledNumber().solve(f, out); out.close(); } private void solve(BufferedReader f, PrintWriter out) throws IOException { int T = read(f); HashSet set = new HashSet(); for (int i=0; i n && m <= B) { count++; } } set.clear(); } out.println(""Case #"" + (i+1) + "": "" + count); } } public int read(BufferedReader f) throws IOException { return Integer.parseInt(f.readLine()); } public int[] read(BufferedReader f, int N) throws IOException { String[] t = f.readLine().split("" ""); int[] a = new int[N]; for (int i=0; i 10) { int sub = 0; Map map = new HashMap(); for (int n=a; n<=b; n++) { if (n < 10) {n = 10; continue;} String sn = String.valueOf(n); sub = sn.length(); int m = 0; for (int o=0; o n && m <= b && !map.containsKey(n + "","" + m)) { //System.out.println(n + "","" + m); map.put(n + "","" + m, n + "","" + m); answer++; } } } } writeOutput(result + answer, out); } } out.close(); } catch(Exception e) { e.printStackTrace(); } } private static BufferedReader readFile(FileReader in) throws FileNotFoundException { return new BufferedReader(in); } private static void writeOutput(String text, BufferedWriter out) throws IOException { out.write(text); out.write(""\n""); } } " B11585,"package br.com.codejam.qualification; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) throws IOException { String file = ""C-small-attempt1""; Scanner sc = new Scanner(new FileReader(file + "".in"")); PrintWriter pw = new PrintWriter(new FileWriter(file + "".out"")); int T = new Integer(sc.nextLine()); Map, String> mapAll = new HashMap, String>(); Map map = new HashMap(); int h = 1; for (int t = 1; t <= T; t++) { String line = sc.nextLine(); String[] numbers = line.split("" ""); mapAll = new HashMap, String>(); int A = new Integer(numbers[0]); int B = new Integer(numbers[1]); if ((String.valueOf(A)).length() > 1) { for (int i = B; i > A; i--) { for (int j = A; j < i; j++) { String auxA = String.valueOf(j); for (int m = 0; m < auxA.length(); m++) { if (auxA.charAt(0) != '0') { if (new Integer(auxA) == i) { map = new HashMap(); map.put(String.valueOf(j), String.valueOf(i)); mapAll.put(map, ""sucesso""); } } StringBuilder sb = new StringBuilder(); sb.append(auxA.charAt(auxA.length() - 1)); sb.append(auxA.substring(0, auxA.length() - 1)); auxA = sb.toString(); } } } } pw.print(""Case #"" + h + "": ""); pw.println(mapAll.size()); /*for(Map m : mapAll.keySet()) { for(String s : m.keySet()) { pw.print(s + "" - ""); pw.println(m.get(s)); } } pw.println(""###########################""); pw.println();*/ h++; } pw.flush(); pw.close(); sc.close(); } } " B12496,"import java.io.*; class ProbC { String calculate(int low,int up) { String ans=""""; int anscount=0; int l=low; int u=up; for(int i=l;i<=u;i++) { String num=Integer.toString(i); for(int j=1;j0) { int a=temp%10; temp=temp/10; uc++; } temp=low; while(temp>0) { int a=temp%10; temp=temp/10; lc++; } if(uc==lc) { System.out.println(""A and B have same number of digits""); String result=obj.calculate(low,up); String finalans=""Case #""+(i+1)+"": ""+result+System.getProperty(""line.separator""); dout.writeBytes(finalans); } else { System.out.println(""A and B do not have same number of digits""); } } } }" B10273,"import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; public class RecycleNumbers { @SuppressWarnings(""deprecation"") private static void solveProblem() { // Stream to read file FileInputStream fin; // Stream to write file FileOutputStream fout; try { // Open an input stream // fin = new FileInputStream (""B-large.in""); fin = new FileInputStream (""input.txt""); // Open an output stream fout = new FileOutputStream (""output.txt""); // reader DataInputStream reader = new DataInputStream(fin); // writer PrintStream writer = new PrintStream(fout); int numCases = Integer.parseInt(reader.readLine()); String line = """"; for (int i = 1; i <= numCases; i++) { line = ""Case #"" + i + "": "" + solveCase(reader); writer.println(line); System.out.println(line); } // Close our input stream fin.close(); // Close our output stream fout.close(); } // Catches any error conditions catch (IOException e) { System.err.println (""Unable to read from file""); System.exit(-1); } catch (Exception e) { e.printStackTrace(); } } @SuppressWarnings(""deprecation"") public static String solveCase(DataInputStream reader) throws Exception, IOException { return getNumRecyclers(reader.readLine().split("" "")); } private static String getNumRecyclers(String[] values) { int A = Integer.parseInt(values[0]); int B = Integer.parseInt(values[1]); int n, m, numRescyclers = 0; String numS = """"; for (n = A; n <= B; n++) { numS = n + """"; for (int length= numS.length(), j = 0; j < length; j++) { // A <= n < m <= B. m = Integer.parseInt(numS); if ( A <= n && n < m && m <= B ) numRescyclers++; // if ( A <= n && n < m && m <= B ) { // numRescyclers++; // System.out.println(""(""+n+"",""+m+"")""); // } numS = numS.charAt(length-1) + numS.substring(0, length-1); } } return numRescyclers + """"; } public static void main(String[] args) { solveProblem(); } } " B11226,"package codezam.util; import java.math.BigDecimal; public class MathUtil { public static BigDecimal pow(int a, int b) { BigDecimal result = new BigDecimal(a); BigDecimal number = new BigDecimal(a); if (b==0) { result = new BigDecimal(1); } else { for (int i=1; i output = new ArrayList(); private static Map input; public static void main(String args[]) { try { RecycleNumbers.fileRead(); RecycleNumbers.coreLogic(); RecycleNumbers.fileWrite(); } catch (IOException e) { e.printStackTrace(); } } private static void fileRead() throws IOException { try { fr = new FileReader(""D:/data/C-small-attempt0.in""); BufferedReader br = new BufferedReader(fr); input = new HashMap(); String line; int counter = 1; while ((line = br.readLine()) != null) { input.put(counter, line); counter++; } System.out.println(input); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { fr.close(); } } private static void fileWrite() throws IOException { int counter = 1; try { bw = new BufferedWriter(new FileWriter(new File(""D:/data/output.txt""), true)); for (String writeLine : output) { bw.write(""Case #"" + counter + "": ""); bw.write(writeLine); bw.newLine(); counter++; } bw.close(); } catch (Exception e) { e.printStackTrace(); } } private static void coreLogic() { int noOfCases = Integer.valueOf(input.remove(Integer.valueOf(""1""))); System.out.println(""Number of Cases: "" + noOfCases); StringBuffer outputString; for (int counter = 2; counter <= noOfCases + 1; counter++) { outputString = new StringBuffer(); String processLine = input.get(Integer.valueOf(counter)); if (processLine != null) { while (processLine != null) { System.out.println(""################Case #: "" + (counter - 1) + ""########################################""); System.out.println(""Processing line: "" + processLine); outputString.append(processString(processLine)); break; } output.add(outputString.toString()); } } } private static String processString(String processLine) { StringTokenizer strToken = new StringTokenizer(processLine, "" ""); String start = """"; String end = """"; int output = 0; start = strToken.nextToken(); end = strToken.nextToken(); System.out.println(""Start: "" + start); System.out.println(""End: "" + end); int modulus = 10; int length = start.length(); int counterLength = start.length(); int startNumber = Integer.parseInt(start); int endNumber = Integer.parseInt(end); List finalOutput = new ArrayList(); //Set finalOutput = new HashSet(); if (startNumber >= 10) { while (true) { System.out.println(""Length : "" + length); System.out.println(""Modulus Length : "" + String.valueOf(modulus).length()); if (length >= String.valueOf(modulus).length()) { for (int counter = startNumber; counter <= endNumber; counter++) { int numberA = counter; int calculation = (int) (((numberA % modulus) * Math.pow(10, counterLength - 1)) + (numberA / modulus)); if ((calculation > numberA) && (calculation <= endNumber)) { System.out.println(""@@@Number a: "" + numberA + "" Calculation: "" + calculation + "" Ouput: "" + (output++)); finalOutput.add(numberA); } } } else { break; } modulus = modulus * 10; counterLength = counterLength - 1; } } return String.valueOf(finalOutput.size()); } } " B12652,"package codejem; import java.io.*; import java.util.HashSet; import java.util.Set; public class RecycleNumber { public static void main(String[] args) throws IOException { InputStream is; if (args.length > 0) { is = new FileInputStream(args[0]); }else{ is = System.in; } BufferedReader inputReader = new BufferedReader(new InputStreamReader(is)); String firstLine = inputReader.readLine(); int count_of_cases = Integer.parseInt(firstLine); for (int idx_of_case = 1; idx_of_case <= count_of_cases; idx_of_case++) { String caseLine = inputReader.readLine(); String[] numbers = caseLine.split("" ""); int start = Integer.parseInt(numbers[0]); int end = Integer.parseInt(numbers[1]); int count = count_of_recyclable(start, end); System.out.println(String.format(""Case #%d: %d"", idx_of_case, count)); } } public static int count_of_recyclable(int start, int end) { int count = 0; for (int number = start; number <= end; number++) { char[] chars = int_to_char_array(number); char[] max_number = int_to_char_array(end); Set matchNumbers = new HashSet(); for (int chars_to_move = 1; chars_to_move < chars.length; chars_to_move++) { char[] rotated_chars = rotated_chars(chars, chars_to_move); if (rotated_chars[0] != '0' && not_greater_than_number(rotated_chars, max_number) && less_than_number(chars, rotated_chars)) { matchNumbers.add(String.valueOf(rotated_chars)); } } count+= matchNumbers.size(); } return count; } public static boolean not_greater_than_number(char[] rotated_chars, char[] max_number) { for (int i = 0; i < rotated_chars.length; i++) { if (max_number[i] > rotated_chars[i]) { return true; } if (rotated_chars[i] > max_number[i]) { return false; } } return true; } public static boolean less_than_number(char[] rotated_chars, char[] max_number) { for (int i = 0; i < rotated_chars.length; i++) { if (max_number[i] > rotated_chars[i]) { return true; } if (rotated_chars[i] > max_number[i]) { return false; } } return false; } private static char[] int_to_char_array(int number) { return String.valueOf(number).toCharArray(); } public static char[] rotated_chars(char[] chars, int chars_to_move) { int length = chars.length; char[] result = new char[length]; System.arraycopy(chars, length - chars_to_move, result, 0, chars_to_move); System.arraycopy(chars, 0, result, chars_to_move, length - chars_to_move); return result; } } " B12591,"import java.io.*; import java.util.*; public class Init { /** * @param args */ public static void main(String[] args) { try { // ----------------------------------------------------- // BufferedReader br = new BufferedReader(new FileReader(""C:\\input.in"")); BufferedWriter bw = new BufferedWriter(new FileWriter(""C:\\output.out"")); int testcases = Integer.parseInt(br.readLine()); // For each test case for(int i = 0; i < testcases; i++){ StringTokenizer st = new StringTokenizer(br.readLine(),"" ""); int low = Integer.parseInt(st.nextToken()); int high = Integer.parseInt(st.nextToken()); int recycled = 0; // Loop through all numbers in the range for (int j = low; j <= high; j++) { String currentval = Integer.toString(j); // Test each arrangement of the current number to see if its a recycled pair for (int k = 1; k < currentval.length(); k++) { String newvalue = currentval.substring(k) + currentval.substring(0,k); if(newvalue.charAt(0) == '0') continue; // Check for leading 0 int newval = Integer.parseInt(newvalue); if(j < newval && newval <= high){ System.out.print(j); System.out.print("" ""); System.out.println(newval); recycled++; } } } bw.write(""Case #""+Integer.toString(i+1)+"": ""+Integer.toString(recycled)); bw.newLine(); } bw.flush(); bw.close(); // ----------------------------------------------------- // } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } " B12728,"/* *Do you ever become frustrated with television because you keep seeing the same things, *recycled over and over again? Well I personally don't care about television, *but I do sometimes feel that way about numbers. *Let's say a pair of distinct positive integers (n, m) is recycled if you can obtain m by *moving some digits from the back of n to the front without changing their order. For example, *(12345, 34512) is a recycled pair since you can obtain 34512 by moving 345 from the end of 12345 to the front. *Note that n and m must have the same number of digits in order to be a recycled pair. Neither n nor m can have leading zeros. *Given integers A and B with the same number of digits and no leading zeros, *how many distinct recycled pairs (n, m) are there with A = n < m = B? * **/ import java.io.*; public class Recycled_Numbers { public static void main(String[] args) { try { BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(new File(""g:/H.txt"")))); int n=Integer.parseInt(br.readLine()); String str=null; int A,B; String arr[]=new String[n]; String array[]; File f=new File(""g:/OutputX.txt""); f.createNewFile(); int count=0; int temp1,temp2; boolean result=false; for(int i=0;i recycled = new HashSet(); for(int index=1; index < length; index++) { boolean lowerLimitBreached = true; for(int i=0;i nChar) { lowerLimitBreached = false; break; } else if(mChar < nChar) { lowerLimitBreached = true; break; } } if(lowerLimitBreached) continue; boolean upperLimitBreached = false; for(int i=0;i mChar) { upperLimitBreached = false; break; } else if(bChar < mChar) { upperLimitBreached = true; break; } } if(upperLimitBreached) continue; StringBuilder strBuilder = new StringBuilder(); for(int i=0;i seen = new HashSet(); int T = Integer.parseInt(br.readLine()); for (int t=1; t<=T; t++) { String[] nums = br.readLine().split(""\\s+""); int A = Integer.parseInt(nums[0]); int B = Integer.parseInt(nums[1]); int tally = 0; for (int i=A; i<=B; i++) { String istr = Integer.toString(i); seen = new HashSet(); for (int j=1; j i) && (newi <= B)) { if (seen.add(newi)) { tally++; //System.out.println(i + "" "" + newi); } } } } System.out.println(""Case #"" + t + "": "" + tally); } } catch (IOException e) { throw new RuntimeException(e); } } } " B12904,"package com.brianghig.gcj.recyclednumbers; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; public class RecycledNumbers { public static void main(String[] args) throws Exception { Date start = new Date(); RecycledNumbers rn = new RecycledNumbers(); List pairs = rn.readInput(); // TODO Remove //rn.printPairs( pairs ); List uniqueRecycledNumbers = rn.getCountOfUniqueRecycledNumbers( pairs ); rn.writeOutput( uniqueRecycledNumbers ); System.out.println(""Took "" + (new Date().getTime() - start.getTime()) + ""ms""); } private void writeOutput(List uniqueRecycledNumbers) throws FileNotFoundException, IOException { StringBuffer sb = new StringBuffer(); for( int i=0; i < uniqueRecycledNumbers.size(); i++ ) { sb.append(""Case #"" + (i+1) + "": "" + uniqueRecycledNumbers.get(i) + ""\n"" ); } IOUtils.write(sb.toString(), new FileOutputStream(""recycledNumbersOutput.txt""), ""UTF-8"" ); } private void printPairs(List pairs) { for( Pair p : pairs ) { System.out.println(""n: "" + p.getN() + ""; m: "" + p.getM()); } } private List getCountOfUniqueRecycledNumbers(List pairs) { List uniqueRecycledNumbers = new ArrayList(); for( Pair p : pairs ) { uniqueRecycledNumbers.add( getCountOfUniqueRecycledFromPair( p ) ); } return uniqueRecycledNumbers; } private int getCountOfUniqueRecycledFromPair(Pair p) { assert( p != null ); //TODO long n = p.getN(); long m = p.getM(); if( n == m ) { // Quick check to ensure they're not equal. If so, none in between since A <= n < m <= B return 0; } String nString = String.valueOf( n ); String mString = String.valueOf( m ); // ok to use int because 1 <= A <= B <= 2,000,000 int length = nString.length(); List pairs = new ArrayList(); System.out.println(""Solving for Pair: "" + n + "" and "" + m); for( long x = n; x < m; x++ ) { String testString = String.valueOf(x); //System.out.println(""Testing String: "" + testString + "" for Pair: "" + n + "" and "" + m); // char[] ch = new char[ testString.length() ]; for( int i=1; i < length; i++ ) { String begin = testString.substring(0, length - i); String end = testString.substring(length - i, length); String newnum = (end + begin); // System.out.println(""Testing "" + newnum + "" from beginning: "" + begin + "" and ending: "" + end); Long newlong = Long.valueOf(newnum); if( x < newlong && //n < newlong && newlong <= m ) { System.out.println(""Pair: "" + n + "" and "" + m + "" has new pair: "" + x + "" and "" + newlong + "" from "" + testString); pairs.add( new Pair(x, newlong) ); } } } System.out.println(""Pairs Size Before Parsing: "" + pairs.size()); removeDuplicatesFromPairs( pairs ); System.out.println(""Pairs Size After Parsing: "" + pairs.size()); return pairs.size(); } private void removeDuplicatesFromPairs(List pairs) { List pairsToRemove = new ArrayList(); for( Pair a : pairs ) { // System.out.println(""Checking for dupes of pair n: "" + a.getN() + "" and m: "" + a.getM() ); for( Pair b : pairs ) { //System.out.println(""Comparing pair A: "" + a.getN() + "","" + a.getM() + "" and B: "" + b.getN() + "","" + b.getM() ); // System.out.println(""Comparing a.n: "" + a.getN() + "" to b.m: "" + b.getM()); if( a != b && ( ( a.getN() == b.getM() && a.getM() == b.getN() ) || ( a.getN() == b.getN() && a.getM() == b.getM() ) ) ) { boolean remove = true; for( Pair r1 : pairsToRemove ) { if( r1.getN() == b.getN() && r1.getM() == b.getM() ) { // Skip removing the second iteration of this pair remove = false; break; } } if( remove ) { //System.out.println(""Removing pair n: "" + b.getN() + "" and m: "" + b.getM()); System.out.println(""Removing duplicate pair A: "" + a.getN() + "","" + a.getM() + "" and B: "" + b.getN() + "","" + b.getM() ); pairsToRemove.add(b); } break; } } } for( Pair r : pairsToRemove ) { pairs.remove(r); } } public List readInput() throws FileNotFoundException, IOException { String inputFile = ""recycledNumbersInput.txt""; List pairs = new ArrayList(); List input = IOUtils.readLines(new FileInputStream( inputFile )); Long testCases = Long.valueOf( input.get(0) ); // Start at line 1, assuming at least one test case, since 1 ≤ T ≤ 50. for( int t=1; t <= testCases; t++ ) { String pairLine = input.get( t ); String[] pairTokens = StringUtils.split(pairLine, "" ""); pairs.add( new Pair( Long.valueOf(pairTokens[0]), Long.valueOf(pairTokens[1]) ) ); } return pairs; } } " B11882,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.InputStreamReader; import java.io.Reader; import java.util.HashSet; import java.util.Set; public class ProB { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub File infile = new File(""C-small-attempt0.in""); File outfile = new File(""out.txt""); BufferedReader reader = null; BufferedWriter writer = null; try{ reader = new BufferedReader(new FileReader(infile)); writer = new BufferedWriter(new FileWriter(outfile)); String ss = reader.readLine(); String out; String []nums; int t = Integer.parseInt(ss),i,j,res; int a,b; for(i=1;i<=t;i++){ out = ""Case #"" + i + "": ""; ss = reader.readLine(); nums = ss.split("" ""); a = Integer.parseInt(nums[0]); b = Integer.parseInt(nums[1]); res = 0; for(j=a;j= 10){ head = p / base; tail = p % base; if(tail >= (base / 10)){ tail *= max / base; tail += head; if(tail > p && tail <=b) { if(!set.contains(tail)){ set.add(tail); res++; } } } base /= 10; } return res; } private static void sort(int []scores,int n) { int i,j,t,s; for(i=0;i s){ s = scores[j]; t = j; } } s = scores[i]; scores[i] = scores[t]; scores[t] = s; } } } " B13193,"import java.util.ArrayList; import java.util.Scanner; public class Prob3 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub // TODO Auto-generated method stub Scanner scan = new Scanner(System.in); int num = scan.nextInt(); scan.nextLine(); for(int i=0;i d = new ArrayList(length); for(int i=0;i n && m <= B && m >= A && mod != 0 && !d.contains(m)){ //System.out.println(""n: "" + n + "" m: "" + m); d.add(m); res++; } } return res; } } " B12066,"package codeJam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.HashSet; import java.util.Iterator; /** * http://code.google.com/codejam/contest/1460488/dashboard#s=p2 * @author Weiwei Cheng */ public class RecycledNumbers { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new FileReader(""_input.in"")); BufferedWriter bw = new BufferedWriter(new FileWriter(""_output.in"")); br.readLine(); String line = null; int count = 0; while((line=br.readLine())!=null){ int num = 0; String[] input = line.split("" ""); int low = Integer.parseInt(input[0]); int high = Integer.parseInt(input[1]); for(int i=low; i=low && j>i){ num++; } } } bw.append(""Case #"" + ++count + "": "" + num); bw.newLine(); } br.close(); bw.close(); } public static int[] getRecycledNumbers(int num){ String str = Integer.toString(num); HashSet set = new HashSet(); for(int i=0; i itr = set.iterator(); int i=0; while(itr.hasNext()){ ans[i++] = itr.next(); } return ans; } } " B12571,"import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(new FileReader(""C-small-attempt0.in"")); PrintWriter pw = new PrintWriter(new FileWriter(""outputC1.txt"")); int caseCount = sc.nextInt(); sc.nextLine(); int a, b, count, c, k, l; for (int caseNum = 0; caseNum < caseCount; caseNum++) { a = sc.nextInt(); b = sc.nextInt(); count = 0; for (int i = a; i <= b; i++) { k = 10; l = (int) Math.pow(10, (int) Math.log10(i)); HashSet pairs = new HashSet(); while (k < i) { c = (i % k)*l + i/k; if (i < c && c <= b) { pairs.add(c); } k *= 10; l /= 10; } count += pairs.size(); } pw.write(""Case #"" + (caseNum + 1) + "": ""); pw.write(count + ""\n""); } pw.flush(); pw.close(); sc.close(); } } " B11814,"/** * Google CodeJam 2012 * Qualification round - Problem C * Recycled Numbers * * Solved by Üllar Soon */ package eu.positivew.codejam.recycled; import java.io.File; import java.util.ArrayList; import eu.positivew.codejam.framework.CodeJamIO; /** * Recycled Numbers main class. * * @author Üllar Soon */ public class RecycledNumbersMain { /** * Main controller for RecycledNumbers. * * @param args Command line arguments */ public static void main(String[] args) { // Parse command line arguments String inUrl = ""input.txt""; String outUrl = ""output.txt""; if(args.length >= 1) inUrl = args[0]; if(args.length >= 2) outUrl = args[1]; File inFile = new File(inUrl); File outFile = new File(outUrl); CodeJamIO cio = new CodeJamIO(); cio.inputOpen(inFile); cio.outputOpen(outFile); if(cio.getTestCases() > 0) { RecycledNumbersCase inCase; int i = 0; while(i < cio.getTestCases() && (inCase = (RecycledNumbersCase)cio.inputReadCase(new RecycledNumbersParser())) != null) { cio.outputWriteCase("""" + countRecycledNumbers(inCase.getA(), inCase.getB())); i++; } } cio.inputClose(); cio.outputClose(); } /** * Counts the distinct occurring pairs of recycled numbers between A and B (inclusive). * * @param A left limiter * @param B right limiter * @return number of distinct recycled numbers between A and B */ private static int countRecycledNumbers(int A, int B) { int count = 0; ArrayList foundPairs = new ArrayList(); for(int i = A; i <= B; i++) { String nStr = """" + i; for(int j = 1; j < nStr.length(); j++) { String mStr = nStr.substring(j) + nStr.substring(0, j); if(mStr.charAt(0) == '0') continue; try { int n = Integer.parseInt(nStr); int m = Integer.parseInt(mStr); if(A <= n && n < m && m <= B) { if(!foundPairs.contains(new IntPair(n, m))) { foundPairs.add(new IntPair(n, m)); count++; } } } catch(NumberFormatException ex) { System.err.println(""Number conversion error!""); } } } return count; } } " B12578,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Round0; import custom.Output; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** * * @author shyam */ public class C { static String inputfile=""./src/Small.in""; static String outputfile=""./src/Small.out""; //static String inputfile=""./src/Large.in""; //static String outputfile=""./src/Large.out""; public static void main(String args[])throws Exception{ BufferedReader br=new BufferedReader(new FileReader(inputfile)); PrintWriter pw = new PrintWriter(new FileWriter(outputfile)); String row=""""; StringTokenizer st; // first line to count no of records row=br.readLine(); int T=Output.ipri(row); // initial variables for(int count=1;count<=T;count++){ row=br.readLine(); // read each record // tokenize: default space st=new StringTokenizer(row); // variables int A= Output.ipri((st.nextToken().toString())); int B= Output.ipri((st.nextToken().toString())); int c_pairs = 0; List pairs = new ArrayList(); // operations for(int i=A;i<=B;i++){ String dig = """"+i; if(dig.length() == 1){ break; } int pos=0; for(int j=0;j MultiMap map = MultiMapKeyToSet.make(); map.put(""a"", ""x""); map.put(""a"", ""x""); map.put(""a"", ""y""); map.put(""b"", ""z""); System.out.println(Join.joinRecursive(map.entrySet(), "", "", ""["", ""]"")); * * @author luke */ public class MultiMapKeyToSet { HashMap> map = new HashMap>(); public static MultiMapKeyToSet make() { return new MultiMapKeyToSet(); } /** Return true if this multimap did not already contain the specified value at the specified key. */ public boolean put(S key, T value) { HashSet set = map.get(key); if (set == null) { set = new HashSet(); map.put(key, set); } return set.add(value); } public void putAll(S key, Iterable values) { boolean putSomething = false; for (T val : values) { put(key, val); putSomething = true; } if (!putSomething && !map.containsKey(key)) // If putting an empty collection, need to create an empty set at the key map.put(key, new HashSet()); } public void putAll(S key, T[] values) { if (values.length == 0 && !map.containsKey(key)) // If putting an empty collection, need to create an empty set at the key map.put(key, new HashSet()); else for (T val : values) put(key, val); } public HashSet get(S key) { return map.get(key); } /** * Get the single value mapped to by the key, or null if no value mapped to for this key. * * @throws IllegalRuntimeException * if there is more than one value mapped to by this key. */ public T getSingleVal(S key) { HashSet set = map.get(key); return CollectionUtils.getSingleVal(set); } public boolean containsKey(S key) { return map.containsKey(key); } public int sizeKeys() { return map.size(); } public Set>> entrySet() { return map.entrySet(); } /** * Return the union of all values in all mapped sets (i.e. the union of all values mapped to by some key in this MultiMap). * NOTE: creates a new HashSet with the current union on every invocation, so if you modify the contents of the returned * HashSet, it won't affect the map. */ public HashSet valuesUnion() { return CollectionUtils.union(map.values()); } public HashMap> getRawMap() { return map; } public Set keySet() { return map.keySet(); } /** Invert the mapping */ public MultiMapKeyToSet invert() { MultiMapKeyToSet inv = new MultiMapKeyToSet(); for (Entry> ent : map.entrySet()) { S key = ent.getKey(); for (T val : ent.getValue()) inv.put(val, key); } return inv; } public ArrayList>> toList() { ArrayList>> result = new ArrayList>>(); for (Entry> ent : map.entrySet()) result.add(Pair.make(ent.getKey(), ent.getValue())); return result; } /** Write out to a TSV file */ public void writeOutToFile(String tsvFile) throws IOException { PrintWriter writer = new PrintWriter(tsvFile); for (Entry> ent : map.entrySet()) { S key = ent.getKey(); StringBuilder buf = new StringBuilder(); buf.append(key); for (T val : ent.getValue()) buf.append(""\t"" + val); writer.println(buf.toString()); } writer.close(); } /** Read in a String->String map from a TSV file */ public static MultiMapKeyToSet readFromFile(String tsvFile) throws IOException { MultiMapKeyToSet map = new MultiMapKeyToSet(); for (String line : new FileLineIterator(tsvFile)) { String[] parts = Split.split(line, ""\t""); String key = parts[0]; for (int i = 1; i < parts.length; i++) map.put(key, parts[i]); } return map; } } " B13138,"import java.util.HashSet; import java.util.Scanner; public class c { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub new c().go(); } private void go() { Scanner in=new Scanner(System.in); int numc=in.nextInt(); for(int cnum=1;cnum<=numc;cnum++){ int a=in.nextInt(),b=in.nextInt(),ans=0; for(int n=a;n<=b;n++){ String ns=""""+n; HashSet temp=new HashSet(); for(int i=0;in&&m<=b&&!temp.contains(m)){ ans++; temp.add(m); } } } System.out.printf(""Case #%d: %d\n"", cnum,ans); } } } " B10940,"package com.khajochi.codejam; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { try { RecycledNumbers sp = new RecycledNumbers(); FileInputStream fstream = new FileInputStream(""/Users/msmart/Documents/My Work/Workspace/M/resource/2012round1/1CSmall.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String str = br.readLine(); int count = 1; while ((str = br.readLine()) != null) { // System.out.println(str); int start = Integer.parseInt(str.split("" "")[0]); int end = Integer.parseInt(str.split("" "")[1]); int possible = findPossible(start,end); System.out.println(""Case #"" + count++ + "": "" + possible); } in.close(); } catch (Exception e) { System.err.println(e); } } private static int findPossible(int start, int end) { int count = 0; HashMap exclude = new HashMap (); for (int i = start; i <= end; i++) { String num = String.valueOf(i); if ( num.length() > 1 ) { for (int j = 1; j < num.length(); j++) { int newNum = Integer.valueOf(num.substring(j,num.length()) + num.substring(0,j)).intValue(); // System.out.println(newNum); if ( newNum >= start && newNum <= end && newNum != Integer.parseInt(num) ) { boolean skip = false; if ( exclude.get(num) != null && exclude.get(num).equals(String.valueOf(newNum)) ) skip = true; if ( exclude.get(newNum) != null && exclude.get(String.valueOf(newNum)).equals(num) ) skip = true; if ( skip == false ) { // System.out.println(""Yes : "" + num + "" > "" + newNum); exclude.put(num, String.valueOf(newNum)); count++; continue; } } } } } // System.out.println(count/2); return count/2; } } " B11870," import java.io.*; import java.util.*; class ProblemC { public static void main(String[] args) throws IOException { FileReader fr = new FileReader(args[0]); BufferedReader br = new BufferedReader(fr); String[] splittArray; int[] points; int A,B,res; int T = Integer.parseInt(br.readLine()); //System.out.println(T); String dummy; String result=""""; for(int i=1;i<=T;i++) { dummy=br.readLine(); splittArray=dummy.split("" ""); A=Integer.parseInt(splittArray[0]); B=Integer.parseInt(splittArray[1]); res=0; for(int j=A;j result=new LinkedList(); String dummy; int dummy2; for(int i=1;i<=a.length()-1;i++) { dummy=a.substring(i,a.length())+a.substring(0,i); dummy2=Integer.parseInt(dummy); if(dummy2>b && dummy2<=c && !result.contains(dummy2)) result.add(dummy2); } return result.size(); } } " B11320,"import java.util.Scanner; /* */ public class C { public static void main(String[] args) { String stA, stB; int a, b, bb, success = 0; Scanner in = new Scanner(System.in); int t = in.nextInt(); for (int i = 1; i <= t; i++) { a = in.nextInt(); b = in.nextInt(); success = 0; for (int j = a; j <= b; j++) { stA = Integer.toString(j); for (int k = stA.length() - 1; k > 0; k--) { stB = stA.substring(k); stB = stB + stA.substring(0, k); bb = Integer.valueOf(stB); if (j < bb && bb <= b) { success++; } } } System.out.format(""Case #%d: %d\n"", i, success); } } }" B11640,"package codejam; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class Recycled { public static void main(String[] args) throws IOException { Scanner scan = new Scanner(new File(""Recycled.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""Recycled.out""))); int N = Integer.valueOf(scan.nextLine()); int id =1; while(scan.hasNextLine()) { String letters = scan.nextLine(); String[] letter = letters.split("" ""); int A = Integer.valueOf(letter[0]); int B = Integer.valueOf(letter[1]); int result = RecycledAlgorithm(A, B); out.println(""Case #"" + id + "": "" + result); id++; } out.close(); } public static int RecycledAlgorithm(int A,int B) { int num = 0; for(int n=A; n<=B ;n++) { for(int m=n+1;m<=B;m++) { String allLetters = String.valueOf(n) + String.valueOf(n); String findLetters = String.valueOf(m); if(allLetters.contains(findLetters)) num ++; } } return num; } } " B13044,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.HashSet; import java.util.StringTokenizer; public class MainC { private static boolean esValido(Integer n,Integer A,Integer B,boolean comp) { int i=0; boolean valido=false; if (!comp || (n>=A && n9) { while((i+1) conj) { String aux=rotar(i.toString()); Integer num=Integer.parseInt(aux); if (esValido(num,A,B,true)) { if (!i.equals(num)) { conj.add(new Par(i,num)); } //System.out.println(""Se encuentra el par "" + i + "", ""+num + "" ya que esValido ""+num+"" en el intervalo ""+ A+ ""-""+B); } for (int j=0;j conj=new HashSet(); for (int i=A;i 2) D = B - (int) Math.pow(10, Integer.toString(D).length() - 2); else D = B; int number = 0; //System.out.println(D); for(int i=A; i list = new ArrayList(); for(int c=1;c= A && t <= B && t > i && !list.contains(t) ) { //out.print(i); //out.print("",""); //out.println(t); list.add(t); number++; } } } out.println(Integer.toString(number)); //System.out.println(Integer.toString(number)); } in.close(); out.close(); } catch (IOException e) { System.err.println(""Caught IOException: "" + e.getMessage()); } } }" B10603,"package codejam2012.qualification.c; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; import com.google.common.base.Charsets; import com.google.common.io.Resources; public final class GoC { public static void main(String[] args) throws Exception { String name = args[0]; String nameIn = name + "".in""; String nameOut = name + "".out""; String dataIn = Resources.toString(Resources.getResource(nameIn), Charsets.ISO_8859_1); try (PrintStream out = new PrintStream(nameOut)) { run(new Scanner(dataIn), out); } } public static void run(Scanner in, PrintStream out) { new GoC(in, out).run(); } private final Scanner in; private final PrintStream out; public GoC(Scanner in, PrintStream out) { this.in = in; this.out = out; } public void run() { int T = in.nextInt(); for (int t = 1; t <= T; ++t) { int A = in.nextInt(); int B = in.nextInt(); out.println(String.format(""Case #%d: %d"", t, run(A, B))); } } private static class Pair { final int a; final int b; public Pair(int a, int b) { this.a = a; this.b = b; } public static Pair of(int a, int b) { return new Pair(a, b); } @Override public String toString() { return ""("" + a + "", "" + b + "")""; } public boolean valid(int A, int B) { String n = Integer.toString(a); String m = Integer.toString(b); return (A <= a) && (a < b) && (b <= B) && (n.length() == m.length()) && (n.charAt(0) != '0') && (m.charAt(0) != '0'); } } private static int run(int A, int B) { System.out.println(""A: "" + A + "" B: "" + B); HashSet done = new HashSet<>(); for (int i = A; i <= B; ++i) { int[] digits = digits(i); int first = digits[0]; for (int j = digits.length - 1; j > 0; --j) { int curr = digits[j]; if (curr >= first) { Pair pair = Pair.of(i, undigits(recycle(digits, j))); if (pair.valid(A, B)) { done.add(pair); System.out.println(pair); } } } } System.out.println(done.size()); System.out.println(); return done.size(); } private static int[] digits(int a) { char[] chars = Integer.toString(a).toCharArray(); int[] result = new int[chars.length]; for (int i = 0; i < result.length; ++i) { result[i] = Character.digit(chars[i], 10); } return result; } private static int undigits(int[] digits) { int result = 0; for (int i : digits) { result *= 10; result += i; } return result; } private static int[] recycle(int[] digits, int from) { int[] result = new int[digits.length]; int index = 0; for (int i = from; i < digits.length; ++i) { result[index++] = digits[i]; } for (int i = 0; i < from; ++i) { result[index++] = digits[i]; } return result; } } " B11391,"import java.util.*; class Recycle{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int testcase, A, B; testcase = sc.nextInt(); for(int i=1;i<=testcase;i++){ A = sc.nextInt(); B = sc.nextInt(); System.out.println(""Case #""+i+"": ""+countpair(A,B)); } } public static int countpair(int A, int B){ int numdigit, temp = A, temp2, counter; int[] remember; counter = 0; while(A<=B){ remember = new int[7]; numdigit = (int)Math.log10((double)A) + 1; temp = A; for(int i=0;i A && checker<=B){ for(i=0;i= a) { cnt++; hasused[ans] = true; //System.out.printf(""%d,%d\n"",i,ans); } } } ret += cnt * (cnt + 1) /2; } System.out.println(ret); } } } " B11753,"import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class QrC { private CodeJamTextInputReader input = null; private CodeJamTextOutputWriter output = null; public static void main(String args[]) { // CodeJamUtils.initLineEndings(); try { QrC qrA = new QrC(); qrA.run(new File(args[0]), new File(args[1])); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidInputException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public QrC() { } public void run(File outputFile, File inputFile) throws InvalidInputException, IOException { try { input = new CodeJamTextInputReader(inputFile); output = new CodeJamTextOutputWriter(outputFile); actualRun(); } finally { if (input != null) { input.close(); } if (output != null) { output.close(); } } } private void actualRun() throws IOException { while (input.hasNextTestCase()) { String in = input.readNextLine(); final int textCaseNum = input.getLastReadTestCaseNumber(); output.outputTestCase(textCaseNum, singleTestCase(in)); } } private String singleTestCase(String in) { CodeJamLineParser parser = new CodeJamLineParser(in); final int lowerBound = parser.readNextInt(); final int upperBound = parser.readNextInt(); int numOfRecycled = 0; Set alreadyHit = new HashSet(); RecycledPair comparePair = new RecycledPair(); for (int i = lowerBound; i <= upperBound; ++i) { int leftMask = getHighestMask(i); int rightMask = 10; while (leftMask >= 10) { int recycled = buildRecycled(i, leftMask, rightMask); comparePair.set(i, recycled); if (recycled != i && recycled >= lowerBound && recycled <= upperBound && !alreadyHit.contains(comparePair)) { alreadyHit.add(new RecycledPair(comparePair)); ++numOfRecycled; } rightMask = rightMask * 10; leftMask = leftMask / 10; } } return Integer.toString(numOfRecycled); } int buildRecycled(int in, int leftMask, int rightMask) { int rightPart = in % rightMask; int leftPart = in / rightMask; return (rightPart * leftMask) + leftPart; } int getHighestMask(int in) { int mask = 10; while (in / mask != 0) { mask = mask * 10; } return mask / 10; } int getNumOfDigits(int in) { int numOfDigits = 1; int mask = 10; while (in / mask != 0) { ++numOfDigits; mask = mask * 10; } return numOfDigits; } } " B11032,"package codejam; import java.io.*; import java.util.HashSet; public class Numb { public static void main(String[] args)throws IOException{ HashSet hs; BufferedReader cin=new BufferedReader(new FileReader(""i3.in"")); PrintWriter cout=new PrintWriter(new BufferedWriter(new FileWriter(""out3.txt""))); String[] in; int x,y,j,num,count; int t=Integer.parseInt(cin.readLine()); for(int i=0;i(); String s=Integer.toString(j); int l=s.length(); for(int k=l-1;k>0;k--){ if(s.charAt(k)=='0') continue; num=Integer.parseInt(s.substring(k)+s.substring(0,k)); if(num>j && num<=y && !hs.contains(num)){ hs.add(num); count++; } } } cout.println(""Case #""+(i+1)+"": ""+count); } cout.flush(); } } " B12747,"import java.util.*; import java.util.regex.*; import java.text.*; import java.math.*; import java.awt.geom.*; import java.io.*; public class cx{ public static void main(String[] args){ try{ File output; FileWriter outputwriter; BufferedWriter out; String filename = ""bx.out""; output = new File(filename); outputwriter = new FileWriter(output); out = new BufferedWriter(outputwriter); //System.out.println(""siap""); //out.write(""ardhianvv\nll""); BufferedReader f = new BufferedReader(new FileReader(""a.in"")); StringTokenizer st = new StringTokenizer(f.readLine()); int angka = Integer.parseInt(st.nextToken()); for(int a=0;ajkl = new HashSet(); for(int b=aa;b<=bb;b++){ String as = """"+b; //if(a==3) //System.out.println(""- ""+as); int len = as.length(); for(int c=0;cb && gg<=bb){ //if(a==3) //System.out.println((hasil+1)+ "" ""+b+"" ""+gg); jkl.add(b+"" ""+gg); //hasil++; } } } //System.out.println(jkl.size()); if(a!=angka-1) out.write(""Case #""+(a+1)+"": ""+jkl.size()+""\n""); else out.write(""Case #""+(a+1)+"": ""+jkl.size()); } out.close(); } catch(Exception cc){ System.out.println(cc.toString()); } } }" B12180,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package qualificationRound2012; import java.io.File; import java.io.PrintWriter; import java.util.Scanner; /** * * @author AHMED */ public class RecycledNumbers { public static void main(String[] args)throws Exception{ RecycledNumbers r = new RecycledNumbers(); //System.out.println(isRecycledPair(12345 , 51234)); //System.out.println(""0123456"".substring(2,6)); //414144414 //441414441 } public RecycledNumbers() throws Exception{ Scanner sc = new Scanner(new File(""C-small-attempt0.in"")); PrintWriter pin = new PrintWriter(new File(""C-small-attempt0.out"")); int T = Integer.parseInt(sc.nextLine()); int A,B; int counter = 0; int x = 0; for(int testCaseIndex = 1 ; testCaseIndex <=T ; testCaseIndex++){ A = sc.nextInt(); B = sc.nextInt(); //System.out.println(A+"" ""+B); for(int n = A ; n <= B ;n++){ for(int m = (n+1) ; m<=B ;m++){ //pin.print(n+"" ""+m); if(isRecycledPair(n,m))counter++; } } pin.print(""Case #""+testCaseIndex+"": ""+counter); if(testCaseIndex!=T)pin.print(""\n""); counter = 0; } pin.close(); sc.close(); } private static boolean isRecycledPair(int n, int m){ if(n<10 && m<10)return false;//all digits < 10 cannto be recycled. String nString = Integer.toString(n); String mString = Integer.toString(m); int length = nString.length(); int starting_mIndex = 0; String temp; for(int index = 0 ; index < length ; index++){ for(starting_mIndex = 0 ; starting_mIndex < length ; starting_mIndex++){ temp = mString.substring(starting_mIndex); temp+=mString.substring(0, starting_mIndex); if(temp.equals(nString))return true; } } return false; /* String nString = Integer.toString(n); String mString = Integer.toString(m); int length = mString.length(); int nStringIndex; int mStrinIndex = mString.indexOf(nString.charAt(0)+"""");//starting index //System.out.println(mStrinIndex); if(mStrinIndex == -1)return false; for(nStringIndex = 0 ; nStringIndex < length ; nStringIndex++){ if(nString.charAt(nStringIndex)!=mString.charAt(mStrinIndex))return false; mStrinIndex = (mStrinIndex+1)%length; } return true;*/ } } " B12893,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.HashSet; import java.util.Set; public class QRC { // Basics for all problems private static final String LARGE = ""large""; private static final String SMALL = ""small""; private static final String IN = "".in""; private static final String OUT = "".out""; private static String SET; // Problem specific Globals private static Set mPairs; public static void main(String[] args) throws Exception { SET = SMALL; // Which set id being evaluated readInputFile(SET+IN); } private static void readInputFile(String in) throws Exception { BufferedReader br = new BufferedReader(new FileReader(new File(SET+IN))); String line = null; int caseCount = 1; br.readLine(); while ( (line = br.readLine()) != null ) { String[] input = line.split("" ""); final int A = Integer.parseInt(input[0]); final int B = Integer.parseInt(input[1]); mPairs = new HashSet(); for (int n = A; n < B; n++ ) { String rotation = String.valueOf(n); int digitCount = rotation.length(); for ( int i = 0; i < digitCount; i++ ) { rotation = rotateN(rotation); int m = Integer.parseInt(rotation); if ( m > n && m <= B ) { mPairs.add(new Pair(n,m)); //System.out.println("" --> (""+n+"", ""+m+"") @ ""+mPairs.size()); } } } writeOutputLine(String.format(""Case #%d: %d"", caseCount, mPairs.size())); caseCount++; } br.close(); } private static String rotateN(String nAsString) { String bulk = nAsString.substring(0,nAsString.length()-1); char jumper = nAsString.charAt(nAsString.length()-1); return jumper+bulk; } private static void writeOutputLine(String line) throws Exception { BufferedWriter bw = new BufferedWriter(new FileWriter(new File(SET+OUT),true)); bw.append(line); bw.newLine(); bw.flush(); bw.close(); } } " B12483,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; public class CodeJamSolverRecycle { public static HashMap> valueToIndexMap=new HashMap>(); public static void main(String[] args) { int numTestCases=0; int numLinePerTestCase=1; int currentCase=0; String inputFileName=""C-small-attempt0.in""; //String inputFileName=""input.in""; BufferedReader br=null; StringBuilder solutionString=new StringBuilder(); int lineCount=0; try{ String line; br=new BufferedReader(new FileReader(inputFileName)); while((line=br.readLine())!=null){ lineCount++; if(lineCount==1){ numTestCases=Integer.parseInt(line); continue; } String[] splittedLine=line.split(""\\s+""); long a=Long.parseLong(splittedLine[0]); long b=Long.parseLong(splittedLine[1]); String solution=getSolution(a,b); System.out.println(solution); currentCase++; solutionString.append(""Case #""+currentCase+"": ""+solution+""\n""); } br.close(); writeTextToFile(inputFileName.replace("".in"", "".out""), solutionString.toString().trim()); } catch(IOException ex){ System.out.println(""Unable to read from file!""); ex.printStackTrace(); } } private static String getSolution(long a, long b) { HashSet resultSet=new HashSet(); for(long n=a;n<=b;n++){ String nString=Long.toString(n); for(int i=1;i>(); for(int i=0;i indicesList=new ArrayList(); if(valueToIndexMap.containsKey(intArray[i])){ indicesList=valueToIndexMap.get(intArray[i]); } indicesList.add(i); valueToIndexMap.put(intArray[i], indicesList); } return intArray; } public static void writeTextToFile(String fileName, String textToWrite){ try{ BufferedWriter bw= new BufferedWriter( new FileWriter(fileName)); bw.write(textToWrite); bw.close(); } catch(IOException ex){ System.out.println(""Unable to write to file!""); ex.printStackTrace(); } } } " B11209,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; public class C { public static void main(String[] args) { try { Scanner in = new Scanner(new File(""C.in"")); BufferedWriter writer = new BufferedWriter(new FileWriter(new File(""C.out""))); int T = in.nextInt(); in.nextLine(); for (int i=0; i set = new HashSet(); for (int j=1; j X && C <= B && !(set.contains(C))) { set.add(C); res++; //System.out.println(""X=""+X + "", C=""+C); } } } writer.append(""Case #"" + (i+1) + "": "" + res + ""\n""); } writer.close(); } catch (IOException e) { e.printStackTrace(); } } public static int moveLast(int X, int digits) { int last = 0; int p = 1; int p2 = 1; for (int i=0; i 0) { X /= 10; k++; } return k; } } " B12314,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.io.*; /** * * @author virginia * */ public class RecycledNumbers { public static int countn(int v) { int count=0; while (v> 0 && count<10 ) { int r = v % 10; count++; v = v / 10; } return count; } public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new FileReader(""C-small-attempt1.in"")); BufferedWriter output=new BufferedWriter(new FileWriter(""Output.txt"")); PrintWriter pw = new PrintWriter(output); int n = Integer.parseInt(br.readLine()); int[][] result = new int[n][2]; String line; int a= 0; while ((line = br.readLine()) != null) { String[] tokens = line.split(""\\s""); for (int j = 0; j <2; j++) { result[a][j] = Integer.parseInt(tokens[j]); } a++; } int index = 0; for(int i =0; i < n; i++) { int found=0; index++; int A=result[i][0]; int B=result[i][1]; for(int j=A;j<=B;j++) { int cnt=0; int num=j; int rev=0; while (num> 0 && cnt<10 ) { int r = num % 10; cnt++; num = num / 10; } int num1=j; int num2=j; int p=cnt-1; int r=0; do { cnt--; int s=(num1)%10; num2=num2/10; num1=(int)(s*Math.pow(10,(p)))+(num2); num2=num1; if(RecycledNumbers.countn(j)==RecycledNumbers.countn(num1)) { if((A<=j)&&(j0); } pw.print(""Case #"" + index + "": ""); pw.println(found); System.out.print(""Case #"" + index + "": ""); System.out.println(found); } output.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } " B11815,"/** * Google CodeJam 2012 * Qualification round - Problem C * Recycled Numbers * * Solved by Üllar Soon */ package eu.positivew.codejam.recycled; import eu.positivew.codejam.framework.CodeJamInputCase; /** * Recycled Numbers test case class. * * @author Üllar Soon */ public class RecycledNumbersCase implements CodeJamInputCase { private Integer[] value = null; public RecycledNumbersCase(Integer[] value) { this.value = value; } public Integer[] getValue() { return value; } public void setValue(Integer[] value) { this.value = value; } public int getA() { if(value.length >= 2) return value[0]; else return -1; } public int getB() { if(value.length >= 2) return value[1]; else return -1; } @Override public String getType() { return ""Integer[]""; } } " B12758,"import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; public class Problem3 { /** * @param args */ public static void main(String[] args) { File file = new File(""small-input.in""); File outputFile = new File(""output.txt""); try { FileWriter writer = new FileWriter(outputFile); BufferedWriter out = new BufferedWriter(writer); Scanner scanner = new Scanner(file); int count = 0; while (scanner.hasNextLine()) { count = count + 1; String line = scanner.nextLine(); if (count >= 2) { int finalCount = 0; System.out.println(line); String[] stringArr = line.split("" ""); int num1 = Integer.parseInt(stringArr[0]); int num2 = Integer.parseInt(stringArr[1]); int tempnum1 = num1; //System.out.println(""number1 is "" + num1); //System.out.println(""number2 is "" + num2); for (; tempnum1 <= num2; tempnum1++) { String str = String.valueOf(tempnum1); ArrayList usedList = new ArrayList(); for (int j = 1; j < str.length(); j++) { String str1 = str.substring(str.length() - j, str .length()); String str2 = str.substring(0, str.length() - j); String newStr = str1 + str2; int newIntVal = Integer.parseInt(newStr); if ((num1 <= newIntVal) && ((num2 >= newIntVal))) { if(newIntVal>tempnum1){ if(!usedList.contains(newIntVal)){ System.out.println(""tempNum1 is ""+tempnum1); System.out.println(""newIntVal== ""+newIntVal); usedList.add(newIntVal); finalCount = finalCount+1; System.out.println(""-------------------------------------------------------------""); //System.out.println(""finalCount is ""+finalCount); } } } } } out.write(""Case #"" + (count - 1) + "": ""+finalCount); out.newLine(); } } out.close(); writer.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B11407,"package codejam; import java.util.ArrayList; public class RecycledNumbers { public static void recycled(String in,String out){ InOutTool iot = new InOutTool(in,out); ArrayList js = new ArrayList(); for(int i=1;i1){ ArrayList list = new ArrayList(); for(int k=ns.length()-1;k>0;k--){ String temp = ns.substring(k) + ns.substring(0, k);//move if(!temp.startsWith(""0"")){ int t = Integer.parseInt(temp); if(t=f&&(String.valueOf(t).length()==ns.length())&&(!list.contains(String.valueOf(t)))){ list.add(String.valueOf(t)); count ++; } } } } n++; } js.add(""Case #"" + i + "": "" + count); } iot.clear();iot.addAll(js); System.out.println(iot.outText()); } public static void main(String...args){ RecycledNumbers.recycled(""C-small-attempt0.in"", ""C-small-attempt0.out""); } } " B13054,"import java.io.*; import java.util.Scanner; import java.util.ArrayList; public class RecycledNo { private Scanner input = null; private PrintWriter output = null; private int numOfCases; int getNextCount=0; ArrayList al = new ArrayList(); public static void main(String[] args) { RecycledNo myRecycle = new RecycledNo(); // for (int i=1;i<=12;i++) // { // System.out.println(myRecycle.getNext(1,10)); // } //System.out.println(myRecycle.recycle(""123456789"",5)); try { myRecycle.solve(); } catch(IOException ioe) { System.out.println(""oops""); System.exit(0); } } public int getNext(int a, int b) { getNextCount=getNextCount+1; if(a+getNextCount-1<=b) return a+getNextCount-1; else return -1; } public int recycle(String numString, int loc) //recycled part begins with loc, including. Use 1,2,3 as index, excluding 0 { String newNumString = numString.substring(loc-1)+numString.substring(0,loc-1); try { return Integer.parseInt(newNumString); } catch(NumberFormatException NFE) { System.out.println(""wrong format""); } return -1; } public void solve() throws IOException { input = new Scanner(new File(""C-small-attempt0.in"")); output = new PrintWriter(""output.txt""); numOfCases = input.nextInt(); for (int i = 1; i <= numOfCases; i++) { int min=input.nextInt(); int max=input.nextInt(); int count = 0; for(int j = 1; j<=max-min+1;j++) { int nextInt=getNext(min,max); String s = """"+nextInt; for (int k = 2; k<=s.length();k++) //loop for a specific getNext() { if (s.charAt(k-1)=='0') continue; if((recycle(s,k)<=max)&&(recycle(s,k)>=min)&&(recycle(s,k)>nextInt)&&(!al.contains(""""+recycle(s,k)))) { count = count + 1; //System.out.println(s+"" ""+recycle(s,k)); } al.add(""""+recycle(s,k)); } al.clear(); } output.println(""Case #""+i+"": ""+count); getNextCount=0; } output.close(); input.close(); } }" B10026,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; public class RecycledNumbers { static boolean isRecycled(int a, int b, int length) { String aString = String.valueOf(a); String bString = String.valueOf(b); for (int i = 0; i < length - 1; i++) { // System.out.println(aString.substring(length - 1 - i) + aString.substring(0, length - 1 - i)); if (bString.equals(aString.substring(length - 1 - i) + aString.substring(0, length - 1 - i))) { return true; } } return false; } public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int testCases = Integer.parseInt(br.readLine()); HashMap lengths = new HashMap(); for (int i = 1; i <= 2000000; i++) { lengths.put(i, String.valueOf(i).length()); } for (int t = 1; t <= testCases; t++) { String[] ab = br.readLine().split("" ""); int a = Integer.parseInt(ab[0]); int b = Integer.parseInt(ab[1]); int aLog = ab[0].length() - 1; int bLog = ab[1].length() - 1; int count = 0; for (int i = a; i <= b; i++) { int iLength = lengths.get(i); for (int j = i + 1; j <= b; j++) { if (iLength != lengths.get(j)) { break; } if (isRecycled(i, j, iLength)) { count++; } } } System.out.println(""Case #"" + t + "": "" + count); } } } " B13261,"import java.io.IOException; class Round1C { private int Case; public Round1C(int Case, int A, int B) { this.Case = Case; int result = this.Computer(A, B); this.outPut(result); } /* * N±qA¨ìB * §â¨C­Ó¼Æ¦rN§@±ÛÂà«áªºµ²ªG¡A * §PÂ_¡A¬O§_¤j©óN¥B¤p©óµ¥©óB * ¬Oresult++ * * */ private int Computer(int A, int B){ int result = 0; if(this.degree(A) == this.degree(B)){ for(int N = A; N <= B; N++){ for(int i = 1; i <= degree(N); i++){ int r = Rotation(N, i); // System.out.println(""\t"" + r); if(N < r && r <= B){ result++; } } } } return result; } private int Rotation(int temp, int order){ int result = 0; String rotation = Integer.valueOf(temp).toString(); rotation = rotation.substring(order) + rotation.substring(0, order); result = Integer.parseInt(rotation); return result; } private int degree(int temp){ for(int i = 1; ;i++){ temp /= 10; if(temp == 0){ return i; } } } private void outPut(int result) { try { System.out.println(""Case #"" + Case + "": "" + result); Main.bufWriter.write(""Case #"" + Case + "": "" + result); Main.bufWriter.newLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B11422,"package fun.codeslam.recycling; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; public class Main { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); Integer testCaseCount = Integer.parseInt(reader.readLine()); for (Integer testCaseNumber = 1; testCaseNumber <= testCaseCount; testCaseNumber++) { String[] elements = reader.readLine().split("" ""); System.out.append(""Case #"" + testCaseNumber + "": ""); System.out.append(numberOfReyclingsInRange(Integer.parseInt(elements[0]), Integer.parseInt(elements[1])) .toString()); System.out.append('\n'); } } private static Integer numberOfReyclingsInRange(Integer min, Integer max) { Integer numberOfReyclings = 0; for (Integer number = min; number <= max; number++) { numberOfReyclings += numberOfReyclings(number, max); } return numberOfReyclings; } private static Integer numberOfReyclings(Integer number, Integer max) { Map isset = new HashMap(); Integer numberOfReyclings = 0; Integer length = number.toString().length(); for (Integer beginIndex = 1; beginIndex < length; beginIndex++) { String endPart = number.toString().substring(beginIndex); String frontPart = number.toString().substring(0, beginIndex); Integer newNumber = Integer.parseInt(endPart + frontPart); if (newNumber.toString().length() == number.toString().length() && number < newNumber && newNumber <= max && isset.get(newNumber) == null) { isset.put(newNumber, true); numberOfReyclings++; } } return numberOfReyclings; } } " B10370,"import java.io.*; import java.util.*; class Recycle { public static void main(String [] args) throws Exception{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(in.readLine()); for(int i = 0; i < T; i++){ int ans = 0; StringTokenizer st = new StringTokenizer(in.readLine()); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); for(int j = A; j <= B; j++){ String s = """" + j; HashMap hm = new HashMap(); for(int k = 0; k < s.length(); k++){ String rot = s.substring(k,s.length()) + s.substring(0,k); hm.put(Integer.parseInt(rot),0); } for(int k : hm.keySet()){ if(j mm = new LinkedList(); //mm.add(new LinkedList()); //int[][] mm; //for(int ii=0;ii=10){ for(int j=A;j oks = new ArrayList(); for(int k=0;kn && m<=B) { boolean isNewOne = true; for(int kkk=0;kkk set = new HashSet(); String tokens[] = bf.readLine().split("" ""); int A = Integer.parseInt(tokens[0]), B = Integer.parseInt(tokens[1]), ans = 0; for (int I = A; I < B; I++) { String i = I + """"; for (int j = 1; j < i.length(); j++) { String re = i.substring(j) + i.substring(0, j); if (I < Integer.parseInt(re) && Integer.parseInt(re) <= B) { if (!set.contains(i + ""-"" + re)) ans++; set.add(i + ""-"" + re); } } } bw.write(String.format(""Case #%d: %d\n"", c + 1, ans)); } bw.close(); } } " B10322,"package sebastianco; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { public static void main(String[] args) throws Exception { BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new FileReader(new File(args[0]))); writer = new BufferedWriter(new FileWriter(new File(args[1]))); final int nrOfTestCases = Integer.valueOf(reader.readLine()); String lineSepartor = """"; for (int i = 1; i <= nrOfTestCases; i++) { writer.write(lineSepartor); writer.write(String.format(""Case #%d: %d"", i, new TestCase(reader.readLine()).computePairs())); lineSepartor = ""\n""; } } finally { if (writer != null) { writer.flush(); writer.close(); } reader.close(); } } public static class TestCase { private int a; private int b; public TestCase(String caseLine) { String[] tokens = caseLine.split("" ""); a = Integer.parseInt(tokens[0]); b = Integer.parseInt(tokens[1]); } public int computePairs() { Set distinctPairs = new HashSet(); final String strB = String.valueOf(b); final int maxRotations = strB.length() - 1; int recycledPairs = 0; for (int i = a; i < b; i++) { String strI = String.valueOf(i); // System.out.println(""=="" + strI); StringBuilder number = new StringBuilder(strI); for (int j = 1; j <= maxRotations; j++) { rotate(number); String strNumber = number.toString(); if (strI.compareTo(strNumber) < 0 && strNumber.compareTo(strB) <= 0) { if (distinctPairs.add(strI + strNumber)) { recycledPairs++; // System.out.println(strNumber); } } } } return recycledPairs; } private void rotate(StringBuilder number) { char c = number.charAt(number.length() - 1); for (int i = number.length() - 1; i > 0; i--) { number.setCharAt(i, number.charAt(i-1)); } number.setCharAt(0, c); } } } " B12792,"import java.io.File; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.Scanner; /** * Created by IntelliJ IDEA. * User: james * Date: 4/14/12 * Time: 3:20 PM * To change this template use File | Settings | File Templates. */ public class Recycled { public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(new File(""inputs/recycled.in"")); int cases = sc.nextInt(); for (int i = 1; i <= cases; i++) { int a = sc.nextInt(); int b = sc.nextInt(); int num = 0; for (int j = a; j <= b; j++) { String s = j + """"; HashSet set = new HashSet(); for (int k = 1; k < s.length(); k++) { String rotated = rotate(s, k); if (!rotated.startsWith(""0"")) { int paired = Integer.parseInt(rotated); if (paired > j && paired <= b) { set.add(paired); } } } num += set.size(); } System.out.printf(""Case #%s: %s\n"", i, num); } } private static String rotate(String s, int i) { String rotated = s.substring(s.length() - i) + s.substring(0, s.length() - i); return rotated; } } " B12658,"import java.util.Scanner; public class plain { static int A[],B[],n[]; public static void main(String args[]) { int t=0; Scanner in=new Scanner(System.in); t=in.nextInt(); in.nextLine(); A=new int[t]; B=new int[t]; n=new int[t]; for(int i=0;i=0;o--) { b=arr[0]; for(int p=0;p<(len-1);p++) { arr[p]=arr[p+1]; } arr[len-1]=b; int rev=0; a=0; for(int p=0;p=A[i] && rev<=B[i] && rev>num ) { for(int k=0;k<(A[i]-B[i]);k++) { if(rev==no2[i]) { g=1; break; } } if(g==0) { ln++; no2[ln]=rev; tot++; } g=0; } } return tot; } } " B13001,"package mgg.problems; import java.util.ArrayList; import java.util.List; import mgg.utils.FileUtil; import mgg.utils.Pair; import mgg.utils.StringUtils; /** * @author manolo * @date 14/04/12 */ public class ProblemC { public final static String EXAMPLE_IN = ""C-example.in""; public final static String EXAMPLE_OUT = ""C-example.out""; public final static String C_SMALL_IN = ""C-small-attempt0.in""; public final static String C_SMALL_OUT = ""C-small-attempt0.out""; public final static String C_LARGE_IN= ""C-large-practice.in""; public final static String C_LARGE_OUT = ""C-large-practice.out""; public final static String delim = "" ""; public static String solve(FileUtil util) { String line = util.getLine(); List listOfArgs = StringUtils.stringWithIntegersToList(line, delim); final int A = listOfArgs.get(0); System.out.println(""\tA = "" + A); final int B = listOfArgs.get(1); System.out.println(""\tB = "" + B); //ArrayList solution = new ArrayList(); int found = 0; for(int i = A; i < B ; i++){ for(int j = A + 1; j <= B ; j++){ if(i 0){ n = n / 10; result++; } return result; } private static int moveCiphersToFront(int number, int howManyCiphers, int numCiphers) { String num = """" + number; String newNumber = num.substring(numCiphers-howManyCiphers, numCiphers) + num.substring(0, numCiphers-howManyCiphers); //System.out.println(""new number: "" + newNumber); return Integer.parseInt(newNumber); } } " B12450,"import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.Scanner; public class C { public static HashSet used; public static void main(String[] args) throws IOException { PrintWriter out = new PrintWriter(new File(""C.out"")); Scanner in = new Scanner(System.in); int cases = in.nextInt(); used = new HashSet(); for(int caseOn = 1; caseOn <= cases; caseOn++) { used.clear(); int a = in.nextInt(); int b = in.nextInt(); int ans = 0; for(int i = a; i < b; i++) { if(used.contains(i)) continue; int count = 0; ArrayList rotations = gen(i); for(int t : rotations) { if(!used.contains(t)) { used.add(t); if(a <= t && t <= b) { count++; } } } count--; ans+=(count*(count+1))/2; } out.printf(""Case #%d: %d\n"",caseOn,ans); } out.close(); } public static ArrayList gen(int a) { int dig = countDigits(a); int ten = 1; for(int i = 1; i < dig; i++) { ten*=10; } ArrayList ret = new ArrayList(); for(int i = 0; i < dig; i++) { if(countDigits(a)==dig) ret.add(a); a = (a%10)*ten + (a/10); } return ret; } public static int countDigits(int a) { int c = 0; while(a!=0) { c++; a/=10; } return c; } } /* 4 1 9 10 40 100 500 1111 2222 */ " B11261,"import java.util.HashMap; import java.util.Scanner; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { Scanner s = new Scanner(System.in); //number of case tests int n; int a, b; n = s.nextInt(); s.nextLine(); for(int t=1; t<= n; t++){ a = s.nextInt(); b = s.nextInt(); s.nextLine(); int counter = 0; for(int i = a; i myNumbers = new ArrayList(); int recycledPairs = 0; firstNumber = Integer.valueOf(lineArray[0]); lastNumber = Integer.valueOf(lineArray[1]); for (int i = lastNumber; i >= firstNumber; i--) { myNumbers.add(i); } for (int i = myNumbers.size() - 1; i >= 0 ; i--) { if (i > myNumbers.size() - 1) { continue; } ArrayList myCombinations = new ArrayList(); String[] numberSplit = String.valueOf(myNumbers.get(i)).split(""""); String myNewNumber = """"; int numberSplitLength = numberSplit.length - 1; int myOriginalNumber = myNumbers.get(i); for (int j = numberSplitLength - 1; j > 0 ; j--) { if (myNewNumber != """") { numberSplit = myNewNumber.split(""""); myNewNumber = """"; } myNewNumber += numberSplit[numberSplit.length - 1]; for (int k = 1; k < numberSplit.length - 1; k++) { myNewNumber += numberSplit[k]; } if (myNewNumber.startsWith(""0"")) { continue; } if (Integer.valueOf(myNewNumber) > lastNumber) { continue; } if (myNewNumber.equalsIgnoreCase(String.valueOf(myOriginalNumber))) { continue; } if (Integer.valueOf(myNewNumber) > myOriginalNumber) { if (!myCombinations.contains(Integer.valueOf(myNewNumber))) { myCombinations.add(Integer.valueOf(myNewNumber)); } } } for (int k = 0; k < myCombinations.size(); k++) { if (myNumbers.contains(myCombinations.get(k))) { // System.out.println(""("" + myOriginalNumber + "","" + myNewNumber + "")""); recycledPairs++; } } if (myNumbers.contains(myOriginalNumber)) { myNumbers.remove(myNumbers.indexOf(myOriginalNumber)); } } outputLine += String.valueOf(recycledPairs); writeFile(outputLine); } private static class Combinations { } // private static class Scores { // int total = 0; // int score1 = 0; // int score2 = 0; // int score3 = 0; // int scoreToEqual = 0; // boolean score2Added = false; // boolean score1Added = false; // // // public int getTotal() { // return score1 + score2 + score3; // } // // public boolean correct() { // if (getTotal() == total) { // return true; // } else { // return false; // } // } // // public void setDefaultScore (int defaultScore) { // score1 = defaultScore; // score2 = defaultScore; // score3 = defaultScore; // } // // public boolean bestScore() { // if ((score1 >= scoreToEqual) || (score2 >= scoreToEqual) || (score3 >= scoreToEqual)) { // return true; // } else { // return false; // } // } // // } public static void main(String[] args) { try{ FileInputStream fstream = new FileInputStream(""input.txt""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; int lineNumber = 0; while ((strLine = br.readLine()) != null) { lineNumber++; processLine(strLine, lineNumber); } in.close(); }catch (Exception e){ System.err.println(""Error Main: "" + e.getMessage()); e.printStackTrace(); } } private static void writeFile(String line) { try{ System.out.println(line); FileWriter fstream = new FileWriter(""out.txt"",true); BufferedWriter out = new BufferedWriter(fstream); out.write(line + ""\n""); out.close(); }catch (Exception e){ System.err.println(""Error writeFile: "" + e.getMessage()); } } } " B10233,"import java.io.*; import java.util.*; public class PracticeC { /* ‚±‚±‚©‚ç•ÒW */ private static final String fname = ""C-small-attempt3.in""; // “ü—Í—p‚̃tƒ@ƒCƒ‹–¼ // private static final int N = 10000; // private static void search(int v) // { // if (v < 21) // return; // String in = Integer.toString(v); // for (int i = 0; i < in.length(); i++) // { // String vs = """"; // for (int j = 0; j < in.length(); j++) // { // char n = in.charAt((i + j + 1) % in.length()); // if (vs.equals("""") && n == '0') // break; // vs += n; // } // // System.out.println(v2); // if (vs.equals("""")) // continue; // int v2 = Integer.valueOf(vs); // if (v > v2) val[v]++; // } // } private static void search(int v, int A, int B) { use = new boolean[B+1]; String in = Integer.toString(v); for (int i = 0; i < in.length(); i++) { String vs = """"; for (int j = 0; j < in.length(); j++) { char n = in.charAt((i + j + 1) % in.length()); if (vs.equals("""") && n == '0') break; vs += n; } // System.out.println(v2); if (vs.equals("""")) continue; int v2 = Integer.valueOf(vs); if (v2 >= A && v > v2 && !use[v2]) { use[v2] = true; val[v]++; } } } public static int val[]; public static boolean use[]; public static void solve() { int T = sc.nextInt(); // for (int i = 21; i < val.length; i++) search(i); // for (int i = 0; i < 100; i++) if(val[i] != 0) // System.out.println(i+"":""+val[i]); for (int i = 1; i <= T; i++) { int A = sc.nextInt(); int B = sc.nextInt(); val = new int[B+1]; for (int j = A; j <= B; j++) search(j, A, B); int cnt = 0; for (int j = A; j <= B; j++) { // if(val[j] != 0) System.out.println(j+"":""+val[j]); cnt += val[j]; } // System. out.println(""Case #"" + i + "": "" + (cnt)); } } /* ‚±‚±‚Ü‚Å */ private static Scanner sc; private static PrintWriter out; public static void main(String args[]) { try { sc = new Scanner(new File(fname)); // sc = new Scanner(System.in); out = new PrintWriter(new BufferedWriter(new FileWriter(new File(fname + ""_out.dat"")))); } catch (Exception e) { e.printStackTrace(); } solve(); out.close(); } } " B10696,"import java.util.*; import java.io.*; import java.lang.*; class RecycledNumbers { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = Integer.parseInt(sc.nextLine()); boolean[] taken = new boolean[2000001]; for (int i=0; i 1) { //System.out.println(j+"" ""+c); int r = 0; for (int k=c-1; k>=1; k--) r += k; count += r; } } } /*int cc= 0; for (int a=A; a<=B; a++) { for (int b=a+1; b<=B; b++) { boolean found = false; for (int k=1; k stat = new HashMap(); private static final int range = 1005; public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(new File( ""/home/girsh/Desktop/coding/codejam/input""))); int[][] x = init(); int t = Integer.parseInt(reader.readLine()); for (int i = 1; i <= t; i++) { String input = reader.readLine(); String[] f = input.split("" ""); Integer A = Integer.parseInt(f[0]); Integer B = Integer.parseInt(f[1]); int ans = 0; for(int g = A;g readInput() { List list = new ArrayList(); try { BufferedReader input = new BufferedReader(new FileReader( INPUT_FILE_PATH)); try { String line = null; while ((line = input.readLine()) != null) { list.add(line); } } finally { input.close(); } } catch (IOException ex) { ex.printStackTrace(); } return list; } public static void writeOutput(List output) { PrintWriter writer = null; try { writer = new PrintWriter(new FileWriter(OUTPUT_FILE_PATH)); for (String line : output) { writer.println(line); } writer.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (writer != null) writer.close(); } } public static void main(String[] args) { List recycledNumbers = RecycledNumbers.parseFromFile(CodeJam.readInput()); List output = new ArrayList(); for(int i = 0; i < recycledNumbers.size(); i++) { System.out.println(recycledNumbers.get(i)); String line = """"; line += ""Case #"" + (i + 1) + "": "" + recycledNumbers.get(i).calculate(); output.add(line); } CodeJam.writeOutput(output); } } " B10103,"import java.util.*; import java.io.*; import java.math.*; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; try { inputStream = new FileInputStream(""c.in""); outputStream = new FileOutputStream(""c.out""); } catch (FileNotFoundException e) { System.err.println(""File not found""); return; } InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solver solver = new Solver(); solver.solve(in, out); out.close(); } } class Solver { public void solve(InputReader in, PrintWriter out) { int t = in.nextInt(); for (int i = 0; i < t; i++) { int a = in.nextInt(); int b = in.nextInt(); int ans = 0; for (int j = a; j <= b; ++j) { String s = (new Integer(j)).toString(); TreeSet use = new TreeSet(); for (int k = 0; k < s.length() - 1; k++) { s = (s.substring(1)).concat(s.substring(0, 1)); //System.err.println(s); if (s.charAt(0) == '0') { continue; } int w = Integer.parseInt(s); if (w > j && w <= b && !use.contains(w)) { ans++; use.add(w); } } } out.print(""Case #""); out.print(i + 1); out.print("": ""); out.println(ans); } } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } } " B12079,"package jp.funnything.competition.util; import java.util.List; import com.google.common.collect.Lists; public class Lists2 { public static < T > List< T > newArrayListAsArray( final int length ) { final List< T > list = Lists.newArrayListWithCapacity( length ); for ( int index = 0 ; index < length ; index++ ) { list.add( null ); } return list; } } " B12560,"import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { public static void main(String[] args) { Scanner in = new Scanner(System.in); int noCases = in.nextInt(); for(int i = 0; i < noCases; i++){ int a = in.nextInt(); int b = in.nextInt(); int noDigits = Integer.toString(a).length(); Set checkedNumber = new HashSet(); for(int number = a; number <= b; number++){ for (int digit = 1; digit < noDigits; digit++) { if(number % Math.pow(10, digit) == 0){ continue; } int rotatedNumber = rotate(number, digit, noDigits); Pair pair = new Pair(rotatedNumber,number); if (rotatedNumber >= a && rotatedNumber <= b && !checkedNumber.contains(pair) && number != rotatedNumber) { checkedNumber.add(pair); } } } System.out.println(""Case #""+(i+1)+"": "" + checkedNumber.size()); } } static class Pair{ int value1, value2; public Pair(int value1, int value2){ this.value1 = value1; this.value2 = value2; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (value1+value2); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (value1 != other.value1 && value1 != other.value2) return false; if (value2 != other.value2 && value2 != other.value1) return false; return true; } public String toString(){ return ""(""+value1+"",""+value2+"")""; } } public static int rotate(int number, int noPlaces, int noDigits){ int rotatedNumber = number; int divider = (int) Math.pow(10, noDigits-1); for(int i = 0; i < noPlaces; i++){ int digit = rotatedNumber % 10; rotatedNumber = digit*divider + rotatedNumber / 10; } return rotatedNumber; } } " B11634,"import java.util.*; import java.io.*; public class qualC { public static void main(String[] args) throws IOException { Scanner sin = new Scanner(new File(""/Users/G/Documents/Programming/Java/CodeJam2012/C-small-attempt0.in"")); int t = sin.nextInt(), a, b; for(int i = 1; i <= t; ++i) { a = sin.nextInt(); b = sin.nextInt(); int ret = 0; for(long j = a; j <= b; ++j) { if(j >= 10) { int length = 0; long firstPosition, shift=j; for(firstPosition = 1; firstPosition <= shift; firstPosition*=10) length++; firstPosition /= 10; long[] numbers = new long[length]; for(int k = 0; k < length; ++k) { long lastDigit = shift%10; shift /= 10; shift += firstPosition*lastDigit; numbers[k] = shift; boolean found = false; for(int m = 0; m < k; ++m) { if(shift == numbers[m]) { found = true; break; } } if(shift >= a && shift <= b && j < shift && lastDigit != 0 && !found) { ret++; } } } } System.out.println(""Case #""+i+"": ""+ret); } } } " B10732,"package com.edwarddrapkin; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Scanner; public class Numbers { private boolean isRecylced(int m, int n) { String sm = m + """"; String sn = n + """"; //eliminate some common cases // same number apparently doesn't count... if(sm.equals(sn)) { return false; } //not the same length while(sm.length() < sn.length()) { sm = ""0"" + sm; } while(sn.length() < sm.length()) { sn = ""0"" + sn; } //chars in m not in n for(char c : sm.toCharArray()) { if(!sn.contains("""" + c)) { return false; } } //vice versa for(char c : sn.toCharArray()) { if(!sm.contains("""" + c)) { return false; } } for(int i = 1; i < sm.length(); i++) { String slice = sm.substring(i) + sm.substring(0, i); if(slice.equals(sn)) { return true; } } return false; } private static String[] readFile(String file) throws IOException { Scanner scanner = new Scanner(new File(file)); String numLines = scanner.nextLine(); int nl = Integer.parseInt(numLines); String[] lines = new String[nl]; int i = 0; while(scanner.hasNextLine() && i < nl) { lines[i] = scanner.nextLine(); ++i; } return lines; } public static void main(String[] args) throws Exception { Numbers num = new Numbers(); String[] lines = readFile(""C:/Users/Eddie/Desktop/google_input.txt""); int i = 1; for(String line : lines) { Scanner lScanner = new Scanner(line); int low = lScanner.nextInt(); int high = lScanner.nextInt(); int numPossible = 0; for(int idx = low; idx <= high; idx++) { for(int inner = idx; inner <= high; inner++) { if(num.isRecylced(idx, inner)) { //System.out.println(high + "" "" + low + "" "" + idx + "" "" + inner); numPossible++; } } } System.out.println(""Case #"" + i + "": "" + numPossible); i++; } } } " B11239,"import java.util.Scanner; public class RecycledNumbers { static int recycle(int n, int B) { String nString = String.valueOf(n); int out = 0; for (int i = 0; i < nString.length(); i++) { int cut = nString.length() - (i + 1); String temp = nString.substring(cut) + nString.substring(0, cut); int pair = Integer.parseInt(temp); if (n < pair && pair <= B) { //System.out.println(n + "" "" + pair); out++; } } return out; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int cases = sc.nextInt(); StringBuilder out = new StringBuilder(); for (int i = 1; i <= cases; i++) { int A = sc.nextInt(); int B = sc.nextInt(); int pairs = 0; for (int j = A; j < B; j++) { pairs += recycle(j, B); } out.append(""Case #"" + i + "": "" + pairs + ""\n""); } System.out.print(out); } } " B11426,"import java.io.*; import java.util.*; public class RecycledNumbers { static int A, B; public static void main(String[] args) throws IOException { Kattio io = new Kattio(System.in, new FileOutputStream(""recycle.out"")); int T = io.getInt(); for (int test = 1; test <= T; test++) { A = io.getInt(); B = io.getInt(); int res = 0; for (int i = A; i <= B; i++) { res += recycle(i); } io.println(""Case #""+test+"": ""+res); } io.close(); } static int recycle(int num) { int start = num; if (num/10 == 0) return 0; int m = 1; while (m <= num) { m*= 10; } m/= 10; int d = num/m; int res = 0; while (true) { num %= m; num *= 10; num += d; d = num/m; if (d != 0 && num > start && num <= B) res++; if (num == start) return res; } } static class Kattio extends PrintWriter { public Kattio(InputStream i) { super(new BufferedOutputStream(System.out)); r = new BufferedReader(new InputStreamReader(i)); } public Kattio(InputStream i, OutputStream o) { super(new BufferedOutputStream(o)); r = new BufferedReader(new InputStreamReader(i)); } public boolean hasMoreTokens() { return peekToken() != null; } public int getInt() { return Integer.parseInt(nextToken()); } public double getDouble() { return Double.parseDouble(nextToken()); } public long getLong() { return Long.parseLong(nextToken()); } public String getWord() { return nextToken(); } private BufferedReader r; private String line; private StringTokenizer st; private String token; private String peekToken() { if (token == null) try { while (st == null || !st.hasMoreTokens()) { line = r.readLine(); if (line == null) return null; st = new StringTokenizer(line); } token = st.nextToken(); } catch (IOException e) { } return token; } private String nextToken() { String ans = peekToken(); token = null; return ans; } } }" B10316,"package ProblemC; import java.io.*; import java.util.StringTokenizer; public class RecycledNums { /** * @param args */ public RecycledNums(){ } public static void recycledNums() throws IOException{ BufferedReader rdr = new BufferedReader(new FileReader(""C-small-attempt0.in"")); PrintWriter pw = new PrintWriter(new FileWriter(""C.out"")); int cases = Integer.parseInt(rdr.readLine()); for (int i = 0; i < cases; i++) { String line = rdr.readLine(); StringTokenizer st = new StringTokenizer(line); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); int result = 0; for (int n=A; n0; j--){ //System.out.println(ns+"" ""+ms.substring(j, ns.length())+"" ""+ms.substring(0, j)); if(ms.equals(ns.substring(j, ms.length())+ns.substring(0, j))){ result++; break; //System.out.println(n+"" ""+m); } } } } } pw.println(""Case #""+(i+1)+"": ""+result); } pw.close(); rdr.close(); } public static void main(String[] args)throws IOException { // TODO Auto-generated method stub recycledNums(); } } " B13067,"import java.io.File; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.Iterator; import java.util.Scanner; public class A { public static void main(String[] args) { new A().run(); } private void run() { Scanner s; try { s = new Scanner(new File(""A.in"")); int t = s.nextInt(); s.nextLine(); for (int i = 0; i < t; i++) { HashMap map = new HashMap(); int count = 0; int a = s.nextInt(); int b = s.nextInt(); for(int j=a;j<=b;j++){ String str = """"+j; String tmp = str; for (int k = 0; k < str.length()-1; k++) { tmp = tmp.charAt(tmp.length()-1) + tmp.substring(0, tmp.length()-1); int m = Integer.parseInt(tmp); if(Integer.parseInt(tmp) > j && m <=b ){ if(!map.containsKey(j+""_""+m)){ map.put(j+""_""+m, true); count++; } } } } System.out.println(""Case #""+(i+1)+"": ""+count); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B13189,"import java.io.*; import java.util.*; import java.math.*; public class Timus implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer st; Random rnd; final int limit = 2000000; ArrayList[] sets; void addShifts(int number) { String numStr = Integer.toString(number); int totalShifts = numStr.length() - 1; numStr += numStr; for(int i = 1; i <= totalShifts; i++) { String shiftStr = numStr.substring(i, i + totalShifts + 1); int shift = Integer.parseInt(shiftStr); if(shift > number && !sets[number].contains(shift)) { sets[number].add(shift); } } } void precalc() { sets = new ArrayList[limit + 1]; for(int i = 0; i < sets.length; i++) { sets[i] = new ArrayList(); } for(int n = 0; n <= limit; n++) { addShifts(n); Collections.sort(sets[n]); //out.println(n + "" "" + sets[n]); } } int solveOne(int l, int r) { int res = 0; for(int n = l; n <= r; n++) { for(int m : sets[n]) { if(m > r) { break; } else { ++res; } } } return res; } void solve() throws IOException { precalc(); int tests = nextInt(); for(int test = 1; test <= tests; test++) { out.printf(""Case #%d: %d\n"", test, solveOne(nextInt(), nextInt())); } } public static void main(String[] args) { new Timus().run(); } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); rnd = new Random(); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(42); } } String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }" B12668,"import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Hashtable; import java.util.Scanner; import java.util.TreeSet; public class RecycleNumber { private static TreeSet result = new TreeSet(); private static Hashtable resultingString ; private static Hashtable> reverseMapping ; private static ArrayList values = new ArrayList(); private static int totalCount = 1 ; public static void main(String[] args) throws FileNotFoundException { new RecycleNumber().doProcessing(new File(""D:\\codejam\\C\\sample.txt"")); //reverseString(""1512"", ""5121"",100,500); } public void doProcessing(File inputFile) throws FileNotFoundException { Scanner scanner = new Scanner(inputFile).useDelimiter(""\n""); if (scanner != null) { int totalCases = Integer.parseInt(scanner.next().trim()); int k = 1; if (totalCases > 0) { while (scanner.hasNext()) { String[] rowValues = scanner.next().trim().split("" ""); int lowerLimit = Integer.parseInt(rowValues[0].trim()); int upperLimit = Integer.parseInt(rowValues[1].trim()); int successCase = getReverCount(lowerLimit, upperLimit); // System.out.println(""Case #Lower Limit ; "" + lowerLimit + // "" : Upper Limit = "" + upperLimit + "" "" + k++ + "": "" + // successCase); System.out.println(""Case #"" + k++ + "": "" + successCase); } } } scanner.close(); } public int getReverCount(int lowerNumber, int upperLimit) { //int count = 0; //int nums = 0; resultingString = new Hashtable(); reverseMapping = new Hashtable>(); values = new ArrayList(); for (int i = lowerNumber; i <= upperLimit; i++) { //System.out.println(""@@@@@@@@@@"" + i); //showPattern("""", String.valueOf(i),i,lowerNumber,upperLimit); String val = String.valueOf(i); //System.out.println(""String value of "" + i + "" is "" + val); char firstChar = val.charAt(val.length() - 1); // System.out.println(""First Char = "" + firstChar); String subString = val.substring(0, val.length() - 1); // System.out.println(""Sub String = "" + subString); reverseString(val, new String(firstChar + subString), upperLimit, lowerNumber); } //System.out.println(""Possibilities = "" + result.size() + "" Lower Num = "" + lowerNumber + "" : Upper Lim "" + upperLimit + ""\n "" + resultingString + ""\n Reverse Mappings : "" + reverseMapping); result = new TreeSet(); //System.out.println(""Total Counts : "" + values.size()); // System.out.println(""Numbers : "" + nums); return resultingString.size(); } public static boolean containsReverseEntry(int key, int val){ boolean contains = false ; ArrayList arrayList = reverseMapping.get(key); if (arrayList != null){ contains = arrayList.contains(val); } return contains ; } public static void makeReverseEntry(int key, int value){ ArrayList arrayList = reverseMapping.get(key); if (arrayList == null){ arrayList = new ArrayList(); } arrayList.add(value); reverseMapping.put(key, arrayList); //System.out.println(""List "" + reverseMapping); } public static void reverseString(String orgString, String val, int upperLimit, int lowerLimit){ if (orgString.equals(val)){ return ; }else{ int formatedValue = Integer.parseInt(val); // System.out.println(""Original Value = "" + orgString + "" : Formated Value = "" + formatedValue + "" Upper Limit = "" + upperLimit + "" : Lower Limit - "" + lowerLimit ); if (formatedValue >= lowerLimit && formatedValue <= upperLimit){ int integer = 0 ; int orgValue = Integer.parseInt(orgString); boolean containsReverseEntry = containsReverseEntry(orgValue,formatedValue); if ( !containsReverseEntry){ values.add(formatedValue); //System.out.println(""Placing Value - ("" + orgString + "","" + formatedValue + "") "" + totalCount++); resultingString.put(orgValue, formatedValue); //reverseMapping.put(formatedValue, orgValue); makeReverseEntry(formatedValue, orgValue); // System.out.println(""Placing Value - ("" + orgString + "","" + formatedValue + "") Total Count "" + totalCount ); //System.out.println(""Placing Reverse Value - ("" + formatedValue + "","" + orgString + "") Total Count "" + totalCount++ ); } } char firstChar = val.charAt(val.length() - 1); // System.out.println(""First Char = "" + firstChar); String subString = val.substring(0, val.length() - 1); // System.out.println(""Sub String = "" + subString); reverseString(orgString, new String(firstChar + subString), lowerLimit, upperLimit); } } public void showPattern(String st, String chars, int baseString, int lowerLimit, int upperLimit) { if (chars.length() <= 1){ result.add(st + chars); int palString = Integer.parseInt(st + chars); if (palString < upperLimit && palString != baseString && palString > lowerLimit && resultingString.get(palString) == null ){ resultingString.put(baseString, palString); values.add(palString); } System.out.println(st + chars); }else for (int i = 0; i < chars.length(); i++) { try { String newString = chars.substring(0, i) + chars.substring(i + 1); showPattern(st + chars.charAt(i), newString,baseString,lowerLimit,upperLimit); } catch (Exception e) { e.printStackTrace(); } } } public int reverseInteger(int number) { int reverse = 0; while (number != 0) { reverse = reverse * 10; reverse = reverse + number % 10; number = number / 10; } return reverse; } } " B11446,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; public class ProblemC { public static void main (String[] args) throws Exception{ BufferedReader fin = new BufferedReader(new FileReader(""E:/C-small-attempt0.in"")); String line = fin.readLine(); BufferedWriter out = new BufferedWriter(new FileWriter(""E:/C-small-attempt0.out"")); int ln = 1; while ((line = fin.readLine()) != null && line.length() != 0){ line = line.trim(); String[] parts = line.split(""\\s+""); int a = Integer.parseInt(parts[0]); int b = Integer.parseInt(parts[1]); int count = 0; for (int i = a; i < b; i++){ String s = Integer.toString(i); ArrayList list = new ArrayList(); for (int j = 1; j < s.length(); j++){ String newString = s.substring(j) + s.substring(0,j); int newInt = Integer.parseInt(newString); if ((newInt > i) && (newInt <= b) && (list.contains(newInt) == false)){ list.add(newInt); count++; } } } out.write(""Case #"" + ln + "": "" + count); out.write(""\n""); ln++; } fin.close(); out.close(); } }" B10752,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package third; import java.io.File; import java.io.IOException; import java.util.Scanner; /** * * @author Yogendra */ public class Third { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { File f = new File(""input.txt""); Scanner s = new Scanner(f); int [] check; int answer=0; int total=s.nextInt(); for(int i=0;i99 && last<=999) { check = new int [1000]; int temp1,temp2,temp21,temp3; f1=1; temp21=j/10; temp2=temp21%10; temp3=j%10; temp1=temp21/10; for(int l=0;l<=999;l++) { check[l]=0; } if(temp3>=temp1) { int tempnum=(temp3*100)+(temp1*10)+temp2; if((tempnum <=last)&&(tempnum>j) && check[tempnum]!=1) { check[tempnum]=1; answer++; } } if(temp2>=temp1 ) { int tempnum=(temp2*100)+(temp3*10)+temp1; if((tempnum<=last)&&(tempnum > j) && check[tempnum]!=1 ) { check[tempnum]=1; answer++; } } } else if((first > 9 && last<=99)) { check = new int [99]; for(int k=0;k<99;k++) { check[k]=0; } int temp1,temp2; temp1= j/10; temp2=j%10; if(temp2>temp1) { int tempnum=(temp2*10)+temp1; if((tempnum<=last)&&(check[tempnum]!=1)) { answer++; check[tempnum]=1; } } } } System.out.println(""Case #""+(i+1)+"": ""+answer); answer=0; } } } " B10035,"package com.google.cj; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.StringTokenizer; public class Recycling { public static void main(String[] args) { List fileContents = IOHandler .readInput(""/home/wzedan/cj/input/recycling.in""); List output = getPairs(fileContents); IOHandler.writeOutput(output, ""/home/wzedan/cj/output/recycling.out""); } private static List getPairs(List fileContents) { List output = new ArrayList(); for (String line : fileContents) { StringTokenizer st = new StringTokenizer(line); String lowerLimit = st.nextToken(); String upperLimit = st.nextToken(); if (lowerLimit.length() == 1 && upperLimit.length() == 1) { output.add("""" + 0); continue; } int maxShiftFactor = upperLimit.length() - 1; List refCharacters = new ArrayList(); buildRefCharacters(lowerLimit, upperLimit, refCharacters); int noOfPairs = 0; List shiftedList = new ArrayList(); for (int distance = 1; distance <= maxShiftFactor; distance++) { System.out.println(""Distance = ["" + distance + ""]""); shiftedList.addAll(shiftList(refCharacters, distance, Integer.valueOf(upperLimit) , Integer.valueOf(lowerLimit))); Set s = new HashSet(shiftedList); shiftedList.clear(); shiftedList.addAll(s); System.out.println(""ShiftedList length ["" + shiftedList.size() + ""]""); System.out.println(shiftedList); } System.out.println(""No of pairs ["" + shiftedList.size() + ""] for lowerLimit ["" + lowerLimit + ""] and upperLimt ["" + upperLimit + ""]""); output.add("""" + shiftedList.size()); } return output; } private static int findMatches(List refCharacters, List shiftedList) { int noOfPairs = 0; // for (int i = 0; i < shiftedList.size(); i++) { // if (refCharacters.contains(shiftedList.get(i).value)) { // noOfPairs +=1; // } // } return shiftedList.size(); } private static void buildRefCharacters(String lowerLimit, String upperLimit, List refCharacters) { for (int i = Integer.valueOf(lowerLimit); i <= Integer .valueOf(upperLimit); i++) { refCharacters.add("""" + i); } } private static List shiftList(List refCharacters, int distance, int upperLimit , int lowerLimit) { List shiftedList = new ArrayList(); for (int i = 0; i < refCharacters.size(); i++) { Entry entry = shift(refCharacters.get(i), i, distance, upperLimit , lowerLimit); if (entry != null) { shiftedList.add(entry); } } return shiftedList; } public static Entry shift(String n, int index, int distance, int upperLimit , int lowerLimit) { String nCopy = n; if (!hasAllSameDigit(n)) { //System.out.println(""Shifting ["" + n + ""] distance ["" + distance + ""]""); String shiftPattern = n .substring(n.length() - distance); int shiftPatternIndex = n.length() - shiftPattern.length(); String modifiedN = n.substring(0, shiftPatternIndex); n = shiftPattern + modifiedN; if (n.startsWith(""0"")) { n = nCopy; } int nInteger = Integer.valueOf(n); // A <= n < m <= B if(nInteger < lowerLimit){ n = nCopy; } if (nInteger > upperLimit) { n = nCopy; } if(Integer.valueOf(nCopy) > nInteger ){ n = nCopy; } } return !n.equals(nCopy) ? new Entry(nCopy, n) : null; } private static boolean hasAllSameDigit(String n) { char c = n.charAt(0); for (int i = 0; i < n.length(); i++) { if (n.charAt(i) != c) { return false; } } return true; } } " B12374,"import java.io.BufferedReader; import java.io.FileReader; public class C { private boolean isR(int a, int b) { char[] sa = String.valueOf(a).toCharArray(); char[] sb = String.valueOf(b).toCharArray(); if (sa.length != sb.length) return false; int n = sa.length; for (int i = 1; i < n; i++) { boolean ok = true; for (int k = 0; k < n; k++) { char c = sb[(k + i) % n]; if (c != sa[k]) { ok = false; break; } } if (ok) return true; } return false; } int count(int a, int b) { int c = 0; for (int i = a; i < b; i++) { for (int j = i + 1; j <= b; j++) { if (isR(i, j)) { c++; } } } return c; } private void main2(String[] args) throws Exception { BufferedReader br = new BufferedReader(new FileReader(args[0])); String line = br.readLine(); int count = Integer.parseInt(line); for (int i = 0; i < count; i++) { line = br.readLine(); int s = line.indexOf(' '); int a = Integer.parseInt(line.substring(0, s)); int b = Integer.parseInt(line.substring(s + 1)); System.out.println(""Case #"" + (i + 1) + "": "" + count(a, b)); } br.close(); } public static void main(String[] args) throws Exception { new C().main2(args); } } " B12934,"package com.embege.codejam; import java.util.Arrays; import java.util.Scanner; public class CJ2012QualiCRecycled { static int len(int n) { int c = 1; while ((n = n/10) > 0) c++; return c; } static boolean checkDigits(int a, int b) { if (len(a) != len(b)) return false; String sa = Integer.toString(a); String sb = Integer.toString(b); char []ca = sa.toCharArray(); char []cb = sb.toCharArray(); Arrays.sort(ca); Arrays.sort(cb); int len = ca.length; for(int i = 0; i < len; i++) if(cb[i] != ca[i]) return false; return true; /* for (int i=0; i bLimits = null; BufferedReader br; // loading try { br = new BufferedReader(new InputStreamReader(new FileInputStream(args[0]))); String line; int lCounter = 0; int numLines, low, upp; Limits ls; String[] bounds; while ((line = br.readLine()) != null) { if (lCounter == 0) { numLines = Integer.parseInt(line); bLimits = new ArrayList(numLines); lCounter++; } else { bounds = line.split("" ""); low = Integer.parseInt(bounds[0]); upp = Integer.parseInt(bounds[1]); ls = new Limits(low, upp); bLimits.add(ls); } } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // go int count = 1; for (Limits ls : bLimits) { calcRecycledPairs(ls.getLow(), ls.getUpp(), count); count++; } } private static void calcRecycledPairs(int low, int upp, int count) { Set recPairs = new HashSet(); for (int num = low; num <= upp; num++) { int numRotations = Integer.toString(num).length() - 1; int originalNum = num; // recNums.add(originalNum); String numS = Integer.toString(num); String rotNumS; int rotNum; while (numRotations > 0) { rotNumS = rotate(numS); // System.out.println(""["" + numS + "";"" + rotNumS + ""]""); rotNum = Integer.parseInt(rotNumS); if (!(originalNum == rotNum) && !numS.equals(rotNumS) && rotNum >= low && rotNum <= upp && !recPairs.contains(new RecycledPair(originalNum, rotNum))) { // System.out.println(""*** ("" + originalNum + "","" + rotNum + // "")""); recPairs.add(new RecycledPair(originalNum, rotNum)); } numS = rotNumS; numRotations--; } } System.out.println(""Case #"" + count + "": "" + recPairs.size()); } private static String rotate(String num) { String last = Character.toString(num.charAt(num.length() - 1)); char[] prefix = new char[num.length() - 1]; num.getChars(0, num.length() - 1, prefix, 0); String s = last + new String(prefix); return s; } } " B12902,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; public class RecycledNumbers { public static void main(String[] args){ try{ // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(args[0]); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; //Read File Line By Line int numTest = Integer.parseInt(br.readLine()); for(int i = 0; i < numTest; i ++){ String str = br.readLine(); String numbers[] = str.split("" ""); int count = recycledNumbers(Integer.parseInt(numbers[0]),Integer.parseInt(numbers[1])); int x = i + 1; System.out.println(""Case #"" + x + "": "" + count); } //Close the input stream in.close(); }catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } public static int recycledNumbers(int min, int max){ int digits = Integer.toString(min).length(); int current = min; int count = 0; while(current <= max){ ArrayList newNumbers = new ArrayList(); for(int i = 1; i < digits; i++){ String movedDigits = Integer.toString(current).substring(i); String remainingDigits; if(i == 1){ remainingDigits = Character.toString(Integer.toString(current).charAt(0)); } else{ remainingDigits = Integer.toString(current).substring(0,i); } int newNumber = Integer.parseInt(movedDigits + remainingDigits); if(newNumber != current && newNumber <= max && newNumber >= min ){ boolean alreadyExists = false; for(Integer no : newNumbers){ if(no.intValue() == newNumber){ alreadyExists = true; } } if(!alreadyExists){ if(current < newNumber){ count ++; //System.out.println(""("" + current + "","" + newNumber + "")""); newNumbers.add(new Integer(newNumber)); } } } } current++; } return count; } } " B11632,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; public class EagleProblemC { public static void main(String args[]) throws IOException { BufferedReader bfr = new BufferedReader(new FileReader(""inputC.txt"")); Writer output = null; File file = new File(""EagleOutputC.txt""); output = new BufferedWriter(new FileWriter(file)); int T = Integer.parseInt(bfr.readLine()); int i = 0; while (i < T) { String[] tempString = bfr.readLine().split("" ""); int total = 0; int A = Integer.parseInt(tempString[0]); int B = Integer.parseInt(tempString[1]); for (int j = A; j <= B; j++) { long tempNumber = j; long tempStart = tempNumber; int numdigits = (int) Math.log10((double) tempNumber); int multiplier = (int) Math.pow(10.0, (double) numdigits); while (true) { long r = tempNumber % 10; // 1234 = 123; tempNumber = tempNumber / 10; tempNumber = tempNumber + multiplier * r; if (tempNumber == tempStart) break; if ((int)tempNumber >= A && (int)tempNumber <= B) { total++; } } } output.write(""Case #"" + (i + 1) + "": "" + (total/2)); if (i != T - 1) { output.write(""\n""); } i++; } output.close(); } } " B12851,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.io.Reader; import java.util.HashMap; import java.util.HashSet; import java.util.Set; public class Main { public static HashMap mapp = new HashMap(); public static void main(String[] args) throws Exception { PrintWriter writer = new PrintWriter(new FileWriter(""output.txt"")); BufferedReader input = new BufferedReader(new FileReader(""C-small-attempt0.in"")); int size=Integer.parseInt(input.readLine()); for(int i=0; i mySet = new HashSet(); String tokens[] = input.readLine().split("" ""); int lowLimit = Integer.parseInt(tokens[0]); int highLimit = Integer.parseInt(tokens[1]); int count=0; for(int j=lowLimit; j set = new HashSet<>(); for (int n = A; n < B; n++) { set.clear(); String nstr = String.valueOf(n); for (int i = 1; i < keta; i++) { String rot = nstr.substring(i) + nstr.substring(0, i); int m = Integer.parseInt(rot); if (n < m && m <= B && set.add(m)) { // System.out.printf(""%d %d%n"", n, m); ans++; } } } System.out.printf(""Case #%d: %d%n"", no, ans); } public static void main(String[] args) { int T = in.nextInt(); for (int i = 0; i < T; i++) { solve(i + 1); } } } " B11822,"import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { public static void main(String[] args) throws IOException { File file = new File(""in.txt""); Scanner scanner = new Scanner(file); FileWriter outFile = new FileWriter(""out.txt""); PrintWriter out = new PrintWriter(outFile); int N = scanner.nextInt(); for (int i = 0; i < N; i++) { int A = scanner.nextInt(); int B = scanner.nextInt(); Set set = new HashSet(); for (int n = A; n <= B; n++) { char[] c = Integer.toString(n).toCharArray(); for (int k = 0; k < c.length - 1; k++) { char temp = c[c.length - 1]; for (int l = c.length - 1; l > 0; l--) { c[l] = c[l - 1]; } c[0] = temp; StringBuilder s = new StringBuilder(); for (int l = 0; l < c.length; l++) { s.append(c[l]); } String m = s.toString(); if (A <= Integer.parseInt(m) && Integer.parseInt(m) <= B && n < Integer.parseInt(m)) { set.add(Integer.toString(n).concat(m)); } } } out.println(""Case #"" + (i + 1) + "": "" + set.size()); } out.close(); } } " B12435,"import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new File(""resource/input.in"")); int T = sc.nextInt(); int i = 1; while (i<=T) { int A = sc.nextInt(); int B = sc.nextInt(); System.out.println(""Case #""+i+"": ""+process(A, B)); i++; } } private static int process(int A, int B) { List added = new ArrayList(); int counter = 0; for(int i=A; i<=B; i++){ String s = i+""""; for(int j=0; j=A && nx<=B && nx!=i && !added.contains(i+""|""+nx) && !added.contains(nx+""|""+i)){ counter++; added.add(i+""|""+nx); added.add(nx+""|""+i); } } } return counter; } } " B11858,"/************************************************************************* * Compilation: javac In.java * Execution: java In * * Reads in data of various types from: stdin, file, URL. * * % java In * * Remarks * ------- * - isEmpty() returns true if there is no more input or * it is all whitespace. This might lead to surprising behavior * when used with readChar() * *************************************************************************/ import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.net.URL; import java.net.URLConnection; import java.util.Locale; import java.util.Scanner; /** * Input. This class provides methods for reading strings * and numbers from standard input, file input, URL, and socket. *

* The Locale used is: language = English, country = US. This is consistent * with the formatting conventions with Java floating-point literals, * command-line arguments (via Double.parseDouble()) * and standard output (via System.out.print()). It ensures that * standard input works the number formatting used in the textbook. *

* For additional documentation, see Section 3.1 of * Introduction to Programming in Java: An Interdisciplinary Approach by Robert Sedgewick and Kevin Wayne. */ public final class In { private Scanner scanner; // assume Unicode UTF-8 encoding //private String charsetName = ""UTF-8""; private String charsetName = ""ISO-8859-1""; // assume language = English, country = US for consistency with System.out. private Locale usLocale = new Locale(""en"", ""US""); /** * Create an input stream for standard input. */ public In() { scanner = new Scanner(new BufferedInputStream(System.in), charsetName); scanner.useLocale(usLocale); } /** * Create an input stream from a socket. */ public In(Socket socket) { try { InputStream is = socket.getInputStream(); scanner = new Scanner(new BufferedInputStream(is), charsetName); scanner.useLocale(usLocale); } catch (IOException ioe) { System.err.println(""Could not open "" + socket); } } /** * Create an input stream from a URL. */ public In(URL url) { try { URLConnection site = url.openConnection(); InputStream is = site.getInputStream(); scanner = new Scanner(new BufferedInputStream(is), charsetName); scanner.useLocale(usLocale); } catch (IOException ioe) { System.err.println(""Could not open "" + url); } } /** * Create an input stream from a file. */ public In(File file) { try { scanner = new Scanner(file, charsetName); scanner.useLocale(usLocale); } catch (IOException ioe) { System.err.println(""Could not open "" + file); } } /** * Create an input stream from a filename or web page name. */ public In(String s) { try { // first try to read file from local file system File file = new File(s); if (file.exists()) { scanner = new Scanner(file, charsetName); scanner.useLocale(usLocale); return; } // next try for files included in jar URL url = getClass().getResource(s); // or URL from web if (url == null) { url = new URL(s); } URLConnection site = url.openConnection(); InputStream is = site.getInputStream(); scanner = new Scanner(new BufferedInputStream(is), charsetName); scanner.useLocale(usLocale); } catch (IOException ioe) { System.err.println(""Could not open "" + s); } } /** * Does the input stream exist? */ public boolean exists() { return scanner != null; } /** * Is the input stream empty? */ public boolean isEmpty() { return !scanner.hasNext(); } /** * Does the input stream have a next line? */ public boolean hasNextLine() { return scanner.hasNextLine(); } /** * Read and return the next line. */ public String readLine() { String line; try { line = scanner.nextLine(); } catch (Exception e) { line = null; } return line; } /** * Read and return the next character. */ public char readChar() { // (?s) for DOTALL mode so . matches any character, including a line termination character // 1 says look only one character ahead // consider precompiling the pattern String s = scanner.findWithinHorizon(""(?s)."", 1); return s.charAt(0); } // return rest of input as string /** * Read and return the remainder of the input as a string. */ public String readAll() { if (!scanner.hasNextLine()) { return null; } // reference: http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html return scanner.useDelimiter(""\\A"").next(); } /** * Return the next string from the input stream. */ public String readString() { return scanner.next(); } /** * Return the next int from the input stream. */ public int readInt() { return scanner.nextInt(); } /** * Return the next double from the input stream. */ public double readDouble() { return scanner.nextDouble(); } /** * Return the next float from the input stream. */ public double readFloat() { return scanner.nextFloat(); } /** * Return the next long from the input stream. */ public long readLong() { return scanner.nextLong(); } /** * Return the next byte from the input stream. */ public byte readByte() { return scanner.nextByte(); } /** * Return the next boolean from the input stream, allowing ""true"" or ""1"" * for true and ""false"" or ""0"" for false. */ public boolean readBoolean() { String s = readString(); if (s.equalsIgnoreCase(""true"")) return true; if (s.equalsIgnoreCase(""false"")) return false; if (s.equals(""1"")) return true; if (s.equals(""0"")) return false; throw new java.util.InputMismatchException(); } /** * Read ints from file */ public static int[] readInts(String filename) { In in = new In(filename); String[] fields = in.readAll().trim().split(""\\s+""); int[] vals = new int[fields.length]; for (int i = 0; i < fields.length; i++) vals[i] = Integer.parseInt(fields[i]); return vals; } /** * Read doubles from file */ public static double[] readDoubles(String filename) { In in = new In(filename); String[] fields = in.readAll().trim().split(""\\s+""); double[] vals = new double[fields.length]; for (int i = 0; i < fields.length; i++) vals[i] = Double.parseDouble(fields[i]); return vals; } /** * Read strings from a file */ public static String[] readStrings(String filename) { In in = new In(filename); String[] fields = in.readAll().trim().split(""\\s+""); return fields; } /** * Read ints from standard input */ public static int[] readInts() { In in = new In(); String[] fields = in.readAll().trim().split(""\\s+""); int[] vals = new int[fields.length]; for (int i = 0; i < fields.length; i++) vals[i] = Integer.parseInt(fields[i]); return vals; } /** * Read doubles from standard input */ public static double[] readDoubles() { In in = new In(); String[] fields = in.readAll().trim().split(""\\s+""); double[] vals = new double[fields.length]; for (int i = 0; i < fields.length; i++) vals[i] = Double.parseDouble(fields[i]); return vals; } /** * Read strings from standard input */ public static String[] readStrings() { In in = new In(); String[] fields = in.readAll().trim().split(""\\s+""); return fields; } /** * Close the input stream. */ public void close() { scanner.close(); } /** * Test client. */ public static void main(String[] args) { In in; String urlName = ""http://introcs.cs.princeton.edu/stdlib/InTest.txt""; // read from a URL System.out.println(""readAll() from URL "" + urlName); System.out.println(""---------------------------------------------------------------------------""); try { in = new In(urlName); System.out.println(in.readAll()); } catch (Exception e) { System.out.println(e); } System.out.println(); // read one line at a time from URL System.out.println(""readLine() from URL "" + urlName); System.out.println(""---------------------------------------------------------------------------""); try { in = new In(urlName); while (!in.isEmpty()) { String s = in.readLine(); System.out.println(s); } } catch (Exception e) { System.out.println(e); } System.out.println(); // read one string at a time from URL System.out.println(""readString() from URL "" + urlName); System.out.println(""---------------------------------------------------------------------------""); try { in = new In(urlName); while (!in.isEmpty()) { String s = in.readString(); System.out.println(s); } } catch (Exception e) { System.out.println(e); } System.out.println(); // read one line at a time from file in current directory System.out.println(""readLine() from current directory""); System.out.println(""---------------------------------------------------------------------------""); try { in = new In(""./InTest.txt""); while (!in.isEmpty()) { String s = in.readLine(); System.out.println(s); } } catch (Exception e) { System.out.println(e); } System.out.println(); // read one line at a time from file using relative path System.out.println(""readLine() from relative path""); System.out.println(""---------------------------------------------------------------------------""); try { in = new In(""../stdlib/InTest.txt""); while (!in.isEmpty()) { String s = in.readLine(); System.out.println(s); } } catch (Exception e) { System.out.println(e); } System.out.println(); // read one char at a time System.out.println(""readChar() from file""); System.out.println(""---------------------------------------------------------------------------""); try { in = new In(""InTest.txt""); while (!in.isEmpty()) { char c = in.readChar(); System.out.print(c); } } catch (Exception e) { System.out.println(e); } System.out.println(); System.out.println(); // read one line at a time from absolute OS X / Linux path System.out.println(""readLine() from absolute OS X / Linux path""); System.out.println(""---------------------------------------------------------------------------""); in = new In(""/n/fs/csweb/introcs/stdlib/InTest.txt""); try { while (!in.isEmpty()) { String s = in.readLine(); System.out.println(s); } } catch (Exception e) { System.out.println(e); } System.out.println(); // read one line at a time from absolute Windows path System.out.println(""readLine() from absolute Windows path""); System.out.println(""---------------------------------------------------------------------------""); try { in = new In(""G:\\www\\introcs\\stdlib\\InTest.txt""); while (!in.isEmpty()) { String s = in.readLine(); System.out.println(s); } System.out.println(); } catch (Exception e) { System.out.println(e); } System.out.println(); } } " B11681,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package uk.co.epii.codejam.common; /** * * @author jim */ public abstract class AbstractProcessor implements Processor { public Output process(Input input) { int lines = Integer.parseInt(input.getHeader()[0]); String[] data = input.getData(); if (lines != data.length) throw new IllegalArgumentException(""There are a different number "" + ""of data lines to the number specified in the header""); String[] out = new String[lines]; for (int i = 0; i < lines; i++) { out[i] = processLine(data[i]); } return new Output(out); } } " B10072,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; public class e { private static class ABPair{ int A; int B; } static boolean isPerm(int m, int n){ boolean ret = false; for(int i = 0;i= margin) { best++; } } else if (c[j + 3] % 3 == 1 || c[j + 3] % 3 == 2) { if (((c[j + 3] / 3) + 1) >= margin) { best++; } } } } else { for (int j = 0, k = suprise; j < contestants; j++) { int remain = c[j + 3] % 3; int dv = c[j + 3] / 3; if (remain == 0) { if (dv >= margin) { best++; } else if (k > 0 && (dv + 1) >= margin && (dv + 1) <= c[j + 3]) { best++; k--; } } else if (remain == 1) { if (((dv) + 1) >= margin && (dv + 1) <= c[j + 3]) { best++; } } else if (remain == 2) { if (((dv) + 1) >= margin && (dv + 1) <= c[j + 3]) { best++; } else if (k > 0 && (dv + 2) >= margin && (dv + 1) <= c[j + 3]) { best++; k--; } } } } b.append("""" + best); b.newLine(); } b.flush(); a.close(); b.close(); } catch (Exception e) { e.printStackTrace(); } } }" B10557,"import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class B { public static void main(String args[]) throws FileNotFoundException{ //Scanner scanner = new Scanner(new FileInputStream(""input.in"")); Scanner scanner = new Scanner(System.in); int nt = scanner.nextInt(); scanner.nextLine(); //PrintWriter printWriter = new PrintWriter(new FileOutputStream(""output.out"")); PrintWriter printWriter = new PrintWriter(System.out); for (int i = 0; i < nt; i++) { printWriter.print(""Case #""+(i+1)+"": ""); printWriter.println(solveIt(scanner.nextLine())); } printWriter.close(); } private static String solveIt(String nextLine) { List list= new ArrayList(); int A = Integer.parseInt(nextLine.split("" "")[0]); int B = Integer.parseInt(nextLine.split("" "")[1]); int result = 0; for (int i = A; i < B; i++) { String k = """"+i; for (int j = 0; j < k.length()-1; j++) { String k1 = k.substring(k.length()-(j+1), k.length()) + k.substring(0,k.length()-(j+1)); if(Integer.parseInt(k1) > i && Integer.parseInt(k1) <= B){ if(!list.contains(i+""--""+k1)){ list.add(i+""--""+k1); result++; } } } } return result+""""; } } " B11676,"import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashSet; import java.util.List; import java.util.Set; public class Recycled { public static void main(String[] args) throws IOException { Path input = Paths.get(""/Users/mdymczyk/google-codejam/Tongues/src/input.in""); List lines = Files.readAllLines(input, Charset.forName(""UTF-8"")); lines.remove(0); int i = 1; for(String line : lines) { Set pairs = new HashSet(); StringBuilder sb = new StringBuilder(); sb.append(""Case #""+i+"": ""); int lower = Integer.parseInt(line.split("" "")[0]); int upper = Integer.parseInt(line.split("" "")[1]); int length = line.split("" "")[0].length(); for(int j = lower ; j <= upper ; j++) { for(int k = 1; k < length; k++) { int rearranged = rearrangeLastNDigits(j, k); if(rearranged != j && (rearranged >= lower && rearranged <= upper)){ pairs.add(new Pair(j, rearranged)); } } } sb.append(pairs.size()); System.out.println(sb); i++; } } private static int rearrangeLastNDigits(int j, int k) { String stringRepresentation = Integer.toString(j); String reordered = stringRepresentation.substring(k, stringRepresentation.length()) + stringRepresentation.substring(0, k); return Integer.parseInt(reordered); } } class Pair { int n, m; public Pair(int n, int m) { this.n = n; this.m = m; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * m*n; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (m != other.m && m != other.n) return false; if (n != other.n && n != other.m) return false; return true; } } " B13202,"package tr0llhoehle.cakemix.googleCodeJam.recycledNumbers; import java.io.IOException; import java.text.ParseException; import tr0llhoehle.cakemix.utility.googleCodeJam.IOManager; public class Main { /** * @param args */ public static void main(String[] args) { if (args.length >= 1) { IOManager io = new IOManager( new RNSolver(), (Class) new RNProblem().getClass()); try { io.start(args[0]); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } " B11937,"package com.google.codejam.util; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class CodeJamInputFile extends File { /** * */ private static final long serialVersionUID = 8294095294390757204L; private BufferedReader reader; private int cases; public CodeJamInputFile(String pathname) { super(pathname); try { this.setReader(); } catch (FileNotFoundException e) { } try { this.setCases(Integer.valueOf(this.getReader().readLine())); } catch (NumberFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private void setReader() throws FileNotFoundException { reader = new BufferedReader(new FileReader(this)); } public BufferedReader getReader() { return reader; } public void setCases(int cases) { this.cases = cases; } public int getCases() { return cases; } public void close() { try { reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String getLine() { String line = """"; try { line = reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return line; } } " B13199,"package tr0llhoehle.cakemix.utility.googleCodeJam; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.LinkedList; import java.util.Scanner; /** * {@link IOManager} is used to manage all input and output operations needed * for your java-solution of a Google codejam problem. * * It uses the class/interface {@link Problem} and {@link Solver}. * * @author Cakemix * * @param * The type of your concrete Solver-implementation which solves the * Problem P. * @param

* The type of your concrete Problem. * @see Problem * @see Solver */ public class IOManager, P extends Problem> { private S solver; private Class

clazz; private LinkedList

problems; /** * Creates a new IOManager. * * @param solver * The solver-instance which is to be used for solving the * problems. * @param clazz * A Class object of one exemplary concrete Problem P. This is * needed to correctly instantiate new concrete Problems. */ public IOManager(S solver, Class

clazz) { this.clazz = clazz; this.solver = solver; } private P createProblem() throws InstantiationException, IllegalAccessException { return clazz.newInstance(); } /** * Starts the IO-operations and solves the Problems contained in the file * pointed to by the filePath. * * @param filePath * A String describing the location of an input-file (usually * *.in) * @throws IOException * @throws ParseException */ public void start(String filePath) throws IOException, ParseException { int amountOfProblems; File out; Scanner lineScanner; File in = new File(filePath); Scanner scanner; FileWriter writer; System.out.print(""Creating files... ""); if (filePath.length() >= 3 && filePath.substring(filePath.length() - 3).equals("".in"")) { filePath = filePath.substring(0, filePath.length() - 3); } filePath += "".out""; out = new File(filePath); out.createNewFile(); System.out.println(""Done!""); System.out.print(""Creating file reader and writers... ""); scanner = new Scanner(in); writer = new FileWriter(out); System.out.println(""Done!""); System.out.print(""Parsing the input file... ""); amountOfProblems = scanner.nextInt(); scanner.nextLine(); problems = new LinkedList

(); for (int probID = 0; probID < amountOfProblems; probID++) { P problem = null; try { problem = createProblem(); SupportedTypes[] probTypes = problem.getTypes(); for (SupportedTypes t : probTypes) { switch (t) { case INT: lineScanner = new Scanner(scanner.nextLine()); problem.addValue(lineScanner.nextInt()); break; case DOUBLE: lineScanner = new Scanner(scanner.nextLine()); problem.addValue(lineScanner.nextDouble()); break; case BOOLEAN: lineScanner = new Scanner(scanner.nextLine()); problem.addValue(lineScanner.nextBoolean()); break; case STRING: problem.addValue(scanner.nextLine()); break; case LIST_INT: lineScanner = new Scanner(scanner.nextLine()); ArrayList ints = new ArrayList(); while (lineScanner.hasNext()) { ints.add(lineScanner.nextInt()); } problem.addValue(ints); break; case LIST_DOUBLE: lineScanner = new Scanner(scanner.nextLine()); ArrayList doubles = new ArrayList(); while (lineScanner.hasNext()) { doubles.add(lineScanner.nextDouble()); } problem.addValue(doubles); break; case LIST_BOOLEAN: lineScanner = new Scanner(scanner.nextLine()); ArrayList booleans = new ArrayList(); while (lineScanner.hasNext()) { booleans.add(lineScanner.nextBoolean()); } problem.addValue(booleans); break; case LIST_STRING: lineScanner = new Scanner(scanner.nextLine()); ArrayList strings = new ArrayList(); while (lineScanner.hasNext()) { strings.add(lineScanner.next()); } problem.addValue(strings); break; default: System.err .print(""Default case! This is not a good sign... ""); } } } catch (IllegalAccessException e) { System.err.println(""Couldn't instantiate the problem!""); e.printStackTrace(); } catch (InstantiationException e) { System.err.println(""Couldn't instantiate the problem!""); // TODO Auto-generated catch block e.printStackTrace(); } if (problem != null) { problems.add(problem); } } System.out.println(""Done!""); System.out.print(""Closing the input file... ""); scanner.close(); System.out.println(""Done!""); System.out.print(""Solving the problems... ""); for (int i = 0; i < problems.size(); i++) { writer.append(""Case #"" + (i+1) + "": "" + solver.solve(problems.get(i)) + System.getProperty(""line.separator"")); } System.out.println(""Done!""); System.out.print(""Closing the writer... ""); writer.close(); System.out.println(""Done!""); System.out.println(""Shutting down, output lies here:""); System.out.println(filePath); } } " B10833,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.StringTokenizer; public class ProblemC { /** * @param args * @throws IOException * @throws NumberFormatException */ public static void main(String[] args) throws NumberFormatException, IOException { FileReader fileread = new FileReader(""C-small-attempt0.in""); FileWriter filewrite = new FileWriter(""C-small-attempt0.out""); BufferedReader in = new BufferedReader(fileread); int cases = Integer.parseInt(in.readLine()), mycase = 0; StringTokenizer s; while(cases-- > 0) { int A, B, count = 0; s = new StringTokenizer(in.readLine()); A = Integer.parseInt(s.nextToken()); B = Integer.parseInt(s.nextToken()); for(int i = A; i < B; i++) { for(int j = i + 1; j <= B; j++) { String str = i + """"; for(int c = 0; c < str.length(); c++) { String x = str.substring(c); String y = str.substring(0, c); String res = x + y; if(Integer.parseInt(res) == j) { count++; break; } } } } filewrite.write(""Case #"" + ++mycase + "": "" + count + ""\n""); } filewrite.close(); } } " B11563,"package codejam.is; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; /** * Created with IntelliJ IDEA. * User: ofer * Date: 4/13/12 * Time: 8:53 PM * To change this template use File | Settings | File Templates. */ public class TestRunner { public void runTests(String inputFilePath, String outputFilePath, Class testClass) { try { BufferedReader br = new BufferedReader(new FileReader(inputFilePath)); int numOfTests = Integer.parseInt(br.readLine()); Test[] tests = new Test[numOfTests]; for (int i = 0; i < numOfTests; i++) { tests[i] = (Test)testClass.newInstance(); tests[i].run(br.readLine()); } br.close(); BufferedWriter bw = new BufferedWriter(new FileWriter(outputFilePath)); for (int i = 0; i < numOfTests; i++) { bw.write(tests[i].getOutput(i+1)); } bw.close(); } catch (Exception e) { System.out.println(""Caught exception: "" + e); e.printStackTrace(); } } } " B10177,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.*; /** * @author rohitkg */ public class Task implements Runnable { private static final String TASK_ID = ""C-small-attempt0""; private static final String IN_FILE = TASK_ID + "".in""; private static final String OUT_FILE = TASK_ID + "".out""; private Scanner in; private PrintWriter out; int n,i,t,A,B; int res; private void init() { try { in = new Scanner(new File(IN_FILE)); } catch (FileNotFoundException ignored) {} try { out = new PrintWriter(OUT_FILE); } catch (FileNotFoundException ignored) {} n = in.nextInt(); } private void read() { A=in.nextInt(); B=in.nextInt(); } private void solve() { res=0; if(A<10) return; HashSet set=new HashSet(); for(int i=A;i<=B;i++){ String num ="""" + i; int length=num.length(); for(int pos=1;pos<=length;pos++){ String recNum=num.substring(pos) + num.substring(0,pos); int recInt=Integer.parseInt(recNum); if(recInt>i && recInt<= B){ //res++; if(!(set.contains(i + "", "" +recInt) || set.contains(recInt + "", "" + i))){ set.add(i + "", "" +recInt); } // System.out.println(i + "", "" +recInt); //else //out.println(""Pairs : "" + i + "", "" + recInt); } } } res=set.size(); } private void write() { out.println(""Case #"" + t + "": "" + res); } public void run() { init(); for (t = 1; t <= n; t++) { read(); solve(); write(); } out.close(); } public static void main(String[] args) { new Thread(new Task()).start(); } } " B11630,"import java.util.ArrayList; import java.util.Scanner; public class DancingWithTheGooglers { public static void main(String[] args){ Scanner keyin=new Scanner(System.in); int T=keyin.nextInt(); keyin.nextLine(); int caseCount=0; while ((T--)!=0){ int A=keyin.nextInt(); int B=keyin.nextInt(); int count=0; caseCount++; ArrayList result=new ArrayList(); for (int n=A; n<=B; n++){ for (int m=n+1; m<=B; m++){ String strN=Integer.toString(n); String strM=Integer.toString(m); for (int i=1; i=1;k--) { String tmp1=tmp.substring(k)+tmp.substring(0,k); if(tmp1.charAt(0)=='0') continue; int t1=Integer.parseInt(tmp1); if(t1>j && t1>=a && t1<=b) { int flag=0; for(int kk=0;kk1) for(int j=1;j pairedNumbers = new HashMap(); for (int i = 1; i < d; i++) { int subIndex = d - i; if (currentNumber.charAt(subIndex) == '0') { continue; } String newNumber = currentNumber.substring(subIndex) + currentNumber.substring(0, subIndex); if (pairedNumbers.containsKey(newNumber)) { continue; } long m = Long.valueOf(newNumber); if (m <= n || m > B) { continue; } pairedNumbers.put(newNumber, ""Y""); pairCount++; } } return String.valueOf(pairCount); } } " B12017,"import java.util.ArrayList; import java.util.List; public class RecyclePair { private static boolean IsRecycle(int a, int n, int m, int b, List pairs, String pair){ return a <= n && n < m && m <= b && !pairs.contains(pair); } public static int Calculate(int a, int b){ int count = 0; List pairs = new ArrayList(); for(int n=a;n<=b;n++){ for(int j=1;j number) { count++; } } } private int nextRecycled(int i, int exp) { int r = i % 10; i = (i - r) / 10; i += r * exp; return i; } } } " B13188,"package proba; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class ProblemC { private static Set list; /** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { Scanner s = new Scanner(new FileInputStream(""C-small-attempt0.in"")); int cases = s.nextInt(); s.nextLine(); for (int i = 0; i < cases; i++) { int A = s.nextInt(); int B = s.nextInt(); Set set = new HashSet(); if (s.hasNextLine()) s.nextLine(); for(int j=A;j<= B;j++) { String string = String.valueOf(j); char[] arr = string.toCharArray(); for (int k = 1; k < arr.length; k++) { StringBuilder sb = new StringBuilder(); String sub = string.substring(arr.length - k); String sub1 = string.substring(0,arr.length -k); sb.append(sub); sb.append(sub1); int num = Integer.valueOf(sb.toString()); if (j < num && num <= B) { MN mn = new MN(j,num); set.add(mn); } } } System.out.println(""Case #"" + (i + 1) + "": "" + set.size()); } } private static class MN { int m; int n; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + m; result = prime * result + n; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MN other = (MN) obj; if (m != other.m) return false; if (n != other.n) return false; return true; } public MN(int m, int n) { super(); this.m = m; this.n = n; } public int getM() { return m; } public void setM(int m) { this.m = m; } public int getN() { return n; } public void setN(int n) { this.n = n; } } } " B10907,"import java.io.*; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class NumberMagic { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader in = new BufferedReader(new FileReader(""input.small"")); int cases = Integer.parseInt(in.readLine()); String [] tests = new String[cases]; Set set = new HashSet(); for(int i=0;i numbers = new ArrayList(); String inp1, inp2; for (int i=n;i<=m;++i){ inp1 = String.valueOf(i); for (int j=inp1.length()-1; j>0;--j){ if('0' != inp1.charAt(j) ){ inp2=inp1.substring(j)+inp1.substring(0, j); num2= Integer.parseInt(inp2); if (m >=num2 && n<=num2&& i != num2 && !numbers.contains(new Pair(i, num2))){ numbers.add(new Pair(i, num2)); //System.out.println(new Pair(i, num2)); ++result; } } } } /*Pair p1, p2; List list = new ArrayList(); boolean found=false; for (int i=0 ; i< numbers.size();++i){ p1 = numbers.get(i); found=false; for (int j=0; j< list.size();++j){ p2=list.get(j); if (p1.n== p2.n && p1.m == p2.m){ found=true; break; } } if(!found){ list.add(p1); } } System.out.println(list); System.out.println(list.size());*/ //System.out.println(numbers); //System.out.println(numbers.size()); //for (int i=0; i< ) return result; } static int process (int n, int m){ System.out.println(""\n\n\nn: ""+n+""\tm: ""+m); int result=0, num2; List numbers = new ArrayList(); List pos; List nums = new ArrayList(); List temp = new ArrayList(); char firstChar; String inp1, inp2; for (int i=n;i<=m;++i){ inp1 = String.valueOf(i); if ( ! nums.contains(inp1)){ firstChar=inp1.charAt(0); temp = new ArrayList(); for (int j=inp1.length()-1; j>0;--j){ if('0' != inp1.charAt(j) && inp1.charAt(j)>=firstChar){ inp2=inp1.substring(j)+inp1.substring(0, j); num2= Integer.parseInt(inp2); if (m > num2 && n< num2 && i != num2 && !numbers.contains(new Pair(i, num2))){ nums.add(inp2); temp.add(inp2); System.out.print(new Pair(i, num2)); ++result; } } } if(2<= temp.size()){ result+=((temp.size()-1)*(temp.size()))/2; System.out.println(""Added : ""+((temp.size()-1)*(temp.size()))/2); } }else{ nums.remove(inp1); } /*pos = getTheLeastPosition(inp1); for ( int j=0;j< pos.size();++j){ inp2 = inp1.substring(pos.get(j))+inp1.substring(0, pos.get(j)); num2= Integer.parseInt(inp2); if(i != num2 && m >= num2){ numbers.add(new Pair(i, num2)); System.out.println(new Pair(i, num2)); ++result; } }*/ } return result; } static List getTheLeastPosition(String inp){ List pos= new ArrayList(); int ps=0; char base = inp.charAt(0); boolean passedBase=false; for (int i=base-48;i<=9;++i, ++base){ if ( -1 != (ps = inp.indexOf(base))){ if (passedBase){ pos.add(ps); break; } pos.add(ps); while (0 != ps &&-1 != (ps = inp.indexOf(base, ps+1))){ passedBase=true; pos.add(ps); } } } if (-1 != ps){ while (-1 != (ps = inp.indexOf(base, ps+1))){ pos.add(ps); } } return pos; } static class Pair implements Comparable{ int n, m; public Pair() { super(); // TODO Auto-generated constructor stub } public Pair(int n, int m) { super(); if ( n < m){ this.n = n; this.m = m; }else{ this.n = m; this.m = n; } } public int getN() { return n; } public void setN(int n) { this.n = n; } public int getM() { return m; } public void setM(int m) { this.m = m; } @Override public String toString() { return ""\nPair [n="" + n + "", m="" + m + ""]""; } @Override public boolean equals(Object arg0) { Pair p = (Pair)arg0; if ((n == p.n && m == p.m ) || (n == p.m && m== p.n)){ //System.out.println(""Equals""); return true; } return false; } @Override public int compareTo(Pair o) { if ((n == o.n && m == o.m ) || (n == o.m && m== o.n)){ return 0; }else if(n < o.n ){ return -1; }else { return 1; } } } } " B11606,"import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class GoogleRecycler { public static void main(String args[]) throws IOException{ Scanner scan = new Scanner(System.in); PrintWriter print = new PrintWriter(new FileWriter(""GoogleRecycler.out"")); Integer cases = Integer.parseInt(scan.nextLine()); for(int i=0; i s = new HashSet(); for (int m = from; m <= to; m++) { for (int p : convertedNumbers(m)) { if (p > m && p <= to) { if (s.contains(m + "" "" + p)) { System.out.println(m + "" "" + p + "" "" + from + "" "" + to); } s.add(m + "" "" + p); res++; } } } return res; } public Set convertedNumbers(int original) { int digits = (int) Math.ceil(Math.log10(original)); if (digits < 1) { return new HashSet(); } int pow = (int) Math.pow(10, digits - 1); int l = pow; int s = 10; Set res = new HashSet(); for (int i = 0; i < digits - 1; i++) { if (original % s != 0) { int x = (original % s) * pow + original / s; if (x != original && x > l) { res.add(x); } } s *= 10; pow /= 10; } return res; } } " B13262,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class Main { private static int T = 0; public static BufferedReader bufReader; public static BufferedWriter bufWriter; public static File wFile, rFile; private static int tMinLimit = 1; private static int tMaxLimit = 50; private static String rFilename = ""C-small-attempt0.in""; private static String wFilename = ""OUTPUT0.txt""; /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub rFile = new File(rFilename); bufReader = new BufferedReader(new InputStreamReader( new FileInputStream(rFile), ""utf8"")); wFile = new File(wFilename);// «Ø¥ßÀɮסA·Ç³Æ¼gÀÉ bufWriter = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(wFile, false), ""utf8"")); T = Integer.valueOf(bufReader.readLine().trim()); if (tMinLimit <= T && T <= tMaxLimit) { for (int i = 1; i <= T; i++) { String[] AB = bufReader.readLine().split("" ""); new Round1C(i, Integer.parseInt(AB[0]), Integer.parseInt(AB[1])); } } bufWriter.close(); } }" B10908," import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; class Main { static int p[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; static int length(int n) { int ans = 0; while (n > 0) { ++ans; n /= 10; } return ans; } static int rotate(int n, int len) { int d = n % 10; n /= 10; n = p[len - 1] * d + n; return n; } static void redirect() throws FileNotFoundException { System.setIn(new FileInputStream(""c.in"")); System.setOut(new PrintStream(""c.out"")); } public static void main(String[] args) throws FileNotFoundException { redirect(); Scanner in = new Scanner(System.in); int tc; tc = in.nextInt(); for (int t = 1; t <= tc; t++) { int a, b, n, x, y; a = in.nextInt(); b = in.nextInt(); Set s = new TreeSet(); int ans ; int len = length(a); for (int i = a; i <= b; i++) { n = i; if (i == p[len]) len++; while (true) { n = rotate(n, len); if (n == i) break; if (a <= n && n <= b) { x = i; y = n; if (x > y) { int tmp = x; x = y; y = tmp; } s.add(new Pair(x, y)); } } } ans = s.size(); System.out.printf(""Case #%d: %d\n"", t, ans); } } } class Pair implements Comparable { int x,y; public Pair(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Pair p) { if (x != p.x) return x - p.x; else return y - p.y; } } " B11989,"import java.io.*; import java.util.*; import java.awt.Point; class Case{ int num0; long num1,num2; String result=""""; public Case(File aFile) { try{ StringBuilder contents = new StringBuilder(); BufferedReader input = new BufferedReader(new FileReader(aFile)); String line = input.readLine(); num0 = Integer.valueOf(line).intValue(); int i=1; while (i<=num0 && ( line = input.readLine()) != null){ StringTokenizer st = new StringTokenizer(line,"" ""); num1=Long.valueOf(st.nextToken()).longValue(); num2=Long.valueOf(st.nextToken()).longValue(); oneCase(i,num1,num2); i++; } } catch (IOException ex){ ex.printStackTrace(); } } public String getResult (){ return result; } public void oneCase (int c,long n1,long n2){ String re=""""; //*** output System.out.println(""case=""+c+"": ""+n1+"":""+n2); //*** int y=0; for (long i=n1; i<=n2; i++){ y+=checkRecycle(n1,n2,i); } re=y+""""; result+=""Case #""+c+"": ""+re+System.getProperty(""line.separator""); } public int checkRecycle (long n1, long n2, long num){ String numSt=Long.valueOf(num).toString(); if (numSt.length()<2) return 0; int re=0; Vector allNum=new Vector(); for (int i=1; inum){ if (Long.valueOf(newNumSt).longValue()>n1 && Long.valueOf(newNumSt).longValue()<=n2){ boolean found=false; for (int j=0;!found&&j0)System.out.println(""checkRecycle ""+numSt+"" re=""+re+"" allNum=""+allNum); return re; } } public class ReadWriteTextFile { static public String getContents(File aFile) { StringBuilder contents = new StringBuilder(); try { BufferedReader input = new BufferedReader(new FileReader(aFile)); try { String line = null; while (( line = input.readLine()) != null){ contents.append(line); contents.append(System.getProperty(""line.separator"")); } } finally { input.close(); } } catch (IOException ex){ ex.printStackTrace(); } return contents.toString(); } static public void setContents(File aFile, String aContents) throws FileNotFoundException, IOException { if (aFile == null) { throw new IllegalArgumentException(""File should not be null.""); } if (!aFile.exists()) { throw new FileNotFoundException (""File does not exist: "" + aFile); } if (!aFile.isFile()) { throw new IllegalArgumentException(""Should not be a directory: "" + aFile); } if (!aFile.canWrite()) { throw new IllegalArgumentException(""File cannot be written: "" + aFile); } Writer output = new BufferedWriter(new FileWriter(aFile)); try { output.write( aContents ); } finally { output.close(); } } public static void main (String... aArguments) throws IOException { File testFile = new File(""source.txt""); File testFile2 = new File(""result.txt""); Case allcases = new Case(testFile); setContents(testFile2, allcases.getResult()); } } " B10794,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class RecycledNumbers { private BufferedReader reader; private BufferedWriter writer; /** * @param args */ public static void main(String[] args) { RecycledNumbers rn = new RecycledNumbers(args[0]); rn.executeTests(); } public RecycledNumbers(String filename) { // Open file File file = new File(filename); try { reader = new BufferedReader(new FileReader(file)); writer = new BufferedWriter(new FileWriter(file+"".out"")); } catch (IOException e) { // Failed to open new buffered reader System.err.println(""Failed to open FileReader""); e.printStackTrace(); System.exit(-1); } } private void executeTests() { // Read number of test cases int numberOfTests = 0; try { // Read number of tests (first line) numberOfTests = Integer.parseInt(reader.readLine()); } catch (NumberFormatException | IOException e) { // Failed to read a line System.err.println(""Failed to read a line""); e.printStackTrace(); System.exit(-1); } for (int testCase = 1; testCase <= numberOfTests; testCase++) { String[] input; try { input = reader.readLine().split(""\\s""); int min = Integer.parseInt(input[0]); int max = Integer.parseInt(input[1]); List scores = new ArrayList(); int answer = totalRecycledPairs(min, max); writer.write(""Case #"" + testCase + "": "" + answer + '\n'); } catch (IOException e) { e.printStackTrace(); } } try { reader.close(); writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } private static int totalRecycledPairs(int min, int max) { // Number -> Unique Pair Count Map uniquePairCount = new HashMap(); int total = 0; for (int number = min; number <= max; number++) { int count = 0; for (Integer recycled : getRecycledPairs(number)) { if (!uniquePairCount.containsKey(recycled) && recycled <= max && recycled >= min) { count++; } } uniquePairCount.put(number, count); total += count; } return total; } private static Set getRecycledPairs(int number) { Set pairs = new HashSet(); String numberString = String.valueOf(number); for (int i = 1; i < numberString.length(); i++) { String rcirc = numberString.substring(numberString.length() - i) + numberString.substring(0, numberString.length() - i); int pair = Integer.parseInt(rcirc); if (numberString.length() == String.valueOf(pair).length() && pair != number) { pairs.add(Integer.parseInt(rcirc)); } } return pairs; } } " B13042,"import java.io.*; class Recycle{ public static void main(String arg[])throws Exception { File f=new File(""C-small-attempt0.in""); FileInputStream fin=new FileInputStream(f); File f2=new File(""bo.txt""); FileOutputStream fout=new FileOutputStream(f2); BufferedWriter bwr=new BufferedWriter(new OutputStreamWriter(fout)); BufferedReader br=new BufferedReader(new InputStreamReader(fin)); String g=""""; int ipn=Integer.parseInt(br.readLine()); int ipni=1; int a,b; String e=""""; int n,m; while(--ipn >=0) { int count=0; g=br.readLine(); a=Integer.parseInt(g.substring(0,g.indexOf("" "")) ); b=Integer.parseInt( g.substring(g.indexOf("" "")+1,g.length())) ; for(int i=a;i<=b;i++) { n=i; for(int j=0 ; j<(i+"""").length()-1; j++) { m=shift(n); if(m>-1) if(i String join(Iterable list, String delim) { if (list == null) return null; StringBuilder buf = new StringBuilder(); int idx = 0; for (T item : list) { if (idx++ > 0) buf.append(delim); buf.append(item.toString()); } return buf.toString(); } public static String join(Iterable list, String delim, Lambda customToString) { if (list == null) return null; StringBuilder buf = new StringBuilder(); int idx = 0; for (T item : list) { if (idx++ > 0) buf.append(delim); buf.append(customToString.apply(item)); } return buf.toString(); } public static String join(T[] array, String delim) { if (array == null) return null; StringBuilder buf = new StringBuilder(); for (int i = 0, n = array.length; i < n; i++) { if (i > 0) buf.append(delim); buf.append(array[i].toString()); } return buf.toString(); } public static String join(int[] array, String delim) { if (array == null) return null; StringBuilder buf = new StringBuilder(); for (int i = 0, n = array.length; i < n; i++) { if (i > 0) buf.append(delim); buf.append(array[i]); } return buf.toString(); } public static String join(float[] array, String delim) { if (array == null) return null; StringBuilder buf = new StringBuilder(); for (int i = 0, n = array.length; i < n; i++) { if (i > 0) buf.append(delim); buf.append(array[i]); } return buf.toString(); } public static String join(double[] array, String delim) { if (array == null) return null; StringBuilder buf = new StringBuilder(); for (int i = 0, n = array.length; i < n; i++) { if (i > 0) buf.append(delim); buf.append(array[i]); } return buf.toString(); } public static String join(char[] array, String delim) { if (array == null) return null; StringBuilder buf = new StringBuilder(); for (int i = 0, n = array.length; i < n; i++) { if (i > 0) buf.append(delim); buf.append(array[i]); } return buf.toString(); } public static String join(Iterable list) { return join(list, """"); } public static String join(T[] array) { return join(array, """"); } public static String join(Iterable list, String delim, String prefix, String suffix) { return prefix + join(list, """") + suffix; } public static String join(T[] array, String prefix, String suffix) { return prefix + join(array, """") + suffix; } /** Recursively join an Iterable that may optionally consist of Iterables. If the items within the Iterable are of type Entry, they are joined as ""key : value"". If value is an Iterable, it is recursed upon. */ @SuppressWarnings(""rawtypes"") public static String joinRecursive(Iterable iterable, String delim, String prefix, String suffix) { if (iterable == null) return null; StringBuilder buf = new StringBuilder(); buf.append(prefix); int idx = 0; for (Object item : iterable) { if (idx++ > 0) buf.append(delim); if (item instanceof Iterable) { buf.append(joinRecursive((Iterable) item, delim, prefix, suffix)); } else if (item instanceof Entry) { Entry ent = (Entry) item; buf.append(ent.getKey().toString()); buf.append("" : ""); Object val = ent.getValue(); if (val instanceof Iterable) buf.append(joinRecursive((Iterable) val, delim, prefix, suffix)); else buf.append(val.toString()); } else { buf.append(item.toString()); } } buf.append(suffix); return buf.toString(); } /** Join a map and recursively join values in the map */ public static String joinRecursive(Map map, String delim, String prefix, String suffix) { return joinRecursive(map.entrySet(), delim, prefix, suffix); } } " B11869,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.StringTokenizer; public class RecycledNumbers { static BufferedReader br; static PrintWriter pw; static HashMap map; public static void main(String args[])throws IOException { initFiles(); readFiles(); } private static void readFiles()throws IOException { int n = Integer.parseInt(br.readLine()); for(int i=1; i<=n; i++) { StringTokenizer tokens = new StringTokenizer(br.readLine()); int A = Integer.parseInt(tokens.nextToken()); int B = Integer.parseInt(tokens.nextToken()); int count = findPairs(A, B); pw.println(""Case #"" + i + "": "" + count); } pw.close(); br.close(); } private static int findPairs(int A, int B) { map = new HashMap(); int numRecycleables = 0; for(int i = A; i <= B; i++) { numRecycleables += getNumRecycled(i, B); } return map.size(); } private static int getNumRecycled(int n, int B) { String nStr = """" + n; int count = 0; for(int i = 1; i < nStr.length(); i++) { String mStr = nStr.substring(i) + nStr.substring(0, i); int m = Integer.parseInt(mStr); if(m > n && m <= B) { System.out.println(n + ""--> "" + m); map.put(nStr + mStr, true); count++; } } return count; } private static void initFiles()throws IOException { br = new BufferedReader(new FileReader(""C-small-attempt0.in"")); pw = new PrintWriter(new FileWriter(""Recycle.out"")); } } " B12378,"import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintWriter; import java.util.Scanner; public class Recycled { /** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { // TODO Auto-generated method stub Scanner s = new Scanner(new File(""C:\\Users\\Owner\\Desktop\\a-small.in"")); FileOutputStream fos = new FileOutputStream(""C:\\Users\\Owner\\Desktop\\a-small.out""); PrintWriter pw = new PrintWriter(fos); int testCases = s.nextInt(); s.nextLine(); for(int i = 0; i < testCases; ++i){ int n = s.nextInt(); int m = s.nextInt(); int result = 0; pw.print(""Case #"" + (i + 1) +"": ""); String nstr ; String mstr ; String temp; for(int k = m; k > n; --k){ mstr = k + """"; for(int p = n; p < m && p < k; p++){ nstr = """" + p; for(int q = 0; q < mstr.length(); ++q){ temp = mstr.substring(0,mstr.length() - 1); mstr = mstr.charAt(mstr.length() - 1) + temp; if(mstr.equals(nstr)){ result++; break; } } } } pw.print(result); if(i != testCases - 1) pw.println(); } pw.close(); s.close(); } } " B10092,"import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { final long MAX = 2000000; try { Scanner in = new Scanner(new FileReader(""input.in"")); PrintWriter out = new PrintWriter(""output.out""); int N=in.nextInt(); int[][] count=new int[10][(int)MAX]; List input = new ArrayList(); long A, B; String tmp, compA, compB, subA1, subA2, subA, prevK="""", prevL=""""; char check; int index=0, same=0, strlength; for(int i=0;i= A){ if(n == run); else{ count++; } } } } System.out.print(""Case #"" + (t+1) + "": "" + (count/2)+""\n""); result += ""Case #"" + (t+1) + "": "" + (count/2)+""\n""; } output.write(result); output.close(); } } " B12809,"import java.io.File; import java.io.PrintWriter; import java.util.HashSet; import java.util.Locale; import java.util.Scanner; import java.util.Set; public class C { final static String PREFIX = ""C:\\codejam\\C""; // final static String FILE_NAME = PREFIX + ""-test""; final static String FILE_NAME = PREFIX + ""-small-attempt0""; // final static String FILE_NAME = PREFIX + ""-large""; private Scanner in; private PrintWriter out; public static void main(String[] args) throws Exception { Locale.setDefault(Locale.US); new C().solveAll(); } private void solveAll() throws Exception { in = new Scanner(new File(FILE_NAME + "".in"")); out = new PrintWriter(new File(FILE_NAME + "".out"")); int tcn = in.nextInt(); for (int tc = 1; tc <= tcn; tc++) { solve(tc); } out.close(); } private void solve(int tc) { int a = in.nextInt(); int b = in.nextInt(); long res = 0; for (int i = a; i <= b; i++) { String is = String.valueOf(i); Set set = new HashSet(); for (int j = 1; j < is.length(); j++) { String x = is.substring(j) + is.substring(0, j); if (x.startsWith(""0"")) { continue; } int c = Integer.parseInt(x); if (c > i && c <= b) { set.add(c); } } res += set.size(); } out.format(""Case #%d: %s\n"", tc, res); System.out.format(""Case #%d: %s\n"", tc, res); } } " B12774," public class UniqueList { private int[] number; private int totalSize, size; public UniqueList(int allocatedSize) { totalSize = allocatedSize; number = new int[totalSize]; size = 0; } public void add(int n) { for (int i = 0; i < size; i++) { if (number[i] == n) return; } number[size ++] = n; } public int getSize() { return size; } } " B10097,"package se.round1.problem3; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import se.round1.util.JamUtil; public class Problem3 { Map trans = new HashMap(); public static void main(String[] args) throws IOException{ new Problem3(); } public Problem3() throws IOException{ BufferedReader reader = JamUtil.getReader(""problem3/C-small-attempt0.in""); int currCase = 0; int nrOfCases = Integer.parseInt(reader.readLine()); String s = """"; System.out.println("">>>>>>>>""+nrOfCases); BufferedWriter writer = JamUtil.getWriter(""problem3/output.txt""); while((s = reader.readLine()) != null){ currCase++; int res = solveLine(s); String sol = ""Case #""+currCase+"": ""+res+""\n""; System.out.println(res); writer.write(sol); } writer.close(); System.out.println(""done.""); } private int solveLine(String line){ int start = Integer.parseInt(line.split("" "")[0]); int stop = Integer.parseInt(line.split("" "")[1]); Map> map = buildMap(start, stop); int sum = 0; int rotCount = 0; for(int i=start;i<=stop;++i){ String curr = Integer.toString(i); sum = 0; char[] charArray = curr.toCharArray(); for(char c : charArray) sum += c; if(map.get(sum).size() > 1) rotCount += rotTryArr(curr, map.get(sum)); } return rotCount/2; } private int rotTryArr(String target, List list){ int count = 0; for(String s : list){ if(isSameString(s, target)){ count++; } } return count; } private boolean isSameString(String s1, String s2){ if(s1.equals(s2)) return false; char[] cs1 = s1.toCharArray(); char[] cs2 = s2.toCharArray(); if(cs1.length != cs2.length) return false; for(int i=0;i> buildMap(int start, int stop){ HashMap> m = new HashMap>(); for(int i=start;i<=stop;++i){ String curr = Integer.toString(i); int sum = 0; char[] charArray = curr.toCharArray(); for(char c : charArray) sum += c; if(m.containsKey(sum)){ m.get(sum).add(curr); } else{ List s = new ArrayList(); s.add(curr); m.put(sum, s); } } return m; } } " B10077,"package jamo; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class RecycledNumbers { public static void main(String[] args) { List lines = readFromFile(""rnumbers.txt""); int number = Integer.parseInt(lines.get(0)); int a = 0; int b = 0; for (int i = 1; i <= number; i++) { String[] a_b = lines.get(i).split("" ""); a = Integer.parseInt(a_b[0]); b = Integer.parseInt(a_b[1]); System.out.println( ""Case #""+i+"": ""+checkPair(a, b)); } } public static int sumOfDigits(Integer number) { int sum = 0; String n = number.toString(); char[] digits = n.toCharArray(); for (int i = 0; i < digits.length; i++) { sum += Integer.parseInt(Character.toString(digits[i])); } return sum; } public static boolean same(String a, String b) { char[] _a = a.toCharArray(); char[] _b = b.toCharArray(); if (_a.length != _b.length) { return false; } Arrays.sort(_a); Arrays.sort(_b); String a_ = new String(_a); String b_ = new String(_b); return a_.equals(b_); } public static List iterations(Integer a) { char[] a_ = a.toString().toCharArray(); List out = new ArrayList(); String start = new String(a_); for (int i = 0; i < a_.length; i++) { if (out.contains(Integer.parseInt(start))) { } else { out.add(Integer.parseInt(start)); start = next(start); } } return out; } public static String next(String val) { char[] a_ = val.toCharArray(); char[] x = new char[a_.length]; for (int i = 1; i < a_.length; i++) { x[i - 1] = a_[i]; } x[a_.length - 1] = a_[0]; return new String(x); } public static int nextPair(Integer a) { char[] a_ = a.toString().toCharArray(); char[] x = new char[a_.length]; for (int i = 1; i < a_.length; i++) { x[i - 1] = a_[i]; } x[a_.length - 1] = a_[0]; return Integer.parseInt(new String(x)); } public static int checkPair(int a, int b) { int pairs = 0; int previ = 0; int prevnext = 0; int next = 0; if (b < 10) return 0; for (int i = a; i <= b; i++) { List its = iterations(i); for (int j = 0; j < its.size(); j++) { next = its.get(j); if (next <= b && next > i) { pairs += 1; } prevnext = next; } previ = i; } return pairs; } public static List readFromFile(String filename) { List lines = new ArrayList(); try { FileInputStream fstream = new FileInputStream(filename); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { lines.add(strLine); // System.out.println(strLine); } in.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } return lines; } } " B12373,"package codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.FilenameFilter; import java.math.BigInteger; import java.util.HashSet; import java.util.Set; public class Codejam { private static File[] getInputFiles(String filePath) { File dir = new File(filePath); // filter .in files FilenameFilter onlyInFiles = new FilenameFilter() { public boolean accept(File file, String name) { return name.endsWith("".in"") || file.isFile(); } }; File[] inputFiles = dir.listFiles(onlyInFiles); return inputFiles; } private static BigInteger binomial(final int N, final int K) { BigInteger ret = BigInteger.ONE; for (int k = 0; k < K; k++) { ret = ret.multiply(BigInteger.valueOf(N - k)).divide( BigInteger.valueOf(k + 1)); } return ret; } private static Set getCombinations(String numberStr, int min, int max) { // System.out.println(""numberStr "" + numberStr); Set allStrings = new HashSet(); char[] numberStrChars = numberStr.toCharArray(); String currentNumber; int StrLength = numberStrChars.length; // System.out.println(""StrLength "" + StrLength); for (int i = 0; i < StrLength - 1; i++) { char firstChar = numberStrChars[0]; for (int j = 1; j < StrLength; j++) numberStrChars[j - 1] = numberStrChars[j]; numberStrChars[StrLength - 1] = firstChar; currentNumber = new String(numberStrChars); // System.out.println(""currentNumber "" + currentNumber); if (!currentNumber.equals(numberStr) && Integer.parseInt(currentNumber) >= min && Integer.parseInt(currentNumber) <= max) allStrings.add(currentNumber); } return allStrings; } private static BigInteger getRecycledPairs(int min, int max) { //System.out.println(""getRecycledPairs start""); BigInteger recycledPairs = BigInteger.ZERO; Set recycledPairStrings = new HashSet(); for (int i = min; i <= max; i++) { String currentNumber = Integer.toString(i); if (!recycledPairStrings.contains(currentNumber)) { Set currentCombinations = getCombinations( currentNumber, min, max); if (currentCombinations.size() > 0) { recycledPairStrings.addAll(currentCombinations); recycledPairs = recycledPairs.add(binomial( currentCombinations.size() + 1, 2)); } } } //System.out.println(""getRecycledPairs end "" + recycledPairs); return recycledPairs; } private static void processFile(File fileName) { System.out.println(""Processing file "" + fileName); try { // get reader for current file BufferedReader br = new BufferedReader(new FileReader(fileName)); // create writer using current file + .out BufferedWriter bw = new BufferedWriter(new FileWriter( fileName.getAbsolutePath() + "".out"")); // get test cases int testCases = Integer.parseInt(br.readLine()); // process all test cases for (int currTestCase = 1; currTestCase <= testCases; currTestCase++) { String[] ab = br.readLine().split("" ""); int A = Integer.parseInt(ab[0]), B = Integer.parseInt(ab[1]); BigInteger result = getRecycledPairs(A, B); String currTestCaseResult = ""Case #"" + currTestCase + "": "" + result; System.out.println(currTestCaseResult); bw.write(currTestCaseResult); bw.newLine(); } // close the reader and writer br.close(); bw.flush(); bw.close(); } catch (Exception e) {// catch exception if any System.err.println(""Error: "" + e.getMessage()); } } /** * @param args */ public static void main(String[] args) { System.out.println(""start""); // get files to process File[] inputFiles = getInputFiles(""data""); if (inputFiles != null) { for (File inputFile : inputFiles) processFile(inputFile); } } } " B10611,"import java.io.*; import java.util.*; public class Recyled { public static void main(String [] args) throws Exception { BufferedReader br = new BufferedReader(new FileReader(""C-small-attempt0.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""C-small.out""))); int T = Integer.parseInt(br.readLine()); for(int i = 1; i <= T; i++) { StringTokenizer st = new StringTokenizer(br.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); int ans = 0; for(int n = a; n <= b; n++) { for(int m = n+1; m<=b; m++) { if(isRecycled(n,m)) { ans++; } } } out.println(""Case #""+i+"": ""+ans); } out.close(); } public static boolean isRecycled(int n, int m) { String a = """"+n; String b = """"+m; if(a.length() != b.length()) { return false; } for(int i = 0; i < a.length(); i++) { String k = a.substring(i)+a.substring(0,i); if(k.equals(b)) { return true; } } return false; } }" B10016,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; public class R1P3 { /** * @param args */ public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new FileReader(""C-small-attempt0.in"")); BufferedWriter bw = new BufferedWriter(new FileWriter(""small3.out"")); String inLine; int t = Integer.parseInt(in.readLine()); int counter = 0; while ((inLine = in.readLine()) != null) { counter++; String[] toks = inLine.split("" ""); long beg = Long.parseLong(toks[0]); long end = Long.parseLong(toks[1]); long c = 0; for (long i = beg; i < end; i++) { c += rotateNumber(i, end); } System.out.println(""Case #"" + counter + "": "" + c); bw.write(""Case #"" + counter + "": "" + c); bw.newLine(); } in.close(); bw.close(); } public static long rotateNumber(long number, long end) { long start = number; int numdigits = (int) Math.log10((double) number); // would return // numdigits - 1 int multiplier = (int) Math.pow(10.0, (double) numdigits); long counter = 0; while (true) { long q = number / 10; long r = number % 10; number = number / 10; number = number + multiplier * r; if (start < number && number <= end) counter++; if (number == start) break; } return counter; } } " B11108,"import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class RecycledNumbers { /** * @param args */ static int a = -1; static int b = -1; static int T = -1; static int A = -1; static int B = -1; static File newFile = null; static Scanner scan = null; static int[] n = null; static int[] m = null; static int q = 1; static int num = 1; static int count = 0; public static void main(String[] args) throws IOException { try { newFile = new File(""C:/Users/PANKAJJAKHAR/Desktop/small.in""); scan = new Scanner(newFile); scan.hasNextLine(); T = scan.nextInt(); while(scan.hasNextLine()) { if(!scan.hasNextInt()) return; // A = scan.nextInt(); // B = scan.nextInt(); for(int f = 0; f < 1; f++) { A = scan.nextInt(); B = scan.nextInt(); } int nMin = A; int nMax = B - 1; int mMax = B; int mMin = A + 1; int c = 0; n = new int[B - A]; m = new int[B - A]; //fill n values for(int i = nMin; i <= nMax; i++) { n[c] = i; // System.out.print("" "" + n[c]); c++; } int x = 0; //fill m values for(int j = mMin; j <= mMax ; j++) { m[x] = j; // System.out.print("" "" + m[x]); x++; } int lenNnum = -1; for(int i = 0; i < n.length; i++) { int numN = n[i]; String numNStr = Integer.toString(numN); lenNnum = numNStr.length(); // if(lenNnum == 1) // { // // } // else for(int j = 0; j < m.length; j++) { int mNumber = m[j]; if(n[i] < mNumber) { for(int k = 0; k < lenNnum - 1; k++) { String newNumLead = numNStr.substring(0, k + 1); String newNumTrail = numNStr.substring(k + 1); String finalStr = newNumTrail + newNumLead; int lenFinalStr = finalStr.length(); int finalInt = Integer.parseInt(finalStr); String mNumStr = Integer.toString(m[j]); int lenmNumStr = mNumStr.length(); // if(lenFinalStr == lenmNumStr) // { if(finalInt == mNumber) { count = count + 1; } // } } } } } System.out.println(""Case #"" + num + "": "" + count); num++; count = 0; // System.out.println(count); } } catch (FileNotFoundException e) { e.printStackTrace(); } } } " B12003,"import java.util.*; import java.util.*; public class soalC{ public static void main(String[] args){ Scanner scan=new Scanner(System.in); int tc = scan.nextInt(); for (int i = 0 ; i < tc; i++) { int awal = scan.nextInt(); int akhir = scan.nextInt(); int index = awal; int count = 0; for (int j = awal; j <= akhir ; j++) { for (int k = j+1; k <= akhir ; k++) { if (checkRecycle(j,k)) { count++; } } } System.out.println(""Case #""+(i+1)+"": ""+count); } } public static boolean checkRecycle(int m, int n) { String x = n+""""; for (int i = 0 ; i < x.length() ; i++) { if (Integer.parseInt(x.substring(i,x.length())+(x.substring(0,i)))==m) { return true; } } return false; } } " B10285,"import java.util.*; public class Recycled { public static void main(String[] args) throws Exception { Scanner s = new Scanner(System.in); int T = Integer.parseInt(s.nextLine()); for (int t = 0; t < T; t++) { int A = s.nextInt(); int B = s.nextInt(); long[] values = new long[B + 1]; Set set = new HashSet(); for (int i = A; i <= B; i++) { String istr = """" + i; for (int j = 1; j < istr.length(); j++) { String prefix = istr.substring(istr.length() - j, istr.length()); String suffix = istr.substring(0, istr.length() - j); // Set set = new HashSet(); if (prefix.charAt(0) != '0') { String newNumber = prefix + suffix; int newNumberInt = Integer.parseInt(newNumber); // System.out.println(newNumberInt); if (newNumberInt > i && newNumberInt <= B && String.valueOf(i).length() == String.valueOf(newNumberInt).length()) { // if (set.contains(newNumberInt)) // System.out.println(newNumberInt); // set.add(newNumberInt); values[newNumberInt] += 1; Pair p = new Pair(i, newNumberInt); set.add(p); // System.out.println(""("" + i + "", "" + newNumberInt + "")""); } } } } long sum = 0; for (int i = A; i <= B; i++) { sum += values[i]; } System.out.println(""Case #"" + (t + 1) + "": "" + set.size()); } } } class Pair { int n; int m; public Pair(int n, int m) throws Exception { if (n >= m) throw new Exception(); this.n = n; this.m = m; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; if (m != pair.m) return false; if (n != pair.n) return false; return true; } @Override public int hashCode() { int result = n; result = 31 * result + m; return result; } }" B10479,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import javax.security.auth.x500.X500Principal; public class RecycledNumbers { static HashSet set = new HashSet(); static ArrayList rotate = new ArrayList(); int counter = 0; int count=1; public static void main(String[] args) { try { BufferedReader in = new BufferedReader(new FileReader(""input.txt"")); BufferedWriter out = new BufferedWriter(new FileWriter(""A-small.out"")); RecycledNumbers x = new RecycledNumbers(); String str; in.readLine(); while ((str = in.readLine()) != null) { x.recycle(str); out.write(""Case #""+(x.count++)+"": ""+x.counter+""\n""); x.counter = 0; } in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } void recycle(String in) { int a = Integer.parseInt(in.split("" "")[0]); int b = Integer.parseInt(in.split("" "")[1]); for (int n = a; n < b ; n++) { rotateNumber(n); if(rotate.size()>0){ for (int i = 0; i < rotate.size(); i++) { int m = rotate.get(i); if(a <= n && n < m && m <= b) counter++; } } } } static void rotateNumber(int number){ rotate = new ArrayList(); int start = number; int numdigits = (int) Math.log10((double)number); int multiplier = (int) Math.pow(10.0, (double)numdigits); while(true){ int q = number / 10; int r = number % 10; //1234 = 123; number = number / 10; number = number + multiplier * r; if(number == start) return; rotate.add(number); } } } " B13161,"package org.weiwei.recyclenumber; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; /** * Created with IntelliJ IDEA. * User: ding * Date: 12-4-14 * Time: 下午1:57 * To change this template use File | Settings | File Templates. */ public class FileProcessor { public static void testOutput(String input, String output) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(input)); PrintWriter pw = new PrintWriter(output); String line = reader.readLine(); int total = Integer.parseInt(line.trim()); line = reader.readLine(); int i = 1; while(line != null) { String[] elems = line.trim().split("" ""); RecyleBin bin = new RecyleBin(Integer.parseInt(elems[0]), Integer.parseInt(elems[1])); pw.write(""Case #""+i+"": ""+bin.exhaust()); pw.write(""\r\n""); line = reader.readLine(); i++; } reader.close(); pw.close(); } public static void main(String[] args) throws IOException { testOutput(""F:\\input.txt"", ""F:\\output.txt""); } } " B10937," /** * Name: Shivam99 * email: shivthedestroyer99@gmail.com */ import java.io.*; public class ProblemC { public static void main(String[] args) throws IOException{ FileReader fr=new FileReader(args[0]); BufferedReader br=new BufferedReader(fr); String str=br.readLine(); int t=Integer.parseInt(str); String ss=""""; int c=1; while(c<=t){ str=br.readLine(); int pos=str.indexOf(' '); String f=str.substring(0,pos); String s=str.substring(++pos,str.length()); int a=Integer.parseInt(f); int b=Integer.parseInt(s); int ans=0; ss+=""Case #""+c+"": ""; if(a!=b && f.length()>1){ for(int ind=a;indind && num<=b){ arr[count]=num; boolean chk=true; for(int j=1;j<=count;j++){ if(arr[j-1]==num) chk=false; } if(chk) ans++; } count++; } } } ss+=ans+""\n""; c++; } System.out.print(ss); br.close(); fr.close(); } } " B12194,"import java.io.*; import java.util.*; public class Solution { private StringTokenizer st; private BufferedReader in; private PrintWriter out; final String file = ""C-small-attempt0""; public void solve() throws IOException { int tests = nextInt(); int[] pows10 = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000}; for (int test = 0; test < tests; ++test) { int a = nextInt(); int b = nextInt(); int[] o = new int[6]; int pow10 = 0; int ans = 0; for (int i = a; i <= b; ++i) { int c = 0; while (pows10[pow10] <= i) { ++pow10; } for (int sh = 1; sh < pow10; ++sh) { int val = i / pows10[sh] + (i % pows10[sh]) * pows10[pow10 - sh]; if (i < val && val <= b) { o[c++] = val; } } Arrays.sort(o, 0, c); for (int j = 0; j < c; ++j) { if (j == 0 || o[j] != o[j - 1]) { ans++; } } } out.printf(""Case #%d: %d%n"", test + 1, ans); } } public void run() throws IOException { in = new BufferedReader(new FileReader(file + "".in"")); out = new PrintWriter(file + "".out""); eat(""""); solve(); out.close(); } void eat(String s) { st = new StringTokenizer(s); } String next() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } eat(line); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); new Solution().run(); } }" B11952,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Map; import java.util.StringTokenizer; import java.util.TreeMap; public class Recycle { public static String recycle(int a, int b) { int result = 0; int digit, temp, cnt; String str; int array[] = new int[b + 1]; for (int i = 0; i < b; i++){ array[i] = 0; } str = a+""""; digit = str.length(); for (int i = a; i < b; i++){ if (array[i] == 1) continue; array[i] = 1; temp = i; cnt = 0; for (int j = 0; j < digit - 1; j++){ temp = (temp / 10) + (temp % 10)*(int)Math.pow(10, digit - 1); if (temp == i) break; if (a <= temp && temp <= b){ if(array[temp] == 0){ cnt++; array[temp] = 1; //System.out.println(String.format(""(%d, %d)"", i, temp)); } } } result += factorial(cnt); } return """" + result; } public static int factorial(int a){ if (a <= 0) return 0; return a + factorial(a - 1); } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int T = 0; String str = """"; File input = new File(args[0]); FileReader fileReader; BufferedReader br; File output = new File(""output_recycle.txt""); BufferedWriter bw; StringTokenizer tokenizer; try { bw = new BufferedWriter(new FileWriter(output)); fileReader = new FileReader(input); br = new BufferedReader(fileReader); str = br.readLine(); T = Integer.parseInt(str); for (int i = 0; i < T; i++) { int a; int b; str = br.readLine(); tokenizer = new StringTokenizer(str); a = Integer.parseInt(tokenizer.nextToken()); b = Integer.parseInt(tokenizer.nextToken()); bw.write(String.format(""Case #%d: %s\n"", i+1, recycle(a, b))); } br.close(); fileReader.close(); bw.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B11240,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; /** * @author alex * */ public class ProblemCRecycledNumbers { public static void main(String args[]) { try{ String fileDir = ""/Users/alex/Documents/workspace/codejam2012/src/""; String inputFile = ""C-small-attempt3""; // String inputFile = ""CSmallInput0""; FileInputStream fstream = new FileInputStream(fileDir+inputFile+"".in""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String firstLine = br.readLine(); int numberOfTests = Integer.parseInt(firstLine); String strLine; Integer numberOfRecurrences; // open write file descriptor FileWriter ofstream = new FileWriter(fileDir+inputFile+""-output.txt""); BufferedWriter out = new BufferedWriter(ofstream); //Read File Line By Line for(int loop=0;loopmatched for:"" + Integer.parseInt( revnioudigitsString )); result++; } } else if(nioudigits.length==3) { char[] revnioudigits1 = {nioudigits[2], nioudigits[0], nioudigits[1]}; String miou11 = new String(revnioudigits1); char[] revnioudigits2 = {nioudigits[1], nioudigits[2], nioudigits[0]}; String miou12 = new String(revnioudigits2); if( ((alpha < Integer.parseInt( miou11 )) && (Integer.parseInt( miou11 ) <= beta) && (niou < Integer.parseInt( miou11 ) && ( Integer.parseInt( miou11 ) != Integer.parseInt( miou12 ) ) ) ) ) { // System.out.println("">>matched for:"" + Integer.parseInt( revnioudigitsString1 )); result++; } if( ( (alpha < Integer.parseInt( miou12 )) && (Integer.parseInt( miou12 ) <= beta) && (niou < Integer.parseInt( miou12 ) && ( Integer.parseInt( miou11 ) != Integer.parseInt( miou12 ) )) ) ) { // System.out.println("">>matched for2:"" + Integer.parseInt( revnioudigitsString1 )); result++; } } } return result; } } " B12269,"import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner sin = new Scanner(System.in); int cases, a, b; int[] ans; cases = sin.nextInt(); ans = new int[cases]; for (int i = 0; i < cases; i++) { int count = 0; a = sin.nextInt(); b = sin.nextInt(); for (int j = a; j <= b; j++) { String ori = String.valueOf(j); int[] temp = new int[ori.length() - 1]; int tempIndex = 0; for (int k = 1; k < ori.length(); k++) { String newStr = ori.substring(k, ori.length()) + ori.substring(0, k); int newInt; boolean skip = false; if (newStr.charAt(0) == '0') continue; newInt = Integer.parseInt(newStr); for (int m = 0; m < tempIndex; m++) if (temp[m] == newInt) { skip = true; break; } if (skip == false) temp[tempIndex++] = newInt; else continue; if (j < newInt && newInt >= a && newInt <= b) count++; } } ans[i] = count; } for (int i = 0; i < cases; i++) System.out.println(""Case #"" + (i + 1) + "": "" + ans[i]); } }" B11988,"import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.Writer; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { private String mInputFileName; private String mOutputFileName; private long A; private long B; private Set mPairSet = new HashSet(); public RecycledNumbers(String inputFileName, String outputFileName) { mInputFileName = inputFileName; mOutputFileName = outputFileName; } public void solve() { long start = System.currentTimeMillis(); Scanner scanner = null; try { scanner = new Scanner(new FileReader(mInputFileName)); Writer output = new BufferedWriter(new FileWriter(mOutputFileName)); int cases = scanner.nextInt(); for (int i = 1; i <= cases; i++) { mPairSet.clear(); A = scanner.nextLong(); B = scanner.nextLong(); System.out.println(""CASE: "" + i + "" / "" + cases); if (i > 1) output.write(""\n""); output.write(""Case #"" + i + "": ""); output.write(getAnswer()); } output.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (scanner != null) scanner.close(); } System.out.println(""TIME: "" + (System.currentTimeMillis() - start)); } private String getAnswer() { int res = 0; for (long i = A; i <= B; i++) { res += getNumPairs(i); } //System.out.println(res); return """" + res; } private int getNumPairs(long num) { int res = 0; String numStr = """" + num; int len = numStr.length(); if (len > 1) { for (int i = 1; i < len; i++) { String newStr = numStr.substring(i) + numStr.substring(0, i); long newNum = Long.parseLong(newStr); if (newNum > num && newNum <= B) { String pair = num + "" "" + newNum; if (!mPairSet.contains(pair)) { mPairSet.add(pair); res++; } } } } return res; } public static void main(String[] args) { String fileName = ""test""; String extension = "".txt""; String outputSuffix = ""_output""; new RecycledNumbers(fileName + extension, fileName + outputSuffix + extension).solve(); } } " B10462," import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.TreeSet; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author ikhwan */ public class C { public static void main(String []args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String input = br.readLine(); int test = Integer.parseInt(input); StringTokenizer token; for(int i=1;i<=test;i++) { String temp = br.readLine(); token = new StringTokenizer(temp,"" ""); String n1 = token.nextToken(); String m1 = token.nextToken(); int a=Integer.parseInt(n1),b=Integer.parseInt(m1); System.out.println(""Case #""+i+"": ""+run(a,b)); pool.clear(); } //String k = ""102""; //System.out.println(run(Integer.parseInt(k),988)); } static TreeSet pool = new TreeSet(); public static int run(int A,int B) { int counter=0; int k = B-1; for(int i=A;i { String n,m; pair(String nn,String mm) { n=nn; m=mm; } public int compareTo(pair t) { return (n+m).compareTo((t.n+t.m)); } } } " B10024,"package WQ; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; public class Problem_C { /** * @param args * @throws FileNotFoundException */ public static boolean check(String s) { for (int i = 0; i < s.length() - 1; i++) { if (s.charAt(i) != s.charAt(i + 1)) return true; } return false; } public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new FileReader(""C-small-attempt0.in"")); PrintWriter out = new PrintWriter(""out1.txt""); int num = in.nextInt(); for (int CASE = 1; CASE <= num; CASE++) { int a = in.nextInt(); int b = in.nextInt(); HashSet hs = new HashSet(); for (int i = a; i <= b; i++) { String s = i + """"; if (check(s) && s.length() > 1) { for (int k = s.length() - 2, j = 0; k >= 0 && j < s.length() - 1; j++, k--) { String newS = s.substring(k + 1) + s.substring(0, k + 1); int newInt = Integer.parseInt(newS); if (newInt <= b && i < newInt && s.length() == (newInt + """").length() && !newS.equals(s)) { if (i < Integer.parseInt(newS)) hs.add(i + "" "" + newS); else hs.add(newS + "" "" + i); } } } } out.println(""Case #"" + CASE + "": "" + hs.size()); } out.close(); } } " B12918,"package com.google.code.p_c; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; public class Main { private static final String fromFile = ""D:\\hobbies & work\\programing\\CodeJamTextFiles\\2012\\C-small-attempt0.in""; private static final String toFile = ""D:\\hobbies & work\\programing\\CodeJamTextFiles\\2012\\C-small-attempt0.out""; /** * @param args */ public static void main(String[] args) { System.out.println(""Problem C start""); try { FileInputStream fstream = new FileInputStream(fromFile); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter fstreamout = new FileWriter(toFile); BufferedWriter out = new BufferedWriter(fstreamout); String strLine; boolean firstLine = true; int i = 1; while ((strLine = br.readLine()) != null) { if (!firstLine) { System.out.println(strLine); int ans = ansForLine(strLine); System.out.println(""Case #"" + i + "": "" + ans + ""\n""); out.write(""Case #"" + i + "": "" + ans + ""\n""); i++; } else { firstLine = false; } } out.close(); in.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } System.out.println(""Problem C end""); } private static int ansForLine(String strLine) { String [] sp = strLine.split("" ""); String n1s = sp [0]; String n2s = sp [1]; int n1 = Integer.parseInt(n1s); int n2 = Integer.parseInt(n2s); int count = 0; for (int i = n1; i < n2 ; i++) { String s1 = Integer.toString(i); String s1b = s1; System.out.println(""--- "" + s1); for (int j = 0; j < s1.length() - 1; j++) { s1 = s1.charAt(s1.length() - 1) + s1.substring(0, s1.length() - 1); //System.out.println(s1); if (s1.equals(Integer.toString(i))) continue; if (Integer.parseInt(s1) >= n1 && Integer.parseInt(s1) <= n2 && Integer.parseInt(s1) > Integer.parseInt(s1b)) { System.out.println(""y "" + s1); count ++; //break; } else { System.out.println(""n "" + s1); } } } return count; } } " B10890,"package de.at.codejam.gui; import javax.swing.JFrame; import de.at.codejam.util.CodeJamConstants; public class CodeJamWindow extends JFrame implements CodeJamConstants { private static final long serialVersionUID = 3904464282318628286L; private static final String titleBase = ""Google Code Jam - Client""; public CodeJamWindow() { super(titleBase); super.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setPreferredSize(DEFAULT_WINDOW_SIZE); setSize(DEFAULT_WINDOW_SIZE); } public void setAssignmentName(String assignmentName) { setTitle(titleBase + "" ("" + assignmentName + "")""); } } " B13180,"import java.io.*; import java.util.*; public class C { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new FileReader(""C-small-attempt0.in"")); PrintWriter pw = new PrintWriter(new FileWriter(""C-small-output.txt"")); int T = sc.nextInt(); int result; for (int k=1; k <= T; k++) { int A = sc.nextInt(); int B = sc.nextInt(); Hashtable allResults = new Hashtable(); String nString = """" + A; int numDigits = nString.length(); // find number of digits result = 0; for (int n=A; nn) && (recycled<=B) ) { String mn = n + "","" + recycled; if (!allResults.contains(mn)) { allResults.put(mn.hashCode(), mn); result++; } } } } System.out.format(""Case #%d: %d\n"", k, result); pw.format(""Case #%d: %d\n"", k, result); } pw.flush(); pw.close(); sc.close(); } }" B10536,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStreamReader; public class Recycle { // Method to Solve the Problem public void Solve(int c ,String a , String b){ int first = Integer.parseInt(a); int second = Integer.parseInt(b); String test=""""; String convert; int num; int result=0; int result2=0; // if(String.valueOf(b).length()==1){ // System.out.println(""Case #""+c+"": 0""); // } System.out.print(""Case #""+c+"": ""); for (int i = first; i <= second; i++) { test=String.valueOf(i); if(test.length()==2){ convert = test.charAt(1)+""""+test.charAt(0); num = Integer.parseInt(convert); if(num<=second && num>=i && num!= i) result++; } if(test.length()==3){ convert = test.charAt(2)+""""+test.charAt(0)+""""+test.charAt(1); num = Integer.parseInt(convert); if(num<=second && num>=i && num!= i) result2++; convert = test.charAt(1)+""""+test.charAt(2)+""""+test.charAt(0); num = Integer.parseInt(convert); if(num<=second && num>=i && num!= i) result2++; } } result= (result) + (result2); System.out.println(result); //System.out.println(result2); } // Method to read from the file public void readFile() throws FileNotFoundException{ int iter=0; String s; try{ FileInputStream fstream = new FileInputStream(""C-small-attempt0.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); br.readLine(); while ((s = br.readLine()) != null) { String [] numbers = s.split("" ""); Solve(++iter, numbers[0],numbers[1]); } in.close(); }catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } public static void main(String[] args) throws Exception { Recycle s = new Recycle(); s.readFile(); } } " B10749,"import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; public class RecycledNumbers { public static void main(String[] args) { try { FileWriter w = new FileWriter(new File(""E:\\output.out"")); BufferedReader r = new BufferedReader(new FileReader(new File(""E:\\C-small-attempt0.in""))); int numbeOfCases = Integer.parseInt(r.readLine()); for(int t = 0; t < numbeOfCases; t++) { String[] nums = r.readLine().split("" ""); int b = Integer.parseInt(nums[1]); int a = Integer.parseInt(nums[0]); int number = 0; HashMap f = new HashMap(); for(int n = a, digits = nums[0].length(), max = (int) (Math.pow(10, digits) - 1); n < max; n++) for(int j = 1; j < digits; j++) if(n % Math.pow(10, j) >= Math.pow(10, j - 1)) { int m = (int) ((n % Math.pow(10, j)) * (Math.pow(10, digits - j)) + n / Math.pow(10, j)); if(m > n && m <= b && !f.containsKey(m + "","" + n) && !f.containsKey(n + "","" + m)) { number++; f.put(m + "","" + n,""""); f.put(n + "","" + m,""""); } } w.write(""Case #"" + (t + 1) + "": "" + number); if(t < numbeOfCases - 1) w.write(""\n""); } w.close(); r.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }" B10656,"package br.com.app; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.util.Scanner; public class RecycledNumbers { private static int totCasos, contCasos, contador, totNumerosMovidos, indice; private static long a, b, n, m; private static String numerosN, numerosM; private static StringBuilder temp = new StringBuilder(); private static StringBuilder saida = new StringBuilder(); private static File arquivoEntrada = new File(""/home/emanuel/input.txt""); private static File arquivoSaida = new File(""/home/emanuel/output.txt""); private static BufferedReader leitura; private static FileOutputStream fos; private static String linha; private static String[] entrada; public static void main(String[] args) { try { leitura = new BufferedReader(new FileReader(arquivoEntrada)); linha = leitura.readLine(); totCasos = Integer.parseInt(linha); for (int i = 0; i < totCasos; i++) { linha = leitura.readLine(); entrada = linha.split("" ""); a = Long.parseLong(entrada[0]); b = Long.parseLong(entrada[1]); for (n = a; n < b - 1; n++) { for (m = n + 1; m <= b; m++) { numerosN = String.valueOf(n); numerosM = String.valueOf(m); indice = numerosN.length() - 1; totNumerosMovidos = 0; while (totNumerosMovidos < numerosN.length()) { temp.append(numerosN.substring(indice)).append(numerosN.substring(0, indice)); if (temp.toString().equals(String.valueOf(numerosM))) { contador++; break; } temp.delete(0, temp.length()); indice--; totNumerosMovidos++; } } } contCasos++; saida.append(""Case #"").append(contCasos).append("": "").append(contador).append(""\n""); contador = 0; } fos = new FileOutputStream(arquivoSaida); fos.write(saida.toString().getBytes()); fos.close(); } catch (Exception e) { System.out.println(e.getMessage()); } } } " B12710,"import java.io.*; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class RecycledNumbers { BufferedReader br; StringTokenizer st = new StringTokenizer(""""); private void solve() throws IOException { // final String IO_FILE = null; final String IO_FILE = ""./C/C-small-attempt0""; final PrintWriter pw; if (IO_FILE == null) { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(System.out); } else { br = new BufferedReader(new FileReader(IO_FILE + "".in"")); pw = new PrintWriter(IO_FILE + "".out""); } int testCases = nextInt(); for (int ti = 1; ti <= testCases; ti++) { int a = nextInt(); int b = nextInt(); int ans = find(a, b); pw.println(""Case #"" + ti + "": "" + ans); } br.close(); pw.close(); } private int find(int a, int b) { int ans = 0; for (int n = a; n <= b; n++) { ans += check(n, b); } return ans; } private int check(final int n, final int b) { int length = 0, copy = n, pow10 = 1; while (copy > 0) { length++; copy /= 10; pow10 *= 10; } int firstDigitPow10 = pow10 / 10; int x = n; Set set = new HashSet(); for (int i = 0; i < length - 1; i++) { int lastDigit = x % 10; x /= 10; int m = lastDigit * firstDigitPow10 + x; if (lastDigit != 0 && n < m && m <= b) { set.add(m); } x = m; } return set.size(); } String nextString() throws IOException { while (!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextString()); } public static void main(String[] args) throws IOException { new RecycledNumbers().solve(); } } " B12900,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; public class gcjq3 { public static void main(String[] args) { try{ FileInputStream ifstream = new FileInputStream(""files/C-small-attempt0.in""); DataInputStream in = new DataInputStream(ifstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileOutputStream ofstream = new FileOutputStream(""files/output""); DataOutputStream out = new DataOutputStream(ofstream); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out)); int numCases = Integer.parseInt(br.readLine()); for(int i=0; i processedNumber = new HashSet(); //System.out.println(A + "" "" + B); for(int a=A; a<=B; a++) { if(processedNumber.contains(a) || isAllTheSameDigits(a)) continue; processedNumber.add(a); int eligibleNumbers = 1; int numberToProcessed = a; //System.out.print(""numberToProcessed:"" + numberToProcessed +"",""); for(int j=0; j processedNumber, int number) { if(number >=A && number <=B && !processedNumber.contains(number)) return true; else return false; } } " B12548,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recyclednumbers; /** * * @author WC */ public class RecycledNumbers { /** * @param args the command line arguments */ public static void main(String[] args) { (new RecycledNumbers()).findRecycledNumbers(""C-small-attempt0.in"", ""C-small-attempt0.out"", ""\n""); } private void findRecycledNumbers(String filename, String outputFile, String separator) { int numberOfTestCases = CodeJamFileManager.getIntFromFirstLineOfFile(filename, separator); String[] testCases = CodeJamFileManager.getTextLinesOfFile(filename, separator); String output = """"; for (int i = 1; i <= numberOfTestCases; i++) { output += ""Case #"" + i + "": "" + getNumberOfRecycledInts(testCases[i]) + (i != numberOfTestCases ? separator : """"); } CodeJamFileManager.saveOutputFile(output, outputFile, separator); } private int getNumberOfRecycledInts(String testcase) { int[] params = getIntArrayFromString(testcase.split("" "")); int lower = params[0]; int upper = params[1]; int currentM = lower + 1; int numberOfRecycles = 0; while (currentM <= upper) { int count = timesRecycled(lower, currentM++); numberOfRecycles += count; } return numberOfRecycles; } private int timesRecycled(int lower, int currentM) { String currentMStr = String.valueOf(currentM); char[] individualNumbers = currentMStr.toCharArray(); int timesRecycled = 0; for (int i = 1; i < individualNumbers.length; i++) { int flip = flip(individualNumbers, i); if (flip >= lower && flip < currentM) { timesRecycled++; } } return timesRecycled; } private int flip(char[] individualNumbers, int positionsToFlip) { char[] flip = new char[individualNumbers.length]; int startInt = individualNumbers.length - positionsToFlip; int flipPos = 0; while (startInt < individualNumbers.length) { flip[flipPos++] = individualNumbers[startInt++]; } int i = 0; while (i < (individualNumbers.length - positionsToFlip)) { flip[flipPos++] = individualNumbers[i++]; } return Integer.parseInt(String.valueOf(flip)); } private int[] getIntArrayFromString(String[] intStrArray) { int[] intArray = new int[intStrArray.length]; int i = 0; for (String intStr : intStrArray) { intArray[i++] = Integer.parseInt(intStr); } return intArray; } } " B11484,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; public class C { private void solve() throws IOException { int T = nextInt(); while (T-- > 0) { int A = nextInt(); int B = nextInt(); int res = 0; for (int i = A; i <= B; i++) for (int j = i + 1; j <= B; j++) { if (can(i, j)) { res++; } } pf(); pl(res); } } private boolean can(int i, int j) { String s = """" + i; for (int c = 0; c < s.length(); c++) { String a = s.substring(c); String b = s.substring(0, c); String res = a + b; if (Integer.parseInt(res) == j) return true; } return false; } public static void main(String[] args) { new C().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(new FileReader(""C.in"")); // reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; // writer = new PrintWriter(System.out); writer = new PrintWriter(""C.out""); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } BigInteger nextBigInteger() throws IOException { return new BigInteger(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } void p(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.flush(); writer.print(objects[i]); writer.flush(); } } void pl(Object... objects) { p(objects); writer.flush(); writer.println(); writer.flush(); } int cc; void pf() { writer.printf(""Case #%d: "", ++cc); writer.flush(); } } " B12007,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; class Case { public int A; public int B; public Case(int a, int b) { A = a; B = b; } } class ProblemC { private String mInputFilename; private int T; private ArrayList mCases; private BufferedReader mReader; private BufferedWriter mWriter; public ProblemC(String inputFilename) { T = 0; mCases = null; mInputFilename = inputFilename; } private boolean openFiles() { if (mInputFilename != null) { try { mReader = new BufferedReader(new FileReader(mInputFilename)); mWriter = new BufferedWriter(new FileWriter(mInputFilename.replace(""in"", ""out""))); } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } return true; } return false; } private void closeFiles() { try { mReader.close(); mWriter.close(); } catch (IOException e) { e.printStackTrace(); } } private boolean readInput() { if (mReader != null) { try { String line; // number of test cases line = mReader.readLine(); T = Integer.valueOf(line); System.out.println(""Cases: "" + T); mCases = new ArrayList (); // read input cases for (int i = 0; i 0) { num *= 10; digit--; } return num; } private int getShiftedNum(int num, int digit) { int ret = 0; int digitNum = getDigitInt(digit); int top = num / digitNum; ret = (num%digitNum)*10 + top; return ret; } private void findWay(int seq, Case item) { Case in = item; int A = in.A; int B = in.B; int result = 0; for (int num = A; num<=B; num++) { int digit = getDigit(num); // System.out.println(""num: "" + num + "", digit: "" + digit); int n = num; int m = n; for (int j = 0; j < digit-1; j++) { m = getShiftedNum(m, digit); // System.out.println(""num: "" + num + "", m: "" + m); if (m > n && m <= B) { System.out.println(""found: ("" + n + "", "" + m + "")""); result++; } } } writeOutput(seq, result); } // test run main public void run() { openFiles(); readInput(); for (int i = 0; i 0) inputFilename = new String(args[0]); else inputFilename = new String(""sample.in""); ProblemC solve = new ProblemC(inputFilename); solve.run(); } } " B10859,"package be.mokarea.gcj.recyclednumbers; import be.mokarea.gcj.common.TestCase; public class RecycledNumbersTestCase extends TestCase { private final int a; private final int b; protected RecycledNumbersTestCase(int caseNumber, int a, int b) { super(caseNumber); this.a = a; this.b = b; } public int getA() { return a; } public int getB() { return b; } } " B10131,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class main2 { /** * @param args * @throws IOException * @throws NumberFormatException */ public static void main(String[] args) throws NumberFormatException, IOException { // TODO Auto-generated method stub BufferedReader m = new BufferedReader(new InputStreamReader(System.in)); PrintWriter ou = new PrintWriter(""file.txt""); int n = Integer.parseInt(m.readLine()); for (int i = 0; i < n; i++) { String cas = m.readLine(); String [] a = cas.split("" ""); int base = Integer.parseInt(a[0]); int count = 0; int count1=0; if(a[0].length()==1){ System.out.print(""Case #""+(i+1)+"": ""+count); System.out.print(""\n""); }else{ Boolean con = false;; int cass = Integer.parseInt(a[0]); do { // con = false;; // String newcase = a[0].charAt(0)+""""; // for(int j=0 ;j { /** Return at most n items from the beginning of the Iterable. */ public static ArrayList head(Iterable collection, int n) { ArrayList head = new ArrayList(); int count = n; if (n > 0) for (T item : collection) { head.add(item); if (--count == 0) break; } return head; } /** Return at most n items from the end of the List. */ public static ArrayList tail(List list, int n) { ArrayList tail = new ArrayList(); for (int len = list.size(), i = Math.max(len - n, 0); i < len; i++) tail.add(list.get(i)); return tail; } } " B11393,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class C { public static void main(String[] args) throws FileNotFoundException { Scanner read = new Scanner(new File(""C-small-attempt0.in"")); PrintWriter out = new PrintWriter(new File(""c-small.out"")); int numberOfTests = read.nextInt(); for (int i = 1; i <= numberOfTests; i++) { int a = read.nextInt(); int b = read.nextInt(); int countOfDigits = 0; int t = 1; while (a / t != 0) { countOfDigits++; t *= 10; } t /= 10; int result = 0; for (int n = a; n < b; n++) { int m = n; for (int k = 1; k < countOfDigits; k++) { int lastDigit = m % 10; m = m / 10; m = lastDigit * t + m; if (m <= b && m > n) { result++; } } } out.println(String.format(""Case #%d: %d"", i, result)); } out.close(); } } " B12401,"package recyclednumbers; import inout.In; import inout.Out; public class Main { public static void main(String[] args) throws Exception { String[] strings = In.read(""C-small-attempt1.in"", 1); int n = 1; for (String s : strings) { long cont = 0; String[] split = s.split("" ""); long min = Long.parseLong(split[0]); long max = Long.parseLong(split[1]); if ((min + """").length() > 1) { for (long i = min; i < max; i++) { String newstr1 = """" + i; ext: for (long j = i + 1; j <= max; j++) { String newstr2 = """" + j; for (int k = newstr1.length() - 1; k > 0; k--) { String str = newstr1.substring(k) + newstr1.substring(0, k); if (str.equals(newstr2)) { cont++; continue ext; } } } } } Out.write(""output.txt"", n++, cont + """"); } } } " B11293,"package codejam2012; import java.io.File; import java.io.PrintWriter; import java.util.Scanner; import java.util.concurrent.TimeUnit; public class RecycledNumbers { private boolean[] data; private int min; private int max; private int digits; private int mask; public RecycledNumbers(int min, int max) { this.min = min; this.max = max; digits = (int) Math.ceil(Math.log10(max)); mask = (int) Math.pow(10, digits); initData(); } private void initData() { data = new boolean[max - min + 1]; } public int eval() { int[] result = new int[digits]; int total = 0; for (int number = min; number <= max; number++) { if (!isTested(number)) { int n = getRecycleNumbers(number, result); int real_n = setTested(result, n); if (real_n > 1) { total += real_n * (real_n - 1) / 2; } } } return total; } private int setTested(int[] result, int n) { int tested = 0; for (int i = 0; i < n; i++) { if (!data[result[i] - min]) { data[result[i] - min] = true; tested++; } } return tested; } private int getRecycleNumbers(int number, int[] result) { int count = 0; for (int i = 0; i < digits; i++) { if (number >= min && number <= max) { result[count++] = number; } int number10 = number * 10; number = (number10 % mask) + (number10 / mask); } return count; } private boolean isTested(int number) { return data[number - min]; } public static void main(String[] args) throws Exception { PrintWriter output = new PrintWriter(""output3.txt""); Scanner scanner = new Scanner(new File(""input3.txt"")); try { int input_T = scanner.nextInt(); for (int i = 0; i < input_T; i++) { int input_A = scanner.nextInt(); int input_B = scanner.nextInt(); RecycledNumbers testing = new RecycledNumbers(input_A, input_B); long start = System.nanoTime(); int eval = testing.eval(); output.printf(""Case #%d: %d\n"", i + 1, eval); System.out .printf(""Case #%d: %d (%d)\n"", i + 1, eval, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start)); } } finally { output.close(); scanner.close(); } } } " B10373,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Set; public class Recycled { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = br.readLine(); int t = Integer.parseInt(line); for (int i = 0; i < t; i++) { Set set = new HashSet(); line = br.readLine(); String[] split = line.split("" ""); int A = Integer.parseInt(split[0]); int B = Integer.parseInt(split[1]); int digits = String.valueOf(A).length(); if (digits != 1){ for (int j = A; j <= B; j++) { String oldString = String.valueOf(j); // System.out.println(""AA "" + oldString); for (int j2 = 1; j2 < digits; j2++) { String newString = oldString.substring(j2).concat(oldString.substring(0, j2)); if(newString.charAt(0) == '0')continue; int newInt = Integer.valueOf(newString); if (newInt >= A && newInt <= B && j pairs = new TreeSet(); for(int i = A; i <= B; i++){ int[] n = toArray(i); calcRecycledPairs(n, B, pairs); } return pairs.size(); } private int calcRecycledPairs(int[] n, int B, SortedSet pairs) { int num = 0; int[] m = new int[n.length]; int ni,mi; for (int i = 1; i < n.length; i++) { for(int j = 0; j < n.length-i; j++) { m[j+i] = n[j]; } for(int j = n.length-i; j < n.length; j++) { m[j-n.length+i] = n[j]; } ni = fromArray(n); mi = fromArray(m); if(mi <= B && ni < mi && isValidM(m)) { num++; pairs.add(new Pair(ni, mi)); // System.out.println(""(""+ni+"", ""+mi+"")""); } } return num; } private boolean isValidN(int[] n) { int tmp = n[0]; for (int i = 1; i < n.length; i++) { if(n[i] != tmp) return true; tmp = n[i]; } return false; } private boolean isValidM(int[] m) { if(fromArray(m) < Math.pow(10,m.length-1)) return false; return true; } private int[] toArray(int i) { int digits = (int)Math.ceil(Math.log10(i+1)); int[] arr = new int[digits]; for(int c = 1; c<=digits;c++) { arr[digits-c] = i % 10; i = i/10; } return arr; } private int fromArray(int[] arr) { int i = 0; for (int j = 0; j < arr.length; j++) { i = 10*i+arr[j]; } return i; } } " B10470,"import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RN { static ArrayList str2list(String s) { ArrayList r = new ArrayList(); for (char c : s.toCharArray()) { r.add(c); } return r; } static String list2str(ArrayList cs) { StringBuilder builder = new StringBuilder(cs.size()); for (Character c : cs) builder.append(c); return builder.toString(); } static ArrayList cycles(String s) { ArrayList cs = str2list(s); ArrayList res = new ArrayList(); for (int i = 0; i < cs.size(); i++) { Collections.rotate(cs, 1); res.add(list2str(cs)); } HashSet hs = new HashSet(res); return new ArrayList(hs); } static void log(String fs, Object... args) { System.err.println(String.format(fs, args)); } public static void main(String[] args) throws FileNotFoundException { String filename = ""src/C-small-attempt0.in""; Scanner sc = new Scanner( new FileInputStream( new File(filename))); PrintWriter pw = new PrintWriter( new FileOutputStream( new File(filename + "".result""))); int N = sc.nextInt(); for (int task = 1; task <= N; task++) { int A = sc.nextInt(); int B = sc.nextInt(); int cnt = 0; for (int i = A; i <= B; i++) { String s = Integer.toString(i); for (String r : cycles(s)) { int n = Integer.parseInt(r); if (n >= A && n <= B && r.charAt(0) != '0' && !r.equals(s)) { cnt++; } } } pw.println(String.format(""Case #%d: %d"", task, cnt / 2)); } pw.close(); } } " B12743,"package RecycledNumbers; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { try{ String userDir = System.getProperty(""user.dir""); //get working directory userDir.replaceAll(""['\']"", ""\\""); // replace all chars '\' with '\\' in the string File file = new File(System.getProperty(""user.dir"") + ""\\QualificationRound\\RecycledNumbers\\in-out\\C-small-attempt0.in""); Scanner fileScanner = new Scanner(file); //delimiter is how input text is set up in this case it's the new line char fileScanner.useDelimiter(System.getProperty(""line.separator"")); //declared for file writing BufferedWriter outFile = new BufferedWriter(new FileWriter(System.getProperty(""user.dir"") + ""\\QualificationRound\\RecycledNumbers\\in-out\\C-small.out"")); int counter, inCounter, masterCounter, numCases, startIndex, result, Amin, Bmax, numLength, ininCounter, deepCounter, passInt; String inputText; Amin = 0; Bmax = 0; String numConv; numCases = Integer.parseInt(fileScanner.nextLine()); ArrayList intList = new ArrayList(); ArrayList intList2 = new ArrayList(); for(masterCounter = 1; masterCounter <= numCases; masterCounter++){ inputText = fileScanner.nextLine(); startIndex = 0; result = 0; for( counter = 0; counter < inputText.length(); counter ++){//parse A n B if (inputText.charAt(counter) == ' ') { Amin = Integer.parseInt(inputText.substring(startIndex, counter)); startIndex = counter + 1; } } Bmax = Integer.parseInt(inputText.substring(startIndex, counter)); //get current length of numbers numLength = String.valueOf(Amin).length(); for(counter = Amin; counter < Bmax; counter++){ for(inCounter = counter + 1; inCounter <= Bmax; inCounter++){ passInt = inCounter; while(passInt > 0){ intList.add(passInt % 10); //get modulous passInt = passInt / 10;//div by 10 } for(ininCounter = 0; ininCounter < numLength; ininCounter++){ for(deepCounter = 0; deepCounter < intList.size() -1; deepCounter++) intList2.add(intList.get(deepCounter+1)); intList2.add(intList.get(0)); numConv = """"; for(deepCounter = 0; deepCounter < intList2.size(); deepCounter++){ numConv = intList2.get(deepCounter) + numConv; } passInt = Integer.parseInt(numConv); if(counter == passInt){ result++; //if(masterCounter == 4) //System.out.println(counter + "" = "" + passInt + "" Actual #: "" + inCounter); } intList = (ArrayList) intList2.clone(); intList2.clear(); } intList.clear(); } } System.out.println(""Case #"" + masterCounter + "": "" + result); outFile.write(""Case #"" + masterCounter + "": "" + result + ""\n""); } fileScanner.close(); outFile.close(); } catch (FileNotFoundException e) { System.out.println(""File not found""); e.printStackTrace(); } catch (IOException e) { System.out.println(""IOException""); } } } " B10038,"package Qual2012; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class Qual2012C { public static void main(String args[]){ String filePath = ""X:\\GCJ\\2012C-small-attempt0.in""; // String filePath = ""X:\\GCJ\\2012C-large-attempt0.in""; FileInputStream fis = null; BufferedReader readFile = null; String line; try { fis = new FileInputStream(filePath); readFile = new BufferedReader(new InputStreamReader(fis, ""ISO-8859-1"")); line = readFile.readLine(); int T = Integer.parseInt(line); for (int i = 1; i <= T; i++) { line = readFile.readLine(); System.out.println(""Case #"" + i + "": "" + solve(line) ); } } catch(Exception e) { e.printStackTrace(); }finally{ try { fis.close(); readFile.close(); } catch (IOException e) { e.printStackTrace(); } } } private static int solve (String line) { String[] temp = line.split("" ""); int a = Integer.parseInt(temp[0]); int b = Integer.parseInt(temp[1]); int ret = 0; for (int i = a; i < b; i++) ret += count(i, b); return ret; } private static int count(int x, int b) { int ret = 0; int digitnum = 0; int temp = x; boolean[] isCounted = new boolean[b + 1]; while (temp > 0) { digitnum ++; temp /= 10; } for (int i = 10; i <= x; i *= 10) { int target = 0; target += x / i; target += (x % i) * (Math.pow(10, digitnum) / i); if (target > x && target <= b && !isCounted[target] ) { ret++; isCounted[target] = true; } } return ret; } } " B11691,"import java.util.Scanner; public class ProblemC { public static int rotate(int x) { int y = x % 10; x /= 10; int cd = (x + """").length(); if (x == 0) { cd = 0; } y *= Math.pow(10, cd); y += x; return y; } public static String rotate(String x) { String r = x.substring(0, 1); if (x.length() > 1) { r = x.substring(1) + r; } return r; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int tt = 1; tt <= t; tt++) { int a = sc.nextInt(); int b = sc.nextInt(); int c = 0; for (int i = a; i <= b; i++) { String s = i + """"; while (true) { s = rotate(s); int x = Integer.parseInt(s); if (x == i) { break; } if (x > i && x >= a && x <= b) { // System.out.println(i + "" "" + x); c++; } } } System.out.println(""Case #"" + tt + "": "" + c); } } } " B10653,"package codejam; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class Problem3 { private static final int POWERS_OF_TEN[] = new int[] { 1, 10, 100, 1000, 10000, 100000, 1000000 }; public static void main(String[] args) throws IOException { Scanner scanner = new Scanner(new File(args[0])); int cases = scanner.nextInt(); PrintWriter printWriter = new PrintWriter(new File(args[1])); for (int i = 0; i < cases; i++) { int a = scanner.nextInt(); int b = scanner.nextInt(); printWriter.write(""Case #"" + (i+1) + "": "" + solve(a,b) + ""\n""); } printWriter.close(); scanner.close(); } private static int solve(int a, int b) { int c = 0; int t[] = new int[6]; for (int n = a; n <= b; n++) { // calc 'd' as number of digits int d = 0; int nn = n; while (nn > 0) { d++; nn /= 10; } // fill 't' with rotated numbers for (int i = 1; i < d; i++) { t[i - 1] = (n % POWERS_OF_TEN[i]) * POWERS_OF_TEN[d-i] + (n / POWERS_OF_TEN[i]); } // see how many of numbers from 't' form a pair for (int i = 0; i < d - 1; i++) { if (t[i] > n && t[i] <= b) { boolean alreadyIncluded = false; for (int j=0;j inputVector = null; try { file = filesHandler.openFileForReading(inputFilename); inputVector = filesHandler.readLinesFromFile(file); } catch (GiveUpException e) { System.err.println(""exiting..""); } catch (IOException e) { System.err.println(""error while reading..""); } // ---------------| Place Code Here |------------------------- // output = Practice( inputVector ); // output = QualificationRound_A(inputVector); // output = QualificationRound_B(inputVector); output = QualificationRound_C(inputVector); // -----------------| End of Code |--------------------------- try { filesHandler.writeToFile(outputFilename, output); System.out.println(""\n----------------------------------\n""); System.out.println(output); } catch (GiveUpException e) { System.err.println(""error while writing..""); } } private static String QualificationRound_A(Vector pInputVector) { String output = """"; int T = Integer.valueOf(pInputVector.get(0)); for (int i = 1; i <= T; i++) { String result = Googlerese.translate(pInputVector.get(i)); output = output + ""Case #"" + i + "": "" + result + ""\n""; } return output; } private static String QualificationRound_B(Vector pInputVector) { String output = """"; int T = Integer.valueOf(pInputVector.get(0)); for (int i = 1; i <= T; i++) { String line[] = pInputVector.get(i).split("" ""); int N = Integer.parseInt(line[0]); int S = Integer.parseInt(line[1]); int P = Integer.parseInt(line[2]); int[] Ti = new int[N]; for (int j = 0; j < N; j++) Ti[j] = Integer.parseInt(line[j + 3]); int result = Dancing.howMany(N, S, P, Ti); output = output + ""Case #"" + i + "": "" + result + ""\n""; } return output; } private static String QualificationRound_C(Vector pInputVector) { String output = """"; int T = Integer.valueOf(pInputVector.get(0)); for (int i = 1; i <= T; i++) { String line[] = pInputVector.get(i).split("" ""); int A = Integer.parseInt(line[0]); int B = Integer.parseInt(line[1]); int result = Recycled.howMany(A, B); output = output + ""Case #"" + i + "": "" + result + ""\n""; } return output; } } " B13176,"package com.irabin.google.codejam.problem3; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Scanner; public class RecycledNumber { private Scanner scanner; private PrintWriter writer; public RecycledNumber(InputStream in, OutputStream os) { scanner = new Scanner(in); writer = new PrintWriter(os); } public void solve() { int n = Integer.parseInt(scanner.nextLine()); for (int i = 1; i <= n; i++) { writer.print(""Case #"" + i + "": ""); String output = """"; int A = scanner.nextInt(); int B = scanner.nextInt(); int total = 0; for (int j = A; j <= B; j++) { String str = String.valueOf(j); if (str.length() < 2) { continue; } int startIndex = 1; int endIndex = str.length(); while (startIndex < endIndex) { String notSubStr = str.substring(0, startIndex); String substr = str.substring(startIndex); String newValue = substr.concat(notSubStr); int C = Integer.valueOf(newValue); String strJ = String.valueOf(j); String strC = String.valueOf(C); if (A<=j && j < C && C <= B && strJ.length()==strC.length()) { total = total + 1; } startIndex = startIndex + 1; } } output = String.valueOf(total); writer.println(output); writer.flush(); } writer.close(); } public static void main(String args[]) { InputStream input = null; input = RecycledNumber.class.getResourceAsStream(args[0]); OutputStream output = null; try { output = new FileOutputStream(args[1]); } catch (FileNotFoundException e) { e.printStackTrace(); } RecycledNumber practise1 = new RecycledNumber(input, output); practise1.solve(); } } " B11397,"/* @Gayan Kaushalya * 14-04-2012 * */ import java.util.Scanner; import java.io.*; public class Numbers{ static String[] inp; static String[] inpp; static String oo; public static void main(String args[])throws IOException{ FileInputStream in = new FileInputStream(""C-small-attempt0.in""); DataInputStream inn = new DataInputStream(in); BufferedReader br = new BufferedReader(new InputStreamReader(inn)); FileWriter out = new FileWriter(""out1.txt""); BufferedWriter bw = new BufferedWriter(out); int num = Integer.parseInt(br.readLine()); inp = new String[num]; inpp = new String[num]; for(int i=0; im) return 0; if( (nn.substring(0,1)==""0"") || (mm.substring(0,1)==""0"") ) return 0; if(mm.length()!=nn.length()) return 0; if(mm.length()==1) return 0; else{ for(int i=1; i 0 && m < a.length && a[m] >= a[0] && a.length == b.length && checkSmallerThan(a, b, m)) { if (a[m] == a[0]) { int indexMoved = m + 1; int indexOriginal = 1; int arrayLength = a.length; while (indexMoved < arrayLength) { if (a[indexMoved] > a[indexOriginal]) { return true; } else if (a[indexMoved] < a[indexOriginal]) { return false; } indexMoved++; indexOriginal++; } int i = 0; int delta = arrayLength - m; while ((i + delta) < a.length) { if (a[i] > a[i + delta]) { return true; } else if (a[i] < a[i + delta]) { return false; } i++; } return false; } else { return true; } } else { return false; } } private static boolean checkSmallerThan(int a[], int b[], int m) { int changableM = m; int arrayLength = a.length; int actualIndex = 0; while (changableM < arrayLength) { if (a[changableM] < b[actualIndex]) { return true; } else if (a[changableM] > b[actualIndex]) { return false; } changableM++; actualIndex++; } int indexA = 0; while (indexA < m) { if (a[indexA] < b[actualIndex]) { return true; } else if (a[indexA] > b[actualIndex]) { return false; } indexA++; actualIndex++; } return true; } private static int recycle(int a, int b) { int counter = 0; int[] bArray = intToArray(b); int constantM = bArray.length - 1; while (a <= b) { int[] aArray = intToArray(a); int m = constantM; ArrayList listOfChangedNumbers = new ArrayList<>(); while (m > 0) { if (validRecycledNumber(aArray, bArray, m)) { int recycledNumber = moveRecycled(aArray, m); if (!listOfChangedNumbers.contains(recycledNumber)) { listOfChangedNumbers.add(recycledNumber); counter++; } } m--; } a++; } return counter; } private static int moveRecycled(int[] a, int m) { int result = 0; int changableM = m; int aLength = a.length; String[] resultArray = new String[aLength]; int index = 0; while (changableM < aLength) { resultArray[index] = Integer.toString(a[changableM]); changableM++; index++; } int actualIndex = 0; while (index < aLength) { resultArray[index] = Integer.toString(a[actualIndex]); index++; actualIndex++; } String resultString = """"; int i = 0; while (i < resultArray.length) { resultString = resultString + resultArray[i]; i++; } result = Integer.parseInt(resultString); return result; } } " B10046,"import java.util.List; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Scanner; import java.util.Set; public class ProblemC { /** * @param args */ public static void main(String[] args) { File in = new File( ""D:/Feng/Workspace/googlecodejam2012/problemC/in/C-small-attempt0.in""); try { BufferedWriter out = new BufferedWriter(new FileWriter( ""D:/Feng/Workspace/googlecodejam2012/problemC/out/out.txt"")); StringBuilder s; String line = """"; int min, max = 0; int count = 1; Scanner scanner = new Scanner(in); // Ignore the first line showing total count scanner.nextLine(); while (scanner.hasNextLine()) { s = new StringBuilder(""Case #""); s.append(count); s.append("": ""); line = scanner.nextLine(); String[] limits = line.split("" ""); min = Integer.parseInt(limits[0]); max = Integer.parseInt(limits[1]); s.append(countRecycledPairs(min, max)); System.out.println(s); out.write(s.toString()); out.newLine(); count++; } scanner.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static int countRecycledPairs(int min, int max) { //List recycledPairs = new ArrayList(1000); Set recycledPairs = new HashSet(); String s = """"; int m; for (int n = min; n < max; n++) { // Need at least 2 digits to recycle // Cannot have trailing zeroes i.e. n mod 10 = 0 // Cannot have digits that are all the same s = String.valueOf(n); for (int numDigitsToReplace = 1; numDigitsToReplace < s.length(); numDigitsToReplace++) { // System.out.print(numDigitsToReplace + "", ""); m = recycle(n, numDigitsToReplace); if ((m > n) && (m <= max)) { recycledPairs.add(n + "":"" + m); //count++; } } } //System.out.print(recycledPairs.size()); //System.out.println(recycledPairs.toString()); return recycledPairs.size(); } public static int recycle(int n, int numDigits) { String s = String.valueOf(n); StringBuilder sb = new StringBuilder(s); String rearDigits = s.substring(s.length() - numDigits); sb.delete(sb.length() - numDigits, sb.length()); sb.insert(0, rearDigits); if (sb.toString().startsWith(""0"")) { return 0; } return Integer.parseInt(sb.toString()); } public static boolean hasSameDigits(int i) { String s = String.valueOf(i); char[] chars = s.toCharArray(); char firstDigit = chars[0]; for (char c : chars) { if (c != firstDigit) return false; } return true; } } " B11500," import java.util.*; import java.io.*; public class Recycle { public static void main(String[] args) { try { Scanner scan = new Scanner(new File(""Recycle.in"")); int x = Integer.parseInt(scan.nextLine()); for(int y=0;y set = new HashSet(); for (int i = 0; i < l; ++i) { m = m / 10 + ((int) Math.pow(10, l-1)) * (m % 10); if (m > n && m <= B) { set.add(m); } } count += set.size(); } return count; } public static void main(String[] args) throws IOException { String filename = args[0]; BufferedReader br = new BufferedReader(new FileReader(filename)); int T = Integer.parseInt(br.readLine()); for (int i = 1; i <= T; ++i) { String[] line = br.readLine().split("" ""); int A = Integer.parseInt(line[0]); int B = Integer.parseInt(line[1]); System.out.println(""Case #"" + i + "": "" + count(A, B)); } } }" B10191,"package CodeJam2012.Qualification; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; public class ProblemC { private static final String DIRECTORIO = ""D:\\CodeJam\\CodeJam2012\\Qualification\\ProblemC\\""; private static final String FILE_IN = ""ejemplo.in""; // private static final String FILE_IN = ""A-small-practice.in""; // private static final String FILE_IN = ""A-small-attempt0.in""; // private static final String FILE_IN = ""A-large.in""; private static final String FILE_OUT = ""ejemplo.out""; // private static final String FILE_OUT = ""a-small-practice.out""; // private static final String FILE_OUT = ""a-small.out""; // private static final String FILE_OUT = ""a-large.out""; public static void main(String[] args) throws Exception { // Se prepara para leer del fichero y escribir FileReader fr = new FileReader(DIRECTORIO + FILE_IN); BufferedReader bf = new BufferedReader(fr); File ficheroOut = new File(DIRECTORIO + FILE_OUT); ficheroOut.delete(); BufferedWriter bw = new BufferedWriter(new FileWriter(ficheroOut)); int casosPrueba = Integer.parseInt(bf.readLine()); // Se hace cada caso de prueba for (int index = 1; index <= casosPrueba; index++) { String[] entrada = bf.readLine().split("" ""); long A = Integer.parseInt(entrada[0]); long B = Integer.parseInt(entrada[1]); int parejasEncontradas = 0; for (long i=A; i<=B; i++){ long digitos = (long) Math.ceil(Math.log10(B)); ArrayList listaFijos = new ArrayList(); for (int j = 1; j < digitos; j++) { long maximo = (long) Math.pow(10, j); long candidato = (long) Math.floor((i / maximo)); candidato = (long) (candidato + (i % maximo) * Math.pow(10, digitos - j)); if (candidato <= B && candidato > i && !listaFijos.contains(candidato)) { listaFijos.add(candidato); parejasEncontradas++; } } } // Se escribe la solución del caso en pantalla y en fichero String solucion = ""Case #"" + index + "": "" + parejasEncontradas; bw.write(solucion); bw.newLine(); System.out.println(solucion); } // Se cierra el buffer de escritura bw.close(); } } " B13217,"import java.util.*; public class codejam { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); int m=sc.nextInt(); int i; int j; int k; int x; int y; int l; int z; for(i=1;i<=m;i++) { int a=sc.nextInt(); int b=sc.nextInt(); int count=0; for(j=a;j<=b;j++) { x=j; l=Integer.toString(j).length(); int[] used=new int[l]; for(k=1;k<=l-1;k++) { // shift k digits y=(int)Math.pow(10, k)*(x%(int)Math.pow(10, l-k))+x/(int)Math.pow(10,l-k); y=y+2-2; if(x 1) { for (int m = 0; m < myarr.length; m++) { for (int j = 0; j < mystr_length; j++) { if (myarr[m][0] != -1) { for (int z = j + 1; z < mystr_length; z++) { if (myarr[m][j] != -1) { if (myarr[m][j] >= first && myarr[m][j] <= second && myarr[m][z] >= first && myarr[m][z] <= second && myarr[m][j] != myarr[m][z] && myarr[m][z] != -1) { count++; } } } } } } } bw.write(""Case #""+(printer+1)+"": ""+count); bw.newLine(); bw.flush(); } } catch (IOException ex) { } finally { try { bf.close(); } catch (IOException ex) { } } } }" B10877,"package de.at.codejam.problem3.gui; import de.at.codejam.AbstractCodeJamProblemSolver; import de.at.codejam.gui.AbstractCodeJamClient; import de.at.codejam.problem3.Problem3Case; import de.at.codejam.problem3.Problem3Solver; public class Problem3Client extends AbstractCodeJamClient { @Override protected AbstractCodeJamProblemSolver getTaskSolver() { return new Problem3Solver(); } @Override protected String getAssignmentName() { return ""Recycled Numbers""; } public static final void main(String[] args) { Problem3Client client = new Problem3Client(); client.start(); } } " B10344,"package codejam.recycle; import java.util.HashSet; import java.util.Set; public class Recycle { public String solve(String s) { String[] ss = s.split("" ""); int a = Integer.parseInt(ss[0]); int b = Integer.parseInt(ss[1]); int n = ("""" + a).length(); int m = 0; for (int i = a; i <= b; i++) { int[] digits = collectDigits(i); Set done = new HashSet(); for (int j = 1; j < n; j++) { int t = offsetNum(digits, j); if (t <= b && t > i && done.add(t)) { m++; } } } return """" + m; } private int[] collectDigits(int num) { int n = ("""" + num).length(); int[] digits = new int[n]; int i = n; while (i > 0) { digits[--i] = num % 10; num = (int) (num / 10d); } return digits; } private int offsetNum(int[] x, int m) { int a = 0; for (int i = 0; i < x.length; i++) { a += x[(i + m) % x.length] * Math.pow(10, x.length - 1 - i); } return a; } } " B10307,"package bsevero.codejam.qualification; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { private static Set FOUND_PAIRS = new HashSet(); public static int recycle(String minStr, String maxStr) { FOUND_PAIRS = new HashSet(); int min = Integer.valueOf(minStr); int max = Integer.valueOf(maxStr); int total = 0; for(int i = min; i <= max; i++) { total += calculate(i, min, max); } return total; } private static int calculate(int value, int min, int max) { String valueStr = String.valueOf(value); if(valueStr.length() < 2) { return 0; } int count = 0; for(int numDigits = 1; numDigits < valueStr.length(); numDigits++) { String newValueStr = valueStr.substring(valueStr.length() - numDigits, valueStr.length()) + valueStr.substring(0, valueStr.length() - numDigits); int newValue = Integer.valueOf(newValueStr); if(newValue > value && newValue <= max) { if(!FOUND_PAIRS.contains(value + "" "" + newValue)) { FOUND_PAIRS.add(value + "" "" + newValue); count++; } } } return count; } } " B10608,"package io; import java.io.File; import java.util.Scanner; public class Reader { public static String[] getInput(File f){ try { Scanner reader = new Scanner(f); int numLines = Integer.parseInt(reader.nextLine()); String[] res = new String[numLines]; for (int i = 0; i < res.length; i++)res[i] = reader.nextLine(); return res; } catch (Exception e) { e.printStackTrace(); return null; } } } " B11546,"package RecycledNumbers; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Arrays; import java.util.Hashtable; import DancingWithGooglers.Googler; public class MainProcess { /** * @param args */ private int A ; private int B ; public MainProcess(File f){ readFile(f); } private void readFile(File f){ int numCase = 0; try { FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr); String str = """"; if( (str = br.readLine())!=null){ numCase = Integer.parseInt(str); } int count = 0; while( count < numCase){ str = br.readLine(); String[] substr = str.split("" ""); A = Integer.parseInt(substr[0]); B = Integer.parseInt(substr[1]); findAns(count ,substr[0].length()); count++; } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void findAns(int count , int numDigit){ int totalPair=0; if(numDigit<=1){ System.out.println(""Case #"" + (count+1) + "": 0""); } else{ for(int i=A ; i<=B ; i++){ totalPair += findPair(i , numDigit); } System.out.println(""Case #"" + (count+1) + "": "" + totalPair); } } private int findPair(int number , int numDigit){ Hashtable usedTable = new Hashtable(); int numPair =0; for(int i=1 ; i number){ if(!usedTable.containsKey(newNumber)){ numPair++; usedTable.put(newNumber, true); } } } return numPair; } private int getPower(int n){ int number = 1; if(n==0) return number; else{ for(int i=0 ; i< n ; i++){ number *=10; } return number; } } public static void main(String[] args) { // TODO Auto-generated method stub File f = new File("".\\src\\RecycledNumbers\\C-small-attempt0.in""); MainProcess m = new MainProcess(f); } } " B10658,"import java.util.ArrayList; import java.io.IOException; public class exo2 { public static ArrayList listeCouple = new ArrayList() ; public static int T; public static int A ; public static int B ; public static int Result = 0 ; static int k ; static int l ; static int m ; static int n ; static int o ; static int p ; static int q ; public static void digit2(int A,int B,int D){ k = D%10 ; l = (D-k)/10 ; if((k*10+l)>=A && (k*10+l)<=B && !listeCouple.contains(k*10+l) && (k*10+l)>D){ Result = Result + 1 ; listeCouple.add(k*10+l); } } public static void digit3(int A,int B,int D){ k = D%10 ; l = ((D-k)%100) /10; m = (D-l*10-k ) /100; if ((k*100+m*10+l)>=A &&(k*100+m*10+l)<=B //&& !listeCouple.contains(k*100+m*10+l) && (k*100+m*10+l)>D ) { Result = Result + 1 ; //listeCouple.add(k*100+m*10+l); } if ((l*100+k*10+m)>=A &&(l*100+k*10+m)<=B //&& !listeCouple.contains(l*100+k*10+m) &&(l*100+k*10+m)>D ) { Result = Result + 1 ; //listeCouple.add(l*100+k*10+m); } } public static void digit4(int A,int B,int D){ k = D%10 ; l = ((D-k)%100) /10; m = (D-l*10-k)%1000 /100 ; n = (D-m*100-l*10-k)/1000; if ((k*1000+n*100+m*10+l)>=A && (k*1000+n*100+m*10+l)<=B //&& !listeCouple.contains(l*1000+k*100+n*10+m) &&(k*1000+n*100+m*10+l)>D ){ Result = Result + 1 ; //listeCouple.add(k*1000+n*100+m*10+l); } if ((l*1000+k*100+n*10+m)>=A &&(l*1000+k*100+n*10+m)<=B //&& !listeCouple.contains(l*1000+k*100+n*10+m) &&(l*1000+k*100+n*10+m)>D ){ Result = Result + 1 ; //listeCouple.add(l*1000+k*100+n*10+m); } if ((m*1000+l*100+k*10+n)>=A &&(m*1000+l*100+k*10+n)<=B //&& !listeCouple.contains(l*1000+k*100+n*10+m) &&(m*1000+l*100+k*10+n)>D ){ Result = Result + 1 ; //listeCouple.add(m*1000+l*100+k*10+n); } } public static void digit5(int A,int B,int D){ k = D%10 ; l = ((D-k)%100) /10; m = (D-l*10-k)%1000 /100 ; n = ((D-m*100-l*10-k)%10000) / 1000; o = (D-n*1000-m*100-l*10-k)/10000 ; if ((k*10000+o*1000+n*100+m*10+l)>=A && (k*10000+o*1000+n*100+m*10+l)<=B && !listeCouple.contains(k*10000+o*1000+n*100+m*10+l)) { Result = Result + 1 ; listeCouple.add(k*10000+o*1000+n*100+m*10+l); } if ((l*10000+k*1000+o*100+n*10+m)>=A && (l*10000+k*1000+o*100+n*10+m)<=B && !listeCouple.contains(l*10000+k*1000+o*100+n*10+m) ) { Result = Result + 1 ; listeCouple.add(l*10000+k*1000+o*100+n*10+m); } if ((m*10000+l*1000*k*100+o*10+n)>=A && (m*10000+l*1000*k*100+o*10+n)<=B && !listeCouple.contains(m*10000+l*1000*k*100+o*10+n)){ Result = Result + 1 ; listeCouple.add(m*10000+l*1000*k*100+o*10+n); } if ((n*10000+m*1000*l*100+k*10+o)>=A && (n*10000+m*1000*l*100+k*10+o)<=B && !listeCouple.contains(n*10000+m*1000*l*100+k*10+o)){ Result = Result + 1 ; listeCouple.add(m*10000+l*1000*k*100+o*10+n); } } public static void digit6(int A,int B, int D){ k = D%10 ; l = ((D-k)%100) /10; m = (D-l*10-k)%1000 /100 ; n = ((D-m*100-l*10-k)%10000) / 1000; o = ((D-n*1000-m*100-l*10-k)%100000) /10000; p = (D-o*10000-n*1000-m*100-l*10-k)/100000 ; if ((k*100000+p*10000+p*1000+n*100+m*10+l)>=A && (k*100000+p*10000+p*1000+n*100+m*10+l)<=B && !listeCouple.contains(k*100000+p*10000+p*1000+n*100+m*10+l)) { Result = Result + 1 ; listeCouple.add(k*100000+p*10000+p*1000+n*100+m*10+l); } if ((l*100000+k*10000+p*1000+o*100+n*10+m)>=A && (l*100000+k*10000+p*1000+o*100+n*10+m)<=B && !listeCouple.contains(l*100000+k*10000+p*1000+o*100+n*10+m) ) { Result = Result + 1 ; listeCouple.add(l*100000+k*10000+p*1000+o*100+n*10+m); } if ((m*100000+l*10000*k*1000+p*100+o*10+n)>=A && (m*100000+l*10000*k*1000+p*100+o*10+n)<=B && !listeCouple.contains(m*100000+l*10000*k*1000+p*100+o*10+n)){ Result = Result + 1 ; listeCouple.add(m*100000+l*10000*k*1000+p*100+o*10+n); } if ((n*100000+m*10000*l*1000+k*100+p*10+o)>=A && (n*100000+m*10000*l*1000+k*100+p*10+o)<=B && !listeCouple.contains(n*100000+m*10000*l*1000+k*100+p*10+o)){ Result = Result + 1 ; listeCouple.add(n*100000+m*10000*l*1000+k*100+p*10+o); } if ((o*100000+n*10000+m*1000*l*100+k*10+p)>=A && (o*100000+n*10000+m*1000*l*100+k*10+p)<=B && !listeCouple.contains(o*100000+n*10000+m*1000*l*100+k*10+p)){ Result = Result + 1 ; listeCouple.add(o*100000+n*10000+m*1000*l*100+k*10+p); } } public static void digit7(int A,int B,int D){ k = D%10 ; l = ((D-k)%100) /10; m = (D-l*10-k)%1000 /100 ; n = ((D-m*100-l*10-k)%10000) / 1000; o = ((D-n*1000-m*100-l*10-k)%100000) /10000; p = ((D-o*10000-n*1000-m*100-l*10-k)%1000000)/100000 ; q = (D-p*100000-o*10000-n*1000-m*100-l*10-k)/1000000 ; if ((k*1000000+q*100000+p*10000+o*1000+n*100+m*10+l)>=A && (k*1000000+q*100000+p*10000+o*1000+n*100+m*10+l)<=B && !listeCouple.contains(k*1000000+q*100000+p*10000+o*1000+n*100+m*10+l)) { Result = Result + 1 ; listeCouple.add(k*1000000+q*100000+p*10000+o*1000+n*100+m*10+l); } if ((l*1000000+k*100000+q*10000+p*1000+o*100+n*10+m)>=A && (l*1000000+k*100000+q*10000+p*1000+o*100+n*10+m)<=B && !listeCouple.contains(l*1000000+k*100000+q*10000+p*1000+o*100+n*10+m) ) { Result = Result + 1 ; listeCouple.add(l*1000000+k*100000+q*10000+p*1000+o*100+n*10+m); } if ((m*1000000+l*100000+k*10000+q*1000+p*100+o*10+n)>=A && (m*1000000+l*100000+k*10000+q*1000+p*100+o*10+n)<=B && !listeCouple.contains(m*1000000+l*100000+k*10000+q*1000+p*100+o*10+n)){ Result = Result + 1 ; listeCouple.add(m*1000000+l*100000+k*10000+q*1000+p*100+o*10+n); } if ((n*1000000+m*100000+l*10000+k*1000+q*100+p*10+o)>=A && (n*1000000+m*100000+l*10000+k*1000+q*100+p*10+o)<=B && !listeCouple.contains(n*1000000+m*100000+l*10000+k*1000+q*100+p*10+o)){ Result = Result + 1 ; listeCouple.add(n*1000000+m*100000+l*10000+k*1000+q*100+p*10+o); } if ((o*1000000+n*100000+m*10000+l*1000+k*100+q*10+p)>=A && (o*1000000+n*100000+m*10000+l*1000+k*100+q*10+p)<=B && !listeCouple.contains(o*1000000+n*100000+m*10000+l*1000+k*100+q*10+p)){ Result = Result + 1 ; listeCouple.add(o*1000000+n*100000+m*10000+l*1000+k*100+q*10+p); } if ((p*1000000+o*100000+n*10000+m*1000+l*100+k*10+q)>=A && (p*1000000+o*100000+n*10000+m*1000+l*100+k*10+q)<=B && !listeCouple.contains(p*1000000+o*100000+n*10000+m*1000+l*100+k*10+q)){ Result = Result + 1 ; listeCouple.add(p*1000000+o*100000+n*10000+m*1000+l*100+k*10+q); } } public static void traiter(int A,int B, int j) { int D = A ; if (B<10) { Result = 0 ; } else if (B<=100){ for (int i=0;i<(B-A);i++){ digit2(A,B,D+i); } } else if(B<1000){ for (int i=0;i<(B-A);i++){ digit3(A,B,D+i); } } else if(B<10000){ for (int i=0;i<(B-A);i++){ digit4(A,B,D+i); } } else if(B<100000){ for (int i=0;i<(B-A);i++){ digit5(A,B,A+i); } } else if(B<1000000){ for (int i=0;i<(B-A);i++){ digit6(A,B,A+i); } } else if(B<10000000){ for (int i=0;i<(B-A);i++){ digit7(A,B,A+i); } } } public static void read(String arg) throws java.io.IOException { java.util.Scanner lecteur ; java.io.File fichier = new java.io.File(arg); lecteur = new java.util.Scanner(fichier); T = lecteur.nextInt() ; for (int i=0;i<=T;i++){ if (lecteur.hasNextInt()){ A = lecteur.nextInt(); B = lecteur.nextInt() ; traiter(A,B,i); System.out.println(""Case #""+(i+1)+"": ""+Result); } Result = 0 ; listeCouple.removeAll(listeCouple) ; } } public static void main(String[] args) throws IOException{ String arg = null; arg = ""C-small-attempt2.in"" ; read(arg) ; } }" B12793,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class ProblemB { /** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { // TODO Auto-generated method stub Scanner scanner = new Scanner(new File(""/Users/phan/Downloads/C-small-attempt0.in"")); PrintWriter pw = new PrintWriter(""/Users/phan/Downloads/output""); int t = scanner.nextInt(); for (int i = 1; i <= t; i++) { int A = scanner.nextInt(); int B = scanner.nextInt(); int cnt = 0; for (int n = A; n <= B; n++) { int[] digits = new int[7]; int tmp = n; int cntdigit = 0; while (tmp > 0) { digits[cntdigit++] = tmp % 10; tmp = tmp / 10; } int[] mm = new int[cntdigit]; int cnt2 = 0; for (int j = 1; j < cntdigit; j++) { int m = 0; for (int k = j - 1; k >= 0; k--) m = m * 10 + digits[k]; for (int k = cntdigit - 1; k >= j; k--) m = m * 10 + digits[k]; if ( (n < m) && (m <= B) ) { boolean b = true; for (int l = 0; l < cnt2; l++) if (mm[l] == m) b = false; if (b) { cnt++; mm[cnt2++] = m; //System.out.println(n + "" "" + m); } } } } pw.println(""Case #"" + String.valueOf(i) + "": "" + String.valueOf(cnt)); } scanner.close(); pw.close(); } } " B12821,"package zid; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; import java.util.StringTokenizer; public class Cycle { HashSet set = new HashSet(); public static void main(String[] args) { Cycle c = new Cycle(); c.start(args[0]); } private void start(String filename) { try { BufferedReader br = new BufferedReader(new FileReader(filename)); int N = Integer.parseInt(br.readLine()); int n = 1; while (n <= N) { StringTokenizer st = new StringTokenizer(br.readLine()); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); int COUNT = 0; set.clear(); for (int i = A; i <= B; i++) { String iNum = """" + i; int iDigitCount = iNum.length(); for (int j = 0; j < iDigitCount; j++) { iNum = getRecycled(iNum); int recycled = Integer.parseInt(iNum); int recycledDigitCount = iNum.length(); if ( (i < recycled) && (A <= i && recycled <= B) && (recycledDigitCount == iDigitCount) ) { String entry = String.format(""%d|%d"", i, recycled); if (!set.contains(entry)) { set.add(entry); COUNT++; //System.out.println(String.format(""%d | %d"", i, // recycled)); } //else // System.out.println(entry); } } } System.out.println(String.format(""Case #%d: %s"", n,COUNT)); n++; } } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private String getRecycled(String i) { String s = new String(i + """"); String s2 = s.substring(s.length() - 1); s = s.substring(0, s.length()-1); s = s2 + s; return s; } } " B10589,"import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Scanner; public class RecycledNumbers { static ArrayList included; public static void main(String[] args) { // Scanner sc = new Scanner(System.in); Scanner sc; try { sc = new Scanner(new FileInputStream(""C-small-attempt0.in"")); } catch (FileNotFoundException e) { sc = new Scanner(System.in); // file not exist, so get input from console } Writer out; try { out = new OutputStreamWriter(new FileOutputStream(""C-small.out"")); } catch (FileNotFoundException e) { out = new OutputStreamWriter(System.out); // use console } int T = sc.nextInt(); // sc.nextLine(); for (int t = 0; t < T; t++) { int A = sc.nextInt(), B = sc.nextInt(); int count = 0; included = new ArrayList(); for (int max = B; max > A; max--) { count += countShitMatches(max, A); } // output System.out.println(""Case #"" + (t + 1) + "": "" + count); try { out.write(""Case #"" + (t + 1) + "": "" + count + ""\n""); } catch (IOException e) { // do nothing } } try { out.close(); } catch (IOException e) { // do nothing } } static int countShitMatches(Integer input, int min) { int count = 0; String number = input.toString(); for (int i = 1; i < number.length(); i++) { number = digitShift(number); int result = Integer.parseInt(number); if (result >= min && result < input) if (!mappingExists(input, result)) { included.add(new intMapping(input, result)); count++; } } return count; } static String digitShift(String input) { // moves first digit to end of number represented by a String return input.substring(1).concat(input.substring(0, 1)); } // static Boolean mappingExists(Integer k, Integer v) { // return included.contains(new intMapping(k, v)); // } // static Boolean mappingExists(Integer k, Integer v) { // intMapping test = new intMapping(k, v); // // for (intMapping m : included) { // if (m.equals(test)) // return true; // } // // return false; // } static Boolean mappingExists(Integer k, Integer v) { for (intMapping m : included) { if (m.key == k && m.value == v) return true; if (m.key == v && m.value == k) return true; } return false; } static class intMapping { //implements Comparable { public int key, value; public intMapping(int k, int v) { key = k; value = v; } // @Override // public int compareTo(intMapping other) { // if ((other.key == this.key && other.value == this.value) || (other.key == this.value && other.value == this.key)) // return 0; // else return 1; // } } } " B13179,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.HashSet; import java.util.StringTokenizer; public class Problem2 { private static HashSet circularSet = new HashSet(); private static void shift(final long orgNumber_,final long numberN_,final long numberM_){ String orgStr = (""""+orgNumber_); if(orgStr.length() < 2){ return; } String retString = null; String cirKey = null; long shifted = -1; for(int i=0;i 0 && shifted != orgNumber_ && shifted >= numberN_ && shifted <= numberM_){ cirKey = orgNumber_ < shifted ? orgStr+""_""+shifted : shifted+""_""+orgStr; if(!circularSet.contains(cirKey)){ // System.out.println(cirKey); circularSet.add(cirKey); // }else{ // System.out.println(cirKey); } } } } public static void main(String args[]){ File inputFile = new File(args[0]); File outputFile = new File(args[0]+""_out""); try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile))); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile))); int testCases = Integer.parseInt(br.readLine()); String givenNumbers = null; for(int i=0;i getList(long set, int n) { ArrayList integers = new ArrayList<>(); for (int i=0;ilong getForList(Map positions, List objs) { long res = 0L; for (T obj : objs) { int pos = positions.get(obj); res |= getOne(pos); } return res; } public static void cycleSubsets(int num, SubsetCallBack callBack) { callBack.run(0, 0); for (int i = 1; i<=num; i++) { CombinationGenerator generator = new CombinationGenerator(num,i); while (generator.hasMore()) { long n = 0; int[] next = generator.getNext(); for (int i1 : next) { n |= getOne(i1); } callBack.run(n,i); } } } public static interface SubsetCallBack { void run(long subset, int i); } } " B11377,"import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.util.Scanner; public class Main { /** * @param args */ static boolean isRecycled(String s1, String s2) { if (s1.length() != s2.length()) return false; if (s1.compareTo(s2) == 0) return true; for (int i = 0; i < s1.length(); i++) { char c = s1.charAt(0); s1 = s1.substring(1); s1 += c; if (s1.compareTo(s2) == 0) return true; } return false; } static int solve(int A, int B) { int count = 0; for (int i = A; i <= B; i++) for (int j = i + 1; j <= B; j++) { if (isRecycled(Integer.toString(i), Integer.toString(j))) count++; // System.out.println(); } return count; } public static void main(String[] args) throws Exception { Scanner scanner = new Scanner(new File(""input.txt"")); BufferedWriter writer = new BufferedWriter(new FileWriter(""output.txt"")); int N = scanner.nextInt(); for (int i = 1; i <= N; i++) { int A = scanner.nextInt(); int B = scanner.nextInt(); int res = solve(A,B); writer.append(""Case #"" + i + "": "" + res); writer.newLine(); } writer.close(); scanner.close(); } } " B10944,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class Main { public static void main(String args[]) throws NumberFormatException, IOException { BufferedReader in = new BufferedReader(new FileReader(""C-small-attempt0.in"")); PrintWriter out = new PrintWriter(new FileWriter(""out.txt"")); RecycledNumbers prog = new RecycledNumbers(); String inString = """"; int t = Integer.parseInt(in.readLine()); for(int i = 0; i < t; i++) { inString = in.readLine(); String[] word = inString.split("" ""); int a = Integer.parseInt(word[0]); int b = Integer.parseInt(word[1]); out.println(""Case #"" + (i+1) + "": "" + prog.getNumbers(a, b)); } in.close(); out.close(); } private static void printArray(String[] a) { for(int i = 0; i < a.length; i++) { System.out.print(a[i] + "" ""); } System.out.print(""\n""); } } " B10078,"import java.util.Scanner; /** * Abdulaziz * 4/14/12 */ public class Problem3 { public static void main(String[] args) { int count = 0; int t = 50; Scanner scanner = new Scanner(System.in); for (int q = 0; q <= t; q++) { count = 0; String str = scanner.nextLine(); String []arg = str.split("" ""); Integer a = Integer.parseInt(arg[0]); Integer b = Integer.parseInt(arg[1]); for (int i = a; i <= b; i++) { String input = String.valueOf(i); String changed; int len = input.length(); for (int j = 1; j < len; j++) { changed = input.substring(j, len) + input.substring(0, j); if (Integer.valueOf(changed) <= Integer.valueOf(input)) continue; if (Integer.valueOf(changed) <= b && Integer.valueOf(changed) >= a) { count++; } } } System.out.println(""Case #""+(q+1)+"": ""+count); } } } " B11152,"package main; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; public class QualificationC { public static void main(String[] args) throws IOException { String sampleIn = ""input/c_sample.in""; String sampleOut = ""output/c_sample.out""; String smallIn = ""input/C-small-attempt1.in""; String smallOut = ""output/C-small-attempt1.out""; String largeIn = ""input/C-large.in""; String largeOut = ""output/C-large.out""; String inFile = smallIn; String outFile = smallOut; FileWriter fstream = new FileWriter(outFile); BufferedWriter out = new BufferedWriter(fstream); int limit = 2000000; int ncase = 0; Map> map = mapGreaterRecycleds(limit); for (TestCase tc : loadTestCases(inFile)) { ncase++; long recycledsBetween = findPairsBetween(map, tc.a, tc.b); System.out.println(""Case #"" + ncase + "": "" + recycledsBetween); out.write(""Case #"" + ncase + "": "" + recycledsBetween + ""\n""); } out.close(); } private static void test(int n, int limit) { for (int r : getGreaterRecycleds(n, limit)) { System.out.println(r); } } private static long findPairsBetween(Map> map, int a, int b) { long ret = 0; for (int i=a; i> mapGreaterRecycleds(int maxB) { Map> map = new HashMap>(); for (int i = 1; i getGreaterRecycleds(int start, int maxB) { String s = Integer.toString(start); Set ret = new TreeSet(); for (int firstChar = 1; firstChar < s.length(); firstChar++) { String rebuild = s.substring(firstChar) + s.substring(0, firstChar); if (!rebuild.startsWith(""0"")) { int recycled = Integer.parseInt(rebuild); if (recycled <= maxB && recycled > start) { ret.add(recycled); } } } return ret; } public static List loadTestCases(String filename){ List cases = new LinkedList(); try{ BufferedReader reader = new BufferedReader(new FileReader(filename)); String tString = reader.readLine(); int t = Integer.parseInt(tString); for(int i=0; i seen; public static int a; public static int b; public static void main (String [] args) throws IOException { String filename = ""C-small-attempt0""; BufferedReader f = new BufferedReader(new FileReader(filename + "".in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(filename + "".out""))); int numberOfTests = Integer.parseInt(f.readLine()); seen = new HashSet(); for(int n = 1; n <= numberOfTests; n++) { StringTokenizer st = new StringTokenizer(f.readLine()); a = Integer.parseInt(st.nextToken()); b = Integer.parseInt(st.nextToken()); for(int i = a; i <= b; i++) { findNumRotations(i); } int solution = seen.size(); out.println(""Case #"" + n + "": "" + solution); seen = new HashSet(); } out.close(); System.exit(0); } public static void findNumRotations(int num) { int numRots = getRotationCount(num); for(int i = 1; i <= numRots; i++) { int rotated = rotate(num, i, numRots + 1); if (rotated > num && rotated <= b) { seen.add(num + "" "" + rotated); System.out.println(num + "" "" + rotated); } } } private static int rotate(int num, int amt, int digits) { int bottom = (int)(num / Math.pow(10, amt)); int top = (int)(num % Math.pow(10, amt)); return (int)(top * Math.pow(10, digits - amt) + bottom); } private static int getRotationCount(int num) { if (num < 10) return 0; int c = 0; while(num > 0) { num = num / 10; c++; } return c - 1; } } " B11328,"package recycledNumbers; import java.util.ArrayList; public class Algorithms { public static OutputData getOutput(InputData inputdata) { // TODO Auto-generated method stub int [] Results = new int[inputdata.getTest_Number()]; for(int i=0;i number = new ArrayList(); ArrayList numbers = new ArrayList(); int temp = i; while(temp/10>0){ number.add(temp%10); temp = temp/10; } number.add(temp%10); for(int j=0;j part = new ArrayList(); for(int k=0;k j && e <= limS){ k++; } }while(e != j); } os.write((""Case #"" + (i + 1) + "": "" + k+ ""\n"").getBytes()); } } catch (Exception e) { e.printStackTrace(); } } } " B11454,"package recyclednumbers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; public class RecycledNumbers { public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new FileReader(new File(""./recyclednumbers/c-small-attempt0.in""))); BufferedWriter bw=new BufferedWriter(new FileWriter(new File(""./recyclednumbers/small.out""))); int numberOfCase=Integer.parseInt(br.readLine()); StringBuilder out=new StringBuilder(); for(int i=1;i<=numberOfCase;i++){ out.append(""Case #""+i+"": ""); int count=0; String input=br.readLine(); int start=Integer.parseInt(input.substring(0,input.indexOf("" ""))); int end=Integer.parseInt(input.substring(input.indexOf("" "")+1)); for(int j=start;j<=end;j++){ ArrayListlist=new ArrayList(); int n=10; while(j>=n){ int last=j%n; int first=j/n; int recycle=last*(int)Math.pow(10, String.valueOf(first).length())+first; if(recycle>j && recycle<=end){ if(!list.contains(recycle)){ count++; list.add(recycle); } } n*=10; } } out.append(count); if(i recycledPairs = new HashSet(); int a = -1; int b = -1; int tokenCount = 0; while (tokenizer.hasMoreElements()) { tokenCount ++; String token = (String) tokenizer.nextElement(); if (tokenCount == 1) { a = Integer.parseInt(token); }else { b = Integer.parseInt(token); } } int originalA = a; int originalB = b; int noOfRecycledPairs = 0; if (a == b) { return 0; } while (a <= b) { String aStr = """" + a; String bStr = """" + b; int noOfDigits = aStr.length(); if (noOfDigits < 2) { break; }else { int noOfDigitsToMove = 1; while(noOfDigitsToMove < noOfDigits) { String movedDigitsString = aStr.substring(noOfDigits - noOfDigitsToMove); String unmovedDigitsString = aStr.substring(0, noOfDigits - noOfDigitsToMove); int movedDigits = Integer.parseInt(movedDigitsString); int unmovedDigits = Integer.parseInt(unmovedDigitsString); //Check if number at first index is 0. If yes, this is not a valid case int firstDigitOFMovedDigits = Integer.parseInt(movedDigitsString.substring(0,1)); if (firstDigitOFMovedDigits == 0) { noOfDigitsToMove ++; }else { String newNumberString = movedDigitsString + unmovedDigitsString; int newNumber = Integer.parseInt(newNumberString); System.out.println(""old number "" + a + "" new number :: "" + newNumber); if (newNumberString.length() == aStr.length()) { if(newNumber > a && newNumber <= originalB && a >= originalA) { System.out.println(""recycled pair found :: "" + a + "" and "" + newNumber); // Add pair found to a SET so that duplicates get ignored automatically recycledPairs.add(a + "","" + newNumberString); } } noOfDigitsToMove ++; } } } a ++; } noOfRecycledPairs = recycledPairs.size(); return noOfRecycledPairs; } /** * @param args */ public static void main(String[] args) { if (args.length < 2) { System.out.println(""Not enough command line arguments specified. Need 2 (Input and output file paths)""); return; } String inputFilePath = args[0]; try { // String buffer for storing the output StringBuffer output = new StringBuffer(); // Instantiate object to use non static methods RecycledNumbers recycled = new RecycledNumbers(); // read and parse input file FileInputStream fstream = new FileInputStream(inputFilePath); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; int lineNumber = 0; int noOfTestCases = -1; int activeTestCaseNumber = 0; while ((strLine = br.readLine()) != null) { if (lineNumber == 0) { noOfTestCases = Integer.parseInt(strLine); } else { noOfTestCases ++; activeTestCaseNumber ++; // Now that a test case has been parsed, compute output for // this test case // Invoke algorithm here int solutionToTestCase = recycled.computeCountOfRecycledPairs(strLine); // Prepare output string System.out.println(solutionToTestCase); output.append(""Case #"" + activeTestCaseNumber + "": "" + solutionToTestCase); output.append(""\n""); } lineNumber++; } in.close(); // Pass output string to method to write to file recycled.writeOutputToFile(output.toString(), args[1]); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // File read cleanup } } }" B10973,"import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; public class TaskC { static int numberLength; public static void main(String[] args ) throws FileNotFoundException { File fileName = new File(""taskc.txt""); Scanner inFile = new Scanner(fileName); int n = inFile.nextInt(); inFile.useDelimiter(""\\r?\\n""); String[] cases = new String[n]; for (int i = 0; i < n; i++) cases[i] = inFile.next(); List result = new ArrayList(); for (String caseString: cases) { int recycledNumbers = 0; Scanner caseScanner = new Scanner(caseString); String lowerBoundString = caseScanner.next(); int lowerBound = Integer.parseInt(lowerBoundString); int upperBound = caseScanner.nextInt(); for (int i = lowerBound; i <= upperBound; i++) { String iString = new Integer(i).toString(); for (int j = i + 1; j <= upperBound; j++) { String jString = new Integer(j).toString(); if (evaluate(iString, jString)) recycledNumbers++; } } result.add("""" + recycledNumbers); } for (int i = 0; i < result.size(); i++) { System.out.println(""Case #"" + (i+1) + "": "" + result.get(i)); } } private static boolean evaluate(String iString, String jString) { for (int n = 1; n < jString.length(); n++) { String testString = jString.substring(n) + jString.substring(0, n); if (iString.equals(testString)) return true; } return false; } } " B12325,"import java.io.* ; import java.util.* ; public class FileReaderWriter { public static final int WRITE_MODE = 1 ; public static final int READ_MODE = 2 ; private File file ; private BufferedReader br ; private PrintWriter pw ; private int mode ; FileReaderWriter(String fileName , int mode) throws Exception { this.file = new File(fileName) ; this.mode = mode ; if(mode == FileReaderWriter.READ_MODE) { if(!(file.isFile() && file.exists())) { throw new Exception("" File ""+file.getPath()+"" is not available for reading !"") ; } else { br = new BufferedReader(new FileReader(this.file)) ; } } else if(mode == FileReaderWriter.WRITE_MODE) { pw = new PrintWriter(new FileWriter(this.file)) ; } else { throw new Exception(""Unsupported File mode"") ; } } public String readLine() throws Exception { return br.readLine() ; } public Integer readInt() throws Exception { return Integer.parseInt(br.readLine()) ; } public ArrayList readStrList() throws Exception { String readStr = readLine() ; StringTokenizer stTokenizer = new StringTokenizer(readStr) ; ArrayList readStrList = new ArrayList(stTokenizer.countTokens()) ; while(stTokenizer.hasMoreTokens()) { readStrList.add(stTokenizer.nextToken()) ; } return readStrList ; } public ArrayList readIntList() throws Exception { String readStr = readLine() ; StringTokenizer stTokenizer = new StringTokenizer(readStr) ; ArrayList readIntList = new ArrayList(stTokenizer.countTokens()) ; while(stTokenizer.hasMoreTokens()) { readIntList.add(Integer.parseInt(stTokenizer.nextToken())) ; } return readIntList ; } public ArrayList readLongList() throws Exception { String readStr = readLine() ; StringTokenizer stTokenizer = new StringTokenizer(readStr) ; ArrayList readLongList = new ArrayList(stTokenizer.countTokens()) ; while(stTokenizer.hasMoreTokens()) { readLongList.add(Long.parseLong(stTokenizer.nextToken())) ; } return readLongList ; } public void write(String str) throws Exception { pw.print(str) ; pw.flush() ; } public void writeLine(String str) throws Exception { pw.println(str) ; pw.flush() ; } public void writeListLine(ArrayList list, String seperator) throws Exception { ListIterator iterator = list.listIterator() ; while(iterator.hasNext()) { pw.print(iterator.next()) ; if(iterator.hasNext()) pw.print(seperator) ; } pw.print(""\n""); pw.flush(); } public void close() throws Exception { if(mode == FileReaderWriter.READ_MODE) { br.close() ; } else if(mode == FileReaderWriter.WRITE_MODE) { pw.flush() ; pw.close() ; } } } " B10472,"import java.util.Scanner; import java.io.*; public class Prob3 { public static void main(String[] args) throws IOException{ Scanner in = new Scanner(new File(""D:/C-small-attempt0.in"")); PrintStream out = new PrintStream(new File(""D:/outputProb3.txt"")); int lineAmount = Integer.parseInt(in.nextLine()); for (int n = 1; n <= lineAmount; n++) { int a = in.nextInt(); int b = in.nextInt(); int count = 0; for (int i = a; i <= b; i++) { for (int j = ("""" + i).length()-1;j>=1; j--) { if (!("""" + i).substring(j, j+1).equals(""0"")) { String temp = ("""" + i).substring(j, ("""" + i).length()); String x = temp+("""" + i).substring(0, j); if (Integer.parseInt(x) >= a && Integer.parseInt(x) <= b && i != Integer.parseInt(x)) { count++; } } } } int y = count/2; out.println(""Case #""+n+"": ""+y); } in.close(); out.close(); } }" B11077,"package fixjava; import java.util.Collection; import java.util.Comparator; /** * Typed 3-tuple */ public class Tuple4 { private final A field0; private final B field1; private final C field2; private final D field3; public A getField0() { return field0; } public B getField1() { return field1; } public C getField2() { return field2; } public D getField3() { return field3; } public Tuple4(final A field0, final B field1, final C field2, final D field3) { this.field0 = field0; this.field1 = field1; this.field2 = field2; this.field3 = field3; } /** Convenience method so type params of pair don't have to be specified: just do Tuple4.make(a, b, c, d) */ public static Tuple4 make(A field0, B field1, C field2, D field3) { return new Tuple4(field0, field1, field2, field3); } // --------------------------------------------------------------------------------------------------- private static final boolean objEquals(Object p1, Object p2) { if (p1 == null) return p2 == null; return p1.equals(p2); } @Override public final boolean equals(Object o) { if (!(o instanceof Tuple4)) { return false; } else { final Tuple4 other = (Tuple4) o; return objEquals(getField0(), other.getField0()) && objEquals(getField1(), other.getField1()) && objEquals(getField2(), other.getField2()) && objEquals(getField3(), other.getField3()); } } @Override public int hashCode() { int h0 = getField0() == null ? 0 : getField0().hashCode(); int h1 = getField1() == null ? 0 : getField1().hashCode(); int h2 = getField2() == null ? 0 : getField2().hashCode(); int h3 = getField3() == null ? 0 : getField3().hashCode(); return h0 + 53 * h1 + 97 * h2 + 131 * h3; } // --------------------------------------------------------------------------------------------------- public static , B, C, D> Comparator> comparatorOnField0(Collection> tupleCollection) { return new Comparator>() { @Override public int compare(Tuple4 o1, Tuple4 o2) { return o1.getField0().compareTo(o2.getField0()); } }; } public static , C, D> Comparator> comparatorOnField1(Collection> tupleCollection) { return new Comparator>() { @Override public int compare(Tuple4 o1, Tuple4 o2) { return o1.getField1().compareTo(o2.getField1()); } }; } public static , D> Comparator> comparatorOnField2(Collection> tupleCollection) { return new Comparator>() { @Override public int compare(Tuple4 o1, Tuple4 o2) { return o1.getField2().compareTo(o2.getField2()); } }; } public static > Comparator> comparatorOnField3(Collection> tupleCollection) { return new Comparator>() { @Override public int compare(Tuple4 o1, Tuple4 o2) { return o1.getField3().compareTo(o2.getField3()); } }; } // --------------------------------------------------------------------------------------------------- @Override public String toString() { return ""("" + getField0() + "", "" + getField1() + "", "" + getField2() + "", "" + getField3() + "")""; } } " B11900,"package gcj2012; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.LinkedList; public class RecycledNumbers { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader reader = new BufferedReader(new FileReader(new File(""C:\\Users\\GAUTAM\\Downloads\\GCJ2012Inputs\\C-small-attempt0.in""))); int noOfInput = Integer.parseInt(reader.readLine()); StringBuilder finalOutput = new StringBuilder(); for(int i=1;i<=noOfInput;i++) { String input = reader.readLine(); String[] range = input.split("" ""); finalOutput.append(""Case #""+i + "": "" + result(Integer.parseInt(range[0]),Integer.parseInt(range[1]))+""\n""); } reader.close(); BufferedWriter writer = new BufferedWriter(new FileWriter(new File(""C:\\Users\\GAUTAM\\Downloads\\GCJ2012Outputs\\C-small.out""))); writer.write(finalOutput.toString()); writer.close(); } public static int result(int A, int B) { HashSet result = new HashSet(); for(int i = A; i <= B;i++) { LinkedList digits = digits(i); for(int k =0 ; k < digits.size()-1; k++) { int m = rightshift(digits,k); if(m >= A && m <= B && digits.size() == digits(m).size() && m != i) { if(!result.contains(String.valueOf(i) + ""-"" + String.valueOf(m)) && !result.contains(String.valueOf(m) + ""-"" + String.valueOf(i))) { result.add(String.valueOf(i) + ""-"" + String.valueOf(m)); } } } } return result.size(); } public static LinkedList digits(int num) { LinkedList digits = new LinkedList(); while (num > 0 ){ int r = num % 10; digits.addFirst(String.valueOf(r)); num = num / 10; } return digits; } public static int getNum(LinkedList digits) { StringBuilder builder = new StringBuilder(); for(String a : digits) { builder.append(a); } return Integer.parseInt(builder.toString()); } public static int rightshift(LinkedList digits,int noOfDig) { LinkedList newList = new LinkedList(); int k = 0; for(int i = digits.size()-noOfDig-1; i < digits.size();i++ ) { newList.add(k, digits.get(i)); k++; } for(int i = 0; i < digits.size()-noOfDig-1;i++ ) { newList.add(k, digits.get(i)); k++; } return getNum(newList); } } " B10661,"package GoogleCodeJam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.Hashtable; public class RecycledNumbers { public static void main(String[] args) { try{ BufferedReader br = new BufferedReader(new FileReader(""F:/codingContest/recyledNumbersInput.txt"")); BufferedWriter bw = new BufferedWriter(new FileWriter(""F:/codingContest/output.txt"")); String strLine; int T=0; if ((strLine = br.readLine().trim()) != null) { T = Integer.parseInt(strLine); if(T >= 1 && T <= 50){ int A, B, count; String p1, p2, p; Hashtable prev = null; for(int testCase = 0; testCase < T; testCase++){ strLine = br.readLine().trim(); A = Integer.parseInt(strLine.substring(0, strLine.indexOf(' '))); B = Integer.parseInt(strLine.substring(strLine.indexOf(' ')).trim()); count = 0; prev = new Hashtable(); if((A + """").length() == (B + """").length()){ for (int i = A, j; i < B; i++) { for (j = 1; j < (i + """").length(); j++) { p1 = (i + """").substring(0, (i + """").length()-j); p2 = (i + """").substring((i + """").length()-j); p = p2 + p1.substring(0, p1.length()); if((i + """").length() == (Integer.parseInt(p)+"""").length() && B >= Integer.parseInt(p) && i < Integer.parseInt(p) && !prev.containsKey(i+"",""+p)){ prev.put(i+"",""+p, """"); count++; } } } } bw.write(""Case #""+(testCase+1)+"": ""+ count); bw.newLine(); } bw.flush(); bw.close(); br.close(); } } }catch (Exception e) { e.printStackTrace(); } } } " B12868,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package numbers; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; /** * * @author Serban */ public class Input { PrintWriter out; public Input(String fileName) { //C-large-practice.in try { out = new PrintWriter(new File(""result.txt"")); Scanner scan = new Scanner(new File(fileName)); int T = scan.nextInt(); scan.nextLine(); for (int i = 0; i < T; i++) { int A = scan.nextInt(); int B = scan.nextInt(); solve(A, B, digits(A), i); } out.close(); } catch (Exception e) { System.out.println(e.getMessage()); } } private void solve(int A, int B, int digits, int testCase) { out.print(""Case #"" + (testCase + 1) + "": ""); int nr = 0; int n = (int) Math.pow(10, digits); if (A >= 10) { for (int i = A; i < n; i++) { int m = reverse(i, digits); while (m != i) { if (i < m && m <= B) { nr++; } m = reverse(m, digits); } } } System.out.println(nr); out.print(nr); out.println(); out.flush(); } private int digits(int nr) { int digits = 0; while (nr > 0) { nr /= 10; digits++; } return digits; } private int reverse(int nr, int digits) { int last = 0; while (last == 0) { last = nr % 10; nr = nr / 10; } nr = last * (int) Math.pow(10, digits - 1) + nr; return nr; } } " B11290,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.io.IOException; public class Recycle { public static void main(String[] args) { BufferedReader input = null; PrintWriter output = null; try { input = new BufferedReader(new FileReader(args[0])); output = new PrintWriter(new FileWriter(args[1])); String currentLine; int lineNumber = -1; String[] array = new String[2]; while((currentLine = input.readLine()) != null) { lineNumber++; if(lineNumber>0) { array = currentLine.split("" ""); int number1 = Integer.parseInt(array[0]); int number2 = Integer.parseInt(array[1]); int numberOfCases = 0; for(int count1=number1; count1 0) { first = first/10; numberOfPlaces++; } // while for(int count=count1+1; count<=number2; count++) { first = count1; if(first != count) { do { int d = first % 10; first = first/10; int multiply = (int) Math.pow(10, numberOfPlaces); first = d*multiply + first; if(first == count) numberOfCases++; }while(first != count1); } // if } // for } // for output.println(""Case #"" + lineNumber + "": "" + numberOfCases); } // if } // while } // try catch (Exception exception) { System.err.println(exception); } // catch finally { try{ if(input != null) input.close(); } catch (IOException exception) { System.err.println(""Could not close input: "" + exception); } if(output != null) { output.close(); if(output.checkError()) System.err.println(""Soemthing went wrong with the output""); } // if } // finally } // main } // class " B10508," public class Pair2 { public int left; public int right; public Pair2(int left, int right) { this.left = left; this.right = right; } @Override public boolean equals(Object other) { if (!(other instanceof Pair2)) { return false; } Pair2 pOther = (Pair2) other; return (left == pOther.left && right == pOther.right); } @Override public String toString() { return left + "" "" + right; } @Override public int hashCode() { return left * 100001 + right; } } " B10776,"import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; import java.util.Stack; public class RecycledNum { public static void main(String[] args) throws IOException { File file = new File(""C-small-attempt0.in""); Scanner scanner; BufferedWriter out = new BufferedWriter(new FileWriter(""outfile1"")); try { scanner = new Scanner(file); int testCases = scanner.nextInt(); scanner.nextLine(); for(int numTest=0; numTest st = new Stack(); int numDigit =0; int temp = A; while(temp != 0) { st.push(temp%10); numDigit++; temp=temp/10; } int[] digitsA = new int[numDigit]; for(int i=0; i=numDigit) sum=sum*10+curDigits[curindex-numDigit]; else sum=sum*10+curDigits[curindex]; curindex=curindex+1; } if((sum<=B)&&(sum>=A)) cycle=true; if(cycle==true) { if(mark[sum-A]!= true) { mark[sum-A]= true; count++; } } } } if(count==7) totalcount=totalcount+21; else if(count==6) totalcount=totalcount+15; else if(count==5) totalcount=totalcount+10; else if(count==4) totalcount=totalcount+6; else if(count==3) totalcount=totalcount+count; else if(count==2) totalcount=totalcount+1; } out.write(""Case #""+(numTest+1)+"": ""+ totalcount +""\n""); } out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } } " B10442,"package codejam; import java.util.*; public class RecycledNumbers { public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int k = 1; k <= T; k++) { int c = 0; int A = in.nextInt(); int B = in.nextInt(); for (int cand = A; cand <= B; cand++) { String str = Integer.toString(cand); char[] cstr = str.toCharArray(); int n = cstr.length; int first = cstr[0]-0x30; int mod = (int)Math.pow(10, n-1); Set ms = new HashSet(); for (int i = 1; i < n; i++) { int d = cstr[i]-0x30; if (d == 0) continue; if (d >= first) { String teststr = str.substring(i) + str.substring(0, i); if (ms.contains(teststr)) { continue; } ms.add(teststr); int test = Integer.parseInt(teststr); if (test <= B && test > cand) { System.out.println(str + "", "" + teststr + "", "" + A + "", "" + B); c++; } } } } System.out.println(""Case #"" + k + "": "" + c); } } } " B11141,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.falidae; import java.util.*; import java.io.*; /** * * @author LittleRock */ public class RecycledNumbers { public RecycledNumbers() { } public void init() { } public long solve(int a, int b) { Set valid = new HashSet(); long reval = 0l; for (int i = a; i <= b; i++) { String digits = Integer.toString(i); char last = digits.charAt(0); boolean allSame = true; for (int j = 1; j < digits.length(); j++) { if (digits.charAt(j) != last) { allSame = false; } } if (allSame) { continue; } int pow10a = 1; int pow10b = (int)Math.pow(10, digits.length()); valid.clear(); for (int j = 1; j < digits.length(); j++) { pow10a *= 10; pow10b /= 10; int front = i / pow10a; int back = i % pow10a; int shifted = back * pow10b + front; // System.out.println(""front "" + front + "", back "" + back); // System.out.println(""shifted "" + shifted); if (Integer.toString(shifted).length() == digits.length() && shifted <= b && shifted > i) { valid.add(shifted); } } // if (valid.size() > 0) { // System.out.println(i + "" cycle valid "" + valid.size()); // } reval += valid.size(); } return reval; } public static void main(String[] args) throws IOException { Scanner in = new Scanner(new FileReader(""in.txt"")); PrintWriter out = new PrintWriter(new FileWriter(""out.txt"")); RecycledNumbers solver = new RecycledNumbers(); int testCount = in.nextInt(); for (int i = 0; i < testCount; i++) { solver.init(); printIndex(i, out); out.print(solver.solve(in.nextInt(), in.nextInt())); out.println(); } in.close(); out.flush(); out.close(); } private static void printIndex(int i, PrintWriter out) { out.printf(""Case #%d: "", i + 1); } }" B11114,"import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.util.Scanner; import java.util.Vector; public class recycledNumbers{ public static void main(String args[]){ try{ PrintWriter out = new PrintWriter(new FileWriter(""output.txt"")); Scanner sc = new Scanner(new File(args[0])); Integer min, max, d, n, recy; Vector v; Vector recV; int t = sc.nextInt(); for(int i=1;i<=t;i++){ n=0; min = sc.nextInt(); max = sc.nextInt(); d = min.toString().length(); v = new Vector(); for(int j=min;j<=max;j++){ recV = new Vector(); for(int k=1;k=min && recy!=j && !recV.contains(recy)){ if(!v.contains(recy)){ n++; recV.add(recy); v.add(j); } } } } out.println(""Case #""+i+"": ""+n); } out.close(); }catch (Exception e){ } } }" B10744,"package qualification.c; import java.io.File; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * * Problem Do you ever become frustrated with television because you keep seeing the same things, recycled over and over again? Well I personally don't care about television, but I do sometimes feel that way about numbers. Let's say a pair of distinct positive integers (n, m) is recycled if you can obtain m by moving some digits from the back of n to the front without changing their order. For example, (12345, 34512) is a recycled pair since you can obtain 34512 by moving 345 from the end of 12345 to the front. Note that n and m must have the same number of digits in order to be a recycled pair. Neither n nor m can have leading zeros. Given integers A and B with the same number of digits and no leading zeros, how many distinct recycled pairs (n, m) are there with A ≤ n < m ≤ B? Input The first line of the input gives the number of test cases, T. T test cases follow. Each test case consists of a single line containing the integers A and B. Output For each test case, output one line containing ""Case #x: y"", where x is the case number (starting from 1), and y is the number of recycled pairs (n, m) with A ≤ n < m ≤ B. Limits 1 ≤ T ≤ 50. A and B have the same number of digits. Small dataset 1 ≤ A ≤ B ≤ 1000. Large dataset 1 ≤ A ≤ B ≤ 2000000. Sample Input 4 1 9 10 40 100 500 1111 2222 Output Case #1: 0 Case #2: 3 Case #3: 156 Case #4: 287 Are we sure about the output to Case #4? Yes, we're sure about the output to Case #4. * 2012.04.14. 16:22 - 16:38 * @author Chei */ public class RecycledNumbers { Scanner scanner; public static void main(String[] args) throws FileNotFoundException { new RecycledNumbers().solve(); } void solve() throws FileNotFoundException { //scanner = new Scanner(new File(""resources/C-large.in"")); scanner = new Scanner(new File(""resources/C-small-attempt0.in"")); //scanner = new Scanner(new File(""resources/C-example.in"")); int numberOfTestCases = scanner.nextInt(); for (int testCaseIndex = 1; testCaseIndex <= numberOfTestCases; testCaseIndex++) { int result = solveTestCase(); System.out.format(""Case #%d: %d%n"", testCaseIndex, result); } } int solveTestCase() { int a = scanner.nextInt(); int b = scanner.nextInt(); Set recycledNumbers = new HashSet(); int result = 0; for (int num = a; num <= b; num++) { String numString = String.valueOf(num); recycledNumbers.clear(); for (int i = 0; i < numString.length(); i++) { String newString = numString.substring(i) + numString.substring(0, i); if (newString.charAt(0) != '0') { int newNum = Integer.parseInt(newString); if (newNum >= a && newNum <= b) { recycledNumbers.add(newString); } } } result += recycledNumbers.size() - 1; } // all pairs were counted twice return result / 2; } } " B10845,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class C { private void run() throws IOException { // put your code here .. int testcases=nextInt(); int number=1; while(testcases-->0){ long answer=0; int A=nextInt(); int B=nextInt(); for (int i = A; i < B; i++) { String a=new String(i+""""); ArrayList hash=new ArrayList(); for (int j = 1; j < a.length(); j++) { String now =a.charAt(a.length()-1)+a.substring(0,a.length()-1); int n=Integer.parseInt(now); String nlen=n+""""; if(nlen.length()!=now.length()||nlen.equals(a)||n<=i||hash.contains(n+"""")){ a=now; continue; } if(n<=B){ hash.add(n+""""); answer++; } a=now; } } writeln(""Case #""+(number++)+"": ""+answer); } } private int nextInt() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return Integer.parseInt(input.nextToken()); } private long nextLong() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return Long.parseLong(input.nextToken()); } private double nextDouble() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return Double.parseDouble(input.nextToken()); } private String nextString() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return input.nextToken(); } private void write(String output){ out.write(output); out.flush(); } private void writeln(String output){ out.write(output+""\n""); // out.flush(); } private void end() throws IOException{ in.close(); out.close(); System.exit(0); } private BufferedReader in; private PrintWriter out; private StringTokenizer input; public C() throws IOException { //Input Output for Console to be used for trying the test samples of the problem // in = new BufferedReader(new InputStreamReader(System.in)); // out = new PrintWriter(System.out); //------------------------------------------------------------------------- //Input Output for File to be used for solving the small and large test files in = new BufferedReader(new FileReader(""C-small-attempt0.in"")); out = new PrintWriter(""output3.txt""); //------------------------------------------------------------------------- //Initialize Stringtokenizer input input = new StringTokenizer(in.readLine()); } public static void main(String[] args) throws Exception { //------------------------------------------------------------------------- //initializing... C sol = new C(); //------------------------------------------------------------------------- sol.run(); //------------------------------------------------------------------------- //closing up sol.end(); //-------------------------------------------------------------------------- } } " B10124,"package t3; import java.io.*; import java.util.ArrayList; import java.util.StringTokenizer; import java.util.logging.Level; import java.util.logging.Logger; public class T2 { BufferedWriter out; ArrayList list = new ArrayList(); int i = 1; T2(){ try { out = new BufferedWriter(new FileWriter(new File(""output.txt""))); } catch (IOException ex) {} start(); try { out.close(); } catch (IOException ex) { Logger.getLogger(T2.class.getName()).log(Level.SEVERE, null, ex); } } public static void main(String[] args) { T2 t = new T2(); } private void lerArquivo(String input) { File f = new File(input); if(!f.exists()) { System.exit(-1); } try { BufferedReader in = new BufferedReader(new FileReader(f)); String line; int lineCount = 0; in.readLine(); while((line = in.readLine())!=null) { list.add(line); } } catch (Exception e) {} } private void write(String str){ str = ""Case #""+i+"": ""+ str + ""\n""; try { out.write(str, 0, str.length()); i++; } catch (IOException ex) { Logger.getLogger(T2.class.getName()).log(Level.SEVERE, null, ex); } } private void start(){ lerArquivo(""input.txt""); for(String str: list){ int counter = 0; StringTokenizer st = new StringTokenizer(str); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); for(int i = A; i < B-1; i++) for(int j = i+1; j <= B; j++){ if(verify(i, j)){ counter++; } } write(""""+counter); } } private boolean verify(int A, int B){ int k1 = A; int size; for(size = 1; size*10 < A; size*=10); for(int i = 10; i <= A; i*=10){ k1 = A; int temp = k1%i; k1 = (k1-temp)/i; k1 = (((size*10)/i)*temp) + k1; if(k1 == B) return true; } return false; } } " B10629,"import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; public class Solver2 { public static void main(String[] args) { new Solver2(); } private Scanner in; public Solver2(){ try { in = new Scanner(new File(""../Text/C-small-attempt0.in"")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } solve(); in.close(); } public void solve() { int cases = in.nextInt(); ArrayList solutions=new ArrayList(); for (int i = 1; i <= cases; i++) { int lower=in.nextInt(); int upper=in.nextInt(); int amount=0; for(int k= lower;k<=upper;k++){//k van lower tot upper if(k>=10){ String iString=String.valueOf(k); ArrayList allreadyPaired=new ArrayList(); for (int l = 1; l < iString.length(); l++) { String shifted=move(l,iString); int reverseInt=Integer.parseInt(shifted); if(reverseInt<=upper&&reverseInt>lower&&reverseInt>k){ if(!allreadyPaired.contains(reverseInt)) amount++; solutions.add(k); } allreadyPaired.add(reverseInt); } } } System.out.println(""Case #""+i+"": ""+amount); solutions.clear(); } } private String move(int i,String iString) { String result=""""; for (int j = 0; j < i; j++) { String letter=String.valueOf(iString.charAt(iString.length()-i+j)); result+=letter; } for (int j = 0; j < iString.length()-i; j++) { String letter=String.valueOf(iString.charAt(j)); result+=letter; } return result; } } " B11767,"package de.johanneslauber.codejam.model.impl; import de.johanneslauber.codejam.model.ICase; /** * * @author Johannes Lauber - joh.lauber@googlemail.com * */ public class RecycledNumbersCase implements ICase { private final int numberOfAttributes = 1; private int a; private int b; @Override public void setLine(int lineNumber, String lineValue) { if (lineNumber == 1) { String[] spllitedLine = lineValue.split("" ""); a = Integer.parseInt(spllitedLine[0]); b = Integer.parseInt(spllitedLine[1]); } else { System.out.println(""Linenumber is out of range""); } } // Setter & Getter @Override public int getNumberOfAttributes() { return numberOfAttributes; } public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } } " B12330,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(""input.txt""))); String line = br.readLine(); BufferedWriter out = new BufferedWriter(new FileWriter(""output.txt"")); int tests = Integer.valueOf(line.trim()); for (int i = 0; i < tests; i++) { String[] number = br.readLine().split("" ""); int a = Integer.valueOf(number[0]); int b = Integer.valueOf(number[1]); int digits = number[1].length(); int result = 0; int multiplier = 1; for (int j = 0; j < digits - 1; j++) { multiplier *= 10; } for (int j = a; j < b; j++) { int value = j; int size = 0; while (true) { value = value/10 + (value % 10)*multiplier; if (a <= value && value <= b) { size++; } if (a <= value && value < j) { break; } if (value == j) { result += size*(size - 1)/2; break; } } } out.write(""Case #""+ (i + 1) +"": "" + result + ""\n""); } out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }" B13177,"import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; public class RecycledNumbers { public static void main(String[] args) { try { // int T = 4; // int[][] testcases = new int[T][]; // testcases[0] = new int[]{1,9}; // testcases[1] = new int[]{10,40}; // testcases[2] = new int[]{100,500}; // testcases[3] = new int[]{1111,2222}; BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(""C-small-attempt0.in""))); String firstLine = reader.readLine(); int T = Integer.valueOf(firstLine); int[][] testcases = new int[T][]; for(int i = 0; i < T; i++) { String[] testcase = reader.readLine().split("" ""); testcases[i] = new int[2]; testcases[i][0] = Integer.valueOf(testcase[0]); testcases[i][1] = Integer.valueOf(testcase[1]); } RecycledNumbers recylcing = new RecycledNumbers(); for(int i = 0; i < T; i++) { System.out.printf(""Case #%d: "",i+1,testcases[i]); int result = recylcing.count(testcases[i]); System.out.printf(""%s\n"", result); } } catch(Exception ex) { System.out.println(""An error occured:\n""); ex.printStackTrace(); } } public int count(int[] input) { int A = input[0]; int B = input[1]; int hits = 0; for(int i = 0; i <= B - A; i++) { for(int j = 0; j <= B - A; j++) { int lessB = B - i; int moreA = A + j; if(lessB >= moreA) { int switchA = moreA; do { if(lessB == switchA && switchA > moreA) { hits++; break; } char[] chars = Integer.toString(switchA).toCharArray(); chars = rotateCharacters(chars); switchA = Integer.valueOf(String.valueOf(chars)); } while (moreA != switchA); } else { break; } } } return hits; } public char[] rotateCharacters(char[] chars) { if(chars.length > 1) { char charNext = chars[1]; chars[1] = chars[0]; for(int i = 1; i < chars.length - 1; i++) { char charNextNext = chars[i+1]; chars[i+1] = charNext; charNext = charNextNext; } chars[0] = charNext; if(chars[0] == '0') { return rotateCharacters(chars); } else { return chars; } } else { return chars; } } } " B12427,"import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class RecycleNumbers { public static void main(String[] args) { try{ BufferedReader fileIn = new BufferedReader(new FileReader(""C-small-attempt0.in"")); int cases = Integer.valueOf(fileIn.readLine()); Scanner numReader = new Scanner(fileIn); for(int i = 0; i < cases; i++) { int start = numReader.nextInt(); int end = numReader.nextInt(); List p = new ArrayList(); for(int n = start; n <= end; n++) { NumberQueue q = new NumberQueue(n); List returned = q.distinctRoations(start, end); for(NumberQueue.Pair ap : returned) { if(!p.contains(ap)) { p.add(ap); } } } System.out.println(""Case #""+(i+1)+"": ""+p.size()); } } catch(Exception err) { System.out.println(""ERRORRRRRRRRRRRRRRRRRRRRR: ""+ err.getMessage()); err.printStackTrace(); } } } " B10229,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Solution { static int vp[][]; static int no_vp=0; public static void main(String args[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; int t,i; t=Integer.parseInt(br.readLine()); for(i=0;i=a && num<=b && j!=num) { if(j<=num) { if(add(j,num)) result++; } else { if(add(num,j)) result++; } } } } } if(ex2==true) { //Do Nothing } if(ex3==true) { //Do Nothing } System.out.println(""Case #""+(i+1)+"": ""+result); } } static boolean add(int m,int n) { //Pass such that m n && m <= B) { //System.out.println(m + "" "" + n); result ++; } } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for (int k = 0; k> recycledNumbers = new ArrayList>(); for (int i = a; i < b; i++) { String number = Integer.toString(i); for (int j = 1; j < number.length(); j++) { String candidate = number.substring(j) + number.substring(0, j); int candidateAsNumber = Integer.parseInt(candidate); if (candidateAsNumber > i && candidateAsNumber <= b) { Integer recycledNumber = new Integer(candidateAsNumber); if (!recycledNumbers.contains(recycledNumber)) { recycledNumbers.add(new Pair(i, recycledNumber)); } } } } for (Pair pair : recycledNumbers) { System.err.println(a + "" <= "" + pair.a + "" < "" + pair.b + "" <= "" + b); } results[line] = recycledNumbers.size(); } IOHelper.writeFile(args[0].replace("".in"", "".out""), results); } catch (IndexOutOfBoundsException e) { } } } " B11343,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; public class Recycle { /** * @param args */ static int t =0; //static ArrayList> table = new ArrayList>(); public static void inputF() throws FileNotFoundException{ File inputFile = new File(""C-small-attempt1.in""); Scanner in = new Scanner(inputFile); File outputFile = new File(""C-small-attemp1.out""); PrintWriter out = new PrintWriter(outputFile); String result=""""; String input =""""; int n,m=0; t = in.nextInt(); //System.out.println(n); input = in.nextLine(); for (int i=1; i<=t; i++) { n =in.nextInt(); m =in.nextInt(); //System.out.println(""length of the list: ""+list.length); result = ""Case #""+i+ "": ""+ count(n,m); out.println(result); } in.close(); out.close(); } private static int count(int n, int m) { int result =0; boolean isRecycle = false; ArrayList list = new ArrayList(); for (int i=n; i<=m;i++){ String ori=Integer.toString(i); isRecycle = false; list = new ArrayList(); for(int j=1; ji)&(resInt<=m)) { if ((!isRecycle)|((isRecycle)& (!list.contains(resInt)))){ result++; isRecycle=true; list.add(resInt); //System.out.println(i+""-->""+resInt); //out.println(resInt); } } } } return result; } public static void main(String[] args) throws FileNotFoundException { inputF(); } } " B12105,"package com.renoux.gael.codejam.utils; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.net.URISyntaxException; import java.net.URL; /** * Pour tests unitaires * * @author renouxg */ public final class FileUtils { public static File fromWorkspace(String path) throws URISyntaxException { ClassLoader.getSystemResource(path); URL url = FileUtils.class.getClassLoader().getResource(path); return new File(url.toURI()); } public static BufferedReader getReader(File file) throws FileNotFoundException { FileInputStream fis = new FileInputStream(file); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); return br; } } " B11609,"package com.google.codejam.qualrnd.recyclednums; public class RecycledNumbersInput { private int noOfCases; private long[][] numPairs; public RecycledNumbersInput() { } public RecycledNumbersInput(int noOfCases) { this.noOfCases = noOfCases; } public RecycledNumbersInput(int noOfCases, long[][] numPairs) { this.noOfCases = noOfCases; this.numPairs = numPairs; } public int getNoOfCases() { return noOfCases; } public void setNoOfCases(int noOfCases) { this.noOfCases = noOfCases; } public long[][] getNumPairs() { return numPairs; } public void setNumPairs(long[][] numPairs) { this.numPairs = numPairs; } } " B11206,"import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.PrintWriter; import java.util.ArrayList; public class RecycledNumbers2 { public static int analizar(String first, String second ){ ArrayList dupList=new ArrayList(); int contador=0; int primero=Integer.parseInt(first); int segundo=Integer.parseInt(second); for(int i=primero;i<=segundo;i++){ for(int j=i+1;j<=segundo;j++){ for(int k=1;k map = new HashMap(); map.put(j, true); int pair = (j%10)*(int)Math.pow(10, bit)+ j/10; while(!map.containsKey(pair)) { if(j>pair) { map.put(pair, true); pair = (pair%10)*(int)Math.pow(10, bit)+ pair/10; continue; } if(A<=pair && pair<=B) result++; pair = (pair%10)*(int)Math.pow(10, bit)+ pair/10; continue; } } pw.println(""Case #""+(i+1)+"": ""+result); System.out.println(""Case #""+(i+1)+"": ""+result); } pw.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B10636," import java.io.BufferedReader; import java.io.InputStreamReader; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author andy */ public class RecycledNumbers { /** * @param args the command line arguments */ public static void main(String[] args) throws Exception { //char sd = '1'; //int[] sdf = new int[ 10 ]; //System.out.println( sdf[ 0 ] ); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String s = in.readLine(); int numTestCases = Integer.parseInt(s); int a; int b; int len; for( int testCase = 1 ; testCase <= numTestCases ; testCase ++ ) { int count = 0; String ab = in.readLine(); String[] arrAB = ab.split("" ""); a = Integer.parseInt(arrAB[0]); b = Integer.parseInt(arrAB[1]); //System.out.println( ""ab: "" + a + "" "" + b); int[] appearedInThisCycle = new int[numTestCases]; char[] arrA; // arrA = arrAB[0].toCharArray(); //len = arrA.length; for( int n = a ; n < b ; n ++ ) { arrA = String.valueOf(n).toCharArray(); len = arrA.length; int[] cycleArr = new int[ len ]; for( int c = 0 ; c < len ; c ++) { int aValue = 0; for( int ai = 0 ; ai < len ; ai ++) { aValue += Math.pow(10, ai) * Character.digit(arrA[ (c - ai + len) % len ],10); } cycleArr[ c ] = aValue; boolean hasntAlreadyAppeared = true; for( int i = 0 ; i < c ; i ++ ) { if( cycleArr[i] == aValue ) { //System.out.println("":"" + cycleArr[c] + "" "" + aValue); hasntAlreadyAppeared = false; //break; } } if( hasntAlreadyAppeared && aValue > n && aValue <= b ) { //System.out.println(n + "" and "" + aValue ); count ++; } } } System.out.println(""Case #"" + testCase + "": "" + count ); } } } " B13008,"import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Hashtable; public class GJ_QR_C { public static int recycle(int A, int n){ String st = (new Integer(A)).toString(); return Integer.parseInt(st.substring(n) + st.substring(0, n)); } public static int solve(int A, int B){ String st = (new Integer(A)).toString(); String ed = (new Integer(B)).toString(); int res = 0; int N = st.length(); for (int i = A; i= tmp.charAt(0) && tmp.charAt(j) <= ed.charAt(0)){ int rec = recycle(i, j); //System.out.println(i +"" -> ""+ rec); if (rec<=B && i hashSet = new HashSet(); for(int j=A;j<=B; j++){ String num = String.valueOf(j); for(int k=1; k=flippedNum) continue; if(flippedNum>=A && flippedNum<=B){ if(hashSet.contains(num+flippedNum)){ System.out.println(""DUPLICATE!!: "" +num+flippedNum); continue; } System.out.println(""counted: ""+""original: ""+num+"" Flipped: ""+flippedNum); count++; hashSet.add(num+flippedNum); } } } System.out.println(count); totalAccountArray[i] = count; } in.close(); FileWriter fstream = new FileWriter(""C-small-attempt0.out""); BufferedWriter out = new BufferedWriter(fstream); for(int i=1; i<=testCaseNumber;i++){ String outLine = ""Case #""+i+"": ""+totalAccountArray[i-1]+""\n""; out.write(outLine); } out.close(); System.out.println(""File created successfully.""); } } " B11808,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Recycled { public static boolean isRecycled(int a, int b) { String left = a+""""; String right = b+""""; if(left.length()!=right.length()) return false; int l = left.length(); for(int i=0;i 0) { int A = in.nextInt(), B = in.nextInt(); int lenA = (int) Math.log10(A), lenB = (int) Math.log10(B); int prevStart = A; HashSet pairs = new HashSet(); for (int i = lenA; i <= lenB; ++i) { int currPow10 = (int) Math.pow(10, i); int start = (int) Math.max(prevStart, currPow10), end = (int) Math.min(B, 10*currPow10-1); for (int j = start; j <= end; ++j) { int k = j; for (int l = 0; l < i; ++l) { k = (k % currPow10) * 10 + (k / currPow10); if (k >= start && k <= end && k != j) { pairs.add(String.format(""%07d%07d"", Math.min(j, k), Math.max(j, k))); } } } prevStart = end + 1; } System.out.printf(""Case #%d: %d\n"", ++I, pairs.size()); } } } " B10978,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; import java.io.*; /** * * @author vichugof */ public class CodeJam { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here File archivo = null; FileReader fr = null; BufferedReader br = null; String delimiter = "" ""; String[] cadenaNumero; try { archivo = new File (""C://C-small-attempt2.in""); fr = new FileReader (archivo); br = new BufferedReader(fr); String linea; int numeroCasos = 0; linea=br.readLine(); numeroCasos = Integer.parseInt(linea); int A=0; int B=0; int cantidadDigitosN = 0; int cantidadDigitosM = 0; String digitoDerecha = """"; String digitoIzquierda = """"; int numComparar = 0; int cantidadNumReciclabe = 0; CodeJam objCodeJam = new CodeJam(); for(int idxCasos =0; idxCasos A) { for(int idexN=A; idexN0) { iTemp = iTemp/10; iCantidad++; } return iCantidad; } public int obtenerCantidadDigitosDerecha(int num, int numeroDigitos) { int cantidadCien = 10; int numero = num; for(int idxCien=0; idxCien pairs = new HashSet(); char[] digits = String.valueOf(current).toCharArray(); int[] values = new int[digits.length]; for (int i = 0; i < digits.length; ++i) { values[i] = digits[i] - '0'; } for (int first = 1; first < values.length; ++first) { int other = 0; for (int size = 0; size < values.length; ++size) { other *= 10; other += values[(first + size) % values.length]; } if (other > current && min <= other && other <= max) { pairs.add(other); } } total += pairs.size(); } result = String.valueOf(total); // END RESULT COMPUTATION // ------------------------------------------------------------ System.out.println(result); reportResult(num, result); } } public static final int NUM_THREADS = 4; private String file_name; private ArrayList results; public QualifierC(String file_name) { this.file_name = file_name; } public ArrayList calculate() throws IOException, InterruptedException { results = new ArrayList(); ThreadPoolExecutor tpe = new ThreadPoolExecutor(NUM_THREADS, NUM_THREADS, 2, TimeUnit.SECONDS, new LinkedBlockingQueue()); FileReader fr = new FileReader(file_name); BufferedReader br = new BufferedReader(fr); String line = br.readLine(); System.out.println(""Header: "" + line); String[] ints = line.split("" ""); // BEGIN HEADER PARSING // -------------------------------------------------------------------- int total_num = Integer.parseInt(ints[0]); // END HEADER PARSING // -------------------------------------------------------------------- for (int i = 0; i < total_num; ++i) { results.add(""""); // BEGIN READING CASE // ---------------------------------------------------------------- line = br.readLine(); tpe.execute(new Task(i, line)); // END READING CASE // ---------------------------------------------------------------- } br.close(); fr.close(); tpe.shutdown(); tpe.awaitTermination(8, TimeUnit.MINUTES); return results; } public synchronized void reportResult(int num, String result) { results.set(num, result); } public static void main(String[] args) throws IOException, InterruptedException { long time0 = System.currentTimeMillis(); if (args.length < 1) { System.out.println(""Remember command line argument""); System.exit(1); } QualifierC runner = new QualifierC(args[0]); ArrayList results = runner.calculate(); System.out.println(""Run time: "" + (System.currentTimeMillis() - time0) / 1000 + ""s\n""); FileWriter fw = new FileWriter(""results.txt""); BufferedWriter bw = new BufferedWriter(fw); for (int i = 0; i < results.size(); ++i) { System.out.println(""Case #"" + (i + 1) + "": "" + results.get(i)); bw.write(""Case #"" + (i + 1) + "": "" + results.get(i) + ""\n""); } bw.close(); fw.close(); } } " B10351,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class RecycledPairs { public static void main(String args[]) throws IOException { BufferedWriter resultWriter = new BufferedWriter(new FileWriter(""C:\\Users\\Andriy\\workspaces\\codejam\\RecycledPairs\\src\\datasetOutput"")); BufferedReader reader = new BufferedReader(new FileReader(""C:\\Users\\Andriy\\Downloads\\C-small-attempt0.in"")); int totalCases = Integer.parseInt(reader.readLine()); int caseNumber = 0; while (++caseNumber <= totalCases) { String[] numbers = reader.readLine().split("" ""); if (numbers.length != 2 || numbers[0].length() == 1) { resultWriter.write(String.format(""Case #%d: %d\n"", caseNumber, 0)); continue; } int a = Integer.parseInt(numbers[0]); int b = Integer.parseInt(numbers[1]); int recycles = 0; final char[] buffer = new char[numbers[0].length()]; for (int m = a+1; m <= b; m++) { final char[] mChar = String.valueOf(m).toCharArray(); for (int n=a; n < m; n++) { final char[] nChar = String.valueOf(n).toCharArray(); int length = 0; while (++length < mChar.length) { // skip leading zeros final int pivotPos = nChar.length - length; if (pivotPos == '0') { continue; } System.arraycopy(nChar, pivotPos, buffer, 0, length); System.arraycopy(nChar, 0, buffer, length, pivotPos); if (Arrays.equals(buffer, mChar)) { recycles++; break; } } } } resultWriter.write(String.format(""Case #%d: %d\n"", caseNumber, recycles)); } resultWriter.flush(); resultWriter.close(); } } " B12185,"import java.io.BufferedReader; import java.io.FileReader; import java.util.HashSet; import java.util.Set; public class ProblemB { public static void main(String[] args) { try { BufferedReader bufReader = new BufferedReader(new FileReader(args[0])); int numOfCases = Integer.parseInt(bufReader.readLine()); int a, b; for (int i = 0; i < numOfCases; i++) { // should change 2 to numOfCases!!! Set distinctRecycledPairs = new HashSet(); String line = bufReader.readLine(); a = Integer.parseInt(line.substring(0, line.indexOf(' '))); b = Integer.parseInt(line.substring(line.indexOf(' ') + 1, line.length())); //System.out.println(""A = "" + a + "" B = "" + b); for (int j = a; j <= b; j++) { String n = """" + j; for (int k = 1; k < n.length(); k++) { String possibleM = n.substring(k) + n.substring(0, k); if (Integer.parseInt(possibleM) > Integer.parseInt(n) && Integer.parseInt(possibleM) >= a && Integer.parseInt(possibleM) <= b) { // the pair (n,m) may repeat, so use a set // there should be a better way though distinctRecycledPairs.add(n + "" "" + possibleM); } } } System.out.println(""Case #"" + (i+1) + "": "" + distinctRecycledPairs.size()); } bufReader.close(); } catch (Exception e) { e.printStackTrace(); } } } " B11875,"import java.util.*; import java.math.*; import java.io.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; public class Main { //ArrayList lis = new ArrayList(); //ArrayList lis = new ArrayList(); //ArrayList lis = new ArrayList(); static long sum=0; public static void main(String[] args) throws IOException { //googlein.txt Scanner sc =new Scanner(new File(""C-small-attempt0.in"")); File file = new File(""file.txt""); PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file))); // sc.useDelimiter(""(\\s)+|[,]""); int T=sc.nextInt(); for(int k=1; k<=T; k++){ int c=0, a=sc.nextInt(),b =sc.nextInt(); for(int t=a;t<=b;t++){ String s=String.valueOf(t); int l=s.length(),g=1; ArrayList lis = new ArrayList(); for(int u=0;uB.charAt(0)) {} else if(n.charAt(k)b)) {} else if(n.charAt(k)==n.charAt(0)&&(Integer.parseInt(n.substring(k)+n.substring(0,k))<=j)) {} else if(n.equals(n.substring(k)+n.substring(0,k))) {} else count++; } } pw.println(""Case #""+(i+1)+"": ""+count); } pw.close(); bw.close(); fw.close(); } } " B11950,"import java.io.*; public class Recycler { public static void main(String[] args) { Recycler rec = new Recycler(); String line = """"; BufferedReader br; BufferedWriter output; FileWriter fstream; int x; int y; try { br = new BufferedReader(new FileReader(""C-small-attempt0.in"")); line = br.readLine(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } rec.testCases = Integer.parseInt(line); try { fstream = new FileWriter(""output.txt""); output = new BufferedWriter(fstream); br = new BufferedReader(new FileReader(""C-small-attempt0.in"")); br.readLine(); for(int i = 1; i <= rec.testCases ;i++) { line = """"; line = br.readLine(); int j = 0; while( line.charAt(j) != ' ') j++; x = Integer.parseInt(line.substring(0, j)); y = Integer.parseInt(line.substring(j+1)); output.write(""Case #"" + i + "": "" + rec.countPairs(x, y)); output.newLine(); } output.close(); } catch (IOException e) { e.printStackTrace(); } } private int countPairs(int A, int B) { int counter = 0; for(int i = A; i < B; i++) { for(int j = i+1; j <= B; j++){ if(checkR(i,j)){ counter++; } } } return counter; } private boolean checkR(int num1, int num2){ String n = Integer.toString(num1) ; String m = Integer.toString(num2) ; boolean isPair = false; for(int i = m.length()-1; i > 0;i--){ String s = n.substring(i); String ss = n.substring(0, i); String sss = s + ss; if(sss.equals(m)) { isPair = true; } } return isPair; } /* private instance variables */ private int testCases; } " B11049,"package com.clausewitz.codejam.qr2012; import java.io.IOException; import java.util.StringTokenizer; import com.clausewitz.codejam.Solver; public class Recycled extends Solver { private int A = 0; private int B = 0; @Override public void readProblem() throws IOException { String line = fileIn.readLine(); StringTokenizer st = new StringTokenizer(line); A = Integer.parseInt(st.nextToken()); B = Integer.parseInt(st.nextToken()); } @Override public void algorithm(int idx) { int count = 0; for(int i=A;i<=B;++i) { String original = """" + i; String candidate = original; while(true) { candidate = rotate(candidate); if(candidate.equalsIgnoreCase(original)) break; int n = Integer.parseInt(candidate); if(n>=A && n<=B) ++count; } } answer[idx] = """" + count/2; } private String rotate(String s) { if(s.length()==1) return s; return s.substring(1, s.length()) + s.charAt(0); } } " B10577,"package com.gao.t3; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.HashSet; public class Main { public static void main(String args[]){ try{ FileInputStream fin=new FileInputStream(""C:\\Users\\Gao\\Downloads\\C-small-attempt0.in""); //FileInputStream fin=new FileInputStream(""cc.txt""); BufferedReader br=new BufferedReader(new InputStreamReader(fin)); FileOutputStream fout=new FileOutputStream(""out.txt""); BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(fout)); int n=Integer.parseInt(br.readLine()); HashSet hash=new HashSet(); for(int i=0;i=0&&strB.compareTo(B+"""")<=0){ hash.add(strA+"" ""+strB); } } } String str=""Case #""+(i+1)+"": ""+hash.size(); bw.write(str); if(i 0){ a = s.nextInt(); b = s.nextInt(); int ans = 0; for (int i = a; i <=b ; i++) { for (int j = i+1;j <=b ; j++) { String s1 = i + """"; //String s2 = j + """"; String temp = """"; for (int k = 1; k < s1.length() ; k++) { temp = s1.substring(s1.length() - k) + s1.substring(0,s1.length()-k); int r1 = Integer.parseInt(temp); if (r1 == j){ ans++; break; } } } } pw.println(""Case #"" + kase + "": "" + ans); kase++; } pw.close(); s.close(); } public static void main(String[] args) throws IOException { (new C()).run(); } } " B12614,"package util.graph; public abstract class State implements Comparable{ } " B12383,"import java.io.*; import java.util.*; public class Main { public static void main(String... args) throws Exception { int t, a, b, T; Scanner in = new Scanner(new File(""recycled.in"")); //PrintStream out = System.out; PrintStream out = new PrintStream(new File(""recycled.out"")); T = in.nextInt(); for (t = 1; t <= T; t++) { a = in.nextInt(); b = in.nextInt(); int rez = 0; int i, j; int n = (a + """").length(); String B = b + """"; for (i = a; i <= b; i++) { String I = i + """"; Set s = new TreeSet(); s.add(I); for (j = 1; j < n; j++) { String x = I.substring(j) + I.substring(0, j); if (I.compareTo(x) < 0 && x.compareTo(B) <= 0 && s.add(x)) { rez++; } } } out.println(""Case #"" + t + "": "" + rez); } } } " B11582,"import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) throws FileNotFoundException { Scanner scan = new Scanner(new File(""input"")); int cases = scan.nextInt(); for (int i = 1; i <= cases; i++) { int A = scan.nextInt(); int B = scan.nextInt(); int numDigits = (int) (Math.log(A) / Math.log(10)) + 1; int digits[] = new int[numDigits]; int tmp = A; for (int j = numDigits-1; j >= 0; j--) { digits[j] = tmp % 10; tmp /= 10; } int recycled = 0; for (int j = A; j <= B; j++) { int val = j; for (int k = 0; k < numDigits; k++) { int temp = val % 10; val = (val / 10) + (temp * ((int) Math.pow(10, numDigits-1))); if (val == j) { break; } if (val >= A && val <= B && val > j) { recycled++; } } } System.out.println(""Case #"" + i + "": "" + recycled); } } } " B11957,"import java.io.*; public class C { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(in.readLine()); for (int c = 1; c <= t; c++) { String[] line = in.readLine().split("" ""); int a = Integer.parseInt(line[0]); int b = Integer.parseInt(line[1]); int len = line[0].length(); int tenlen = 1; for (int i=1; i n && m <= b) result++; } while (m != n); } System.out.println(""Case #""+c+"": ""+result); } } } " B11474,"import java.io.*; import java.math.*; import java.util.*; public class CodeJam { void runCase(int caseNum) throws IOException { int a = nextInt(); int b = nextInt(); Set res = new HashSet(); for (long i = a; i <= b; ++i) { String s = Long.toString(i); for (int j = 1; j < s.length(); ++j) { char[] arr = new char[s.length()]; for (int k = j; k < s.length(); ++k) arr[k - j] = s.charAt(k); for (int k = 0; k < j; ++k) arr[s.length() - j + k] = s.charAt(k); Long t = Long.parseLong(new String(arr)); if (t > b || t <= i) continue; if (!res.contains(i * 10000000 + t)) res.add(i * 10000000 + t); } } System.out.print(new StringBuilder().append(""Case #"").append(caseNum).append("": "").append(res.size()).toString()); System.out.println(); } public static void main(String[] args) throws IOException { System.setIn(new FileInputStream(new File( ""input.txt""))); PrintStream ps = new PrintStream(new File( ""output.txt"")); System.setOut(ps); new CodeJam().runit(); ps.flush(); ps.close(); return; } BufferedReader in; private StringTokenizer st; PrintWriter out; String next() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } void runit() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); st = new StringTokenizer(""""); int N = nextInt(); for (int i = 0; i < N; i++) { runCase(i + 1); } out.flush(); } } " B12495,"import java.util.Scanner; public class Recycled { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int test = scan.nextInt(); for (int c = 1; c <= test; c++){ int count = 0; int min = scan.nextInt(); int max = scan.nextInt(); if (min < 10) min = 10; for (int x = min; x <= max; x++){ String value = (Integer.valueOf(x)).toString(); for (int a = 0; a < value.length()-1; a++){ String temp = value.substring(value.length()-a-1); temp += value.substring(0,value.length()-a-1); int r = Integer.parseInt(temp); if ( r > x && r <= max ){ count++; //System.out.println(x + "" "" + r ); } } } System.out.println( ""Case #"" + c + "": "" + count); } } } " B11492,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.StringTokenizer; public class RecycledNumbers { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader f = new BufferedReader(new FileReader(""test.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""recycled.out""))); int numberCases = Integer.parseInt(f.readLine()); String log; StringTokenizer st; int lower; int upper; int pairs; for (int i = 1; i <= numberCases; i++) { log = ""Case #"" + i + "": ""; st = new StringTokenizer(f.readLine()); lower = Integer.parseInt(st.nextToken()); upper = Integer.parseInt(st.nextToken()); pairs = calculatePairs(lower,upper); out.println(log + pairs); } out.close(); System.exit(0); } private static int calculatePairs(int lower, int upper) { String baseString; int base; String tempString; int temp; int pairs = 0; HashSet h = new HashSet(); //i = n for (int i = lower; i <= upper; i++) { base = i; baseString = Integer.toString(base); h.clear(); //j = number of digits to swap //if leading 0, then automatically smaller/not valid for (int j = 1; j < baseString.length(); j++) { tempString = baseString; tempString = shiftDigits(tempString, j); temp = Integer.parseInt(tempString); if ((temp > base) && (temp <= upper)) { if (!h.contains(tempString)) { h.add(tempString); pairs++; } } } } return pairs; } private static String shiftDigits(String temp, int n) { return temp.substring(temp.length() - n) + temp.substring(0, temp.length() - n); } } " B12416,"package codejam12; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; public class RoundOneProblemC { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { BufferedReader input = new BufferedReader(new FileReader(""input.txt"")); BufferedWriter output = new BufferedWriter(new FileWriter(""output.txt"")); int noOfTestCases = Integer.parseInt(input.readLine()); for(int i=1;i<=noOfTestCases;i++) { String inputLine = input.readLine(); String strArr[] = inputLine.split(""\\s+""); int a = Integer.parseInt(strArr[0]); int b = Integer.parseInt(strArr[1]); String bStr = Integer.toString(b); char firstBDigit = bStr.charAt(0); int no = 0; for(int num=a;num<=b;num++) { String numStr = Integer.toString(num); char firstChar = numStr.charAt(0); //if(firstChar == firstBDigit) //continue; for(byte k=1;k=firstChar && numStr.charAt(k)<=firstBDigit) { int newNumber = Integer.parseInt(numStr.substring(k) + numStr.substring(0,k)); if(newNumber <= b && newNumber > num) { no++; } } } } output.write(""Case #"" + i + "": "" + no + ""\n""); } input.close(); output.close(); } } " B10799,"import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.TreeSet; public class Qual3 { private static BufferedReader r; private static PrintStream outFile; private static PrintStream out = new PrintStream(new OutputStream() { @Override public void write(int b) throws IOException { System.out.write(b); outFile.write(b); } }); public static void main(String[] args) throws IOException { File f = new File(""/home/blarson/input""); r = new BufferedReader(new FileReader(f)); outFile = new PrintStream(new FileOutputStream(new File(""/home/blarson/output""))); final int numCases = readInt(); for(int i = 0; i < numCases; i++) { out.print(""Case #"" + (i+1) + "": ""); solve(); out.println(); } out.close(); } private static void solve() throws IOException { int[] nums = readIntArray(2); int a = nums[0]; int b = nums[1]; int numRecycled = 0; TreeSet found = new TreeSet(); // Brute force! for(int c = a; c < b; c++) { int numChars = numChars(c); found.clear(); for(int i = 1; i < numChars; i++) { int power = (int) Math.pow(10, i); int left = (int) (c / power); int right = c % power; int num = right * (int)Math.pow(10, numChars-i) + left; if(num > c && num <= b && found.add(num)) { numRecycled++; } } } out.print(numRecycled); } private static int numChars(int c) { if(c < 10) { return 1; } else if (c < 100) { return 2; } else if (c < 1000) { return 3; } else if (c < 10000) { return 4; } else if (c < 100000) { return 5; } else if (c < 1000000) { return 6; } else { return 7; } } private static int[] readIntArray(int maxItems) throws IOException { int[] array = new int[maxItems]; String line = r.readLine().trim(); String[] data = line.split("" ""); for(int i = 0; i < data.length && i < maxItems; i++) { array[i] = new Integer(data[i]); } return array; } private static int readInt() throws IOException { String line = r.readLine().trim(); return new Integer(line); } }" B11262,"import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int T = sc.nextInt(); int caseNum = 0; while(caseNum++ final HashSet allNames = new HashSet(); Lambda, Void> addAllIfNotNull = new Lambda, Void>() { public Void apply(Set newNames) { if (allNames != null) allNames.addAll(newNames); return null; } }; allNames.add(cell.getName()); addAllIfNotNull.apply(cell.getValues(""Main_name"")); addAllIfNotNull.apply(cell.getValues(""Other_name"")); addAllIfNotNull.apply(cell.getValues(""Tree_node"")); addAllIfNotNull.apply(cell.getValues(""Lineage_name"")); * */ public interface Lambda { public V apply(P param); } " B11145,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package problemc; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author mayorandrew */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { BufferedReader input = null; try { input = new BufferedReader(new FileReader(""input.txt"")); FileOutputStream output = new FileOutputStream(""output.txt""); int N = Integer.parseInt(input.readLine()); for(int i=0; i=a && num<=b && num!=k){ boolean found = false; for(int j=1; j ms = new HashSet(); for (int i = 0; i+1 < s.length(); ++i) { s = s.substring(1) + s.charAt(0); int m = Integer.parseInt(s); if (m > n && m <= B && s.charAt(0) != '0') { ms.add(m); } } result += ms.size(); } out.println(""Case #"" + t + "": "" + result); } out.close(); } } " B10950,"import java.io.IOException; import java.util.InputMismatchException; import java.util.Set; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.FileInputStream; import java.io.Writer; import java.math.BigInteger; import java.util.HashSet; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream; try { inputStream = new FileInputStream(""C-small-attempt0.in""); } catch (IOException e) { throw new RuntimeException(e); } OutputStream outputStream; try { outputStream = new FileOutputStream(""recyclednumbers.out""); } catch (IOException e) { throw new RuntimeException(e); } StreamInputReader in = new StreamInputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); RecycledNumbers solver = new RecycledNumbers(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } } class RecycledNumbers { public void solve(int testNumber, StreamInputReader in, OutputWriter out) { out.print(""Case #"" + testNumber + "": ""); int A = in.readInt(), B = in.readInt(); int P = 10; while (A / P > 0) { P *= 10; } int res = 0; Set set = new HashSet(); for(int i = A; i < B; ++i) { int p = 10; set.clear(); while (p < P) { int j = (i % p) * (P / p) + (i / p); if (j <= B && i < j && j / (P / 10) > 0) { set.add(j); } p *= 10; } res += set.size(); } out.printLine(res); } } class StreamInputReader extends InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public StreamInputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(outputStream); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } } abstract class InputReader { public abstract int read(); public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String next() { return readString(); } protected boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } " B11636,"package contest; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.Set; import java.util.HashSet; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); try { int T = Integer.parseInt(in.readLine()); for (int tc = 0; tc> map = new HashMap>(); int count = 0; for (int n=A; n<=B; n++) { List list = getRecList(n); for (int m: list) { if (m<=B && n s = new HashSet(); s.add(m); map.put(n, s); count++; } // System.out.println(""("" +n+ "","" + m + "")"");//testing } } } System.out.println(""Case #"" + (tc+1) + "": "" + count); } } catch (IOException e) { e.printStackTrace(); } } private static List getRecList(int n) { List ret = new ArrayList(); String str = Integer.toString(n); // System.out.println(""processing "" + n); //testing for (int i = str.length()-1; i>0;i--) { ret.add(Integer.parseInt(str.substring(i, str.length()) + str.substring(0, i))); // System.out.println(""adding: "" + Integer.parseInt(str.substring(i, str.length()) + str.substring(0, i)));//testing } return ret; } } " B12949,"package google.solver; public interface ChallengeConstants { public static final String DELIMITER = ""\\""; public static final String CHALLENGE_DEFINITION = ""challengeDefinition""; public static final String BASE_DIR= ""D:\\Development\\Workspaces\\test1\\googleChallanges\\src\\google\\contest""; public static final String CHALLENGE_NAME=""A""; public static final String TEST_IN=""test.in""; } " B10070,"import java.io.*; public class CodeJamQual3b { /** * @param args */ public static void main(String[] args) { try{ // Open the file that is the first // command line parameter File file = new File(""input.in""); FileInputStream fstream = new FileInputStream(""input.in""); //Input file name changed to input.in // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; FileWriter fout = new FileWriter(""out3.txt""); BufferedWriter outprint = new BufferedWriter(fout); //Read File Line By Line int i = 0; while (((strLine = br.readLine()) != null)) { if (i != 0 && i !=1111) { String[] stringArray = strLine.split("" ""); int bot = Integer.parseInt(stringArray[0]); int top = Integer.parseInt(stringArray[1]); int counter = 0; int len = stringArray[0].length(); //top for (int j = bot; j < top+1; j++) { counter = counter + count(j,top,bot,len); //System.out.println(""j = "" + j + "" "" + count(j,top,bot)); } //System.out.println (counter); outprint.write(""Case #"" + i + "": "" + counter); outprint.newLine(); System.out.println(""Case #"" + i + "": "" + counter); } i++; } //Close the input stream in.close(); //Close the output stream outprint.close(); }catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } public static int count(int j, int top, int bot, int len){ char[] cArray = Integer.toString(j).toCharArray(); int out = 0; int[] log = new int[len]; for (int k = 0; k < len-1; k++) { cArray = shift(cArray); boolean flag = true; //System.out.println(new String(cArray)); int recycled = Integer.parseInt(new String(cArray)); if ((j bot) && (recycled <= top)){ //System.out.println(""("" + j + "" , "" + recycled + "")"" + "" [ "" + bot + "" |"" + top + "" ] ""); for (int in = 0; in < len; in++){ if (recycled == log[in]){ flag = false; //System.out.println(""REPEAT"" + recycled); break; } } if (flag == true){ log[k] = recycled; //System.out.println(""("" + j + "" , "" + recycled + "")"" + "" [ "" + bot + "" |"" + top + "" ] ""); out += 1; } } } return out; } public static char[] shift(char[] cArray) { char[] nArray = new char[cArray.length]; nArray[0] = cArray[cArray.length-1]; for (int d = 1; d < cArray.length; d++){ nArray[d] = cArray[d-1]; } return nArray; } } " B12070,"package jp.funnything.prototype; import java.io.File; import java.io.IOException; import java.util.Set; import jp.funnything.competition.util.CompetitionIO; import jp.funnything.competition.util.Packer; import org.apache.commons.io.FileUtils; import com.google.common.collect.Sets; public class Runner { public static void main( final String[] args ) throws Exception { new Runner().run(); } void pack() { try { final File dist = new File( ""dist"" ); if ( dist.exists() ) { FileUtils.deleteQuietly( dist ); } final File workspace = new File( dist , ""workspace"" ); FileUtils.copyDirectory( new File( ""src/main/java"" ) , workspace ); FileUtils.copyDirectory( new File( ""../../../../CompetitionUtil/Lib/src/main/java"" ) , workspace ); Packer.pack( workspace , new File( dist , ""sources.zip"" ) ); } catch ( final IOException e ) { throw new RuntimeException( e ); } } void run() throws Exception { final CompetitionIO io = new CompetitionIO(); final int t = io.readInt(); for ( int index = 0 ; index < t ; index++ ) { final int[] values = io.readInts(); final int a = values[ 0 ]; final int b = values[ 1 ]; io.write( index + 1 , solve( a , b ) ); } io.close(); pack(); } int solve( final int a , final int b ) { int count = 0; final int nDigit = ( int ) Math.floor( Math.log10( a ) ) + 1; final int next = ( int ) Math.pow( 10 , nDigit - 1 ); final Set< Integer > already = Sets.newTreeSet(); for ( int n = a ; n + 1 <= b ; n++ ) { if ( already.contains( n ) ) { continue; } int inRange = 1; already.add( n ); for ( int base = 10 , m = next ; base < n ; base *= 10 , m /= 10 ) { final int v = n / base + n % base * m; if ( already.contains( v ) ) { continue; } if ( v >= a && v <= b ) { inRange++; already.add( v ); } } count += inRange * ( inRange - 1 ) / 2; } return count; } } " B12144,"package qualif.problem3; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; public class RecycledNumbers extends ProblemClass{ public RecycledNumbers(Scanner input) { super(input); } protected String processLine(String line) { String[] inputs = line.split("" ""); Integer lowNumber = new Integer(inputs[0]); Integer highNumber = new Integer(inputs[1]); Integer total = findRecycledNumberBetween(lowNumber,highNumber); return total.toString(); } private Integer findRecycledNumberBetween(Integer lowNumber,Integer highNumber){ int highNumberDigitsNumber = highNumber.toString().split(""(?<=.)"").length; Integer totalRecycled =0; lowNumber = Math.max(lowNumber, 10); for(Integer currentNumber=lowNumber ; currentNumber < highNumber ; currentNumber++ ){ String[] digits = currentNumber.toString().split(""(?<=.)""); if(allDigitsTheSame(digits)){ continue; } ArrayList alreadyCheck = new ArrayList(); for(int permut = 1 ; permut in = null; try { in = readFile(""input.txt""); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } String result = doit(Integer.parseInt(in.remove(0)), in); try { writeFile(result, ""output.txt""); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static ArrayList readFile(String filename) throws IOException{ ArrayList out = new ArrayList(); // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(filename); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; //Read File Line By Line while ((strLine = br.readLine()) != null){ // Print the content on the console out.add(strLine); } //Close the input stream in.close(); return out; } public static String doit(int c, ArrayList cases){ // Main logic StringBuilder out = new StringBuilder(); for(int i = 0; i < c; i++){ String s = cases.get(i); ArrayList sa = new ArrayList(); for(String l : s.split("" "")){ sa.add(Integer.parseInt(l)); } int A = sa.get(0); int B = sa.get(1); int recycles = 0; String t = """"; int size = (A+"""").length(); for(int n = A; n <= B; n++){ t = n+""""; ArrayList passed = new ArrayList(); for(int l = 1; l < size; l++){ int m = Integer.parseInt(t.substring(l)+t.substring(0, l)); if(n >= m || m > B){ continue; } if(passed.contains(m)){ continue; } recycles++; passed.add(m); } } out.append(""Case #""+(i+1)+"": ""+recycles); if(i != c-1){ out.append(""\n""); } } return out.toString(); } public static void writeFile(String output, String file) throws IOException{ FileWriter fstream = new FileWriter(file); BufferedWriter out = new BufferedWriter(fstream); out.write(output); out.close(); } } " B11670,"import java.io.*; import java.util.StringTokenizer; import java.util.Hashtable; /** * Created by IntelliJ IDEA. * User: marcus * Date: 4/14/12 * Time: 1:57 PM * To change this template use File | Settings | File Templates. */ public class RecycledNumbers { public static void main(String a[]) throws IOException { FileInputStream fInputstream = null; try { fInputstream = new FileInputStream(""C-small.in""); } catch (FileNotFoundException e) { //e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } DataInputStream in = new DataInputStream(fInputstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; FileWriter fstream = new FileWriter(""C-small.out""); BufferedWriter out = new BufferedWriter(fstream); String strT = null; strT = br.readLine(); int T = Integer.parseInt(strT); for(int d = 1; d <= T; d++) { String testCase = br.readLine(); StringTokenizer st = new StringTokenizer(testCase, "" ""); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); int dev = 0; int base = 10; while ( dev == 0){ if(A < base){ dev = base /10; } else base *= 10; } int count = 0; Hashtable table = new Hashtable (); for(int i = A; i <= B; i++){ //System.out.println(""i :"" + i); int mul = 10; for(int j = dev; j > 1 ; j/= 10, mul *= 10){ //System.out.println(""J :"" + j); int val = i / j; int rem = i % j; int recycledHalf = (rem * mul) + val; //System.out.println(""recycledHalf :"" + recycledHalf); if(A <= i && i < recycledHalf && recycledHalf <= B ) { System.out.println(A + "" <= "" + i + "" < "" + recycledHalf + "" <= "" + B); String s = String.valueOf(i) + "","" + String.valueOf(recycledHalf); //System.out.println( s ); table.put(s, new Integer(0)); } } } count = table.size(); //System.out.println(""Dev :"" + dev); //System.out.println(""Count :"" + count); out.write(""Case #"" + d + "": "" + count + ""\n""); } in.close(); out.close(); } } " B11712," public interface ICounterZeroEvent { public void fireEvent(); } " B12128,"import java.io.*; import java.util.*; public class Pilot { int Globe_k = 0; int max_units = 30; public static void main(String[] args) { Pilot my = new Pilot(); Calendar cal1 = Calendar.getInstance(); my.doAll(); Calendar cal2 = Calendar.getInstance(); // System.out.println(""seconds : "" + (cal2.getTimeInMillis() - // cal1.getTimeInMillis())/1000); } private static void doME(Vector combination) { System.out.println(combination.toString()); } public void doAll() { try { String out = """"; FileInputStream fstream = new FileInputStream(""in.txt""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine = """"; int glob = Integer.parseInt(strLine = br.readLine()); for (int j = 0; j < glob; j++) { Vector> results = new Vector>(); strLine = br.readLine(); String[] splitted = strLine.split("" ""); int A = Integer.parseInt(splitted[0]); int B = Integer.parseInt(splitted[1]); int num = 0; for (int k = A; k <= B; k++) { int L = Integer.toString(k).length(); int e = L - 1; int C = k; Integer[][] T = new Integer[L][2]; for (int i = 0; i < L; i++) { T[i][0] = (C % 10); C /= 10; T[i][1] = i; } for (int i = 0; i < e; i++) { for (int q = 0; q < L; q++) { T[q][1] = (q + e - i) % L; } // for (int u = 0; u < L; u++) // System.out.println(T[u][0] + "" "" + T[u][1]); int n = k; int m = 0; for (int q = 0; q < L; q++) m += T[q][0] * (int) Math.pow(10, T[q][1]); if (A <= n && n < m && m <= B) { Vector combination = new Vector();; combination.addElement(n); combination.addElement(m); if (!results.contains(combination)) { //doME(combination); results.addElement(combination); //System.out.println(k + "" - "" + m); num++; } } // System.out.println(""---""); } } out += (""Case #"" + (j + 1) + "": "" + num + ""\n""); } in.close(); out = out.trim(); Writer output = null; File file = new File(""out.out""); output = new BufferedWriter(new FileWriter(file)); output.write(out); output.close(); System.out.print(out); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } } " B13043,"import java.io.*; import java.util.*; public class QualificationRoundC { public static int power(int i, int p){ int k = 1; for(int j = 0; j < p; j++) k *= i; return k; } public static int recycle(int n, int k){ int d = power(10, k); int e = power(10, numDigits(n) - k); int right = n % d; int left = n / d; return right * e + left; } public static int numDigits(int n){ int i = 1, k = 0; while(n / i > 0){ i *= 10; k++; } return k; } public static Set getRecycledNumbers(int n){ int digits = numDigits(n); Set recycled = new HashSet(digits - 1); for(int i = 0; i < digits; i++){ int m = recycle(n, i); recycled.add(m); } return recycled; } public static void main(String[] args) throws IOException { String inFile = args[0]; String outFile = args[0].replaceAll(""\\.in$"", "".out""); FileInputStream fileInputStream = new FileInputStream(inFile); Scanner scanner = new Scanner(fileInputStream); FileWriter fileWriter = new FileWriter(outFile); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); int cases = scanner.nextInt(); for(int i = 1; i <= cases; i++){ int A = scanner.nextInt(), B = scanner.nextInt(); int count = 0; for(int n = A; n < B; n++){ Set recycled = getRecycledNumbers(n); Iterator it = recycled.iterator(); while(it.hasNext()){ int m = it.next(); if(n < m && m <= B) count++; } } String answer = String.format(""Case #%d: %d\n"", i, count); System.out.print(answer); bufferedWriter.write(answer); } bufferedWriter.close(); fileWriter.close(); scanner.close(); fileInputStream.close(); } } " B10032,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; import java.util.TreeSet; public class Main { /** * @param args * @throws FileNotFoundException */ public static boolean isRecycledPair(String N, String M) { if (N.equals(M)) return false; boolean retVal = false; for (int i=0; i set = new TreeSet(); int x = 0; for (long n=A; n<=B; n++) { for (long m=n; m<=B; m++) { String fN = Long.toString(n); String fM = Long.toString(m); if (Main.isRecycledPair(fN, fM)) { //set.add(fN + "","" + fM); x++; } } } writer.println(""Case #"" + (i+1) + "": "" + x); } System.out.println(""done""); reader.close(); writer.close(); } } " B12746,"import java.io.*; import java.util.Set; import java.util.HashSet; public class Recycler { public static void main(String[] args) throws IOException, FileNotFoundException { StreamTokenizer st = new StreamTokenizer( new FileReader(args[0])); FileWriter out = new FileWriter(args[1]); st.parseNumbers(); if (st.nextToken() == StreamTokenizer.TT_EOF) eof_error(); int numTestCases = (int) st.nval; int numDistinctPairs = 0; boolean twins = false; Set partners = new HashSet(); for (int t = 0; t < numTestCases; ++t) { if (st.nextToken() == StreamTokenizer.TT_EOF) eof_error(); int A = (int) st.nval; if (st.nextToken() == StreamTokenizer.TT_EOF) eof_error(); int B = (int) st.nval; for (int i = A; i < B; ++i) { String curNumberString = String.valueOf(i); for(int j = 1; j < curNumberString.length(); ++j) { String sub1 = curNumberString.substring(j); String sub2 = curNumberString.substring(0, j); String test = sub1 + sub2; if (Integer.valueOf(test) > i && Integer.valueOf(test) <= B) { if (! partners.contains(Integer.valueOf(test))) { ++numDistinctPairs; partners.add(Integer.valueOf(test)); } } } partners.clear(); } out.write(""Case #"" + (t+1) + "": "" + numDistinctPairs + ""\n""); numDistinctPairs = 0; } out.close(); } private static void eof_error() { throw new RuntimeException(""Unexpected end of file reached""); } } " B10385,"package br.com.feasoft.jam; import java.io.IOException; import java.util.*; /** * User: Homer * Date: 4/13/12 * Time: 9:30 PM */ public class Recycle { public static void main(String[] args) throws IOException { Scanner scanner = new Scanner(System.in); int numberOfCases = scanner.nextInt(); for (int i = 0; i < numberOfCases; i++) { int number1 = scanner.nextInt(); int number2 = scanner.nextInt(); int answer = 0; Map> pairs = new HashMap>(); for ( int j = number1; j <= number2; j++) { int size = Double.valueOf(Math.log10(j)).intValue(); for (int k = 1; k <= size; k++) { int number = shift(j, k); if(pairs.get(j) == null) { pairs.put(j, new HashSet()); } if (number != j && number >= number1 && number <= number2 && !pairs.get(j).contains(number)) { answer++; if(pairs.get(number) == null) { pairs.put(number, new HashSet()); } pairs.get(j).add(number); pairs.get(number).add(j); } } } System.out.printf(""Case #%d: %d\n"", i + 1, answer); } } public static int shift(int number, int quantity) { int digits = Double.valueOf(Math.log10(number)).intValue()+1; int lastDigitsGoingForward = Double.valueOf(number % Math.pow(10, quantity)).intValue(); int newFirstPart = Double.valueOf(lastDigitsGoingForward * Math.pow(10, digits-quantity)).intValue(); int firstDigitsGoingBack = Double.valueOf(number / Math.pow(10, quantity)).intValue(); return newFirstPart + firstDigitsGoingBack; } } " B10179,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package gjam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; /** * * @author iNahoo */ public class GJam { /** * @param args the command line arguments */ public static void main(String[] args) throws Exception { BufferedReader bufferedReader = new BufferedReader(new FileReader(""/Users/iNahoo/Desktop/C-small-attempt0.in"")); String line=""""; int i=1; File output=new File(""/Users/iNahoo/Desktop/gtest/test_.out""); FileWriter fw = new FileWriter(output.getName()); BufferedWriter bw = new BufferedWriter(fw); line = bufferedReader.readLine(); while ((line = bufferedReader.readLine()) != null) { String out_=""Case #""+i+"": ""+reclyC(line); System.out.println(out_); bw.write(out_); i++; } bw.close(); //System.out.print(reclyString(""2"")); //System.out.println(""Case #""+1+"": ""+langVert(""ejp mysljylc kd kxveddknmc re jsicpdrysi"")); // TODO code application logic here } public static int reclyC(String s){ String[] ij=s.split("" ""); int i=Integer.parseInt(ij[0]); int j=Integer.parseInt(ij[1]); int temp=0; String[] input=new String[j-i+1]; for(int k= 0;k""+temp_); for(int m=0;m 1) { for (int j = 1; j < str.length(); j++) { tmp = str.substring(j, str.length()) + str.substring(0,j); if (tmp.startsWith(""0"")) continue; k = Integer.parseInt(tmp); if (k >=a && k <= b && k > i) ans ++; } } } writer.write(String.format(""Case #%d: %d\n"", tt,ans)); System.out.println(String.format(""Case #%d: %d\n"", tt,ans)); } writer.close(); } } " B13076,"import java.io.BufferedWriter; import java.io.IOException; import java.util.ArrayList; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.util.Scanner; import javax.swing.JOptionPane; public class Pair { private int A; private int B; private int pairs; public Pair(int A, int B) { this.A = A; this.B = B; this.pairs = 0; } public int getA() { return this.A; } public int getB() { return this.B; } public int getPairs() { return this.pairs; } public String snake(String the_string, int position) { int len = the_string.length(); int point = len - position; String end = the_string.substring(point); String build = end + the_string.substring(0, point); return build; } public void finder(int base, int limit) { ArrayList doubles = new ArrayList(); String the_base = Integer.toString(base); int len = the_base.length(); for(int i = 1; i < len; i++) { String answ = this.snake(the_base, i); if(!doubles.contains(answ)) { int answer = Integer.parseInt(answ); if(answer <= limit && base < answer) { doubles.add(answ); this.pairs++; } } } } public void find_pairs() { int the_A = this.A; while(the_A < this.B) { this.finder(the_A, this.B); the_A++; } } public static void main(String[] args) throws FileNotFoundException, IOException { String file = JOptionPane.showInputDialog(""Enter the name of the file you wish to use.""); Scanner in = new Scanner(new FileReader(file)); FileWriter fstream = new FileWriter(""out.txt""); BufferedWriter out = new BufferedWriter(fstream); String integ = in.nextLine(); int cases = Integer.parseInt(integ); for(int i = 0; i < cases; i++) { String ab = in.nextLine(); Scanner abs = new Scanner(ab); String a = abs.next(); String b = abs.next(); int int_a = Integer.parseInt(a); int int_b = Integer.parseInt(b); Pair current = new Pair(int_a, int_b); current.find_pairs(); System.out.println(""Case #"" + (i + 1) + "": "" + current.getPairs()); out.write(""Case #"" + (i + 1) + "": "" + current.getPairs() + ""\r\n""); } out.close(); } } " B10803,"import java.util.HashSet; import java.util.Set; public class TestCase { private int totalDigit = -1; private int max; private int min; public TestCase(String s) { String[] results = s.split("" ""); totalDigit = results[0].length(); min = Integer.parseInt(results[0]); max = Integer.parseInt(results[1]); } public int solve() { Set total = new HashSet(); for (int i = min; i <= max; i++) { for (int j = 1; j < totalDigit; j++) { Pair p = getPair(i, j); if (p != null) { //System.out.printf(""Adding pair(%d, %d), %b\n"", p.getFirst(), p.getSecond(), total.add(p)); total.add(p); } } } return total.size(); } private Pair getPair(int number, int digit) { String source = String.valueOf(number); String target; Pair result = null; String first; String second; // if (digit == 1) { // first = source.substring(totalDigit - digit); // second = source.substring(0, digit); //// target = source.substring(0, totalDigit) + source.substring(totalDigit - digit); // } else if (digit == 2) { first = source.substring(totalDigit - digit); second = source.substring(0, totalDigit - digit); // } target = first + second; int targetNumber = Integer.parseInt(target); if (targetNumber >= min && targetNumber <= max & targetNumber != number) { result = new Pair(number, targetNumber); } return result; } } " B10501,"import java.io.*; public class ProblemC { public static void main(String args[]) { try { BufferedReader br = new BufferedReader(new FileReader(""E:\\test.txt"")); int no; no= Integer.parseInt(br.readLine()); int casen=0,i,j; int a,b,count; String temp,t,u; String output; output=""""; String spl[]; String memory,fp,lp; while( casen < no ) { temp = br.readLine(); output += ""Case #""+(casen+1)+"": ""; spl = temp.split("" ""); a = Integer.parseInt(spl[0]); b = Integer.parseInt(spl[1]); count = 0; memory = """"; for(i=a;i<=b; i++) { t = i+""""; for(j=1;j= a) { if( t.length() % 2 == 0 ) { fp= t.substring(0,t.length()/2); lp = t.substring(t.length()/2); if( fp.equals(lp) ) { if(!memory.contains(Integer.parseInt(u)+"" ""+i)) { count++; memory += Integer.parseInt(u) + "" "" + i+""\n""; } } else { count++; } } else { count++; } /*if( memory.contains(Integer.parseInt(u)+"" ""+i) ) System.out.println(Integer.parseInt(u)+"" ""+i); else { count++; memory += Integer.parseInt(u) + "" "" + i+""\n""; }*/ } } } output += count; if( casen != no-1 ) output += ""\n""; casen++; } BufferedWriter bw = new BufferedWriter( new FileWriter(""E:\\result.txt"")); bw.write(output); bw.close(); br.close(); } catch( Exception e ) { e.printStackTrace(); } } }" B13004,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; public class C { public static void main(String[] args) throws NumberFormatException, IOException { File file = new File(args[0]); BufferedReader reader = new BufferedReader(new FileReader(file)); PrintStream printer = new PrintStream(new File(""C-small.txt"")); int T = Integer.parseInt(reader.readLine()); for (int t = 0; t < T; t++) { String line = reader.readLine(); String numStrArr[] = line.split("" ""); int a = Integer.parseInt(numStrArr[0]); int b = Integer.parseInt(numStrArr[1]); String bs = b + """"; long ans = 0; for (int n = a; n < b; n++) { String s = n + """"; List sl = new ArrayList(); for (int i = 1; i < s.length(); i++) { String sb = s.substring(i) + s.substring(0, i); if (sb.compareTo(bs) <= 0 && sb.compareTo(s) > 0 && !sl.contains(sb)) { ans++; sl.add(sb); } } } printer.println(""Case #"" + (t+1) + "": "" + ans); } printer.close(); reader.close(); } } " B10840,"package quals; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Recycler { public static void main(String args[]) { try { System.setIn(new FileInputStream(""C-small-attempt0.in"")); Scanner scanner = new Scanner(System.in); int testCases = scanner.nextInt(); scanner.nextLine(); for (int i = 1; i <= testCases; i++) { int a = scanner.nextInt(); int b = scanner.nextInt(); int numRecycledPairs = recycler(a, b); System.out.println(String.format(""Case #%d: %d"", i, numRecycledPairs)); } } catch (FileNotFoundException e) { e.printStackTrace(); } } private static int recycler(int a, int b) { int numRecycled = 0; int digits = (int) Math.log10(a) + 1; Set recycled = new HashSet(); for (int m = a; m <= b; m++) { for (int pos = 1; pos <= digits; pos++) { int n = recycle(m, pos); if (m < n && n <= b && !recycled.contains(n)) { numRecycled++; recycled.add(n); } } recycled.clear(); } return numRecycled; } private static int recycle(int a, int pos) { return a / (int) Math.pow(10, pos) + (a % (int) Math.pow(10, pos)) * (int) Math.pow(10, (int) Math.log10(a) - pos + 1); } } " B12703,"package cj; import static cj.Utils.*; public class Recycle { public static int count(int a, int b) { int ret = 0; for (int i=a; i<=b; i++) { for (int j=i+1; j<=b; j++) { if (recycled(i, j)) ret++; } } return ret; } public static boolean recycled(int a, int b) { if (a==b) return true; String A = a+""""; String B = b+""""; for (int i=0; i<(int)Math.log10(a)+1; i++) { if (A.equals(B)) return true; B = B.charAt(B.length()-1) + B.substring(0, B.length()-1); } return false; } public static void main(String[] args) { String[] lines = readLines(""in/""+args[0]); int num = new Integer(lines[0]) + 1; String[] print = new String[num-1]; for (int i=1; i s = new HashSet(); int count = 0; for (int n = A; n <= B; n++) { for (int m : getRecycled(n)) { if(m> n && m <= B){ count++; // if(tc < number_of_test_cases-1) // if(!s.add(""("" + n + "","" + m + "")"")) // System.out.println(""("" + n + "","" + m + "")""); } } } out.write(""Case #""+(tc+1)+"": ""+count+newLine); } } catch (IOException e) { System.out.println(""Exception : ""+e); } finally { if(out != null){ try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } private static Set getRecycled(int A){ String a = Integer.toString(A); Set r = new HashSet(); String temp=""""; for(int i =a.length();i>0;i--){ temp = a.charAt(i-1)+temp; String x = temp+a.substring(0, i-1); r.add(Integer.parseInt(x)); } return r; } private static boolean isRecycled(int A, int B){ String a = Integer.toString(A); String b = Integer.toString(B); String temp=""""; for(int i =a.length();i>0;i--){ temp = a.charAt(i-1)+temp; String x = temp+a.substring(0, i-1); if(x.equals(b)){ return true; } } return false; } private static int[] convertToInt(String line){ String data[] = line.split("" ""); int[] rtn = new int[data.length]; for(int i=0;i< data.length ;i++){ rtn[i]=Integer.parseInt(data[i].trim()); } return rtn; } }" B11615,"package quiz2012.quiz3; import java.util.HashSet; import java.util.Set; import domain.QuizSolver; import domain.QuizTestCaseInput; import domain.QuizTestCaseOutput; public class Quiz3Solver implements QuizSolver { @Override public QuizTestCaseOutput solve(QuizTestCaseInput testCaseInput) { Quiz3TestCaseInput input = (Quiz3TestCaseInput) testCaseInput; int numberOfRecycledPairs = 0; int n = input.getN(); String nAsString = String.valueOf(n); int numberOfDigitsOfN = nAsString.length(); int m = input.getM(); // TODO: Remove if the following case can be generalized. if (numberOfDigitsOfN == 1) { return new Quiz3TestCaseOutput(numberOfRecycledPairs); } for (int i = n; i < m; i++) { Set recycledValueSet = new HashSet(); for (int j = 1; j < numberOfDigitsOfN; j++) { int recycledValue = shiftDigitsLeft(i, j); if (recycledValue > i && recycledValue <= m) { recycledValueSet.add(recycledValue); System.out.println(i + "", "" + recycledValue); } } numberOfRecycledPairs += recycledValueSet.size(); } return new Quiz3TestCaseOutput(numberOfRecycledPairs); } public int shiftDigitsLeft(int n, int numberOfShifts) { String nAsString = String.valueOf(n); StringBuffer sb = new StringBuffer(); int numberOfDigitsOfN = nAsString.length(); for (int i = 0; i < numberOfDigitsOfN; i++) { sb.append(nAsString.charAt((numberOfDigitsOfN + i - numberOfShifts) % numberOfDigitsOfN)); } return Integer.valueOf(sb.toString()); } } " B13032,"package qualification.common; import java.io.*; /** * Created by IntelliJ IDEA. * User: ofer * Date: 14/04/12 * Time: 17:21 * To change this template use File | Settings | File Templates. */ public class InputReader { public static String[] getInputLines(String filename){ String[] input = null; File file = new File(filename); try { FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line = br.readLine(); int size = Integer.parseInt(line); input = new String[size + 1]; input[0] = line; for (int i=0 ; i { public static < T1 extends Comparable< T1 > , T2 extends Comparable< T2 > > Comparator< Pair< T1 , T2 > > getFirstComarator() { return new Comparator< Pair< T1 , T2 > >() { @Override public int compare( final Pair< T1 , T2 > o1 , final Pair< T1 , T2 > o2 ) { final int c = o1.first.compareTo( o2.first ); return c != 0 ? c : o1.second.compareTo( o2.second ); } }; } public static < T1 extends Comparable< T1 > , T2 extends Comparable< T2 > > Comparator< Pair< T1 , T2 > > getSecondComarator() { return new Comparator< Pair< T1 , T2 > >() { @Override public int compare( final Pair< T1 , T2 > o1 , final Pair< T1 , T2 > o2 ) { final int c = o1.second.compareTo( o2.second ); return c != 0 ? c : o1.first.compareTo( o2.first ); } }; } public T1 first; public T2 second; public Pair( final Pair< T1 , T2 > that ) { this.first = that.first; this.second = that.second; } public Pair( final T1 first , final T2 second ) { this.first = first; this.second = second; } @Override public boolean equals( final Object obj ) { if ( this == obj ) { return true; } if ( obj == null || getClass() != obj.getClass() ) { return false; } final Pair< ? , ? > that = ( Pair< ? , ? > ) obj; return Objects.equal( this.first , that.first ) && Objects.equal( this.first , that.first ); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ( first == null ? 0 : first.hashCode() ); result = prime * result + ( second == null ? 0 : second.hashCode() ); return result; } @Override public String toString() { return ""Pair [first="" + first + "", second="" + second + ""]""; } } " B12905,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.HashSet; import java.util.Set; public class GCJ3 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub GCJ3 g = new GCJ3(); // System.out.println(); // long i1 = g.calculate(1, 9); // System.out.println(); // long i2 = g.calculate(10, 40); // System.out.println(); // long i3 = g.calculate(100, 500); // long i4 = g.calculate(1111, 2222); // long i5 = g.calculate(28, 93); // System.out.println(i1); // System.out.println(i2); // System.out.println(i3); // System.out.println(i4); // System.out.println(i5); try { // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream( ""C:/PROG/java/work/tc/src/gcj3.txt""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; // Read File Line By Line int lineNum = 1; br.readLine(); while ((strLine = br.readLine()) != null) { // Print the content on the console // System.out.print(strLine+""\t""); String[] val = strLine.split(""\\s""); System.out.print(""Case #"" + lineNum + "": ""); System.out.println(g.calculate(Integer.valueOf(val[0]), Integer.valueOf(val[1]))); // System.out.println(); // System.out.println(strLine.charAt(0)); lineNum++; } // Close the input stream in.close(); } catch (Exception e) {// Catch exception if any e.printStackTrace(); } } public long calculate(int A, int B) { HashMap> map = new HashMap>(); String a = String.valueOf(A); String b = String.valueOf(B); if (a.length() == b.length() && a.length() > 1) { long count = 0; for (long i = A; i <= B; i++) { for (long l = 1; l < a.length(); l++) { long n = 0; long m = i; String nS = String.valueOf(m); String nS2 = nS.substring((int) l, a.length()) + nS.substring(0, (int) l); n = Long.valueOf(nS2); String nS3 = String.valueOf(n); if (n < m && nS3.length() == a.length() && A<=n && m<=B) { // System.out.println(n + "" "" + m); count++; if (map.get(nS3) == null){ HashSet s = new HashSet(); s.add(nS); map.put(nS3, s); }else { map.get(nS3).add(nS); } } } } long count2 = 0; for (String s : map.keySet()){ for (Object o: map.get(s).toArray()){ count2++; } } return count2; } return 0; } } " B12423,"import java.io.*; import java.util.*; public class ProblemC { public class Case { int a, b; public void solve(int caseIndex) { int length = Integer.toString(a).length(); int numPairs = 0; for (int n = a; n <= b; n++) { String ns = Integer.toString(n); LinkedHashSet distinctMs = new LinkedHashSet(); for (int i = 0; i < length; i++) { int m = Integer.parseInt(ns.substring(i) + ns.substring(0, i)); if (m >= a && m <= b && m > n) { distinctMs.add(m); } } numPairs += distinctMs.size(); } println(""Case #"" + (caseIndex + 1) + "": ""+numPairs); } } public void run() throws Exception { BufferedReader r = new BufferedReader(new FileReader(""input.txt"")); int numCases = new InputParser(r.readLine()).readInt(); for (int caseIndex = 0; caseIndex < numCases; caseIndex++) { Case c = new Case(); InputParser p = new InputParser(r.readLine()); c.a = p.readInt(); c.b = p.readInt(); c.solve(caseIndex); } r.close(); } public static void main(String[] args) throws Exception { fileWriter = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(""output.txt"")))); new ProblemC().run(); fileWriter.close(); } public static class InputParser { String text; int pos; public InputParser(String text) { this.text = text; } public void skipSpaces() { while (pos < text.length()) { if (text.charAt(pos) != ' ') break; pos++; } } public String readUntil(char expectedChar) { StringBuilder b = new StringBuilder(); while (pos < text.length()) { char ch = text.charAt(pos); if (ch == expectedChar) break; b.append(ch); pos++; } return b.toString(); } public String readToken() { skipSpaces(); return readUntil(' '); } public int readInt() { return Integer.parseInt(readToken()); } public long readLong() { return Long.parseLong(readToken()); } public char readChar() { char ch = text.charAt(pos); pos++; return ch; } public void readExpectedString(String s) { for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (readChar() != ch) throw new RuntimeException(""Expected: ""+ch); } } } public static PrintWriter fileWriter; public static void print(String text) { fileWriter.print(text); System.out.print(text); } public static void println(String text) { fileWriter.println(text); System.out.println(text); } public static void addToMultiMapArrayList(Key key, Value value, Map> map) { ArrayList list = map.get(key); if (list == null) { list = new ArrayList(); map.put(key, list); } list.add(value); } public static void addToMultiMapLinkedHashSet(Key key, Value value, Map> map) { LinkedHashSet list = map.get(key); if (list == null) { list = new LinkedHashSet(); map.put(key, list); } list.add(value); } public static ArrayList getMultiMapValues(Map> map) { ArrayList result = new ArrayList(); for (Collection list : map.values()) { result.addAll(list); } return result; } } " B13048,"import java.io.*; import java.util.*; class c { public static int count(String A, String B) { int count=0; int a = Integer.parseInt(A); int b = Integer.parseInt(B); for(int i=a; i<=b;i++) { int n = i; int len = String.valueOf(i).length(); for(int j= 1;j < len;j++) { String mod = String.valueOf(i).substring(len-j, len) + String.valueOf(i).substring(0, len - j); int m = Integer.parseInt(mod); if(a<=n && n stringWithIntegersToList(String str, int numItems, String delim){ ArrayList list = new ArrayList(); StringTokenizer tokenizer = new StringTokenizer(str, delim); if (tokenizer.countTokens() != numItems){ throw new RuntimeException(""EXCEPTION: The string \"""" + str + ""\"" has more tokens ("" + tokenizer.countTokens() + "") than you said ("" + numItems + "")""); } for (int i = 0; i < numItems; i++) { list.add(Integer.parseInt(tokenizer.nextToken())); } return list; } public static List stringWithIntegersToList(String str, String delim){ ArrayList list = new ArrayList(); StringTokenizer tokenizer = new StringTokenizer(str, delim); int numOfTokens = tokenizer.countTokens(); for (int i = 0; i < numOfTokens; i++) { list.add(Integer.parseInt(tokenizer.nextToken())); } return list; } public static List stringWithStringsToList(String str, int numItems, String delim){ ArrayList list = new ArrayList(); StringTokenizer tokenizer = new StringTokenizer(str, delim); if (tokenizer.countTokens() != numItems){ throw new RuntimeException(""EXCEPTION: The string \"""" + str + ""\"" has more tokens ("" + tokenizer.countTokens() + "") than you said ("" + numItems + "")""); } for (int i = 0; i < numItems; i++) { list.add(tokenizer.nextToken()); } return list; } public static List stringWithStringsToList(String str, String delim){ //System.out.println(""String: "" + str); ArrayList list = new ArrayList(); StringTokenizer tokenizer = new StringTokenizer(str, delim); //System.out.println(""tokenizer.countTokens() = "" + tokenizer.countTokens()); int numOfTokens = tokenizer.countTokens(); for (int i = 0; i < numOfTokens; i++) { list.add(tokenizer.nextToken()); } return list; } public static List allCharactersToList(String str) { System.out.println(""String: "" + str); ArrayList list = new ArrayList(); for (int i = 0; i < str.length(); i++) { list.add(str.charAt(i)); } System.out.println(""List of characters: "" + list); return list; } } " B11299,"import java.io.*; public class RecycledNumbers { public static void main(String[] args) { BufferedReader in; BufferedWriter out; int T, i; String line; try { in = new BufferedReader(new FileReader(""input.txt"")); out = new BufferedWriter(new FileWriter(""output.txt"")); } catch (FileNotFoundException e) { System.out.println(e.getMessage()); return; } catch (IOException e) { System.out.println(e.getMessage()); return; } try { T = Integer.parseInt(in.readLine()); for (i = 0; i < T; i++) { line = in.readLine(); String lineToWrite = ""Case #"" + (i+1) + "": ""; lineToWrite += String.valueOf(solve(line)); out.write(lineToWrite + ""\n""); } in.close(); out.close(); } catch (IOException e) { System.out.println(e.getMessage()); return; } } public static int solve(String input) { int a, b, counter; String[] inputs = input.split("" ""); a = Integer.parseInt(inputs[0]); b = Integer.parseInt(inputs[1]); counter = 0; for (int n = a; n < b; n++) { int i; for (i = 10; i < b; i *= 10) { int m = split(n, i); if (m > n && m <= b) counter++; } } return counter; } public static int split(int num, int pow) { int half1, half2; half1 = num/pow; half2 = (num%pow) * (orderOf(num) / pow); return half1 + half2; } public static int orderOf(int num) { int i = 1; while (i < num) { i*=10; } return i; } } " B11594,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.HashSet; public class A { public static int a(String str){ int retVal = 0; String arr[] = str.split("" ""); int n = Integer.parseInt(arr[0]); int m = Integer.parseInt(arr[1]); for(int i = n ; i < m; i++){ String cur = Integer.toString(i); cur += cur; HashSet set = new HashSet(); for(int j = 1; j < cur.length()/2 ; j++){ String val = cur.substring(j, j+cur.length()/2); int intVal = Integer.parseInt(val); if(set.add(val) && intVal > i && intVal <= m){ retVal++; //System.out.println(retVal + "":"" +cur.substring(cur.length()/2)+"" : ""+intVal); } } } return retVal; } public static void main(String args[]){ File file = new File(""C-small-attempt0.in""); int T = 0; try{ FileInputStream fstream = new FileInputStream(file); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; if ((strLine = br.readLine()) != null) { T = Integer.parseInt(strLine); } int currentCase = 1; while(T > 0 && currentCase <= T){ String str= br.readLine(); System.out.println(""Case #""+currentCase+"": "" + a(str)); currentCase++; } in.close(); }catch (Exception e){ System.err.println(""Error: "" + e.getMessage()); } } } " B10101,"package com.codejam2012; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class FileUtils { public static String readFile(String fileName){ FileReader reader = null; String temp = null; try { reader = new FileReader(fileName); } catch (FileNotFoundException e1) { e1.printStackTrace(); } StringBuffer strContent = new StringBuffer(""""); try { BufferedReader bufferedReader = new BufferedReader(reader); temp =bufferedReader.readLine(); while (temp != null) { strContent.append(temp + ""\n""); temp =bufferedReader.readLine(); } } catch (Exception e) { System.out.println(e); } return strContent.toString(); } public static void appendToFile(String outputFileName, String dataToPrint) { File file =new File(outputFileName); if(!file.exists()){ try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } FileWriter fileWritter; try { fileWritter = new FileWriter(outputFileName,true); BufferedWriter bufferWritter = new BufferedWriter(fileWritter); bufferWritter.write(dataToPrint); bufferWritter.close(); fileWritter.close(); } catch (IOException e) { e.printStackTrace(); } } public static void deleteFile(String outputFileName) { File file =new File(outputFileName); if(file.exists()){ file.delete(); } } } " B11565,"import java.util.*; import java.math.*; public class recycledNumbers { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner scan = new Scanner(System.in); int numStrings = scan.nextInt(); for(int i =1; i <= numStrings; i++){ int lowerBound = scan.nextInt(); int upperBound = scan.nextInt(); int numDigits = Integer.toString(lowerBound).length(); int ten = 10; int count = 0; for(int j = lowerBound; j <= upperBound ; j++){ int temp = j; for(int k = 1; k <= numDigits; k++){ int temp_rem = temp % ten; int temp_quot = temp /ten; int temp1 = temp_quot + (int )(Math.pow(ten, numDigits-1))*temp_rem; if (temp1 > j && temp1 <= upperBound){ count = count + 1; } temp = temp1; //System.out.println(""\n"" + j + "" "" + temp + "" "" + upperBound + "" "" + count); } } //System.out.println(""LowerBound: "" + lowerBound + ""\n""); //System.out.println(""UpperBound: "" + upperBound + ""\n""); //System.out.println(""numDigits: "" + numDigits + ""\n""); System.out.format(""Case #%d: %d\n"", i, count); } } } " B10638,"import java.io.File; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C{ public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(new File(""C.txt"")); int testCase = Integer.parseInt(sc.nextLine()); for(int Case=1; Case<=testCase; Case++) { int total = 0; int st = sc.nextInt();int en = sc.nextInt(); int len = (new Integer(st)).toString().length(); for(int i=en; i>=st;i--) { Set s = new HashSet(); for(int j=1; j<=len-1;j++) { String sam = (new Integer(i).toString()); //System.out.println(i+ ""Actual String:"" + sam); StringBuffer temp=new StringBuffer(); //System.out.println(""temp 1:""+temp.toString()); temp.append(sam.substring(j)); //System.out.println(""temp 2:""+temp.toString()); temp.append(sam.substring(0, j)); //System.out.println(""temp 3:""+temp.toString()); int num = Integer.parseInt(temp.toString()); if(num>=st && num<=en && num= lower && number <= upper && number > j) { int value = hm.get(s + ""#"" + newNumber) != null ? (Integer) hm.get(s + ""#"" + newNumber) : 0; if (value != number) { hm.put(s + ""#"" + newNumber, number); pair++; } } } } } } } if (i < cases - 1) { fw.write(""Case #"" + (i + 1) + "": "" + pair + ""\n""); } else { fw.write(""Case #"" + (i + 1) + "": "" + pair); } hm.clear(); } fw.close(); in.close(); } catch (IOException e) { System.out.println(e.toString()); } } } " B10530,"import java.io.BufferedReader; import java.io.FileReader; import java.io.PrintWriter; import java.io.FileWriter; import java.util.*; public class C { public C( String fn) { try{ BufferedReader r = new BufferedReader( new FileReader( fn + "".in"")); PrintWriter w = new PrintWriter( new FileWriter( fn + "".out"")); int t = Integer.valueOf( r.readLine()); for( int i = 0; i < t; i++){ String[] line = r.readLine().trim().split( "" ""); int y = 0; int a = Integer.valueOf( line[0]); int b = Integer.valueOf( line[1]); for( int j = a; j < b; j++){ for( int k = j+1; k <= b; k++){ String n = String.valueOf( j); String m = String.valueOf( k); int c = 0; while( (c = n.indexOf( m.charAt( 0), c)) != -1){ if( m.equals( n.substring( c) + n.substring( 0, c))){ y++; break; } c++; } } } w.println( ""Case #"" + (i+1) + "": "" + y); System.out.println( ""Case #"" + (i+1) + "": "" + y); } w.close(); r.close(); }catch( Exception e){} } public static void main( String[] args) throws Exception { new C( args[0]); } }" B11849,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recycle; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.Writer; /** * * @author akila */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException, IOException { FileInputStream fstream = new FileInputStream(""C-small-attempt0.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); File file = new File(""write.txt""); BufferedWriter output = new BufferedWriter(new FileWriter(file)); String st = br.readLine(); int k = Integer.parseInt(st); for (int i = 0; i < k; i++) { int tot = 0; String st1 = br.readLine(); String[] strin = st1.split("" ""); String st2 = strin[0]; //System.out.println(st2); String st3 = strin[1]; //System.out.println(st3); int first = Integer.parseInt(st2); int second = Integer.parseInt(st3); for (int j = first; j <= second; j++) { for (int l = second; l > j; l--) { boolean b = check(j, l); if (b) { tot += 1; // System.out.println(""here""); } } } output.write(""Case #""+(i+1)+"": ""+tot); output.newLine(); // TODO code application logic here } output.close(); } public static boolean check(int n, int m) { String st1 = Integer.toString(n); String st2 = Integer.toString(m); if (st1.equalsIgnoreCase(st2)) { return false; } else if (st1.length() != st2.length()) { return false; } else if (st1.length() == 1) { return false; } else { char a = st2.charAt(0); for (int i = 1; i < st1.length(); i++) { if (st1.charAt(i) == a) { String stnew1 = st1.substring(i); String stnew2, output; if (i != 0) { stnew2 = st1.substring(0, i); output = stnew1.concat(stnew2); } else { String s1 = Character.toString(st1.charAt(0)); output = stnew1.concat(s1); } if (output.equalsIgnoreCase(st2)) { return true; } } } } // if (st1.length() != st2.length()) { // return false; // }else if(st1.length()==1) { // return false; // } // else { // // System.out.println(st1 +"" ""+st2); // if(st1.equalsIgnoreCase(st2)){ // char a = st2.charAt(0); // //System.out.println(a); // for (int i = 1; i < st1.length(); i++) { // if(st1.charAt(i)==a){ // // String newst = st1.substring(i)+st1.substring(0, i-1); // System.out.println(newst); // // System.out.println(newst); // if(newst.equalsIgnoreCase(st2)){ // // System.out.println(newst); // return true; // } // } // } // } // } return false; } } " B11009,"import java.util.*; import java.io.*; class problemC { static class Coordinate implements Comparable { int x, y; public Coordinate(int x, int y) { this.x = x; this.y = y; } public boolean equal(Object o) { if (o == null || !(o instanceof Coordinate)) { return false; } else { return ((Coordinate)o).x == this.x && ((Coordinate)o).y == this.y; } } @Override public int compareTo(Coordinate o) { // TODO Auto-generated method stub if (o.x == this.x && o.y == this.y) return 0; else return -1; } public String toString() { return ""("" + Integer.toString(x) + "","" + Integer.toString(y) + "")""; } } public static void main(String[] args) throws FileNotFoundException { String myFilename = (args.length < 1) ? ""test"" : args[0]; Set mySet = new TreeSet(); Scanner sc = new Scanner(new File(myFilename)); int testCases, A, B, maxDigits, newNum; String currNumStr, shiftedNumStr, frontStr, newStr; testCases = sc.nextInt(); sc.nextLine(); for (int cases = 0; cases < testCases; cases++) { A = sc.nextInt(); B = sc.nextInt(); mySet.clear(); for (int x = A; x <= B; x++) { currNumStr = Integer.toString(x); maxDigits = currNumStr.length(); // Shifting 0 and maxDigits won't change the number for (int digitsToShift = 1; digitsToShift < maxDigits; digitsToShift++) { shiftedNumStr = currNumStr.substring(digitsToShift, currNumStr.length()); if (shiftedNumStr.charAt(0) == '0') continue; frontStr = currNumStr.substring(0, digitsToShift); newStr = shiftedNumStr + frontStr; newNum = Integer.parseInt(newStr); if (x < newNum && newNum >= A && newNum <= B) mySet.add(new Coordinate(x, newNum)); } } System.out.println(""Case #"" + (cases+1) + "": "" + mySet.size()); } } } " B10668,"import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class RecycledNumbers { public static void main(String args[]){ RecycledNumbers r= new RecycledNumbers(); r.convert(args[0]); } public void convert(String filename){ try{ File f= new File(filename); Scanner scan= new Scanner(f); String firstLine= scan.nextLine(); int num= Integer.parseInt(firstLine); int[] answer= new int[num]; int[][] testnum= new int[num][2]; for(int i=0; i0;l=l-1){ String pos= strNum.substring(l,strNum.length())+strNum.substring(0,l); int j= Integer.parseInt(pos); if (j<=pair[1] && j>=pair[0] && j>k){ count=count+1; } } } answer[i]= count; System.out.println(""Case #""+(i+1)+"": ""+count); } } catch(FileNotFoundException e){ } } }" B12522," import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.Scanner; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author JY */ public class ProblemC4Test { private static int testNum; private static int[][] data; private static final int EQUAL = 0; private static final int LESS = 1; private static final int LARGER = 2; public static void main(String[] args) { input(); int[] result = calc(); output(testNum, result); } private static void input() { Scanner in = null; String file = ""C-small-attempt0.in""; try { in = new Scanner(new FileInputStream(file)); } catch (FileNotFoundException ex) { System.out.println(""Error reading file.""); System.exit(0); } //in = new Scanner(System.in); testNum = Integer.parseInt(in.nextLine()); data = new int[testNum][]; for (int i = 0; i < testNum; i++) { String line = in.nextLine(); String[] nums = line.split("" ""); data[i] = new int[2]; data[i][0] = Integer.parseInt(nums[0]); data[i][1] = Integer.parseInt(nums[1]); } } private static int[] calc() { HashSet hs = new HashSet(); int[] res = new int[testNum]; for (int i = 0; i < testNum; i++) { int result = 0; int a = data[i][0]; int b = data[i][1]; int length = getLength(b);; for (int number = a; number <= b; number++) { hs.clear(); for (int shifts = 1; shifts < length; shifts++) { int shiftnum = shift(number, shifts); if (shiftnum <= b && shiftnum > number && !hs.contains(shiftnum)) { result++; hs.add(shiftnum); } } } res[i] = result; } return res; } private static int getLength(int n) { return String.valueOf(n).length(); } private static int shift(int num, int shift) { String numS = String.valueOf(num); int len = numS.length(); numS = reverse(numS, 0, len - shift - 1); numS = reverse(numS, len - shift, len - 1); numS = reverse(numS, 0, len - 1); return Integer.parseInt(numS); } private static String reverse(String target, int start, int end) { char[] tar = target.toCharArray(); while (start < end) { char tmp = tar[start]; tar[start] = tar[end]; tar[end] = tmp; start++; end--; } return new String(tar); } private static void output(int testNum, int[] res) { for (int i = 0; i < testNum; i++) { System.out.printf(""Case #%d: %s\n"", i + 1, res[i]); } } } " B12231,"import java.io.*; class Programa { public static long procesar(String linea) { String vals[]=linea.split("" ""); int digitos=vals[0].length(); long a,b; a=Long.parseLong(vals[0]); b=Long.parseLong(vals[1]); long reciclados=0; int indi,ind = (int)(b-a+1); int parejas[][]=new int[ind][ind]; long t=b-a+1; long cal; long v,resto,pot; String resu,resu2; /* for (long =0;l=a && cal<=b && cal!=l && parejas[indi][ind]==0 && parejas[ind][indi]==0 ) { // System.out.println(""""+l+"" ""+cal); parejas[indi][ind]=1; reciclados++; } } } return reciclados; } public static void main(String args[]) { try{ FileInputStream fstream = new FileInputStream(args[0]); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; strLine = br.readLine(); int casos=Integer.parseInt(strLine); int caso=1; long respuesta=0; while ((strLine = br.readLine()) != null) { respuesta=procesar(strLine); System.out.println(""Case #""+caso+"": ""+respuesta); caso++; } //Close the input stream in.close(); }catch (IOException e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } }" B11069,"package fixjava; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.Future; import fixjava.ParallelWorkQueue.CallableFactory; public class ArrayUtils { // ------------------------------------------------------------------------------------------------ /** Convert a 2D float array into a 2D double array */ public static double[][] toDblArray(float[][] data) { double[][] copy = new double[data.length][data[0].length]; for (int i = 0; i < data.length; i++) for (int j = 0; j < data[0].length; j++) copy[i][j] = data[i][j]; return copy; } /** Convert a 2D double array into a 2D float array */ public static float[][] toFltArray(double[][] data) { float[][] copy = new float[data.length][data[0].length]; for (int i = 0; i < data.length; i++) for (int j = 0; j < data[0].length; j++) copy[i][j] = (float) data[i][j]; return copy; } /** Transpose an array */ public static double[][] transpose(double[][] data) { double[][] copy = new double[data[0].length][data.length]; for (int i = 0; i < data.length; i++) for (int j = 0; j < data[0].length; j++) copy[j][i] = data[i][j]; return copy; } /** Transpose an array */ public static float[][] transpose(float[][] data) { float[][] copy = new float[data[0].length][data.length]; for (int i = 0; i < data.length; i++) for (int j = 0; j < data[0].length; j++) copy[j][i] = data[i][j]; return copy; } // ------------------------------------------------------------------------------------------------ public static float[][] matMulPar(float[][] A, boolean transposeA, float[][] B, boolean transposeB, int numThreads) { return toFltArray(matMulPar(toDblArray(A), transposeA, toDblArray(B), transposeB, numThreads)); } public static double[][] matMulPar(double[][] A, boolean transposeA, double[][] B, boolean transposeB, int numThreads) { final double[][] matA = transposeA ? transpose(A) : A; // Keep B transposed so that matrix multiplication is more able to exploit cache coherence (matrix is stored row-wise) final double[][] matBT = transposeB ? B : transpose(B); final int p = matA.length, q = matA[0].length, q2 = matBT[0].length, r = matBT.length; if (q != q2) throw new IllegalArgumentException(""Array size mismatch""); final double[][] result = new double[p][r]; //final DecimalFormat formatPercent1dp = new DecimalFormat(""0.0%""); try { for (Future res : new ParallelWorkQueue(numThreads, ParallelWorkQueue.makeIntRangeIterable(p), new CallableFactory() { //IntegerMutable counter = new IntegerMutable(); @Override public Callable newInstance(final Integer ii) { return new Callable() { int i = ii.intValue(); double[][] resultLocal = result; int rLocal = r, qLocal = q; double[][] matALocal = matA, matBTLocal = matBT; @Override public Void call() { /** * * TODO: try blocked matrix multiplication to see if it's faster * * for (int ib = 0; ib < p; ib += blockSize) * for (int jb = 0; jb < q; jb += blockSize) * for (int kb = 0; kb < r; kb += blockSize) * for (int i = ib, iMax = Math.min(p, ib + blockSize); i < iMax; i++) * for (int j = jb, jMax = Math.min(q, jb + blockSize); j < jMax; j++) * for (int k = kb, kMax = Math.min(p, kb + blockSize); k < kMax; k++) * prod[i][j] += matALocal[i][k] * matBTLocal[j][k]; * * N.B. the ""+="" operation above needs to use TLS accumulators */ for (int j = 0; j < rLocal; j++) { float tot = 0.0f; for (int k = 0; k < qLocal; k++) tot += matALocal[i][k] * matBTLocal[j][k]; resultLocal[i][j] = tot; } // int count = counter.increment(); // if (count % 10 == 0) // System.out.println(formatPercent1dp.format((count / (float) (pLocal - 1)))); return null; } }; } })) // Barricade res.get(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } return result; } // ------------------------------------------------------------------------------------------------ /** Multiply A by constant b */ public static double[][] matMulByConst(double[][] A, double b) { int p = A.length, q = A[0].length; double[][] result = new double[p][q]; for (int i = 0; i < p; i++) for (int j = 0; j < q; j++) result[i][j] = b * A[i][j]; return result; } /** Multiply A by constant b */ public static float[][] matMulByConst(float[][] A, float b) { int p = A.length, q = A[0].length; float[][] result = new float[p][q]; for (int i = 0; i < p; i++) for (int j = 0; j < q; j++) result[i][j] = b * A[i][j]; return result; } /** Multiply A by B transpose */ public static float[][] matMulABT(float[][] A, float[][] BT) { int p = A.length, q = A[0].length, q2 = BT[0].length, r = BT.length; if (q != q2) throw new IllegalArgumentException(""Array size mismatch""); float[][] result = new float[p][r]; for (int i = 0; i < p; i++) { for (int j = 0; j < r; j++) { float tot = 0.0f; for (int k = 0; k < q; k++) // This is the main matrix multiplication routine, because both operands here // are in row-major order, so we get speedups of 3-8x due to cache coherence // on large matrices. (Use the parallel version for really large matrices...) tot += A[i][k] * BT[j][k]; result[i][j] = tot; } } return result; } /** Multiply A by B transpose */ public static double[][] matMulABT(double[][] A, double[][] BT) { int p = A.length, q = A[0].length, q2 = BT[0].length, r = BT.length; if (q != q2) throw new IllegalArgumentException(""Array size mismatch""); double[][] result = new double[p][r]; for (int i = 0; i < p; i++) { for (int j = 0; j < r; j++) { float tot = 0.0f; for (int k = 0; k < q; k++) // This is the main matrix multiplication routine, because both operands here // are in row-major order, so we get speedups of 3-8x due to cache coherence // on large matrices. (Use the parallel version for really large matrices...) tot += A[i][k] * BT[j][k]; result[i][j] = tot; } } return result; } /** Multiply A by B */ public static float[][] matMulAB(float[][] A, float[][] B) { // Transpose B so it's row-major, and multiply by BTT==B return matMulABT(A, transpose(B)); } /** Multiply A by B */ public static double[][] matMulAB(double[][] A, double[][] B) { // Transpose B so it's row-major, and multiply by BTT==B return matMulABT(A, transpose(B)); } /** Multiply A transpose by B */ public static float[][] matMulATB(float[][] A, float[][] B) { // Transpose B so it's row-major, and multiply by BTT==B return matMulABT(transpose(A), transpose(B)); } /** Multiply A transpose by B */ public static double[][] matMulATB(double[][] A, double[][] B) { // Transpose B so it's row-major, and multiply by BTT==B return matMulABT(transpose(A), transpose(B)); } /** Multiply A transpose by B transpose */ public static double[][] matMulATBT(double[][] A, double[][] B) { return matMulABT(transpose(A), B); } /** Multiply A transpose by B transpose */ public static float[][] matMulATBT(float[][] A, float[][] B) { return matMulABT(transpose(A), B); } // ------------------------------------------------------------------------------------------------ /** Select a random subset of rows in a matrix */ public static float[][] selectRandomRowSubset(int numRows, float[][] mat) { int n = Math.min(numRows, mat.length); float[][] rows = new float[mat.length][]; for (int i = 0; i < mat.length; i++) rows[i] = mat[i]; Random rand = new Random(); for (int i = 0; i < n; i++) { int j = rand.nextInt(mat.length); float[] tmp = rows[i]; rows[i] = rows[j]; rows[j] = tmp; } return Arrays.copyOf(rows, n); } // ------------------------------------------------------------------------------------------------ /** Write a double[][] array to a file */ public static void writeToFile(String filename, String arrayName, double[][] array) { try { System.out.println(""Writing to "" + filename); PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(filename))); writeArray(writer, arrayName, array); writer.close(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } /** Write a double[][] array to a PrintWriter */ public static void writeArray(PrintWriter writer, String name, double[][] arr) { writer.println(name + ""\t"" + arr.length + ""\t"" + arr[0].length); for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[0].length; j++) writer.print((j == 0 ? """" : ""\t"") + arr[i][j]); writer.println(); } } /** Write a double[] array to a PrintWriter */ public static void writeArray(PrintWriter writer, String name, double[] arr) { writer.println(name + ""\t1\t"" + arr.length); for (int i = 0; i < arr.length; i++) writer.print((i == 0 ? """" : ""\t"") + arr[i]); writer.println(); } } " B10453,"package MyAllgoritmicLib; public class Hungary { int INF = 1000*1000*1000; int n; int[][] a; int[] xy, yx; boolean[] vx, vy; int[] minrow, mincol; public Hungary(int[][] a) { // TODO Auto-generated constructor stub this.a = a.clone(); } private boolean dotry (int i) { if (vx[i]) return false; vx[i] = true; for (int j=0; j mapping; public Q3Solver(){ mapping = new HashSet(); } public int solve(int a,int b){ int res = 0; for (int i = a ; i <= b ; i++){ res+= getNumberOfLegalRecycled( b, i); } return res; } private int getNumberOfLegalRecycled( int b, int num) { String numString = """"+num; int numDigits = numString.length(); int res = 0; for (int i = 0 ; i < numDigits - 1 ; i++){ String perm = numString.substring(numDigits - i - 1) + numString.substring(0,numDigits - i -1 ); Integer newNum = Integer.parseInt(perm); String test = newNum+""""; if (test.length() == numDigits){ //checks that there are no leading zeros if ( num != newNum && newNum > num && newNum <= b){ if (!mapping.contains(newNum+"",""+num) && !mapping.contains(num+"",""+newNum)) { res++; mapping.add(num+ "","" +newNum); mapping.add(newNum +"","" +num); } } } } return res; } } " B10963,"package CodeJam; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; public class C { /** * @param args */ static Scanner scan = new Scanner(System.in); static BufferedReader brscan = new BufferedReader(new InputStreamReader( System.in)); static PrintWriter pw; static StringBuilder[] permutation = new StringBuilder[2222222]; static StringBuilder sbuild = new StringBuilder(); public static void main(String[] args) throws FileNotFoundException { pw = new PrintWriter(new File(""output-C.txt"")); // TODO Auto-generated method stub GeneratePermutation(); int tc = scan.nextInt(); int from, to; for (int x = 1; x <= tc; x++) { int count = 0; from = scan.nextInt(); to = scan.nextInt(); for (int n = from; n < to; n++) { count += (SameString(permutation[n], n + 1, to)); } pw.println(""Case #"" + x + "": "" + count); } //pw.println(SameStringB(new StringBuilder(""2212""), new StringBuilder(""2221""))); pw.flush(); pw.close(); } public static boolean SameStringB(StringBuilder ac, StringBuilder bc) { StringBuilder a = new StringBuilder(ac); StringBuilder b = new StringBuilder(bc); int length = a.length(); for (int n=0; n hset = new HashSet(2000); public static int SameString(StringBuilder ac, int min, int max) { StringBuilder a = new StringBuilder(ac); hset.clear(); int length = a.length(); int normal = Integer.parseInt(a.toString()); int count = 0; for (int n = 0; n < length-1; n++) { a.append(a.charAt(0)); a.deleteCharAt(0); if (a.charAt(0) != '0') { int now = Integer.parseInt(a.toString()); if (now >= min && now <= max && hset.contains(now)==false) { hset.add(now); count++; } } } return count; } public static void GeneratePermutation() { for (int n = 1; n < 2222222; n++) { permutation[n] = new StringBuilder(n + """"); } } } " B10918,"import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; /** * Created by IntelliJ IDEA. * User: Ran * Date: Apr 14, 2012 * Time: 3:46:24 AM * To change this template use File | Settings | File Templates. */ public class Recycled { private static int numDigits; private static int mult[] = { 10, 100, 1000, 10000, 100000, 1000000, 10000000 }; private static int shift (int x) { int lastDigit = x % 10; x = x / 10; x += lastDigit * mult[numDigits-2]; return x; } private static boolean isPair (int x, int y) { for (int i = 0; i < numDigits - 1; i++) { x = shift (x); if (x == y) return true; } return false; } public static void main (String[] args) { Scanner s = null; try { // s = new Scanner (new File (""C-small-test.in"")); s = new Scanner (new File (""C-small-attempt0.in"")); } catch (FileNotFoundException e) { e.printStackTrace (); } int t = s.nextInt(); // Traverse all test cases. for (int test = 1; test <= t; test++) { int a = s.nextInt(); int b = s.nextInt(); numDigits = (int)(Math.floor (Math.log10 (a))) + 1; int numPairs = 0; for (int i = a; i < b; i++) for (int j = i + 1; j <= b; j++) if (isPair (i, j)) numPairs++; System.out.println (""Case #"" + test + "": "" + numPairs); } } } " B11117,"import java.io.File; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class RecycleSolution { /** * @param args */ public static void main(String[] args) { String inFilename = ""C-small-attempt0.in""; String outFilename = inFilename.substring(0, inFilename.length() - 3) + "".out""; try { Scanner sc = new Scanner(new File(inFilename)); PrintStream ps = new PrintStream(new FileOutputStream(outFilename)); int testCases = Integer.parseInt(sc.nextLine()); for (int i = 1; i <= testCases; i++) { // logic if (i >= 1) { ps.println(); } String data = sc.nextLine(); String[] parts = data.split("" ""); int min = Integer.parseInt(parts[0], 10); int max = Integer.parseInt(parts[1], 10); int pairCount = 0; for (int test = min; test < max; test++) { List orderings = orderingsOf(test); for (int ordering : orderings) { if (ordering > test && ordering <= max && ordering >= min) { if ((ordering + """").length() == (max + """").length()) pairCount++; } } } System.out.println(""Case #"" + i + "": "" + pairCount); ps.print(""Case #"" + i + "": "" + pairCount); } sc.close(); ps.close(); } catch (Exception ex) { ex.printStackTrace(); } } public static List orderingsOf(int number) { List myOrderings = new ArrayList(); String base = """" + number; int baselen = base.length(); for (int i = 0; i < baselen; i++) { String thisperm = base.substring(baselen - i); if (baselen - i > 0) { thisperm += base.substring(0, baselen - i); } // Strip out 0-starting int tplen = ("""" + Integer.parseInt(thisperm, 10)).length(); if (tplen == baselen) myOrderings.add(Integer.parseInt(thisperm, 10)); } return myOrderings; } } " B12246,"import java.util.Scanner; public class C { public static boolean recycled(int n, int m) { if (n == m) { return false; } else { String A = String.valueOf(n); A += A; String B = String.valueOf(m); return A.contains(B); } } public static void main(String[] args) { Scanner s = new Scanner(System.in); int T = s.nextInt(); for (int i = 0; i < T; i++) { int A = s.nextInt(); int B = s.nextInt(); int count = 0; for (int j = A; j <= B; j++) { for (int k = A; k <= B; k++) { if (recycled(j, k)) { count++; } } } System.out.print(""Case #"" + (i + 1) + "": ""); System.out.println(count / 2); } } } " B10199,"import java.util.*; import java.lang.*; import java.io.*; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; public class main { /** * @param args */ public static String lireString() // lecture d'une chaine { String ligne_lue = null; try { InputStreamReader lecteur = new InputStreamReader(System.in); BufferedReader entree = new BufferedReader(lecteur); ligne_lue = entree.readLine(); } catch (IOException err) { System.exit(0); } return ligne_lue; } public static Scanner s =new Scanner(System.in); public static void main(String[] args) { // TODO Auto-generated method stub System.out.println(""Input""); String filename = ""C:\\A-small-attempt1.in""; String ligne = """"; int nbrLigne = 0, i=0, j=0,rech=0; char cchar=' '; File f = new File(filename); if (f.exists()) { System.out.println(""File exists""); } else { System.out.println(""File does not exist""); } String aa=""ejpmyslckdxvnribtahwfougqz ""; String bb=""ourlangeismpbtdhwyxfckjvzq ""; String g=""""; try { FileInputStream fStream = new FileInputStream(filename); BufferedReader in = new BufferedReader(new InputStreamReader( fStream)); if (in.ready()) { ligne = in.readLine(); nbrLigne = Integer.parseInt(ligne); String res[]=new String[nbrLigne]; for (j = 0; j < nbrLigne; j++) { ligne = in.readLine(); for (i = 0; i < ligne.length(); i++) { g+=bb.charAt(aa.indexOf(ligne.charAt(i))); } System.out.println(""Case #""+(j+1)+"": ""+g); g=""""; } } }catch (IOException e) { System.out.println(""File input error""); } } } " B11601,"import java.io.*; import java.lang.*; import java.util.*; public class C { public static void main(String[] args) { C prob = new C(); prob.run(args[0]); } public void run(String fileName) { try { Scanner fin = new Scanner(new File(fileName)); PrintWriter fout = new PrintWriter(new File(fileName + "".out"")); int T = fin.nextInt(); for (int t = 1; t <= T; ++t) { fout.format(""Case #%d: "", t); int A = fin.nextInt(); int B = fin.nextInt(); int result = 0; TreeSet pairs = new TreeSet(); for (int i = A; i <= B; ++i) { String a = Integer.toString(i); pairs.clear(); for (int j = 1; j < a.length(); ++j) { String b = a.substring(j) + a.substring(0, j); if (b.charAt(0) == '0') continue; int m = Integer.valueOf(b); if ((m >= A) && (m <= B) && (m != i)) { pairs.add(m); } } result += pairs.size(); } result /= 2; fout.format(""%d\n"", result); } fin.close(); fout.close(); } catch (Exception e) { e.printStackTrace(); } } } " B11730,"/* * SpeakingApp.java */ package speaking; import org.jdesktop.application.Application; import org.jdesktop.application.SingleFrameApplication; /** * The main class of the application. */ public class SpeakingApp extends SingleFrameApplication { /** * At startup create and show the main frame of the application. */ @Override protected void startup() { show(new SpeakingView(this)); } /** * This method is to initialize the specified window by injecting resources. * Windows shown in our application come fully initialized from the GUI * builder, so this additional configuration is not needed. */ @Override protected void configureWindow(java.awt.Window root) { } /** * A convenient static getter for the application instance. * @return the instance of SpeakingApp */ public static SpeakingApp getApplication() { return Application.getInstance(SpeakingApp.class); } /** * Main method launching the application. */ public static void main(String[] args) { launch(SpeakingApp.class, args); } } " B12983,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class QuestionC { public static void doPuzzle() { try { File questionfile = new File(""C.in""); BufferedReader questionreader = new BufferedReader(new FileReader(questionfile)); File answerfile = new File(""C.out""); PrintWriter answerwriter = new PrintWriter(new BufferedWriter(new FileWriter(answerfile))); String[] params = null; String question = questionreader.readLine(); int T = Integer.parseInt(question); int[] A = new int[T]; int[] B = new int[T]; for (int i = 0; i < T; i++) { question = questionreader.readLine(); params = question.split("" ""); A[i] = Integer.parseInt(params[0]); B[i] = Integer.parseInt(params[1]); } int[] answer = analyze(T, A, B); for (int i = 0; i < T; i++) { answerwriter.println(""Case #"" + (i+1) + "": "" + answer[i]); } answerwriter.close(); questionreader.close(); } catch (FileNotFoundException e) { e.printStackTrace(); return; } catch (IOException e) { e.printStackTrace(); return; } } private static int[] analyze(int T, int[] A, int[] B) { int[][] blockA = new int[9][T]; int[][] blockB = new int[9][T]; int[][] blockT = new int[9][T]; int[][] blockX = new int[9][T]; int[] blockLen = new int[9]; for (int i = 0; i < T; i++) { int len = String.valueOf(A[i]).length(); blockA[len][blockLen[len]] = A[i]; blockB[len][blockLen[len]] = B[i]; blockT[len][blockLen[len]] = i; blockLen[len]++; } for (int i = 1; i <= 20000000; i++) { String str = String.valueOf(i); int len = str.length(); StringBuilder sb = new StringBuilder(str); for (int j = 1; j < len; j++) { sb = sb.append(sb.charAt(0)).deleteCharAt(0); int value = Integer.parseInt(sb.toString()); if (i == value) break; for (int k = 0; k < blockLen[len]; k++) { if (blockA[len][k] > i) continue; if (blockA[len][k] > value) continue; if (blockB[len][k] < i) continue; if (blockB[len][k] < value) continue; blockX[len][k]++; } } } int[] answer = new int[T]; for (int i = 0; i < 9; i++) { for (int j = 0; j < blockLen[i]; j++) { answer[blockT[i][j]] = blockX[i][j] / 2; } } return answer; } } " B11270,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.HashMap; import java.util.LinkedList; class RecycledNumbers { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.println(""Input? ""); String input = in.readLine(); if(!input.equals(""System.in"")) { in = new BufferedReader(new FileReader(new File(input))); } PrintStream out; out = new PrintStream(new File(""C.out"")); //out = System.out; int cases = Integer.parseInt(in.readLine()); for(int i = 1; i <= cases; i++) { String[] line = in.readLine().split("" ""); int A = Integer.parseInt(line[0]); int B = Integer.parseInt(line[1]); int recycledPairs = 0; HashMap> cache = new HashMap>(); for(int n = A; n < B; n++) { String nStr = Integer.toString(n); for(int wrap = 0; wrap < nStr.length(); wrap++) { String mStr = recycle(nStr, wrap); int m = Integer.parseInt(mStr); if(A <= n && n < m && m <= B) { System.out.println(A + ""<="" + nStr + ""<"" + mStr + ""<="" + B); if(cache.get(n) == null) { cache.put(n, new LinkedList()); cache.get(n).add(m); recycledPairs++; } else if(!cache.get(n).contains(m)) { cache.get(n).add(m); recycledPairs++; } } } } out.print(""Case #"" + i + "": "" + recycledPairs); if(i != cases) out.println(); } if(out != System.out) out.close(); } public static String recycle(String number, int offset) { offset = offset > number.length() - 1 || offset < 0 ? offset % number.length() : offset; if(offset == 0) return number; char[] oldNumber = number.toCharArray(); char[] newNumber = new char[number.length()]; System.arraycopy(oldNumber, offset, newNumber, 0, number.length() - offset); System.arraycopy(oldNumber, 0, newNumber, number.length() - offset, offset); return new String(newNumber); } }" B12311,"package com.brootdev.gcj2012.problemC; import com.brootdev.gcj2012.common.Data; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class Main { private Data data; private long casesNumber; private long currentCase; public static void main(String[] args) throws IOException { new Main().go(args[0], args[1]); } public void go(String inFile, String outFile) throws IOException { data = new Data(inFile, outFile); casesNumber = data.readLongLine(); for (currentCase = 0; currentCase < casesNumber; currentCase++) { data.writeCaseHeader(currentCase); processCase(); } data.out.flush(); } private void processCase() throws IOException { long[] longs = data.readLongsArrayLine(); long A = longs[0]; long B = longs[1]; int digits = ((int) Math.log10(A)) + 1; long mn = (long) Math.pow(10, digits - 1); long sum = 0; Set m2 = new HashSet(); for (long n = A; n < B; n++) { long m = n; m2.clear(); for (int i = 1; i < digits; i++) { int r = (int) (m % 10); m = r * mn + m / 10; if (m <= B && n < m && ! m2.contains(m)) { sum++; m2.add(m); } } } data.out.println(sum); } } " B13086,"import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Scanner; /** * Created with IntelliJ IDEA. * User: aeg * Date: 12/04/14 * Time: 22:58 * To change this template use File | Settings | File Templates. */ public class ReceycledNumbers { public static void main (String[] argc) throws FileNotFoundException { ReceycledNumbers renum = new ReceycledNumbers(); renum.solve(); } private void solve() throws FileNotFoundException { FileInputStream fis = new FileInputStream(""csv/QR_C/C-small-attempt1.in""); Scanner sc = new Scanner(fis); int T = sc.nextInt(); loop: for (int i = 0; i < T; i++) { int A = sc.nextInt(); int B = sc.nextInt(); int count =0; System.out.print(""Case #""+(i+1)+"": ""); // System.out.println(""A is "" + A + "",M is "" + M); if (B < 10) { System.out.println(""0""); continue; } for (int j = A; j < B; j++) { String str = ((Integer) j).toString(); // System.out.println(str +""**""); count +=tryRecycle(str, j, B); } System.out.println(count); } } private int tryRecycle(String str, int j, int b) { int count=0; for(int i=1;in && m<= B) { compteur++; //System.out.println(""(""+String.valueOf(n)+"",""+String.valueOf(m)+"")""); } } } System.out.print(""Case #"" + String.valueOf(x+1) + "": ""); System.out.println(compteur); } } }" B10739,"/* * Google Code Challenge Java * * Code written for the Google Code Challenge by Greg Dougherty * Created: May 7, 2011 * * Copyright 2011 by Greg Dougherty */ package com.google.GregTD.CodeJam2012.Recycled; import java.io.*; /** * @author Greg Dougherty * */ public class Recycled { private static final String kInSuffix = "".in""; private static final String kOutSuffix = "".out""; /** * @param args */ public static void main (String[] args) { String inName = args[0]; int nameLen = inName.indexOf (kInSuffix); String outName = inName.substring (0, nameLen) + kOutSuffix; File dataFile = new File (args[0]); File resultFile = new File (outName); try { BufferedReader dataReader = new BufferedReader (new FileReader (dataFile)); BufferedWriter dataWriter = new BufferedWriter (new FileWriter (resultFile)); String line = dataReader.readLine (); // Get first line int numCases = Integer.valueOf (line).intValue (); // Run each test case for (int i = 0; i < numCases; ++i) { // Get data line = dataReader.readLine (); String[] entries = line.split ("" ""); int minValue = new Integer (entries[0]).intValue (); int maxValue = Integer.valueOf (entries[1]).intValue (); int numPairs = 0; for (int j = minValue; j <= maxValue; ++j) { String str = """" + j; int strLen = str.length (); if (strLen < 2) continue; --strLen; for (int k = 0; k < strLen; ++k) { str = str.charAt (strLen) + str.substring (0, strLen); int value = Integer.valueOf (str).intValue (); if ((value > j) && (value <= maxValue)) ++numPairs; } } dataWriter.write (""Case #"" + (i + 1) + "": "" + numPairs); dataWriter.newLine (); dataWriter.flush (); } } catch (IOException ioE) { ioE.printStackTrace (); } } } " B13071," public class Couple { int a; int b; String s; public Couple(int a, int b) { super(); this.a = a; this.b = b; s = String.valueOf(a) + String.valueOf(b); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Couple other = (Couple) obj; if (a == other.a && b == other.b) return true; if (a == other.b && b == other.a) return true; return false; } } " B10460," public class codejam { public static void main(String argv[]) throws Exception{ RecycledNumbers recycledNumbers=new RecycledNumbers(); recycledNumbers.start(); } } " B11839,"package info.m3o.gcj2012.recyclednumber; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class InputFileLoader { protected File infile; protected List rawInputLines; public List getRawInputLines() { if (rawInputLines == null) { rawInputLines = new ArrayList(); } return this.rawInputLines; } InputFileLoader(String infilepath) { infile = new File(infilepath); assert infile.canRead() == true : ""File "" + infilepath + "" is not readable.""; } public void readInputFile() { assert infile != null : ""Infile is null.""; assert infile.canRead() == true; FileReader fr; BufferedReader br; String str; if (infile.canRead()) { try { fr = new FileReader(infile); br = new BufferedReader(fr); str = br.readLine(); while (str != null) { this.getRawInputLines().add(str); str = br.readLine(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } } } } " B11466," import java.io.*; public class pro3 { private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public static void main ( String [] args ) throws IOException { int N = Integer.parseInt(br.readLine()); for(int i = 0;i < N; i++) System.out.println(""Case #"" + (i+1) + "": "" + cal()); } private static String cal() throws IOException { int start; int end; int lenth; int count=0; String[] buffer = br.readLine().split(""\\s""); start=Integer.parseInt(buffer[0]); end=Integer.parseInt(buffer[1]); lenth=Integer.toString(start).length(); String digit= new String(); String tempdigit=new String(); for(int i=start;i<=end;i++){ digit=Integer.toString(i); for(int j=1;j=start){ if(digit.compareTo(tempdigit)==0) break; /*System.out.println(""digit ""+digit); System.out.println(""tempdigit""+tempdigit); */count++; } } } return Integer.toString(count/2); } }" B13154,"import java.io.*; import java.util.*; public class C { static final int maxn = 2000010; static int A, B; static boolean was[] = new boolean[maxn]; static long ans; static void examine(int x) { String s = """" + x; int n = s.length(); int num = 1; was[x] = true; for (int i = 1; i < n; i++) { s = s.substring(1) + s.charAt(0); if (s.charAt(0) == '0') continue; int y = Integer.parseInt(s); if (was[y]) break; if (y >= A && y <= B) { was[y] = true; num++; } } ans += num * (num - 1) / 2; } public static void main(String[] args) { Scanner in = new Scanner(new InputStreamReader(System.in)); int T = in.nextInt(); for (int q = 1; q <= T; q++) { Arrays.fill(was, false); ans = 0; A = in.nextInt(); B = in.nextInt(); for (int i = A; i <= B; i++) { if (was[i]) continue; examine(i); } System.out.printf(""Case #%d: %d\n"", q, ans); } } } " B11169,"import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; public class C { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(""c.in""))); PrintStream out = new PrintStream(new FileOutputStream(""c.out"")); long count = readInt(in); for (int i = 0; i < count; i++) { String[] data = in.readLine().split("" ""); int a = Integer.parseInt(data[0]); int b = Integer.parseInt(data[1]); int ans = 0; HashSet st = new HashSet(); for (int k = a; k<=b ; k++) { String s = """" + k; for (int p = 1; p < s.length(); p++) { if (s.charAt(p) != '0') { int t = Integer.parseInt(s.substring(p) + s.substring(0, p)); if (t > k && a<= t && t <=b) { String key = s + t; if (!st.contains(key)) { ans++; System.out.println(k + "" "" + t); st.add(key); } } } } } out.println(""Case #"" + (i + 1) + "": "" + ans); } out.flush(); out.close(); } private static long readInt(BufferedReader in) { try { return Long.parseLong(in.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } } " B11892,"import java.util.*; public class RecycledNumbers{ static HashSet hs; public static int single(int n, int[] digits){ int i = 0; while(n>0){ digits[i] = n%10; n = n/10; i++; } return i; } public static int toNumber(int[] d){ int n = 0; for(int i = d.length-1; i>=0; i--){ n = (n*10)+d[i]; } return n; } public static int pairs(int nd, int[] d, int ja, int m){ int total = 0; int last = nd -1; for(int ni = 0; nija) && nn <= m){ total++; hs.add(ja+"",""+nn); } } return total; } public static int solve(int a, int b){ String sa = a+""""; String sb = b+""""; hs = new HashSet(); int la = sa.length(); int lb = sb.length(); if(la == 1) return 0; int[] digitsa = new int[7]; int[] digitsb = new int[7]; int ndigits = single(a, digitsa); single(b, digitsb); int count = 0; for(int ja =a; ja < b; ja++){ int[] digitsja = new int[7]; // System.out.println(""Checking ""+ja); single(ja, digitsja); int npa = pairs(ndigits, digitsja, ja, b ); count+=npa; if(npa > 0){ // System.out.println(""j ""+ja+"" npa ""+npa); } } //System.out.println(count); return hs.size(); } public static void main(String args[]){ Scanner s = new Scanner(System.in); int T = s.nextInt(); for(int i = 0; i set=new TreeSet(); for(int i=0; i<=str.length(); i++){ int c=Integer.parseInt(str); if(Integer.toString(c).length()!=len||(cb)) { str=str.substring(len-1)+str.substring(0,len-1); continue; } str=str.substring(len-1)+str.substring(0,len-1); bool[c]=true; set.add(c); } long res=set.size(); res*=(set.size()-1); res/=2; return res; } public static void main(String args[]) throws IOException{ PrintWriter out=new PrintWriter(new FileWriter(""result.txt"")); BufferedReader in=new BufferedReader(new FileReader(""C-small-attempt0.in"")); //BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); // System.out.print(oneTest(10, 40)); int n=Integer.parseInt(in.readLine()); for(int i=1; i<=n; i++){ String str=in.readLine(); out.print(""Case #""+i+"": ""); StringTokenizer tok=new StringTokenizer(str); out.print(oneTest(Integer.parseInt(tok.nextToken()), Integer.parseInt(tok.nextToken()))); out.println(); System.out.println(i); } out.flush(); System.out.println(""over""); } } " B11975,"package com.sam.googlecodejam.recyclenumbers; import java.util.HashSet; import java.util.Set; import com.sam.googlecodejam.helper.InputReader; public class RecycleNumbers { long pairCount; public void getPairCount(long a, long b) { int length = Long.toString(a).length(); long power = 1; for (int i = 1; i < length; i++) { power = power * 10; } for (long m = a; m < b; m++) { long value = m; Set pairCountSet = new HashSet<>(); for (int i = 0; i < length; i++) { value = value / 10 + (value % 10) * power; if (value > m && value <= b) { pairCountSet.add(value); } } pairCount = pairCount + pairCountSet.size(); } } public static void main(String[] args) { InputReader reader = new InputReader(""c://input.in""); reader.readNextLine(); // read the line number off - we don't need it String lineRead = null; int i = 1; while ((lineRead = reader.readNextLine()) != null) { RecycleNumbers recycleNumbers = new RecycleNumbers(); String values[] = lineRead.split("" ""); recycleNumbers.getPairCount(Long.parseLong(values[0]), Long.parseLong(values[1])); System.out.println(""Case #"" + i + "": "" + recycleNumbers.pairCount); i++; } } } " B10878,"package de.at.codejam.util; import java.util.ArrayList; import java.util.List; public abstract class AbstractCaseSolver implements CaseSolver { private final List statusListenerList = new ArrayList(); @Override public void updateStatus(TaskStatus taskStatus) { for (StatusListener listener : statusListenerList) { listener.updateStatus(taskStatus); } } @Override public void log(int logLevel, String message) { for (StatusListener listener : statusListenerList) { listener.log(logLevel, message); } } public void addStatusListener(StatusListener statusListener) { statusListenerList.add(statusListener); } public void removeStatusListener(StatusListener statusListener) { statusListenerList.remove(statusListener); } protected final String getDefaultResultBegin(TaskStatus taskStatus) { return ""Case #"" + taskStatus.getNumberCurrentCase() + "":""; } } " B12911,"package er.dream.codejam.helpers; import java.io.File; import java.util.List; public abstract class ProblemSolver { protected FileHandler fileHandler = new FileHandler(); protected abstract List handleInput(); public void execute(){ File[] files = fileHandler.listFiles(); for(File f : files){ long start = System.currentTimeMillis(); fileHandler.loadFile(f); List results = handleInput(); fileHandler.writeOutput(results); fileHandler.closeConnection(); long stop = System.currentTimeMillis(); System.out.println(""File ""+f.getName()+"" took me ""+(stop-start)+""ms""); } } } " B10071,"/** * @(#)C.java * * * @author * @version 1.00 2012/4/14 */ import java.util.*; import java.io.*; public class C { public static int recycle(int a, int b) { int count = 0; ArrayList pair = new ArrayList(); for(int i = a; i <= b; i++) { for(int j = i+1; j <= b; j++) { String n1 = """" + i; String n2 = """" + j; for(int k = 1; k <= n1.length(); k++) { if((n2.substring(k) + n2.substring(0, k)).equals(n1) && !pair.contains(n1+n2)) { //System.out.println(n1 + "" equals "" + n2); count++; pair.add(n1+n2); } } } } return count; } public static void main(String [] argz) throws IOException { Scanner reader = new Scanner(new File(""C-small-attempt0.in"")); int numCases = reader.nextInt(); reader.nextLine(); FileWriter fstream = new FileWriter(""out.txt""); BufferedWriter out = new BufferedWriter(fstream); for(int i = 0; i < numCases; i++) { Scanner lineReader = new Scanner(reader.nextLine()); int a = lineReader.nextInt(); int b = lineReader.nextInt(); out.write(""Case #"" + (i+1) + "": "" + recycle(a, b) + ""\n""); } out.close(); } }" B10126,"import java.io.BufferedInputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.FileWriter; class Start{ BufferedInputStream bis=new BufferedInputStream(System.in); PrintWriter out=new PrintWriter(System.out, true); int i,j,k,l,m,n,o,p,q,r,s,t,w,x,y,z,ry,rz,rs; long a,b,c; double d,e,f,g,h; char u,v; String st; int[] in,arr,res; final double pi=3.14159265; final double l2=0.69314718; char chr()throws IOException{ while((ry=bis.read())==10 || ry==13 || ry==32){} return (char)ry; } int num()throws IOException{ rz=0;rs=0; ry=bis.read(); if(ry=='-') rs=-1; else rz+=(ry-'0'); while((ry=bis.read())>='0' && ry<='9') rz=rz*10+(ry-'0'); if(rs==-1) rz=-rz; if(ry==13) bis.read(); return rz; } String str()throws IOException{ StringBuilder sb=new StringBuilder(); while((ry=bis.read())!=10 & ry!=13 && ry!=32) sb.append((char)ry); if(ry==13) bis.read(); return sb.toString(); } String line()throws IOException{ StringBuilder sb=new StringBuilder(); while((ry=bis.read())!=10 && ry!=13) sb.append((char)ry); if(ry==13)bis.read(); return sb.toString(); } int log2(double par){return (int)(Math.log(par)/l2);} long perm(int p1,int p2){ long ret=1; int it; it=p1; while(it>p2) ret*=it--; return ret; } long comb(int p1,int p2){ long ret=1; int it; if(p2p2) ret*=it--; it=p1-p2; while(it>1) ret/=it--; return ret; } public void go()throws IOException{ out =new PrintWriter(new FileWriter(""out.txt""),true); t=num(); w=t; while(--t>=0){ a=0; y=num(); z=num(); if(y<10) y=10; p=(int)Math.log10((double)z); q=(int)Math.pow(10.0, (double)p); for(i=y; i<=z; i++) { k=i; r=p; while(r-->0){ k = (k/10) + ((k%10)*q); if(k>i && k<=z) a++; } } out.println(""Case #""+(w-t)+"": ""+a); } while(bis.available()>0)bis.read(); out.close(); } public static void main(String args[])throws IOException{new Start().go();} } " B10705,"package test.googlejam.year2012.jam; import java.io.IOException; import org.apache.commons.lang.StringUtils; import test.googlejam.base.ProblemProcessor; import test.googlejam.base.ValueReader; public class RecycledNumbers extends ProblemProcessor { static java.util.Map mapping = new java.util.TreeMap(); public static void main(String[] args) throws java.io.IOException { RecycledNumbers processor; String fileName = ""c:/temp/googlejam/RecycledNumbers""; processor = new RecycledNumbers(); processor.setInputFileName(fileName + args[0] + "".in""); processor.setOutputFileName(fileName + args[0] + "".out""); processor.start(); } @Override public String processCase(int caseNumber) throws IOException { java.util.List values; values = this.readValues("" "", new ValueReader() { @Override public String readValue(String token) { return token; } }); String stringA; int valueA, valueB; stringA = values.get(0); valueA = Integer.valueOf(values.get(0)); valueB = Integer.valueOf(values.get(1)); java.util.SortedSet permutations = new java.util.TreeSet(); for ( int currentValue = valueA; currentValue <= valueB; currentValue++ ) { String currentString = Integer.toString(currentValue); for ( int i = 1; i < currentString.length(); i++ ) { String newString = StringUtils.right(currentString, i) + StringUtils.left(currentString, currentString.length() - i); if ( '0' == newString.charAt(0) ) continue; int newValue = Integer.valueOf(newString); if ( (valueA <= newValue) && (newValue <= valueB) ) permutations.add(newValue); } } System.out.println(valueA); System.out.println(valueB); System.out.println(permutations); java.util.Set foundCases = new java.util.HashSet(); for ( int currentValue : permutations ) { String currentString = Integer.toString(currentValue); for ( int i = 1; i < currentString.length(); i++ ) { String newString = StringUtils.right(currentString, i) + StringUtils.left(currentString, currentString.length() - i); if ( '0' == newString.charAt(0) ) continue; int newValue = Integer.valueOf(newString); if ( (currentValue < newValue) && (permutations.contains(newValue))) { String foundCase = valueA + "" <= "" + currentValue + "" < "" + newValue + "" <= "" + valueB; //System.out.println(foundCase); foundCases.add(foundCase); } } } //System.out.println(foundCases); return Integer.toString(foundCases.size()); } } " B11472,"package qualification; import java.io.*; import java.util.*; public class C_RecycledNumbers { //-------------------------------------------------------------------------------- private static String ID=""C""; private static String NAME=""small-attempt0""; private static boolean STANDARD_OUTPUT=false; //-------------------------------------------------------------------------------- public static void main(String[] args) throws Throwable { int[][] results=new int[2000001][]; for (int i=0; i 0 && candidate.compareTo(maxValue) <= 0 && candidate.compareTo(minValue) >= 0) { counter++; } } currentNumber = currentNumber.add(ONE); } return counter; } private void run() throws FileNotFoundException { BigInteger[][] data = parseInput(""input""); Integer[] result = solve(data); printResult(result, ""output""); } private Integer[] solve(BigInteger[][] data) { Integer[] result = new Integer[data.length]; for (int i = 0; i < data.length; i++) { result[i] = count(data[i][0], data[i][1]); } return result; } private BigInteger rotateLeft(BigInteger value, int digits) { String stringValue = value.toString(10); StringBuilder result = new StringBuilder(stringValue.substring(digits)); result.append(stringValue.substring(0, digits)); return new BigInteger(result.toString(), 10); } private void printResult(Integer[] result, String path) throws FileNotFoundException { PrintWriter p = new PrintWriter(new File(path)); try { for (int i = 1; i < result.length+1; i++) { p.format(""Case #%d: %d\n"", i, result[i-1]); } } finally { p.close(); } } private BigInteger[][] parseInput(String path) throws FileNotFoundException { Scanner scanner = new Scanner(new File(path)); try { BigInteger[][] input = new BigInteger[scanner.nextInt()][2]; scanner.nextLine(); // skip to the next line for (int i = 0; i < input.length; i++) { input[i][0] = new BigInteger(scanner.next()); input[i][1] = new BigInteger(scanner.next()); // scanner.nextLine(); } return input; } finally { scanner.close(); } } } " B10722,"import java.util.Scanner; import java.io.*; public class Pair { public static int a, b, l; public static boolean inr(String x) { int t = Integer.parseInt(x); if ((t + """").length() != l) return false; if (t <= b && t >= a) { return true; } else return false; } public static String toS(int x) { String o = """"; return o+x; } public static boolean notInT(String[] t, String x, int c) { for (int i = 0; i < c; i++) if (t[i].equals(x)) return false; return true; } public static int recycle(String s) { int count = 0; String[] t = new String[l]; int c = 1; t[0] = s; for (int i = 0; i < l - 1; i++) { String a = s.substring(0, i + 1); String b = s.substring(i + 1, l); if (notInT(t, b + a, c)) { t[c] = b + a; c++; } } for (int i = 1; i < c; i++) { if (inr(t[i])) count++; } return count; } public static void main(String args[]) throws IOException { int count; Scanner in = new Scanner(new File(""e:/in.txt"")); PrintStream out = new PrintStream(new File(""e:/out.txt"")); int n = in.nextInt(); for (int z = 1; z <= n; z++) { count = 0; a = in.nextInt(); b = in.nextInt(); l = (b + """").length(); for (int i = a; i <= b; i++) { count += recycle(toS(i)); } count /= 2; out.println(""Case #""+z+"": ""+count); } } } " B10798,"public class Main { public static void main(String[] args) throws java.io.FileNotFoundException,java.io.IOException{ java.io.BufferedReader bRead=new java.io.BufferedReader(new java.io.FileReader(""F:\\C-small-attempt0.in"")); java.io.BufferedWriter bWrite=new java.io.BufferedWriter(new java.io.FileWriter(""F:\\C-small-attempt0.out"")); java.util.HashMap mVals=new java.util.HashMap(); StringBuffer output=new StringBuffer(); int noCases=Integer.parseInt(bRead.readLine()); for(int i=0;in&&m<=B&&!mVals.containsKey(m)){noPairs++;mVals.put(m,0);} } n++; } output.append(""Case #""+(i+1)+"": ""+noPairs+""\n""); } bWrite.write(output.toString()); bWrite.close();bRead.close(); } } " B12119,"package es.salamanca.google; import java.io.*; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Ángel Alfonso Gómez */ public class Recycled { public static void main(String[] args) { BufferedReader bf; FileReader fl; FileWriter f2; try { fl = new FileReader(""C:\\C-small-attempt2.in""); f2 = new FileWriter(""C:\\C-small-attempt2.out""); bf = new BufferedReader(fl); int num = Integer.parseInt(bf.readLine()); System.out.println(num); for (int i = 0; i < num; i++) { int cont=0; f2.append(""Case #""+(i+1)+"": ""); System.out.print(""Case #""+(i+1)+"": ""); String linea = bf.readLine(); int num1 = Integer.parseInt(linea.substring(0, linea.indexOf("" ""))); int num2 = Integer.parseInt(linea.substring(linea.indexOf("" "")+1)); for (int j=num1;j0;i--){ aux=String.valueOf(n.charAt(leng-1)); aux+=n.substring(0, leng-1); n=aux; //System.out.println(aux+"" ""+m); if(n.equals(m)) return true; } return false; } } " B12974,"package hu.hke.gcj; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; public class RecycledNumbers { static RecycledNumbers rn = new RecycledNumbers(); /** * @param args */ public static void main(String[] args) { readAndCalculate(args[0], args[1]); } private static void readAndCalculate(String inputF, String outputF) { BufferedReader input = null; BufferedWriter output = null; try { String line = null; input = new BufferedReader(new FileReader(inputF)); output = new BufferedWriter(new FileWriter(outputF)); boolean first = true; int expectedRows = 0; int actualRows = -1; while ((( line = input.readLine()) != null) && (actualRows < expectedRows)) { System.out.print(actualRows+1); System.out.println(""----------------------------------------------------""); if (first) { first = false; expectedRows = Integer.parseInt(line); } else { output.write(""Case #"" +(actualRows+1)+"": ""+ rn.recicledNumbers(line)); if (actualRows +1 < expectedRows) { output.write(""\n""); } } actualRows++; } input.close(); output.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { } } private String recicledNumbers(String line) { C c = new C(line); return c.calculate(); } class C { int a; int b; public C(String line) { String[] numbers = line.split("" ""); a = Integer.parseInt(numbers[0]); b = Integer.parseInt(numbers[1]); } public String calculate() { int result = 0; for (int i = a; i counted = new ArrayList(); for (int j = 1; j < digits.length; j++) { if (digits[j]>=digits[0]) { cycled = cycle(digits, j); if ( (i set = new HashSet(); int cnt=0; for(int i=1; i=n) index%=n; rec[j] = digits[index]; } int out = Integer.parseInt(String.valueOf(rec)); if(out > num && out <= b && !set.contains(out)){ cnt++; set.add(out); } } return cnt; } public void run() throws IOException{ BufferedReader bf = new BufferedReader(new FileReader(""b.in"")); PrintWriter pw = new PrintWriter(new FileWriter(""b.out"")); int kases = Integer.parseInt(bf.readLine()); for(int kase=1; kase<=kases; kase++){ String[] in = bf.readLine().trim().split(""[ ]+""); a = Integer.parseInt(in[0]); b = Integer.parseInt(in[1]); long ret = 0; for(int i=a; i<=b; i++) ret+= countRec(i); pw.println(""Case #"" + kase + "": "" + ret); } pw.close(); } public static void main(String[] args) throws IOException { new B().run(); } } " B11201,"import java.io.File; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; /** * User: Sasha * Date: 09.04.12 * Time: 19:13 */ public class Main { private Scanner sc; private PrintWriter wr; private void prepare() throws Exception { sc = new Scanner(new File(""C:\\Projects\\C-small-attempt0.in"")); File file = new File(""C:\\Projects\\out.txt""); wr = new PrintWriter(file); // wr = new PrintWriter(System.out); } private void solve() { int n = sc.nextInt(); for (int i = 0; i < n; ++i) { HashSet set = new HashSet(); wr.print(String.format(""Case #%d: "", (i + 1))); int a, b; a = sc.nextInt(); b = sc.nextInt(); int res = 0; for (int j = a; j < b; ++j) { res += cnt(j, a, b, set); } wr.println(res); } wr.flush(); } private int cnt(int c, int left, int right, HashSet set) { int res = 0; String s = """" + c; for (int i = 0; i < s.length() - 1; ++i) { String t = s.substring(i + 1) + s.substring(0, i + 1); int d = Integer.parseInt(t); if (left <= d && d <= right && c < d && s.length() == ("""" + d).length()) { if (set.contains(s + t)) continue; set.add(s + t); ++res; } } return res; } public static void main(String args[]) throws Exception { Main main = new Main(); main.prepare(); main.solve(); } } " B10724,"package wwu.quals2012; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import lib.tuple.Pair; import lib.tuple.Tuple; import lib.util.StringUtil; public class Crecycled { static final String fileIn = ""/home/wwu/Desktop/C-small-attempt0.in""; // static final String fileIn = ""data/A-large-practice.in""; static final String fileOut = ""/home/wwu/Desktop/out.txt""; public static Map charMap; public static void main(String[] args) throws Exception { BufferedReader r = new BufferedReader(new FileReader(fileIn)); BufferedWriter w = new BufferedWriter(new FileWriter(fileOut)); String line = r.readLine(); int T = Integer.parseInt(line); for (int caseNum = 0; caseNum < T; caseNum++) { int[] testCase = StringUtil.getIntArray(r.readLine()); int A = testCase[0]; int B = testCase[1]; String str = ""Case #"" + (caseNum + 1) + "": "" + solve(A, B); w.write(str + ""\n""); System.out.println(str); } r.close(); w.close(); } private static String solve(int a, int b) { int numRecyled = 0; for (int outerCompare=a; outerCompare<=b; outerCompare++) { numRecyled += getRecycledPairNum(outerCompare, a, b); // for (int innerCompare=a; innerCompare<=b; innerCompare++) { // if (isRecycledPair(outerCompare, innerCompare)) { // numRecyled++; // } // } } return String.valueOf(numRecyled/2); } private static int getRecycledPairNum(int outerCompare, int a, int b) { int retVal = 0; int lenOfOuter = String.valueOf(outerCompare).length(); int nextRecycledNum = (int) Math.pow(10, lenOfOuter-1)*(outerCompare % 10) + outerCompare/10; for (int i=0; i<=lenOfOuter; i++) { if (outerCompare == nextRecycledNum) { continue; } else if (nextRecycledNum >= a && nextRecycledNum <= b) { retVal++; } nextRecycledNum = (int) Math.pow(10, lenOfOuter-1)*(nextRecycledNum % 10) + nextRecycledNum/10; } return retVal; } // private static boolean isRecycledPair(int outerCompare, int innerCompare) { // // 123 -> 312 // int lenOfOuter = String.valueOf(outerCompare).length(); // int nextRecycledNum = (int) Math.pow(10, lenOfOuter-1)*(outerCompare % 10) + outerCompare/10; // for (int i=0; i<=lenOfOuter; i++) { // if (outerCompare == innerCompare) { // continue; // } else if (nextRecycledNum == innerCompare) { // return true; // } // nextRecycledNum = (int) Math.pow(10, lenOfOuter-1)*(nextRecycledNum % 10) + nextRecycledNum/10; // } // return false; // } // } " B12143,"package qualif.problem3; import java.util.Scanner; public abstract class ProblemClass { public int testCaseNb = 0; private Scanner casesScanner; public ProblemClass(Scanner input){ try{ String nextLine = input.nextLine(); testCaseNb = new Integer(nextLine); } finally{ } this.casesScanner = input; } public String[] process(){ String[] outputs = new String[testCaseNb]; int testFound = 0; try{ while ( casesScanner.hasNextLine() ){ String result = processLine( casesScanner.nextLine() ); outputs[testFound] = result; testFound+=1; } }finally{ casesScanner.close(); } System.out.println(""*******************************************************""); if(testFound==testCaseNb){ System.out.println(""**** There were the expected number of lines ****""); } else{ System.out.println(""**** Failure : not the right number of inputs ****""); } System.out.println(""*******************************************************""); return outputs; } protected abstract String processLine(String line); } " B11083,"package fixjava; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.Map.Entry; public abstract class Filter { abstract boolean accept(T item); public static ArrayList list(Iterable collection, Filter filter) { ArrayList filtered = new ArrayList(); for (U item : collection) if (filter.accept(item)) filtered.add(item); return filtered; } public static HashSet set(Set set, Filter filter) { HashSet filtered = new HashSet(); for (U item : set) if (filter.accept(item)) filtered.add(item); return filtered; } public static HashMap mapKeys(Map map, Filter keyFilter) { HashMap filtered = new HashMap(); for (Entry ent : map.entrySet()) if (keyFilter.accept(ent.getKey())) filtered.put(ent.getKey(), ent.getValue()); return filtered; } public static HashMap mapValues(Map map, Filter valueFilter) { HashMap filtered = new HashMap(); for (Entry ent : map.entrySet()) if (valueFilter.accept(ent.getValue())) filtered.put(ent.getKey(), ent.getValue()); return filtered; } } " B11151,"import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; /** * */ /** * @author Anvesh * */ public class C { /** * @param args */ public static void main(String[] args) { try { Scanner sc = new Scanner(System.in); int caseNo = sc.nextInt(); FileWriter fstream = new FileWriter(""C:/Users/Anvesh/Desktop/out.txt""); BufferedWriter out = new BufferedWriter(fstream); for(int i = 1; i <= caseNo; i++) { int a = sc.nextInt(); int b = sc.nextInt(); int recyclableNo = 0; int start; int end; if(a > b) { end = a; start = b; } else { end = b; start = a; } for(int j = start; j <= end; j++) { for(int k = end; k > j; k--) { if(isPermutation(j, k)) { if(isEquivalent(j, k)) { recyclableNo++; } } } } System.out.println(""Case #"" + i + "": "" + recyclableNo); out.write(""Case #"" + i + "": "" + recyclableNo); out.newLine(); } //Close the output stream out.close(); } catch (IOException e) { e.printStackTrace(); } } private static int getNoOfDigits(long num) { int digitCount = 0; while(num > 0) { num /= 10; digitCount++; } return digitCount; } private static boolean isPermutation(int num1, int num2) { boolean result = false; int[] arr = new int[10]; int temp = num2; while (temp > 0) { arr[temp % 10]++; temp /= 10; } temp = num1; while (temp > 0) { arr[temp % 10]--; temp /= 10; } for (int i = 0; i < 10; i++) { if (arr[i] != 0) { result = true; } } return !result; } private static boolean isEquivalent(int num1, int num2) { boolean result = false; int rem; int digitNo = getNoOfDigits(num1); for(int i = 0; i < digitNo; i++) { if(num1 == num2) { result = true; break; } rem = num1 % 10; num1 /= 10; num1 += rem * Math.pow(10, digitNo - 1); } return result; } } " B12595,"import static java.util.Arrays.deepToString; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class Solution { private static void debug(final Object...objs) { System.out.println(deepToString(objs)); } int rotate(int n, int d) { int f = n / d; return (n - f * d) * 10 + f; } class Pair{ Set elems = new HashSet(); Pair(final int first, final int second) { elems.add(first); elems.add(second); } @Override public int hashCode() { return elems.hashCode(); } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof Pair)) return false; final Pair other = (Pair) obj; return elems.equals(other.elems); } } private String solveCase() throws IOException { final int A = nextInt(); final int B = nextInt(); int d = 1; int N = 1; while (d * 10 <= A) { d *= 10; N++; } int res = 0; Set all = new HashSet(); for (int j = A; j <= B; j++) { Set ns = new HashSet(); int x = rotate(j, d); for (int i = 0; i < N; i++) { if (A <= x && x <= B) ns.add(x); x = rotate(x, d); } int[] as = new int[ns.size()]; int i = 0; for (Integer it : ns) { as[i++] = it; } for (int m = 0; m < as.length - 1; m++) { for (int n = m + 1; n < as.length; n++) { all.add(new Pair(as[m], as[n])); } } } return String.valueOf(all.size()); } private void solve() throws IOException { final int T = nextInt(); for (int test = 0; test < T; test++) { final String result = ""Case #"" + (test + 1) + "": "" + solveCase(); pw.println(result); System.out.println(result); } } private BufferedReader br; private PrintWriter pw; private StringTokenizer st; int nextInt() throws IOException { return Integer.parseInt(next()); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public static void main(final String[] args) throws IOException { new Solution().run(); } private void run() throws IOException { br = new BufferedReader(new FileReader(""input.txt"")); pw = new PrintWriter(""output.txt""); solve(); br.close(); pw.flush(); pw.close(); } }" B11985,"import java.util.ArrayList; import java.util.List; import Utils.FileHelper; public class Gcj2012c { private static String getPairCount(String str) { int A = Integer.parseInt( str.split("" "")[0] ); int B = Integer.parseInt( str.split("" "")[1] ); boolean [] used = new boolean [ B - A + 1]; int size = (A +"""").length(); int rst = 0; for( int num = A ; num <= B; ++num){ int curNum = num; int cnt = 0; for(int i = 0; i< size; ++i){ if(curNum > B || curNum < A || used[curNum - A]); else{ used[curNum - A] = true; cnt ++; } int lastD = curNum % 10; curNum /= 10; curNum = (int) (curNum + Math.pow(10, size - 1) * lastD); } rst += cnt * (cnt-1)/2; } return rst +""""; } private static void solve(String inputPath, String filepath) { FileHelper fHelper = new FileHelper(inputPath); String[] inputStr= new String[fHelper.getTotalSize()]; List rstList = new ArrayList(); fHelper.init(inputStr); for (String str : inputStr) { rstList.add(getPairCount(str)); } rstList = format(rstList); FileHelper.writeFile(filepath, rstList); } public static void main(String[] args) { String inputPath = ""C:\\Users\\xiaohfan\\Desktop\\C-small-attempt0.in""; String filepath = ""C:\\Users\\xiaohfan\\Desktop\\output.txt""; Gcj2012c.solve(inputPath, filepath); } public static List format(List rstList) { List outputList = new ArrayList(); for(int i = 0; i < rstList.size();++i ){ outputList.add(""Case #""+ (i+1) +"": ""+rstList.get(i)); } return outputList; } } " B13079,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; public class ProblemC { public static void main(String [] args) { new ProblemC(); } public ProblemC() { try { String [] inputFiles = { ""C-small"" };//,""A-large"" }; BufferedReader in; PrintWriter out; for(int i = 0 ; i < inputFiles.length; i++) { in = new BufferedReader(new FileReader(inputFiles[i])); out = new PrintWriter(new FileWriter(inputFiles[i]+"".out""),true); int numCases = Integer.parseInt(in.readLine()); int min, max; String [] items = null; for(int j = 0 ; j < numCases; j++) { items = in.readLine().split(""\\s+""); min = Integer.parseInt(items[0]); max = Integer.parseInt(items[1]); int total = 0; for(int x = min; x <= max; x++) { for(int y=x+1; y<= max; y++) { if(checkReycled(x,y)) total++; } } out.println(""Case #"" + (j+1) + "": "" + total); } in.close(); out.close(); } } catch(Exception e) { e.printStackTrace(); } } private boolean checkReycled(int x, int y) { if(x == y) return false; else if(x<10 || y<10) return false; else if(x>=1000) return false; String xstr = new String("""" +x); String ystr = new String("""" +y); if(xstr.length() != ystr.length()) return false; if(xstr.length() == 2) { if(xstr.charAt(0) == ystr.charAt(1) && xstr.charAt(1) == ystr.charAt(0)) return true; } else { if(xstr.charAt(0) == ystr.charAt(1) && xstr.charAt(1) == ystr.charAt(2) && xstr.charAt(2) == ystr.charAt(0)) return true; else if(xstr.charAt(0) == ystr.charAt(2) && xstr.charAt(1) == ystr.charAt(0) && xstr.charAt(2) == ystr.charAt(1)) return true; } return false; } } " B11157,"package code.jam.y2012.quali; import java.io.*; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class ProblemC { private static String PATH = ""F:\\dev\\projects\\code-jam-2012\\src\\code\\jam\\y2012\\quali""; File inputFile = new File(PATH, ""C-small-attempt0.in""); File outputFile = new File(PATH, ""C-small-attempt0.out""); BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""""); public static void main(String[] args) throws Exception { new ProblemC().solve(); } void solve() throws Exception { in = new BufferedReader(new FileReader(inputFile)); out = new PrintWriter(outputFile); for (int testCase = 1, testCount = nextInt(); testCase <= testCount; testCase++) { solve(testCase); } out.close(); } void solve(int testCase) throws IOException { final int min = nextInt(); final int max = nextInt(); Set validPatterns = new HashSet(); for (int i = min; i <= max; i++) { String[] patterns = getRecycledPatterns(String.valueOf(i)); for (int j = 0; j < patterns.length - 1; j++) { for (int k = j; k < patterns.length; k++) { if (isValid(Integer.parseInt(patterns[j]), Integer.parseInt(patterns[k]), min, max)) { validPatterns.add(patterns[j] + ""-"" + patterns[k]); } } } } print(""Case #"" + testCase + "": "" + validPatterns.size()); } private static String[] getRecycledPatterns(String pattern) { String[] result = new String[pattern.length()]; for (int i = 0; i < result.length; i++) { result[i] = pattern.substring(i) + pattern.substring(0, i); } return result; } private boolean isValid(int a, int b, int min, int max) { return min <= a && a < b && b <= max && String.valueOf(a).length()==String.valueOf(b).length(); } private void print(String text) { out.println(text); System.out.println(text); } /** * helpers */ String nextToken() throws IOException { while (!st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int nextChar() throws IOException { return in.read(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextLine() throws IOException { st = new StringTokenizer(""""); return in.readLine(); } boolean EOF() throws IOException { while (!st.hasMoreTokens()) { String s = in.readLine(); if (s == null) { return true; } st = new StringTokenizer(s); } return false; } } " B11486,"import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class Qualification_C { private static final boolean DEBUG = false; /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { List input = readFile(args[0]); int testCases = Integer.parseInt(input.get(0)); String outputFilename = args[0].substring(0, args[0].length() - 2) + ""out""; FileOutputStream output = new FileOutputStream(outputFilename); try { for (int i = 1; i <= testCases; i++) { String[] splitted = input.get(i).split("" ""); int min = Integer.parseInt(splitted[0]); int max = Integer.parseInt(splitted[1]); outputResult(output, i, String.valueOf(getNoOfDistinctPair(min, max))); } } finally { if (output != null) { output.close(); } } } public static int getNoOfDistinctPair(int min, int max) { int result = 0; int value1 = min; int value2 = value1 + 1; while (value1 != value2 && value1 <= max) { String value1Str = String.valueOf(value1); value2 = value1 + 1; while (value2 <= max) { String value2Str = String.valueOf(value2); StringBuilder compareValue = new StringBuilder(value2Str); for (int i = 0; i < value2Str.length(); i++) { // debug(""compare: "" + value1Str + "" == "" + compareValue.toString()); if (value1Str.equals(compareValue.toString())) { debug(value1Str + "" == "" + value2Str + "": "" + value1Str + "" = "" + compareValue.toString()); result++; break; } compareValue.append(compareValue.charAt(0)); compareValue.deleteCharAt(0); } value2++; } value1++; } return result; } public static List readFile(String filename) throws IOException { List lines = new ArrayList(); BufferedReader reader = new BufferedReader(new InputStreamReader( new FileInputStream(filename))); try { String data; while ((data = reader.readLine()) != null) { lines.add(data); } } finally { reader.close(); } return lines; } private static void outputResult(FileOutputStream output, int caseNo, String result) throws IOException { output.write(String.format(""Case #%d: %s\r\n"", caseNo, result).getBytes()); } private static void debug(String debug) { if (DEBUG) { System.out.print(debug + ""\r\n""); } } } " B12370,"package qr2012; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.StringTokenizer; public class RecycledNumbers { public static void main(String[] args) throws Exception { String fileName = args[0]; RecycledNumbers obj = new RecycledNumbers(); obj.solve(fileName); } public void solve(String fileName) throws Exception { BufferedReader br = new BufferedReader(new FileReader(fileName)); BufferedWriter bw = new BufferedWriter( new FileWriter(fileName + "".out"")); int T = Integer.parseInt(br.readLine()); for (int i = 0; i < T; i++) { String str = br.readLine(); StringTokenizer token = new StringTokenizer(str, "" ""); int A = Integer.parseInt(token.nextToken()); int B = Integer.parseInt(token.nextToken()); boolean[] check = new boolean[B + 1]; int n = (int) Math.log10(A); int c1 = (int) Math.pow(10, n); int c2 = c1 * 10; int cnt = 0; for (int j = A; j <= B; j++) { if (j >= c2) { c1 = c2; c2 = c1 * 10; n += 1; } if (check[j]) { continue; } else { check[j] = true; int tmp = j; int ccnt = 1; for (int k = 0; k < n; k++) { tmp = (tmp % 10) * c1 + tmp / 10; if (tmp <= B && tmp >= c1 && tmp >= A && !check[tmp]) { ccnt += 1; check[tmp] = true; } } cnt += ccnt * (ccnt - 1) / 2; } } bw.write(""Case #"" + (i + 1) + "": ""); bw.write("""" + cnt); bw.write(""\r\n""); } bw.close(); br.close(); } private int cycle(int x, int digits) { return (x % 10) * 10000 + (x / 10); } } " B10518,"import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Set; import com.google.common.collect.Sets; import com.google.common.io.LineReader; public class RecycledNumbers { public static void main(String[] args) throws NumberFormatException, IOException { LineReader lineReader = new LineReader(new FileReader(args[0])); FileWriter out = new FileWriter(args[0] + ""-out.txt""); int t = Integer.parseInt(lineReader.readLine()); for (int counter = 1; counter <= t; counter++) { String[] nums = lineReader.readLine().split("" ""); int result = compute(Integer.parseInt(nums[0]), Integer.parseInt(nums[1])); out.write(String.format(""Case #%d: %d\n"", counter, result)); } out.close(); } private static int compute(int a, int b) { Set set = Sets.newHashSet(); int count = 0; for (int n = a; n < b; n++) { String nStr = Integer.toString(n); set.clear(); for (int i = 1; i < nStr.length(); i++) { String fst = nStr.substring(i); String snd = nStr.substring(0, i); int m = Integer.parseInt(fst + snd); if (m > n && m <= b && !set.contains(m)) { set.add(m); count++; } } } return count; } } " B12369," import java.io.FileInputStream; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class ProblemCSmall { public static void main(String[] args) { try { System.setIn(new FileInputStream(""C-small-attempt0.in"")); } catch (Exception e) { } Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for (int t = 1; t <= T; t++) { int A = sc.nextInt(), B = sc.nextInt(); int c = 0; int D = 1 + (int)Math.log10(A); int M = (int)Math.pow(10, D - 1); Set set = new TreeSet(); for (int a = A; a < B; a++) { int aa = a; set.clear(); for (int d = 1; d < D; d++) { aa = aa / 10 + M * (aa % 10); if (a < aa && aa <= B && !set.contains(aa)) { c++; set.add(aa); } } } System.out.printf(""Case #%d: %d\n"", t, c); } } } /* 4 1 9 10 40 100 500 1111 2222 */ " B11760,"package be.tim.recycled; import java.io.*; /** * * @author Tim Boeckstaens * @version 1.0 */ public class Recycle { private int N; public void process(String inputFile, String outputFile) { Recycler recycler = new Recycler(); try { BufferedReader reader = new BufferedReader(new FileReader(inputFile)); FileWriter writer = new FileWriter(outputFile); String line; String string; N = Integer.parseInt(reader.readLine()); for (int i = 1; i <= N; i++) { line = reader.readLine(); if (line != null) { string = recycler.process(line); writer.write(""Case #"" + i + "": "" + string); if(i != N){ writer.write(""\n""); } } else { System.out.println(""Error while reading all lines.""); } } reader.close(); writer.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } " B10597,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; /** * * @author cristian */ public class CodeJam { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here StringBuffer sb; Boolean firstLine = true; try { // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(""/tmp/problemB.txt""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; //Read File Line By Line int line = 1; while ((strLine = br.readLine()) != null) { if (firstLine) { firstLine = false; continue; } sb = new StringBuffer(); // Print the content on the console int A = Integer.parseInt(strLine.split("" "")[0]); int B = Integer.parseInt(strLine.split("" "")[1]); int n = A; int m; int recycled = 0; while (n < B) { recycled += moveLast(n, B); n++; } System.out.println(""Case #"" + line + "": "" + recycled); line++; } //Close the input stream in.close(); } catch (Exception e) {//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } private static int moveLast(int n, int B) { int recycled = 0; int tmpN = n; int m; StringBuffer sb; for (int i = 0; i < (n + """").length() - 1; i++) { sb = new StringBuffer(); sb.append((tmpN + """").charAt((tmpN + """").length() - 1)); if ((tmpN + """").length() < (n + """").length()) { sb.append(""0""); } sb.append((tmpN + """").substring(0, (tmpN + """").length() - 1)); m = Integer.parseInt(sb.toString()); //A ≤ n < m ≤ B if ((n < m) && (m <= B)) { recycled++; } tmpN = m; } return recycled; } } " B11086,"package fixjava; import java.util.Collection; import java.util.Comparator; /** * Typed 3-tuple */ public class Tuple3 { private final A field0; private final B field1; private final C field2; public A getField0() { return field0; } public B getField1() { return field1; } public C getField2() { return field2; } public Tuple3(final A field0, final B field1, final C field2) { this.field0 = field0; this.field1 = field1; this.field2 = field2; } /** Convenience method so type params of pair don't have to be specified: just do Tuple3.make(a, b, c) */ public static Tuple3 make(A field0, B field1, C field2) { return new Tuple3(field0, field1, field2); } // --------------------------------------------------------------------------------------------------- private static final boolean objEquals(Object p1, Object p2) { if (p1 == null) return p2 == null; return p1.equals(p2); } @Override public final boolean equals(Object o) { if (!(o instanceof Tuple3)) { return false; } else { final Tuple3 other = (Tuple3) o; return objEquals(getField0(), other.getField0()) && objEquals(getField1(), other.getField1()) && objEquals(getField2(), other.getField2()); } } @Override public int hashCode() { int h0 = getField0() == null ? 0 : getField0().hashCode(); int h1 = getField1() == null ? 0 : getField1().hashCode(); int h2 = getField2() == null ? 0 : getField2().hashCode(); return h0 + 53 * h1 + 97 * h2; } // --------------------------------------------------------------------------------------------------- public static , B, C> Comparator> comparatorOnField0(Collection> tupleCollection) { return new Comparator>() { @Override public int compare(Tuple3 o1, Tuple3 o2) { return o1.getField0().compareTo(o2.getField0()); } }; } public static , B, C> Comparator> comparatorOnField0Rev(Collection> tupleCollection) { return new Comparator>() { @Override public int compare(Tuple3 o1, Tuple3 o2) { return -o1.getField0().compareTo(o2.getField0()); } }; } public static , C> Comparator> comparatorOnField1(Collection> tupleCollection) { return new Comparator>() { @Override public int compare(Tuple3 o1, Tuple3 o2) { return o1.getField1().compareTo(o2.getField1()); } }; } public static , C> Comparator> comparatorOnField1Rev(Collection> tupleCollection) { return new Comparator>() { @Override public int compare(Tuple3 o1, Tuple3 o2) { return -o1.getField1().compareTo(o2.getField1()); } }; } public static > Comparator> comparatorOnField2(Collection> tupleCollection) { return new Comparator>() { @Override public int compare(Tuple3 o1, Tuple3 o2) { return o1.getField2().compareTo(o2.getField2()); } }; } public static > Comparator> comparatorOnField2Rev(Collection> tupleCollection) { return new Comparator>() { @Override public int compare(Tuple3 o1, Tuple3 o2) { return -o1.getField2().compareTo(o2.getField2()); } }; } // --------------------------------------------------------------------------------------------------- @Override public String toString() { return ""("" + getField0() + "", "" + getField1() + "", "" + getField2() + "")""; } } " B10383,"import java.util.Scanner; public class Utils { public static int readIntegerLine(Scanner sc) { String s = readStringLine(sc); return Integer.parseInt(s); } public static String readStringLine(Scanner sc) { return sc.nextLine(); } public static int readInteger(Scanner sc) { return sc.nextInt(); } } " B10349,"import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.StringTokenizer; public class ProblemC { /** * @param args */ public static void main(String[] args) { System.out.println(""Problem A enter input file:""); Scanner scan = new Scanner(System.in); String sFile = scan.nextLine(); File f = new File(sFile); try { BufferedReader r = new BufferedReader(new FileReader(sFile)); String current; int cnum = 0; while((current = r.readLine())!=null) { if(cnum>0) { System.out.println(""Case #""+cnum+"": ""+solve(current)); } cnum ++; } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static int solve(String current) { StringTokenizer tok = new StringTokenizer(current); int a = 0, b = 0, i = 0, s=0; while(tok.hasMoreElements()){ switch(i) { case 0: a = Integer.parseInt((String) tok.nextElement()); break; case 1: b = Integer.parseInt((String) tok.nextElement()); } i++; } for(int n = a; n n; m--) { int t = m; int digits = String.valueOf(t).length(); for(i = 1; i set = new HashSet<>(); String str = number.toString(); for (int i = 1; i < str.length(); i++) { String begin = str.substring(0, i); String end = str.substring(i); Long recycled = new Long(end + begin); if (recycled > number && recycled >= a && recycled <= b && !set.contains(recycled)) { matches++; set.add(recycled); } } return matches; } private static long handleCase(long a, long b) { long totalMatches = 0; for (long i = a; i <= b; i++) { totalMatches = totalMatches + findMatchesForNumber(i, a, b); } return totalMatches; } /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(args[0]); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; FileWriter outFile = new FileWriter(""c:\\data\\q3\\output.txt""); PrintWriter out = new PrintWriter(outFile); long t = new Long(br.readLine()); for (int i = 0; i < t; i++) { strLine = br.readLine(); StringTokenizer token = new StringTokenizer(strLine); long a = new Long(token.nextToken()); long b = new Long(token.nextToken()); // System.out.println(""numbers: "" + a + "" "" + b); long matches = handleCase(a, b); long index = i+ 1; String strToPrint = ""Case #"" + index + "": "" + matches; out.println(strToPrint); System.out.println(strToPrint); } in.close(); out.close(); } } " B12995,"package mgg.utils; import java.util.List; public class ListUtils { public static String pureList(List list) { StringBuilder builder = new StringBuilder(); for (Object elem : list) { builder.append("" "" + elem); } return builder.substring(1).toString(); } } " B13149,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; public class RecycledNumber { public static void main(String[] args) { try { BufferedReader bfrd = new BufferedReader(new FileReader(""E:\\My Work\\TestWorkspace\\RecycledNumbers\\src\\C-small-attempt3.in"")); int n = Integer.parseInt(bfrd.readLine()); String out = """"; for (int i = 0; i < n; i++) { String s = bfrd.readLine(); out += ""Case #"" + (i + 1) + "": "" + solve(s) + ""\n""; } System.out.println(out); bfrd.close(); } catch (IOException e) { e.printStackTrace(); } } public static String solve(String s) { int iMinNumber = Integer.parseInt(s.split("" "")[0]); int iMaxNumber = Integer.parseInt(s.split("" "")[1]); int iLength; Integer iNoRecycledNo = 1; Integer iNoOfRecycledPairs = 0; ArrayList alInputNos = new ArrayList(); for (int i = iMinNumber; i <= iMaxNumber; i++) { alInputNos.add(i); } for (int number : alInputNos) { StringBuffer sNumber = new StringBuffer(Integer.toString(number)); iLength = sNumber.length(); ArrayList alRecycledPairs = new ArrayList(); for (int i = 1; i < sNumber.length(); i++) { StringBuffer recNum = new StringBuffer(); recNum.append(sNumber.substring(i, sNumber.length())); recNum.append(sNumber.substring(0, i)); int irecNumber = Integer.parseInt(recNum.toString()); String sTempNum = Integer.toString(irecNumber); if (iLength == sTempNum.length()) { if ((!(alRecycledPairs.contains(irecNumber))) && irecNumber <= iMaxNumber && irecNumber >= iMinNumber && !(irecNumber == number) && (alInputNos.contains(irecNumber))) { alRecycledPairs.add(irecNumber); iNoOfRecycledPairs = iNoRecycledNo / 2; iNoRecycledNo++; } } } } return Integer.toString(iNoOfRecycledPairs); } } " B12709,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; public class C { /** * @param args */ public static String rest(ArrayList list) { String n = list.get(0); list.remove(0); return n; }; public static void main(String[] args) { // TODO Auto-generated method stub String line; ArrayList liste = new ArrayList(); BufferedReader buffer = null; try { buffer = new BufferedReader(new FileReader(new File(args[0]))); for (int i = 0; (line = buffer.readLine()) != null; i++) { liste.add(line); } } catch (IOException e) { System.out.println(""IO-Fehler!""); } int anzahl = Integer.parseInt(rest(liste)); // fuer jeden Fall methode aufrufen for (int i = 0; i < anzahl; i++) { methode(i + 1, liste); } } // spezifische code fŸr alle aufgaben public static void methode(int nummer, ArrayList liste) { // buffer und input machen // input ist ein stringarray mit meiner ersten Zeile // String[] input = rest(liste); String[] input = rest(liste).split("" ""); ArrayList arraylist = new ArrayList(); for (int i = 0; i < input.length; i++) { int n = Integer.parseInt(input[i]); arraylist.add(n); } int a = arraylist.get(0); int b = arraylist.get(1); int sum = 0; for (int i = a; i < b; i++) { StringBuilder builder = new StringBuilder(Integer.toString(i)); ArrayList ergebnisse = new ArrayList(); for (int k = 1; k < builder.length(); k++) { if ((Integer.parseInt(umdudeln(builder, k).toString()) > i) && (Integer.parseInt(umdudeln(builder, k).toString()) <= b)) { if (!(ergebnisse.contains(Integer.parseInt(umdudeln(builder,k).toString())))){ sum=sum +1; }; ergebnisse.add(Integer.parseInt(umdudeln(builder,k).toString())); // System.out.println(umdudeln(builder, k).toString()); } } ; } System.out.println(""Case #"" + nummer + "": "" + sum); } public static StringBuilder umdudeln(StringBuilder builder, int i) { if (builder.length() == 1) { return builder; } String eins = builder.substring(0, builder.length() - i); String zwei = builder.substring(builder.length() - i); StringBuilder newbuilder = new StringBuilder(zwei.concat(eins)); // System.out.println("" "" + builder + "" "" + eins + "" "" + zwei + "" "" + newbuilder); return newbuilder; } } " B10256,"package com.numbers.recycle.orchestrator; import java.util.ArrayList; import java.util.List; import com.numbers.recycle.algo.Recycler; import com.numbers.recycle.io.FileOutputWriter; import com.numbers.recycle.io.FileParser; public class NumberRecycler { private FileParser parser = new FileParser(); private Recycler recycler = new Recycler(); private FileOutputWriter writer = new FileOutputWriter(); public void solveAndWriteToOutputFile(String filePath){ List fileContents = parser.readFile(filePath); List outputContents = new ArrayList(); int size = Integer.valueOf(fileContents.get(0)); int counter = 1; while(counter <= size){ outputContents.add(""Case #""+ counter +"": ""+recycler.getRecycledNumberCount(fileContents.get(counter++).split("" ""))); } writer.writeToFile(outputContents); } } " B10332,"import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { public static int f(int x, int min, int max) { String s = Integer.toString(x); String s2 = null; Set set = new HashSet(); for (int i = 1; i < s.length(); i++) { s2 = s.substring(i) + s.substring(0, i); if (Integer.valueOf(s2) > x && Integer.valueOf(s2) <= max && Integer.toString(Integer.valueOf(s2)).length() == s.length()) { set.add(Integer.valueOf(s2)); } } return set.size(); } public static void main(String[] args) throws Exception { System.setOut(new PrintStream(""zz"")); Scanner s = new Scanner(System.in); int T = s.nextInt(); for (int t = 1; t <= T; t++) { int A = s.nextInt(); int B = s.nextInt(); int n = 0; for (int x = A; x < B; x++) { n += f(x, A, B); } System.out.println(""Case #"" + t + "": "" + n); } } } " B10388,"import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * Created by IntelliJ IDEA. * User: nickg * Date: 4/13/12 * Time: 9:57 PM * To change this template use File | Settings | File Templates. */ public class CodeJamThree { public static int numNumbers(int a, int b){ int digits = (int) Math.log10(b); digits++; Set seen = new HashSet(); int total = 0; for(int x = a; x < b; x++){ int pow = 10; seen.clear(); for(int y = 1; y < digits; y++){ int moved = move(x, pow); pow*= 10; if(moved <= b && moved > x) seen.add(moved); } total+= seen.size(); } return total; } public static int move(int src, int pow){ int smallPart = src / pow; int bigPart = src % pow; int factor = (int) Math.log10(smallPart) + 1; pow = (int) Math.pow(10, factor); return bigPart * pow + smallPart; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int numTrials = scanner.nextInt(); for(int i = 0; i < numTrials; i++){ int i1 = numNumbers(scanner.nextInt(), scanner.nextInt()); System.out.println(""Case #"" + (i+1) + "": "" + i1); } } } " B10513,"import java.util.*; import java.io.*; public class C { public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(System.in); System.setOut(new PrintStream(new File(""C.out""))); int T = sc.nextInt(); for(int ca = 1; ca <= T; ca++) { int A = sc.nextInt(); int B = sc.nextInt(); int ans = 0; Set set = new TreeSet(); for(int n=A; n hs = new HashSet(); int min = sc.nextInt(); int max = sc.nextInt(); for (int j = min; j <= max; j++) { String s = j+""""; for(int k =1; kj && compI<=max){ hs.add(j+""""+compI); } } } out.print(""Case #""+(i+1)+"": ""); out.println(hs.size()); System.out.println(hs.size()); } out.flush(); out.close(); } } " B12339,"package test; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; public class testapp { /** * @param args */ public static void main(String[] args) { StringBuilder contents = new StringBuilder(); int totalCase=0; int aVar[]=null,bVar[]=null; int loop=-1; try { String aFile=""c:\\testapp.txt""; BufferedReader input = new BufferedReader(new FileReader(aFile)); try { String line = null; while (( line = input.readLine()) != null){ if(loop==-1) { System.out.println(line.trim()); totalCase =Integer.parseInt(line); aVar =new int[totalCase]; bVar =new int[totalCase]; loop++; continue; } String[] result = line.split(""\\s""); aVar[loop]=Integer.parseInt(result[0]); bVar[loop]=Integer.parseInt(result[1]); loop++; } } finally { input.close(); } } catch (IOException ex){ ex.printStackTrace(); } for(int caseid=0;caseid matchlist=new ArrayList(); while(num<=b) { checkpairs(num,a,b,matchlist); num++; } System.out.println(""Case #""+(caseid+1)+"": ""+matchlist.size()); } } public static int checkpairs(int num,int a, int b,ArrayList matchlist) { int count=0; int rnd=1; int m; double div; int size=String.valueOf(num).trim().length(); while(rnd=a && m<=b && m!=num ) { if(!(matchlist.contains(num+""-""+m)|| matchlist.contains(m+""-""+num))) matchlist.add(num+""-""+m); } rnd++; } return count; } } " B11796,"import java.util.*; import java.io.*; import java.text.*; public class Q { private static long solve(int from, int to) { int[] flag = new int[2000001]; long res = 0; int t=from/10, b = 1; while (t>0) { b*=10;t/=10; } for (int i = from; i < to; ++i) { t = i; do { t = (t /10) + (t%10 * b); if (t > i && t<= to && flag[t] != i + 1) { flag[t] = i + 1; ++res; } } while (t != i); } return res; } public static void main(String[] args) throws Exception { Scanner in = new Scanner(new File(""input.txt"")); PrintStream out = new PrintStream(""output.txt""); int num = in.nextInt(); in.nextLine(); for (int i=0;i 0) p = i; int x = n; int min = n; for(int i = 0; i <= p; i++){ x = ((x%pow[p]) * 10) + x/pow[p]; if(x/pow[p] > 0) min = Math.min(min, x); } return min; } public static int getRoot(int n, int low){ int p = -1; for(int i = 0; i <= 6; i++) if(n/pow[i] > 0) p = i; int x = n; int min = n; for(int i = 0; i <= p; i++){ x = ((x%pow[p]) * 10) + x/pow[p]; if(x/pow[p] > 0 && x >= low) min = Math.min(min, x); } return min; } public static void fill(int n, int m){ f = new long[2000001]; for(int i = n; i <= m; i++) f[getRoot(i, n)]++; } public static void fill(){ f = new long[2000001]; for(int i = 0; i <= CAP; i++) f[getRoot(i)]++; } } " B10812,"import java.io.BufferedReader; import java.io.FileReader; import java.util.Arrays; import java.util.TreeSet; public class Main { public static void main(String[] args) throws Throwable { long init = System.currentTimeMillis(); int MAX = 2000001; //int MAX = 201; int arr[][] = new int[MAX][]; { for (int i = 1; i < MAX; i++) { TreeSet set = new TreeSet(); set.add(i); String num = Integer.toString(i); for (int j = 1; j < num.length(); j++) { String newNum = num.substring(j) + num.substring(0, j); if (newNum.charAt(0) != '0') { int n = Integer.parseInt(newNum); if (n > i && !set.contains(n)) { set.add(n); } } } set.remove(i); arr[i] = new int[set.size()]; { int j = 0; for (Integer n : set) arr[i][j++] = n; } } } long end = System.currentTimeMillis(); BufferedReader in = new BufferedReader(new FileReader(""C-small-attempt0.in"")); for (int i = 0, n = Integer.parseInt(in.readLine().trim()); i < n; i++) { String s[] = in.readLine().trim().split("" +""); int a = Integer.parseInt(s[0]), b = Integer.parseInt(s[1]); int c = 0; for (int j=a; j<=b; j++) { for (int k=0, d; k= value || judge2 >= value || judge3 >= value); if(judge1 >=0 && judge2 >=0 && judge3 >=0) { return judge1 >= value || judge2 >= value || judge3 >= value; } return false; } } /* * e.g. If score is 13,14,15, 15 - avg = 15/3 + (15%3==0)= 5 (3,5,5), * (4,4,5) (4,5,5) (5,5,5) (4,6,5) If score is 22,23,24 22 - avg = 22/3 * +(22%3==0) = 8 (6,8,8), (7,7,8) (7,8,8) (8,8,8), (7,8,9) */ TripletScore possibleValues[] = new TripletScore[6]; public void generateTripletFromScore(int score) { int mean = score / 3 + (score % 3 == 0 ? 0 : 1); iMean = mean; for(int i=0;i<6;i++) { possibleValues[i] = new TripletScore(); } // Non Suprizing possibleValues[0].setValue(mean - 1, mean - 1, mean); possibleValues[1].setValue(mean - 1, mean, mean); possibleValues[2].setValue(mean, mean, mean); // Suprizing possibleValues[3].setValue(mean - 2, mean, mean); possibleValues[4].setValue(mean - 1, mean + 1, mean); possibleValues[5].setValue(mean - 1, mean - 1, mean + 1); } public void isScore(int score) { // check if any combination yeilds a result that would be greater than // the better score // We first check if a non-suprizing one works and only then use up a // suprizing! for (int i = 0; i < 3; i++) { if (possibleValues[i].sum() == score) { if (possibleValues[i].containsGreater(iBestScore)) { iSetCount++; return; } } } if (iSuprize != 0) { for (int i = 3; i < 6; i++) { if (possibleValues[i].sum() == score) { if (possibleValues[i].containsGreater(iBestScore)) { iSetCount++; iSuprize--; return; } } } } } public static void main(String[] args) { InputReader reader = new InputReader(""c://input.in""); reader.readNextLine(); // read the line number off - we don't need it String lineRead = null; int i = 1; while ((lineRead = reader.readNextLine()) != null) { DanceScore score = new DanceScore(); System.out.print(""Case #"" + i + "": ""); i++; String values[] = lineRead.split("" ""); score.iSuprize = Integer.parseInt(values[1]); score.iBestScore = Integer.parseInt(values[2]); for (int LoopCount = 3; LoopCount <= Integer.parseInt(values[0])+2; LoopCount++) { score.generateTripletFromScore(Integer .parseInt(values[LoopCount])); score.isScore(Integer .parseInt(values[LoopCount])); } System.out.println(score.iSetCount); } } } " B11530,"package c; import java.io.*; /** * Google Code Jam C * @author hang * */ public class Main { public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String n_str = br.readLine(); int n_int = Integer.parseInt(n_str); int min, max; for(int i = 1;i<=n_int;i++) { String []s = br.readLine().split(""\\s""); int length = s[0].length(); min = Integer.parseInt(s[0]); max = Integer.parseInt(s[1]); if(max<10) { System.out.println(""Case #"" + i + "": "" + 0); continue; } int number = 0; int multiple_base = 1; for(int j = 1;jk&&new_number<=max) number++; multiple_decrease/=10; } } System.out.println(""Case #"" + i + "": "" + number); } } } " B10791," import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.io.Reader; public class Processor { public void process(TestCaseFactory factory, String filenameIn, String filenameOut) throws IOException, MalformedInputFileException { System.out.println(""Started!""); final Reader in = new FileReader(filenameIn); final BufferedReader br = new BufferedReader(in); final PrintWriter out = new PrintWriter(new File(filenameOut)); final String str1 = br.readLine(); final int ncases = Integer.parseInt(str1); for (int i = 0; i < ncases; i++) { final TestCase item = factory.getInstance(i); item.readInput(br); item.solve(); item.writeOutput(out); } in.close(); out.close(); System.out.println(""Finished!""); } }" B12962,"import java.util.*; import java.io.*; public class Solution { public void doMain() throws Exception { BufferedReader in = new BufferedReader(new FileReader(""input.txt"")); PrintWriter pw = new PrintWriter(new FileWriter(""output.txt"")); int CaseNumber = Integer.parseInt(in.readLine()); for (int cas=1; cas <= CaseNumber; cas++) { int nbr = 0 ; String[] str = in.readLine().split("" ""); int A = Integer.parseInt(str[0]); int B = Integer.parseInt(str[1]); if(A < 10) { pw.println(""Case #""+cas+"": ""+nbr); } else if(A==B){ pw.println(""Case #""+cas+"": ""+nbr); } else{ ArrayList n = new ArrayList(); for(int i=A; i<=B; i++){ String st = Integer.toString(i); int l = st.length(); for(int j=l-1; j>0 ; j--){ String s = st; s = s.substring(j) + s; s = s.substring(0,l); if(Integer.parseInt(s) >A && Integer.parseInt(s) inputLines; private final String filename; private int testCases; private int index = 0; public CodeJamBase(String filename) { this.filename = (filename != """") ? filename : ""sample""; try { inputLines = Files.readAllLines(Paths.get(""data/"" + this.filename + "".in""), Charset.defaultCharset()); } catch (IOException e) { throw new RuntimeException(""Failed to read file: '"" + this.filename + ""'""); } setup(); } protected void setup() { setTestCases(nextInt()); } protected abstract String solution(); public void run() { long startTime = System.currentTimeMillis(); List outputLines = new ArrayList<>(); for (int i = 0; i < testCases; i++) { String outputLine = ""Case #"" + (i + 1) + "": "" + solution(); outputLines.add(outputLine); System.out.println(outputLine); } try { Files.write(Paths.get(""data/"" + filename + "".out""), outputLines, Charset.defaultCharset()); } catch (IOException e) { throw new RuntimeException(""Failed to write file: '"" + filename + ""'""); } System.out.println(); System.err.println(""Total run time: "" + ((System.currentTimeMillis() - startTime) / 1000d) + ""s""); } protected final String nextString() { return inputLines.get(index++); } protected final int nextInt() { return Integer.parseInt(nextString()); } protected final String[] nextStringArray() { return inputLines.get(index++).split("" ""); } protected final int[] nextIntArray() { String[] items = nextStringArray(); int[] result = new int[items.length]; for (int i = 0; i < items.length; i++) { result[i] = Integer.parseInt(items[i]); } return result; } public final void setTestCases(int testCases) { this.testCases = testCases; } } " B10042,"package c; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); sc.nextLine(); int nbr = 1; while (t-- > 0) { int a = sc.nextInt(); int b = sc.nextInt(); int score = 0; Set set = new HashSet(); while (a < b) { if (!set.contains(a)){ String s = a+""""; Set temp = new HashSet(); for (int i = 0; i < s.length(); i++) { if (s.charAt(0) != '0'){ int asdf = Integer.parseInt(s); if (a <= asdf && asdf <= b){ temp.add(asdf); } } s = s.substring(1, s.length()) + s.charAt(0); } set.addAll(temp); int n = temp.size(); while (n > 1){ score += --n; } } a++; } System.out.printf(""Case #%d: %d\n"", nbr++, score); } } } " B11761,"package be.tim.recycled; import java.util.Date; /** * * @author Tim Boeckstaens * @version 1.0 */ public class Main { public static void main(String[] args) { //Date now = new Date(); new Recycle().process(""sampleInput.txt"", ""sampleOutput.txt""); //Date paste = new Date(); //paste. //System.out.println(""Time passed: "" ); } } " B12665," /** * * * @Author :Yasith Maduranga(Merlin) * @version :1.0 * @Date :2012/4/14 * @Copyright GSharp Lab, All Rights Reserved.... */ import java.io.*; import java.util.*; class recyclednumbers { public static void main(String args[]){ try{ BufferedReader br = new BufferedReader(new FileReader(""C-small-attempt0.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""C-small-attempt0.out""))); int noOfCases = Integer.parseInt(br.readLine()); for(int i=0;i myArray=new ArrayList(); myArray.add(a); for(long j=a;j 0; log--) { int recycled = 0; int dec = (int) Math.pow(10, log); int rdec = (int) Math.pow(10, caseLog - (log - 1)); recycled += (i % dec) * rdec; recycled += i / dec; if (recycled > i && recycled <= B) { rval++; } } return rval; } } " B11603,"package recyclednumbers; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; public class Helper { public static void main(String[] str) { System.out.println(rotateDigits(345, 2, true)); } public static int rotateDigits(int number, int noOfDigitesToBeMoved, boolean toLeft){ String str = Integer.toString(number,1); char[] chArr = str.toCharArray(); Queue numQueue = new ArrayBlockingQueue(chArr.length); for(int i = chArr.length-1; i >= 0; i--){ numQueue.add(chArr[i]); } Queue polledItems = new ArrayBlockingQueue(noOfDigitesToBeMoved); for(int i = 0; i < noOfDigitesToBeMoved; i++){ char item = numQueue.poll(); polledItems.add(item); } for(char ch : polledItems){ char item = polledItems.poll(); numQueue.add(item); } StringBuffer sb = new StringBuffer(); for(int i = numQueue.size()-1; i >= 0 ; i--){ sb.append(numQueue.toArray()[i]); } return Integer.parseInt(sb.toString()); } } " B12675,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.StringTokenizer; public class recycle { public static void main(String[] args) { int lines; String input; StringTokenizer strk; int start=1111; int end=2222; int count; try { BufferedReader inputStream = new BufferedReader(new FileReader(""C-large.in"")); BufferedWriter writer = new BufferedWriter(new FileWriter(""output.txt"")); lines = Integer.parseInt(inputStream.readLine()); for(int line=0; line< lines; line++){ count=0; input = inputStream.readLine(); strk = new StringTokenizer(input,"" ""); start = Integer.parseInt(strk.nextToken()); end = Integer.parseInt(strk.nextToken()); for(int j=start; j<=end;j++){ for(int k=j; k<=end;k++){ if(isRecycled(j+"""",k+"""")){ count++; } } } if(line!=lines-1) writer.write(""Case #"" + (line+1) + "": "" + count+""\r\n""); else writer.write(""Case #"" + (line+1) + "": "" + count); } writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } static boolean isRecycled(String x, String y){ int len = x.length(); if(x.equals(y)){ return false; } for(int i=0; i j && Integer.parseInt(test) <= b && !test.equals(temp)){ temp = test; out[i]++; } } } } for (int i = 0; i < t; i++) { System.out.println(""Case #"" + (i + 1) + "": "" + out[i]); } } } " B12056,"import java.util.Arrays; public class HSC { public int a; public int b; public HSC(int a, int b) { this.a = a; this.b = b; } @Override public int hashCode() { return (int) Math.random(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null) return false; if (getClass() != o.getClass()) return false; HSC other = (HSC) o; return other.a == a && other.b == b; } } " B12582,"package com.google.codejam.practice2012.qualificationRound; import com.google.codejam.abs.Problem; import com.google.codejam.utils.files.ManejoArchivos; import java.io.FileNotFoundException; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class RecycledNumbers extends Problem { public RecycledNumbers(String name) throws FileNotFoundException, IOException { super(name); } public static void main(String[] args) throws FileNotFoundException, IOException { //new RecycledNumbers(""RecycledNumbers-Sample""); new RecycledNumbers(""RecycledNumbers-Small""); //new RecycledNumbers(""RecycledNumbers-Large""); } public String execCase() throws IOException { int[] rango = ManejoArchivos.getInts(); int numRecycled = 0; for(int number=rango[0];number= 1) { input = args[0]; if (args.length >= 2) { output = args[1]; } } new RecycledNumbers(input, output); } public RecycledNumbers(String inputString, String outputString) { init(); File input = new File(inputString); File output = new File(outputString); if (!input.isFile()) { System.err.println(""input file not found""); System.exit(1); } if (output.exists()) { output.delete(); } try { String[] cases = readInput(input); String[] results = executeCases(cases); writeOutput(output, results); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } private String[] readInput(File file) throws Exception { Scanner scanner = new Scanner(file); int lines = scanner.nextInt(); scanner.nextLine(); String[] cases = new String[lines]; for (int i = 0; i < lines; i++) { cases[i] = scanner.nextLine().trim(); if (cases[i] == null) { throw new Exception(""not enough input lines""); } } scanner.close(); return cases; } private String[] executeCases(String[] cases) { String[] output = new String[cases.length]; for (int i = 0; i < cases.length; i++) { output[i] = executeCase(i + 1, cases[i]); } return output; } private String parseOutput(int caseID, String answer) { String output = ""Case #"" + caseID + "": "" + answer; System.out.println(output); return output; } private void writeOutput(File output, String[] results) throws Exception { PrintWriter pw = new PrintWriter(new FileWriter(output)); for (int i = 0; i < results.length; i++) { pw.println(results[i]); } pw.close(); } private void init() { } private String executeCase(int caseID, String input) { String[] split = input.split("" ""); int start = Integer.parseInt(split[0]); int end = Integer.parseInt(split[1]); int answer = 0; char[] chars; for (int n = start; n < end; n++) { chars = getNumberChars(n); if (chars == null) { continue; } answer += recycle(n, chars, end); } return parseOutput(caseID, """" + answer); } /** * Returns null if the number can't be recycled */ private char[] getNumberChars(int n) { if (n < 10) { return null; } char[] chars = Integer.toString(n).toCharArray(); int validChars = 0; for (char c : chars) { if (c != '0') { validChars++; } } if (validChars < 2) { return null; } return chars; } private int recycle(int n, char[] chars, int end) { char[] recycle = new char[chars.length]; Set found = new HashSet(); String str; int answer; int recycleTimes = 0; for (int i = 1; i < chars.length; i++) { System.arraycopy(chars, i, recycle, 0, chars.length - i); System.arraycopy(chars, 0, recycle, chars.length - i, i); str = new String(recycle); answer = Integer.parseInt(str); if (answer > n && answer <= end) { if (found.add(str)) { recycleTimes++; } } } return recycleTimes; } } " B10288,"import java.io.*; import java.util.*; public class Recycled { public static class Pair { private int a; private int b; public Pair(int a, int b) { this.a = a; this.b = b; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; if (a != pair.a) return false; if (b != pair.b) return false; return true; } @Override public int hashCode() { int result = a; result = 31 * result + b; return result; } public String toString() { return String.format(""[%d, %d]"", a, b); } } public static void main(String[] args) { try { BufferedReader in = new BufferedReader(new FileReader(""C-small-attempt0.in"")); PrintWriter out = new PrintWriter(new FileWriter(""C-small-attempt0.out"")); int cases = Integer.valueOf(in.readLine().trim()); for (int i =0; i < cases; i++) { StringTokenizer st = new StringTokenizer(in.readLine().trim()); int a = Integer.valueOf(st.nextToken().trim()); int b = Integer.valueOf(st.nextToken().trim()); int pairs = solve(a, b); out.println(String.format(""Case #%d: %d"", i+1, pairs)); } in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } public static int solve(int a, int b) { Set pairs = new HashSet(); for (int i = a; i < b; i++) { String s = String.valueOf(i); for (int j = 1; j < s.length(); j++) { int recycled = Integer.valueOf(s.substring(j)+s.substring(0,j)); if (recycled > i && recycled <= b) { pairs.add(new Pair(i, recycled)); } } } return pairs.size(); } } " B12759,"package com.google.util; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Scanner; public class FileUtil { public static Scanner openFile(String path) { File file = new File(path); Scanner scanner; try { scanner = new Scanner(file); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } return scanner; } public static boolean writeFile(StringBuilder sb, String filetype) { File resultFile = new File(""E:\\Google_Jam\\"" + filetype); try { resultFile.createNewFile(); FileOutputStream os = new FileOutputStream(resultFile); os.write(sb.toString().getBytes()); os.flush(); os.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } return true; } } " B12873,"package br.com.luan; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; public class C { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = br.readLine(); int N = Integer.valueOf(line); // Process which number from stdin for (int i = 0; i < N; i++) { StringBuilder sb = new StringBuilder(line.length()+11); sb.append(""Case #""); sb.append(i+1); sb.append("": ""); line = br.readLine(); String[] split = line.split("" ""); Integer a = Integer.parseInt(split[0]); Integer b = Integer.parseInt(split[1]); int result = processAB(a, b); sb.append(result); sb.append('\n'); System.out.print(sb.toString()); } } private static int processAB(Integer a, Integer b) { return method2(a,b); } @SuppressWarnings(""unused"") private static int method1(Integer a, Integer b) { // Trying the simple approach: to substrings and look up. This might be // enough to pass the small set, but not the big one int result = 0; String aString = a.toString(); String bString = b.toString(); int bDiffA = b.intValue() - a.intValue() +1; Map> occurences = new HashMap>(bDiffA); for (int i = 0; i < bDiffA; i++) { occurences.put(String.valueOf(a.intValue()+i), new HashMap()); } for(String key : occurences.keySet()){ result += macthOccurences(key, occurences, a, b, aString, bString); } return result; } private static int macthOccurences(String key, Map> occurences, Integer a, Integer b, String aString, String bString) { int result = 0; for(int i = key.length(); --i > 0;){ String toFront = key.substring(i, key.length()); String toBack = key.substring(0, i); String full = toFront + toBack; Map secMap = occurences.get(full); if(secMap != null && !key.equals(full)){ Boolean boolean1 = secMap.get(key); if (boolean1 == null){ result=+1; secMap.put(key, Boolean.TRUE); Map secMap2 = occurences.get(key); if(secMap2 != null){ secMap2.put(full, Boolean.TRUE); } } } } return result; } private static int method2(Integer a, Integer b) { String aString = a.toString(); String bString = b.toString(); int bDiffA = b.intValue() - a.intValue() + 1; Map occurences = new HashMap(bDiffA); Map matches = new HashMap(bDiffA); for (int i = 0; i < bDiffA; i++) { occurences.put(String.valueOf(a.intValue()+i), Boolean.FALSE); } for(String key : occurences.keySet()){ macthOccurences2(key, occurences, matches, a, b, aString, bString); } return matches.size(); } private static void macthOccurences2(String key, Map occurences, Map matches, Integer a, Integer b, String aString, String bString) { int kInt = Integer.valueOf(key); for (int i = key.length(); --i > 0;) { String toFront = key.substring(i, key.length()); String toBack = key.substring(0, i); String full = toFront + toBack; Boolean boo = occurences.get(full); if (boo != null && !key.equals(full)) { String first; String second; if (full.charAt(0) != '0') { int fInt = Integer.valueOf(full); if (kInt > fInt) { first = String.valueOf(fInt); second = String.valueOf(kInt); } else { first = String.valueOf(kInt); second = String.valueOf(fInt); } matches.put(first + "" "" + second, Boolean.FALSE); } } } } } " B13016,"import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) throws IOException{ Scanner scanner = new Scanner(new File(""input.txt"")); int numCases = scanner.nextInt(); PrintWriter pw = new PrintWriter(new File(""output3.txt"")); for(int i=1; i <= numCases; i++){ long a = scanner.nextLong(); long b = scanner.nextLong(); int result = 0; // Computer number of digits long digits = computeNumOfDigits(a); // Iterate over all numbers for(long n=a; n <=b; n++){ long m = n; HashSet generateNumbers = new HashSet<>(); for(long j = 1; j < digits; j++){ m = rotateRightMostDigit(m, digits); generateNumbers.add(m); } // Iterate over all numbers generated by each number for(Long l:generateNumbers){ if(computeNumOfDigits(l)==digits && l>n && l<=b){ result++; } } } //System.out.println(""Case #"" + i + "": "" + result); pw.println(""Case #"" + i + "": "" + result); pw.flush(); } } private static long rotateRightMostDigit(long m, long digits) { long d = m%10; long rightPart = m/10; long leftPart = (int) Math.pow(10.0, digits -1); long result = (leftPart * d) + rightPart; return result; } private static long computeNumOfDigits(long inputNum) { if(inputNum == 0){ return 1; } long digits = 0; while(inputNum!=0){ inputNum = inputNum/10; digits++; } return digits; } } " B12896,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Hashtable; public class Recycled_Numbers { public static void main(String[] args) throws IOException { BufferedReader reader=new BufferedReader(new InputStreamReader(System.in)); String x=reader.readLine(); long cases=Long.parseLong(x); Hashtable hash=new Hashtable(); String input=""""; long a=0; String result=""""; long b=0; long i=a; String temp=""""; String ctemp=""""; long counter=0; String []array; for(int j=0;j matches = new HashMap(); for(int j = n; j < m; j++) { for(int k = m; k > j; k--) { //now, shift digits from back of j and compare to k String shifter = String.valueOf(j); for(int shift = 1; shift < length; shift ++) { String front = shifter.substring(0,shift); String back = shifter.substring(shift, shifter.length()); //no leading zeroes after shift if(!back.startsWith(""0"")) { int shiftedInt = Integer.parseInt(back + front); //match! if(shiftedInt == k && (!matches.containsKey(shiftedInt) || matches.get(shiftedInt) != j) ) { answer++; matches.put(shiftedInt, j); } } } } } out.write(""Case #"" + (i + 1) + "": "" + answer + ""\n""); System.out.println(answer); } out.close(); } } " B11297,"import java.io.*; import java.util.StringTokenizer; public class CodeJam1 { static BufferedReader br; static PrintWriter pw; static int a,b,count; public static void main(String[] args)throws Exception{ br=new BufferedReader (new FileReader (""in.txt"")); pw=new PrintWriter (new FileWriter(""out.txt"")); int n=Integer.parseInt( br.readLine() ); for (int i=1;i<=n;i++){ input(); work(); pw.printf(""Case #%d: %d%n"",i,count); } pw.close(); } public static void input()throws Exception{ StringTokenizer data=new StringTokenizer(br.readLine()); a=Integer.parseInt( data.nextToken() ); b=Integer.parseInt( data.nextToken() ); count=0; } public static void work(){ for (int i=a;i<=b;i++){ StringBuffer sbuf=new StringBuffer(String.valueOf(i)); int create; do{ sbuf.append(sbuf.charAt(0)); sbuf.deleteCharAt(0); create=Integer.parseInt( sbuf.toString() ); if (create>i & create<=b) count++; }while(create!=i); } } }" B10708,"import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.Scanner; public class RecycledNumbers { public static long shift(long a, byte n){ return ((a % (long)Math.pow(10, n-1)) * 10 + (a / (long)Math.pow(10, n-1))); } public static byte numberOfDigits(long a){ byte n = 0; while (a > 0){ n++; a /= 10; } return n; } public static void main(String[] args){ File in = new File(args[0]); File out = new File(""b.out""); FileOutputStream w = null; Scanner s = null; try{ w = new FileOutputStream(out); s = new Scanner(in); } catch (FileNotFoundException e) {} int n = s.nextInt(); for (int i = 1; i <= n; i++){ long a = s.nextLong(); long b = s.nextLong(); byte an = numberOfDigits(a); long count = 0; for(long j = a; j<=b; j++){ List l = new LinkedList(); long num = j; for (byte k = 1; k < an; k++){ num = shift(num, an); if ((num > j) && (num <= b) && !l.contains(num)){ //System.out.println(j+"", ""+num); l.add(num); count++; } } } try { w.write((""Case #""+ i +"": ""+count+""\r\n"").getBytes()); } catch (IOException e) { } } try { w.close(); s.close(); } catch (IOException e) {} } } " B11467,"package qualification; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import common.FileTranslatorBasis; public class C { final static int[] digitNum = { 9, 99, 999, 9999, 99999, 999999, 9999999 }; int low; int high; int pow = 1; public C(String low, String high) { for (int i = 0; i < low.length() - 1; i++) { pow = 10 * pow; } this.low = Integer.parseInt(low); this.high = Integer.parseInt(high); } long count; int[] map = new int[2000001]; public void initMap() { int[] tmp = { 1, 11, 111, 1111, 11111, 111111, 1111111, 2, 22, 222, 2222, 22222, 222222, 3, 33, 333, 3333, 33333, 333333, 4, 44, 444, 4444, 44444, 444444, 5, 55, 555, 5555, 55555, 555555, 6, 66, 666, 6666, 66666, 666666, 7, 77, 777, 7777, 77777, 777777, 8, 88, 888, 8888, 88888, 888888, 9, 99, 999, 9999, 99999, 999999, }; for (int i : tmp) { map[i] = -1; } } /** * * @param in */ private void parse(int in) { int pair = 1; if (map[in] == -1) { return; } map[in]=-1; String inStr = String.valueOf(in); char[] chars = inStr.toCharArray(); for (int i = 0; i < chars.length - 1; i++) { in = (in - (chars[i] - 48) * pow) * 10 + (chars[i] - 48); if (valid(in)) { if (map[in] != -1) { pair++; map[in] = -1; } } } count += pair * (pair - 1) / 2; } public long count() { for (int i = low; i <= high; i++) { parse(i); } return count; } private boolean valid(int t) { return t >= low && t <= high; } public static void main(String[] args) throws FileNotFoundException { System.setOut(new PrintStream(new File(""output.txt""))); // String fname = ""sample.txt""; String fname = ""C-small-attempt0.in.txt""; // String fname = ""C-large.in.txt""; FileTranslatorBasis ftb = FileTranslatorBasis.getInstance(fname); int num = ftb.getNumOfCase(); for (int i = 0; i < num; i++) { String[] input = ftb.getStrDataArray(); C c = new C(input[0],input[1]); System.out.println(""Case #"" + Integer.toString(i + 1) + "": "" + String.valueOf(c.count())); } } } " B13052,"import java.io.*; public class Main { public static void main(String[] args) { Main m = new Main(); try { FileInputStream fstream = new FileInputStream(""C-small-attempt2.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine = br.readLine(); int x = Integer.parseInt(strLine); int result; String[] a; for (int j = 0; j < x; j++) { System.out.print(""Case #"" + (j + 1) + "": ""); strLine = br.readLine(); a = strLine.split("" ""); result = 0; int first = Integer.parseInt(a[0]); int second = Integer.parseInt(a[1]); for (int i = first; i < second; i++) { for (int k = i + 1; k <= second; k++) { boolean b = m.check(i + """", k + """"); if (b) result++; } } System.out.println(result); } in.close(); } catch (Exception e) {// Catch exception if any System.err.println(""error""); } } private boolean check(String i, String k) { boolean b = false; for (int j = k.length() - 1; j >= 0; j--) { k = k.charAt(k.length() - 1) + """" + k.substring(0, k.length() - 1); if (k.equalsIgnoreCase(i)) { b = true; break; } if (b) break; } return b; } }" B10219,"import static java.util.Arrays.deepToString; import java.io.*; import java.math.*; import java.util.*; public class C { static int solve() { int A = nextInt(), B = nextInt(); int res = 0; HashSet set = new HashSet<>(); for (int m = A; m <= B; m++) { String w = m + """"; for (int i = 0; i < w.length() - 1; i++) { int x = Integer.parseInt(w.substring(i + 1) + w.substring(0, i + 1)); if (m < x && x <= B) { set.add(((long) x << 30) | m); } } } return set.size(); } public static void main(String[] args) throws Exception { reader = new BufferedReader(new FileReader(""c.in"")); writer = new PrintWriter(""c.out""); int T = nextInt(); for (int i = 0; i < T; i++) { setTime(); int res = solve(); writer.printf(""Case #%d: %s\n"", i + 1, res); printTime(); } printMemory(); writer.close(); } static BufferedReader reader; static PrintWriter writer; static StringTokenizer tok = new StringTokenizer(""""); static long systemTime; static void debug(Object... o) { System.err.println(deepToString(o)); } static void setTime() { systemTime = System.currentTimeMillis(); } static void printTime() { System.err.println(""Time consumed: "" + (System.currentTimeMillis() - systemTime)); } static void printMemory() { System.err.println(""Memory consumed: "" + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1000 + ""kb""); } static String next() { while (!tok.hasMoreTokens()) { String w = null; try { w = reader.readLine(); } catch (Exception e) { e.printStackTrace(); } if (w == null) return null; tok = new StringTokenizer(w); } return tok.nextToken(); } static int nextInt() { return Integer.parseInt(next()); } static long nextLong() { return Long.parseLong(next()); } static double nextDouble() { return Double.parseDouble(next()); } static BigInteger nextBigInteger() { return new BigInteger(next()); } }" B11643,"import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashMap; import java.util.HashSet; import java.util.Set; public class Recycled_Numbers { public static void main(String[] args) { try { // Initialize InputStreamReader converter = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(converter); String curLine = in.readLine(); String[] numbers; int A; int B; // Find number of cases int N = Integer.parseInt(curLine); // Read line by line for (int line = 0; line < N; line++) { curLine = in.readLine(); numbers = curLine.split("" ""); A = Integer.parseInt(numbers[0]); B = Integer.parseInt(numbers[1]); int total = 0; HashMap hm = new HashMap(); for (int number = A; number <= B; number++) { // parse the number as a string String s = Integer.toString(number); String[] digits = new String[s.length()]; int numZeroes = 0; // the array of possible recycled numbers in string form for (int digit = 0; digit < digits.length; digit++) { digits[digit] = s.substring(digit) + s.substring(0, digit); if (digits[digit].charAt(0) == '0') numZeroes++; } // convert to integers int[] dint = new int[digits.length-numZeroes]; int intdigits = 0; for (int digit = 0; digit < digits.length; digit++) { if (digits[digit].charAt(0) != '0') { dint[intdigits++] = Integer.parseInt(digits[digit]); } } // check if in hashtable if (!hm.containsKey(dint[0])) { // put into a set only if between A and B Set set = new HashSet(); for (int digit = 0; digit < dint.length; digit++) { hm.put(dint[digit], 0); if (dint[digit] >= A && dint[digit] <= B) set.add(dint[digit]); } // find the set size and add the appropriate number of pairs int numSet = set.size(); total += numSet * (numSet-1) / 2; } } System.out.println(""Case #"" + (line+1) + "": "" + total); } } catch(Exception e) { System.out.println(""Error: "" + e.getMessage()); } } } " B12098,"package util; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class MyUtil { public static BufferedReader getReader(String filename){ try { return new BufferedReader(new FileReader(""data/"" + filename)); } catch (FileNotFoundException e) { e.printStackTrace(); } return null; } public static BufferedWriter getWriter(String filename){ try { return new BufferedWriter(new FileWriter(""output/"" + filename + "".out.txt"")); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } } " B12956,"package google.contest.B; import google.loader.Challenge; import google.problems.AbstractReader; public class BReader extends AbstractReader { @Override protected Challenge createChallenge(int number) { int theLine = getActualLine(); String[] lines = getLines(); BChallenge chal = new BChallenge(number, lines[theLine]); setActualLine(theLine+1); return chal; } } " B10868," import java.io.*; import java.util.*; class C{} public class Recycle { static Scanner scan; static PrintWriter writer; public static void readProcessOutput() throws Exception{ String outputStr = """"; String result = """"; int index = 1; int testCases = Integer.parseInt(scan.nextLine()); //------- //------- while(index <= testCases ){ //runs testCases number of times System.out.println(""Running testcase : "" + index); int count = 0; //----------- Scanner temp = new Scanner(scan.nextLine()); int A = temp.nextInt(); int B = temp.nextInt(); boolean mark[] = new boolean[B+1]; int c[] = new int[B+1]; for(int i = A; i <=B; i++){ //if(!mark[i]) { int j = i; int k = i; String s = """" + j; do{ //j = (j%div)*10 + (j/div); s = s.substring(1) + s.charAt(0); j = Integer.parseInt(s); if(j >= A && j <= B && j > i && ("""" +j).length() == s.length()){ count++; mark[i] = true; mark[j] = true; c[i]++; } }while(j != k); // if(!mark[i]) // System.out.println(i); // } } // int f =0; // for(int m : c) // f += m; // System.out.println(""count:""+ f); //------------ outputStr = ""Case #"" + index + "": "" + count; writer.println(outputStr); result = """"; outputStr = """"; index++; } scan.close(); writer.close(); } public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); String className = C.class.getSimpleName() ; int choice = 0; do{ System.out.println(""Enter your choice :""); System.out.println(""1) Solve small""); System.out.println(""2) Solve large""); System.out.print(""Choice : ""); choice = in.nextInt(); switch(choice){ case 1 : scan = new Scanner(new File(className + ""-small-practice.in"")); writer = new PrintWriter(new BufferedWriter(new FileWriter(new File(className +""small.txt"")))); readProcessOutput(); System.out.println(""Solved successfully!\n""); break; case 2 : scan = new Scanner(new File(className + ""-large-practice.in"")); writer = new PrintWriter(new BufferedWriter(new FileWriter(new File(className +""large.txt"")))); readProcessOutput(); System.out.println(""Solved successfully!\n""); break; } }while (choice != 0); System.out.println(""Program finished!""); } } " B10491,"import java.util.HashSet; import java.util.Scanner; public class C { public static void main(String args[]) { Scanner in = new Scanner(System.in); int cases; cases = in.nextInt(); in.nextLine(); for(int i = 0; i < cases; i ++ ) { int a = in.nextInt(); int b = in.nextInt(); HashSet found = new HashSet(); int total = 0; if( b >= 10) { if( a < 10 ) { a = 10; } for( int j = a; j <= b; j++ ) { if( !found.contains(j) ) { String theNum = String.valueOf(j); int morphed; theNum = theNum.charAt(theNum.length() -1) + theNum.substring(0, theNum.length()-1); morphed = Integer.valueOf(theNum); while( morphed != j ) { if( !found.contains(morphed) && morphed >=a && morphed <=b ) { total ++; found.add(j); } theNum = theNum.charAt(theNum.length() -1) + theNum.substring(0, theNum.length()-1); morphed = Integer.valueOf(theNum); } } } } System.out.println(""Case #"" + (i+1) + "": "" + total ); } } } " B11700,"import java.text.*; import java.util.*; import java.lang.*; public class solutionRunner { public solutionRunner(){ run(); } private void run(){ int numberOfLines = 1; inpOutHandler io1 = new inpOutHandler(); testCase TC = io1.readInput(""a.txt"", numberOfLines); String result="""";int _i=1; for(String case1:TC.cases){ //int[] a1 = intAfromString(case1.substring(case1.indexOf('\n') +1)); pairs = new HashSet(); long[] a1 = longAfromString(case1.substring(case1.indexOf('\n') +1)); if(_i==TC.cases.length){ result +=""Case #"" + (_i++) +"": "" + numberOfG(a1); }else{ result +=""Case #"" + (_i++) +"": "" + numberOfG(a1) + ""\n""; } } io1.createOutput(""OUTPUT.txt"", result); //System.out.println(result); /* double xx = 1231212.9; DecimalFormat threeDec = new DecimalFormat("".0000000""); String shortString = (threeDec.format(xx)); */ } private long numberOfG(long[] a) { long min = a[0];long max = a[1]; //System.out.println(""<"" + min + "" , "" + max + "">""); for(long n=min; n=min && r<=max){ long temp = encodePair(n,r, max+1); if(!pairs.contains(temp)) pairs.add(temp); } } } } /* for(long _x:pairs){ long[] _tem = decodePair(_x, max+1); System.out.println(""<"" + _tem[0] + "" , "" + _tem[1] + "">""); } */ return pairs.size(); } // returns numbers r : r_i > n and r_i can be recycled from n private long[] largerRecycles(long n) { if(n<10) return null; String _sN = """"+n;int len = _sN.length(); ArrayList recycles = new ArrayList(); long r = leftRotate(n,len); while(r!=n){ if(r>n) recycles.add(r); r = leftRotate(r,len); } if(recycles.size()<1) return null; long[] rs = new long[recycles.size()]; for(int i=0; i pairs;// = new HashSet(); private int[] intAfromString(String s) { String[] words = s.split("" ""); int[] a = new int[words.length]; for(int i=0;iy){ return x; }else{ return y; } } } " B11586,"package google.codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.Set; import java.util.TreeSet; public class Problem3 { public Problem3() { super(); } public static void main(String[] args) { try { BufferedReader reader = new BufferedReader(new FileReader(""D:\\codejam\\2012\\C.in"")); BufferedWriter writer = new BufferedWriter(new FileWriter(""D:\\codejam\\2012\\C.out"")); //... Loop as long as there are input lines. String line = null; reader.readLine(); int i=1; while ((line=reader.readLine()) != null) { writer.write(""Case #""+i+"": ""+convert(line)); writer.newLine(); // Write system dependent end of line. i++; } //... Close reader and writer. reader.close(); // Close to unlock. writer.close(); // Close to unlock and flush to disk. } catch(Exception ex) { ex.printStackTrace(); } } //public static void main(String[] args) { // System.out.println(convert(""123 995"")); // } private static boolean isInRange(String num,int A, int B) { int iNum = Integer.parseInt(num); if(iNum>=A && iNum<=B) return true; return false; } private static Set cycle(String num, int A,int B) { Set cycleSet = new TreeSet(); if(isInRange(num,A,B)) cycleSet.add(num); for(int i=1;i set) { int size = set.size(); return (size*(size-1))/2; } private static int convert(String input) { String[] inputArr = input.split("" ""); try { int A = Integer.parseInt(inputArr[0]); int B = Integer.parseInt(inputArr[1]); Set processedNumber = new TreeSet(); Set childSet = null; int size=0; int totalCount = 0; for(Integer num = A;num<=B;num++) { if(processedNumber.contains(num.toString())) continue; childSet = cycle(num.toString(), A, B); size = size(childSet); if(size>0) { totalCount+=size; processedNumber.addAll(childSet); } } return totalCount; } catch(Exception ex) { ex.printStackTrace(); } return 0; } } " B12498,"import java.io.*;import java.util.*; public class Solution3 { public static void main(String args[]) throws IOException { BufferedReader br=new BufferedReader(new FileReader(""input.txt"")); PrintWriter pw=new PrintWriter(new BufferedWriter(new FileWriter(""output.txt""))); int lines=Integer.parseInt(br.readLine()); for(int q=1;q<=lines;q++) { StringTokenizer st=new StringTokenizer(br.readLine()); int A=Integer.parseInt(st.nextToken()); int B=Integer.parseInt(st.nextToken()); int ctr=0; for(int n=A;n<=B;n++) { for(int m=n+1;m<=B;m++) { String s1=String.valueOf(n); String s2=String.valueOf(m); int x1,x2,i; for(i=0;i 1; --k) { String str = strN.substring(k - 1, strN.length()) + strN.substring(0, k - 1); int a = Integer.parseInt(str); if (a == m) { count++; break; } } } n++; } System.out.println(""Case #"" + p + "": "" + count); } } } " B13058,"import java.util.*; import java.io.*; public class Recycle { public static boolean sameNumbers(int n, int m, int length, int i) { char[] nArray = (n + """").toCharArray(); char[] mArray = (m + """").toCharArray(); for (int j = 0; j < length; j++) { //System.out.println(j + "" "" + i + "" "" + m + "" "" + mArray.length); if (Arrays.binarySearch(nArray, mArray[i]) == -1) return false; } return true; } public static boolean check(int n, int m, int a, int b, int i) { if (n > m) return false; else if (n == m) return false; else if (n < a) return false; else if (m > b) return false; // else if (!sameNumbers(n,m,(n + """").length(), i)) return false; // System.out.println(n + "" "" + m); return true; } public static void main (String []args) throws IOException { final String INPUT_FILE = ""C-small-attempt0.in""; final String OUTPUT_FILE = ""out3.out""; BufferedReader input = new BufferedReader(new FileReader(INPUT_FILE)); PrintWriter out = new PrintWriter(new FileWriter(OUTPUT_FILE)); int repeats = Integer.parseInt(input.readLine()); for (int j = 0; j < repeats; j++) { StringTokenizer g = new StringTokenizer(input.readLine()); int count = 0; int a = Integer.parseInt(g.nextToken()); int b = Integer.parseInt(g.nextToken()); int aLength = (a + """").length(); if (aLength == 1) out.println(""Case #"" + (j + 1) + "": 0""); else { int arrayCounter = 0; for (int k = a; k < b; k++) { for (int i = 1; i < aLength;i++) { String kString = k + """"; //System.out.println(a + "" "" + aLength + "" "" + i); String mString1 = kString.substring(i,aLength); String mString2 = kString.substring(0,i); //System.out.println(kString + "" "" + mString1 + "" "" + mString2); int m = Integer.parseInt(mString1 + mString2); if (check(k,m,a,b,i)) { count++; } } } out.println(""Case #"" + (j + 1) + "": "" + count); } } out.close(); input.close(); } }" B10852,"package practice.GC2012; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Scanner; import java.util.Set; public class recycle { public static void main(String args[]) throws IOException { Scanner s = new Scanner(new File(""Z:\\junkyard\\practice\\resources\\input3.txt"")); FileWriter fo = new FileWriter(new File(""Z:\\junkyard\\practice\\resources\\output3.txt"")); int num = s.nextInt(); for(int i = 1; i<= num; i++) { fo.write(""Case #"" + i + "": ""); int a = s.nextInt(); int b = s.nextInt(); Set alreadyCounted = new HashSet(); for (int j = a;j<=b;j++) { StringBuffer n = new StringBuffer(String.valueOf(j)); for (int p = 0; p < n.length(); p++) { n.append(n.charAt(0)); n.deleteCharAt(0); if (j < Integer.parseInt(n.toString()) && Integer.parseInt(n.toString()) <= b) { alreadyCounted.add(String.valueOf(j) + n.toString()); } } } fo.write(alreadyCounted.size() + ""\n""); } fo.close(); s.close(); } } " B12175,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; /** * * @author Aymen */ public class main { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { int[] v = new int[1000]; String outputFile = System.getenv(""USERPROFILE"") + ""\\Documents\\C-small.out""; String inputFile = System.getenv(""USERPROFILE"") + ""\\Documents\\C-small.in""; //String outputFile = System.getenv(""USERPROFILE"") + ""\\Documents\\output.txt""; //String inputFile = System.getenv(""USERPROFILE"") + ""\\Documents\\input.txt""; BufferedWriter os = new BufferedWriter(new FileWriter(outputFile)); DataInputStream is = new DataInputStream(new FileInputStream(inputFile)); int T = Integer.valueOf(is.readLine()); System.out.println(""T "" + T); for (int i = 0; i < T; i++) { String list = is.readLine(); list += "" ""; int l = list.substring(0, list.indexOf("" "")).length(); int A = Integer.valueOf(list.substring(0, list.indexOf("" ""))); list = list.substring(list.indexOf("" "") + 1); int B = Integer.valueOf(list.substring(0, list.indexOf("" ""))); list = list.substring(list.indexOf("" "") + 1); boolean exist = false; int num, result = 0; String numString, numRotate; v[0] = 0; for (int j = A; j <= B; j++) { num = j; for (int n = 0; n < result; n++) { if (num == v[n]) { } } numString = String.valueOf(num); numRotate = numString; numRotate = numRotate.substring(l - 1) + numRotate.substring(0, l - 1); num = Integer.valueOf(numRotate); while (numRotate.substring(0, 1).equals(""0"")) { numRotate = numRotate.substring(l - 1) + numRotate.substring(0, l - 1); } num = Integer.valueOf(numRotate); while ((num < A) || (num > B)) { numRotate = numRotate.substring(l - 1) + numRotate.substring(0, l - 1); num = Integer.valueOf(numRotate); } while (num != j) { if ((!exist) && (num != j)) { for (int m = j + 1; m <= B; m++) { if (m == num) { v[result] = m; result++; } } } numRotate = numRotate.substring(l - 1) + numRotate.substring(0, l - 1); num = Integer.valueOf(numRotate); while (numRotate.substring(0, 1).equals(""0"")) { numRotate = numRotate.substring(l - 1) + numRotate.substring(0, l - 1); } num = Integer.valueOf(numRotate); while ((num < A) || (num > B)) { numRotate = numRotate.substring(l - 1) + numRotate.substring(0, l - 1); num = Integer.valueOf(numRotate); } } } int m = i + 1; os.write(""Case #"" + m + "": "" + result); os.newLine(); } is.close(); os.close(); } } " B12882,"import java.util.Scanner; public class Recycled { public static void main(String[] args) { Scanner input = new Scanner(System.in); int cases = input.nextInt(); for (int c = 1; c <= cases; c++) { int a = input.nextInt(); int b = input.nextInt(); int matches = 0; for (int n = a; n <= b; n++) { String strN = String.valueOf(n); for (int m = n + 1; m <= b; m++) { String strM = String.valueOf(m); if (check(strN, strM)) matches++; } } System.out.println(""Case #"" + c + "": "" + matches); } } private static boolean check(String a, String b) { for (int k = 1; k < a.length(); k++) { if ((a.substring(k, a.length()) + a.substring(0, k)).equals(b)) return true; } return false; } } " B11608,"import java.io.BufferedReader; import java.io.File; import java.util.HashMap; import java.util.StringTokenizer; import java.io.FileReader; public class C { /** * @param args */ public static void main(String[] args) throws Exception { BufferedReader reader = null; String fileName = ""C-small-attempt2.in""; String outputFileName=fileName.replace("".in"", "".out""); reader=new BufferedReader(new FileReader(fileName)); File outFile=new File(outputFileName); outFile.createNewFile(); int T = Integer.parseInt(reader.readLine()); for (int i = 1; i <=T; i++) { StringTokenizer t=new StringTokenizer(reader.readLine(),"" ""); int start=Integer.parseInt(t.nextToken()); int end=Integer.parseInt(t.nextToken()); int count=0; HashMap map=new HashMap(); for(int j=start;j=start && num>j){ String key=j+""_""+num; if(map.get(key)==null){ map.put(key, key); count++; } } } } System.out.println(""Case #""+i+"": ""+count); } } } " B13005,"/* * recycle nums */ package google.code.jam; import java.io.File; import java.io.PrintWriter; import java.util.Scanner; /** * * @author Jake */ public class GoogleCodeJam { private static int Min; private static int Max; private static PrintWriter out= null; private static File input; private static Scanner in; private static boolean used[]; public static void main(String[] args) { input = new File(""C:/Users/Jake/Documents/C-small-attempt1.in""); String tmp ; int intTmp; int count = 1; try { out= new PrintWriter(""C:/Users/Jake/Documents/out.txt""); in = new Scanner(input); //in = new Scanner(System.in); in.nextLine(); while(in.hasNext()){ Min = in.nextInt(); Max = in.nextInt(); //in.nextLine(); intTmp = Runner(); out.println(""Case #""+ count + "": "" +intTmp); count++; } out.flush(); //tmp = in.nextLine(); //System.out.println(Runner()); } catch (Exception e) { e.printStackTrace(); } } private static int Runner(){ //checks for the number of pairs between min and max used = new boolean[Max-Min]; reset(used); int Count = 0; for(int a = Min; a < Max; a ++){ reset(used); Count = Count + checker(a); } return Count; } private static int checker(int Try){ //finds how many pairs are within the range int pairs= 0; int test=Try; String strtry = new String(Try +""""); for(int a = 0; a <= strtry.length()-1; a ++){ if(Integer.parseInt(strtry)<=Max && Integer.parseInt(strtry)>Try && !used[Integer.parseInt(strtry)-Min-1]){ pairs ++; used[Integer.parseInt(strtry)-Min-1] = true; System.out.println(""pair : ""+Try+"" < ""+ strtry+ "" < "" + Max); } strtry = rotate(strtry); } return pairs; } private static String rotate(String num){ //takes the end of the string and makes it the beging String tmp, last; last = """"+num.charAt(num.length()-1); tmp = num.substring(0,num.length()-1); num = last+ tmp; return num; } private static boolean[] reset(boolean a[]){ //reset the check if used array for(int b = 0; b numeros= new ArrayList(); StringBuffer num, copia; String aux; int test= sc.nextInt(), min, max, largo, cuenta; for (int i=1; i<=test; i++){ numeros.clear(); cuenta= 0; System.out.print(""Case #""+i+"": ""); min= sc.nextInt(); max= sc.nextInt(); for (int j=min; j<=max; j++){ num= new StringBuffer(Integer.toString(j)); largo= num.length(); for (int k= 1; k= min) && (Integer.parseInt(aux) != j) && (!numeros.contains(aux+ "",""+ Integer.toString(j)))){ numeros.add(aux+ "",""+ Integer.toString(j)); numeros.add(Integer.toString(j)+ "",""+ aux); cuenta++; } } } System.out.println(cuenta); } } }" B11405,"import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class C { public static void main (String [] args) throws FileNotFoundException { Scanner input = new Scanner(new File(""csmall.in"")); int count = input.nextInt(); for (int i = 0; i < count; i++) { int A = input.nextInt(); int B = input.nextInt(); System.out.println(""Case #"" + (i+1) + "": "" + doWork(A, B)); } } private static int doWork(int a, int b) { int count = 0; int n = a; int m = a + 1; while (m <= b) { n = a; while (n < m) { if (checkRotation(Integer.toString(n), Integer.toString(m))) count++; n++; } m++; } return count; } private static boolean checkRotation(String given, String toCheck) { char [] giv = given.toCharArray(); char [] temp = new char[giv.length + 1]; int i , j , n; n = temp.length - 1; for (i = 0; i < giv.length; i++) { temp[i] = giv[i]; } for(i = 0; i < given.length(); i++) { temp[n] = temp[0]; for(j = 0; j < n; j++) { temp[j] = temp[j+1]; } char[] moreTemp = new char[giv.length]; for (int k = 0; k < giv.length; k++) { moreTemp[k] = temp[k]; } if ((new String(moreTemp)).equals(toCheck)) { return true; } //System.out.printf(""\n %s"", new String(moreTemp)); } return false; } } " B13122,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) throws NumberFormatException, IOException { // open file and create a buffered reader FileReader input = new FileReader(args[0]); BufferedReader buffer = new BufferedReader(input); //read the number of testcases int max = Integer.parseInt(buffer.readLine().trim()); // read a line and call the solving procedure for a single test case. We expect back the result as a string for (int i = 1; i <= max; i++) { System.out.println(""Case #""+i+"": "" + solve(buffer.readLine())); } } private static long solve(String input) { String[] split = input.split("" ""); int A = Integer.parseInt(split[0]); int B = Integer.parseInt(split[1]); long count = 0; if (A < 10) { return 0; } for(int i = A; i < B; i++) { String str = Integer.toString(i); HashSet all = new HashSet(); for(int j = 1; j < str.length(); j++) { String cycle = str.substring(j)+str.substring(0, j); int value = Integer.parseInt(cycle); if (value > i && value <= B && !all.contains(value)) { all.add(value); count++; } } } return count; } } " B11673,"package com.google.codejam; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class ApplicationRecycledNumbers { public static final String fileName = ""E:/Projects/RnD/GoogleCodeJam/src/com/google/codejam/google_data.txt""; public static void main(String[] args) { try { BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName)); String text = bufferedReader.readLine(); if (text != null) { RecycledNumbersCalculator recycledNumbersCalculator = new RecycledNumbersCalculator(); recycledNumbersCalculator.processData(Integer.parseInt(text), bufferedReader); } } catch (FileNotFoundException e) { System.out.println(""File not found.""); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } class RecycledNumbersCalculator { public void processData(int parseInt, BufferedReader bufferedReader) { String lineData; for (int counter = 1; counter <= parseInt; counter++) { try { lineData = bufferedReader.readLine(); String[] integers = lineData.split("" ""); int smallNumber = Integer.parseInt(integers[0]); int largeNumber = Integer.parseInt(integers[1]); int noOfRecyledPairs = getNoOfDistinctRecycledPairs(smallNumber, largeNumber); System.out.println(""Case #"" + counter + "": "" + noOfRecyledPairs); } catch (IOException e) { e.printStackTrace(); } } } private int getNoOfDistinctRecycledPairs(int smallNumber, int largeNumber) { int noOfRecyledPairs = 0; List numberUsed = new ArrayList(); for (int firstNumber = smallNumber; firstNumber <= largeNumber; firstNumber++) { String firstNumberStr = String.valueOf(firstNumber); for (int m = firstNumber+1; m <= largeNumber; m++) { String secondNumber = String.valueOf(m); int secondNumberLength = secondNumber.length(); for (int p = 1; p <= secondNumberLength-1; p++) { String trailingChars = secondNumber.substring((secondNumberLength-p), secondNumberLength); String startingChars = secondNumber.substring(0, (secondNumberLength-p)); String newNumber = trailingChars + startingChars; if (newNumber.equals(firstNumberStr)) { if (!numberUsed.contains(firstNumber) && !numberUsed.contains(secondNumber)) { noOfRecyledPairs++; break; } } //System.out.println(""trailingChars: "" + trailingChars + "", startingChars: "" + startingChars); } } } return noOfRecyledPairs; } } " B11002,"import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { Scanner sc = new Scanner(new File(""data/C-small-attempt0.in"")); PrintWriter out = new PrintWriter(new File(""data/output.txt"")); Integer count = sc.nextInt(); System.out.println(count); for (int i = 0; i < count; i++) { System.out.println(i); out.println(""Case #"" + (i + 1) + "": "" + countRecycled(sc.nextInt(), sc.nextInt())); } out.close(); } private static int countRecycled(Integer iA, Integer iB) { Set recycled = new HashSet(); if (iA.toString().length() != iB.toString().length()) { return 0; } System.out.println(); System.out.println(iA + "" "" + iB); System.out.println(); int sLength = iA.toString().length(); for (Integer n = iA; n <= iB; n++) { for (int c = 1; c <= sLength; c++) { String left = n.toString().substring(sLength - c, sLength); String right = n.toString().substring(0, sLength - c); String newNumber = left + right; // System.out.println(left + ""-"" + right + ""-"" + newNumber); int intNew = Integer.parseInt(newNumber); if (!newNumber.startsWith(""0"") // same length && intNew <= iB // within range && intNew > n // bigger than the other one ) { recycled.add(n.toString() + "","" + newNumber); } } } return recycled.size(); } } " B12659,"package com.kiwien.google; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class RecycledNumbers { public static void main(String[] args) { final FileInputStream fstream; String lineStr; final StringBuilder sb = new StringBuilder(); try { fstream = new FileInputStream(""./testdata/test.in""); final DataInputStream in = new DataInputStream(fstream); final BufferedReader br = new BufferedReader(new InputStreamReader(in)); final int testNum = Integer.parseInt(br.readLine()); if (testNum <= 0 || testNum > 50) { return; } for (int i = 0; i < testNum; i++) { lineStr = br.readLine(); sb.append(""Case #"" + (i + 1) + "": "" + process(lineStr) + ""\n""); } writeToFile(sb.toString()); System.out.println(sb.toString()); System.out.println(""Finished.""); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (NumberFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private static void writeToFile(String str) { BufferedWriter writer = null; try { final File out = new File(""./results/dancing.out""); writer = new BufferedWriter(new FileWriter(out)); writer.write(str); System.out.println(""Test result saved to "" + out.getAbsolutePath()); } catch (IOException e) { e.printStackTrace(); } finally { try { if (writer != null) writer.close(); } catch (IOException e) { } } } private static String process(String inputStr) { final String[] input = inputStr.split("" ""); final int a = Integer.parseInt(input[0]); final int b = Integer.parseInt(input[1]); final String aDigit = """" + a; final String bDigit = """" + b; if (a >= 1 && b >= a && b <= 2000000 && aDigit.length() == bDigit.length()) { return """" + getRecycledPairNumber(a, b); } else { return ""invalid""; } } public static int getRecycledPairNumber(int a, int b) { if (a < 10) { return 0; } int count = 0; for (int i = a; i <= b - 1; i++) { for (int j = i + 1; j <= b; j++) { if (isRecycled(i, j)) { count++; } } } return count; } private static boolean isRecycled(int m, int n) { final String mStr = """" + m; final String nStr = """" + n; for (int i = 1; i < mStr.length(); i++) { if (mStr.charAt(i) != '0') { final String newStr = mStr.substring(i) + mStr.substring(0, i); if (newStr.equals(nStr)) { return true; } } } return false; } } " B12445,"import java.io.BufferedInputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; public class Main { public static void solve() throws Exception{ int T = in.readInt(),t = 0; String format = ""Case #%d: ""; long count, temp; int a,b; String n; List counted = new ArrayList(); while(t++= a && !counted.contains(temp)){ counted.add(temp); count++; } } } out.println(count); } } static InputReader in; static OutputWriter out; public static void start(){ in = new InputReader(System.in); out = new OutputWriter(System.out); } public static void finish() throws Exception{ out.close(); } public static void main(String[] args) throws Exception { start(); solve(); finish(); } } class InputReader extends BufferedInputStream{ public InputReader(InputStream In){ super(In); } public char readChar() throws Exception{ int c = read(); while(isStringEnd(c)) c = read(); return (char) c; } public int readInt() throws Exception { int sign = 1; int cur = 0; int c = read(); while(isStringEnd(c)) c = read(); if(c == '-'){ sign = -1; c = read(); } do{ cur *= 10; cur += c - '0'; c = read(); }while(!isStringEnd(c)); return cur*sign; } public long readLong() throws Exception { long sign = 1; long cur = 0; int c = read(); while(isStringEnd(c)) c = read(); if(c == '-'){ sign = -1; c = read(); } do{ cur *= 10; cur += c - '0'; c = read(); }while(!isStringEnd(c)); return cur*sign; } public double readDouble() throws Exception { double sign = 1; double cur = 0; int c = read(); while(isStringEnd(c)) c = read(); if(c == '-'){ sign = -1; c = read(); } do{ cur *= 10; cur += c - '0'; c = read(); }while(!isStringEnd(c) && c!= '.'); if(c == '.'){ c = read(); double r = 0.1; do{ cur += r*(c - '0'); r *= 0.1; c = read(); }while(!isStringEnd(c) && c!= '.'); } return cur*sign; } public String readStr() throws Exception{ int c = readChar(); while(isStringEnd(c)) c = read(); StringBuilder res = new StringBuilder(); do{ res.append((char)c); c = read(); }while(!isStringEnd(c)); return res.toString(); } public String readLine() throws Exception{ int c = readChar(); while(isStringEnd(c)) c = read(); StringBuilder res = new StringBuilder(); do{ res.append((char)c); c = read(); }while(!isEOL(c)); return res.toString(); } public char[] readCharArray(int s) throws Exception{ char[] a = new char[s]; for(int i=0; i void printArray(T[] a, String del){ for(int i=0; i void printMat(T[][] a, String delRows, String delCols){ for(int i=0; i void printCollection(Iterable c, String del){ boolean b = true; for(T i : c){ if(b) b = false; else print(del); print(i); } } }" B11584,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class QualificationC { public static void main(String[] args) { try { FileReader input = new FileReader(args[0]); BufferedReader in = new BufferedReader(input); FileWriter output = new FileWriter(""QualificationC.out""); BufferedWriter out = new BufferedWriter(output); String line; int count = 1; line = in.readLine(); int cases = Integer.parseInt(line); line = in.readLine(); while (line != null && count <= cases) { if (count != 1) { out.write(""\n""); } String outStr = ""Case #"" + count + "": "" + getMaxRecycledPairs(line); System.out.println(outStr); out.write(outStr); line = in.readLine(); count++; } out.close(); in.close(); } catch (IOException e) { e.printStackTrace(); } } private static int getMaxRecycledPairs(String line) { String[] lineArr = line.split("" ""); int A = Integer.parseInt(lineArr[0]); int B = Integer.parseInt(lineArr[1]); int count = 0; for (int n = A; n < B; n++) { String nStr = String.valueOf(n); List tempList = new ArrayList(); for (int i = 0; i < nStr.length(); i++) { String mStr = nStr.substring(i) + nStr.substring(0, i); if (mStr.charAt(0) != '0') { int m = Integer.parseInt(mStr); if (m <= B && n < m && !tempList.contains(m)) { tempList.add(m); count++; } } } } return count; } } " B12375,"package qualif3; import java.io.File; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Qualif3 { public static void main(String[] args) throws Exception { Scanner scan = new Scanner(new File(""input"")); int num = Integer.parseInt(scan.nextLine()); for (int i = 1; i <= num; i++) { int a = scan.nextInt(); int b = scan.nextInt(); System.out.println(""Case #"" + i + "": "" + solve(a, b)); } } private static int solve(int a, int b) { if (b < 21) return 0; if (a < 12) a = 12; Set founds = new HashSet(); for (int num = a; num <= b; num++) { int tens = 10; int digits = ((int) Math.log10(num)); int inv = (int) Math.pow(10, digits); while (num / tens > 0) { int q = num / tens; int r = num % tens; int test = r * inv + q; if (test > num && test <= b) { founds.add("""" + num + ""|"" + test); } inv /= 10; tens *= 10; } } return founds.size(); } } " B10435,"package codejam; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) throws Exception { String fileName = ""RecycledNumbers.small.txt""; System.setIn(new FileInputStream(""data/input/"" + fileName)); System.setOut(new PrintStream(new FileOutputStream(""data/output/"" + fileName))); Scanner scanner = new Scanner(System.in); int testCases = scanner.nextInt(); for (int i = 1; i <= testCases; i++) { Set result = new HashSet(); int a = scanner.nextInt(); int b = scanner.nextInt(); for (int j = a; j <= b; j++) { String n = String.valueOf(j); if (n.length() > 0) { for (int x = n.length() - 1; x > 0; x--) { String m = n.substring(x) + n.substring(0, x); if (!m.startsWith(""0"") && Integer.valueOf(n) >= a && Integer.valueOf(n) < Integer.valueOf(m) && Integer.parseInt(m) <= b) { result.add(n + "","" + m); } // System.out.println(n + "","" + m + ""_countOfResult:"" // + result.size()); } } } System.out.println(""Case #"" + i + "": "" + result.size()); } } } " B10409,"package qualification2012; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; public class C { private final String f = ""src\\qualification2012\\C-small-attempt0""; private BufferedReader in; private PrintWriter out; private StringTokenizer token; private C() throws IOException { in = new BufferedReader(new FileReader(f+"".in"")); out = new PrintWriter(f + "".out""); eat(""""); int t = nextInt(); for (int i = 1; i <= t; i++) { write(""Case #""+i+"": ""); solve(); } in.close(); out.close(); } private void solve() throws IOException { int a = nextInt(); int b = nextInt(); if (a < 10){ write(0 + ""\n""); return; } int pair = 0; for (int i = a; i <= b; i++) { char[] digits = Integer.toString(i).toCharArray(); char[] tmp = new char[digits.length]; ArrayList al = new ArrayList<>(); for (int start = 1; start < digits.length; start++) { int number = 0; for(int x = 0; x + 1 < digits.length; x++) { tmp[x] = digits[x + 1]; number += Math.pow(10, (digits.length - x - 1)) * (digits[x + 1] - '0'); } tmp[digits.length - 1] = digits[0]; number += digits[0] - '0'; digits = tmp.clone(); if (number >= a && number <= b && i > number) { if(!al.contains(number)) { al.add(number); pair++; } } } } write(pair + ""\n""); } private String nextLine() throws IOException { return in.readLine(); } private String next() throws IOException { while (!token.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } eat(line); } return token.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(next()); } private long nextLong() throws IOException { return Long.parseLong(next()); } private void eat(String s) { token = new StringTokenizer(s); } private void write(String s) { System.out.print(s); out.print(s); } public static void main(String[] args) { try { new C(); } catch (IOException e) { e.printStackTrace(); } } } " B10649,"/* Original template used was test.java from USACO's training pages. Name: Ante Qu Problem: Recycled Numbers Gmail Account: quante0 */ import java.io.*; import java.util.*; class recycledNumbers { public static void main (String [] args) throws IOException { // Use BufferedReader rather than RandomAccessFile; it's much faster BufferedReader f = new BufferedReader(new FileReader(""C-small-attempt2.in"")); // input file name goes above PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""out.txt""))); int T=Integer.parseInt(f.readLine()); for(int i=0;i B) return false; if (x == i) return false; return true; } private static int shift(int current, int by, int length) { int power = (int) Math.pow(10, by); int shift = (int) Math.pow(10, length - by); return (current % power) * shift + current / power; } public static char translateChar(char current) { if (current == ' ') return ' '; if (current == 'a') return 'y'; if (current == 'b') return 'h'; if (current == 'c') return 'e'; if (current == 'd') return 's'; if (current == 'e') return 'o'; if (current == 'f') return 'c'; if (current == 'g') return 'v'; if (current == 'h') return 'x'; if (current == 'i') return 'd'; if (current == 'j') return 'u'; if (current == 'k') return 'i'; if (current == 'l') return 'g'; if (current == 'm') return 'l'; if (current == 'n') return 'b'; if (current == 'o') return 'k'; if (current == 'p') return 'r'; if (current == 'q') return 'z'; if (current == 'r') return 't'; if (current == 's') return 'n'; if (current == 't') return 'w'; if (current == 'u') return 'j'; if (current == 'v') return 'p'; if (current == 'w') return 'f'; if (current == 'x') return 'm'; if (current == 'y') return 'a'; if (current == 'z') return 'q'; return '.'; } }" B10807,"package codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class RecycledPairs { private static String filename = ""C-small-attempt0.in""; public static boolean isRecycledPair(int n, int m) { String sn = Integer.toString(n); String sm = Integer.toString(m); int length = sn.length(); String shiftedString = """"; for (int i = 1; i <= length; i++) { shiftedString = sn.substring(i, length) + sn.substring(0, i); //System.out.println(shiftedString + "" "" + sn + "" "" + sm); if (shiftedString.equals(sm)) return true; } return false; } public static int recycledPairs(int A, int B) { int acc = 0; for (int n = A, m; n < B; n++) { m = n + 1; for (; m <= B; m++) { if (isRecycledPair(n, m)) acc++; } } return acc; } public static void main(String[] args) {; try { BufferedReader in = new BufferedReader(new FileReader(filename)); BufferedWriter out = new BufferedWriter(new FileWriter(filename + "".out"")); String currentString = in.readLine(); int testCases = Integer.parseInt(currentString); for (int i = 1; i <= testCases; i++) { String[] input = in.readLine().split("" ""); int A = Integer.parseInt(input[0]); int B = Integer.parseInt(input[1]); int result = recycledPairs(A, B); out.write(""Case #"" + i + "": "" + result + '\n'); } out.close(); in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } " B10431,"package codejam; import java.io.*; public class FileWrite { String fileName; BufferedWriter bw; FileWriter fw; FileWrite(String fileName){ this.fileName=fileName; File f=new File(""K:\\CodeJam\\Results\\""+fileName); try{ fw=new FileWriter(f); bw=new BufferedWriter(fw); }catch(Exception e){ System.out.println(""Invalid file name.""); } } public void writeLine(String str){ try { bw.write(str+""\n""); } catch (IOException e) { System.out.println(""Error writing to file""); } } public void close(){ try { bw.close(); fw.close(); } catch (IOException e) { e.printStackTrace(); } } } " B10628,"package Controller; import ProblemSolvers.ProblemSolver; import ProblemSolvers.RecycledNumbers; public class Main { public static void main(String[] args) { ProblemSolver problem = new RecycledNumbers(""recycledNumbers""); problem.process(); } } " B12735,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.StringTokenizer; import java.util.Vector; import java.util.HashMap; public class Algorithm3 { static final String input_path = ""F://workspace//GoogleContest2012//src//input.txt""; static final String output_path = ""F://workspace//GoogleContest2012//src//output.txt""; static int total_case; static int findMax(String line){ StringTokenizer token = new StringTokenizer(line); Integer small = Integer.parseInt((String)token.nextElement()); Integer large = Integer.parseInt((String)token.nextElement()); int number = 0; HashMap map = new HashMap(); for(Integer i=small;ii){ if(map.get(m)==null){ number++; map.put(m, m); } } } } return number; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int i = 0; Vector outputs = new Vector(); try{ File file = new File(input_path); BufferedReader reader =new BufferedReader(new FileReader(file)); String line = reader.readLine(); //skip number total_case = Integer.parseInt(line); while(i j; k--) { if(client.isPossible(String.valueOf(j), String.valueOf(k))) { boolean isCyc = client.isRecycledPair(j, k); if(isCyc) recycledPairs++; //System.out.println(""jk: [""+j+"",""+k+""] : "" + isCyc); } } } System.out.println(""Case #"" + i + "": "" + recycledPairs); //System.out.println(); } } private boolean isPossible(String q, String w) { return getSumDigits(q) == getSumDigits(w); } private int getSumDigits(String num) { int tot = 0; for(char c : num.toCharArray()) { tot += Integer.valueOf(String.valueOf(c)); } return tot; } private Set findAllRotations(String someNum) { int len = someNum.length(); Set res = new HashSet(); for(int i=len; i> 0; i--) { String nxt = someNum.substring(i) + someNum.substring(0, i); //System.out.println(nxt); res.add(nxt); } res.remove(someNum); //prettyPrintSet(res); return res; } private boolean isRecycledPair(int n, int m) { //System.out.println(""n: "" + n + "", m: "" + m); if(n >= m) return false; String nS = String.valueOf(n); String mS = String.valueOf(m); Set rotSet =findAllRotations(nS); for(String each : rotSet) { if(each.equals(mS)) { return true; } } return false; } private String[] getInputLines(String fileName) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(fileName)); List lines = new ArrayList(); String nextLine; while((nextLine = reader.readLine()) != null) { lines.add(nextLine); } return lines.toArray(new String[lines.size()]); } private void prettyPrintSet(Set st) { if(st.isEmpty()) { System.out.println(""{}""); return; } StringBuilder sb = new StringBuilder(""{""); for(String each : st) { sb.append(each).append("",""); } System.out.println(sb.toString().replaceFirst("",$"", ""}"")); } } " B12726,"package com.develog; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.StringTokenizer; public class C { final int A = 0; final int B = 1; BufferedReader reader; BufferedWriter writer; String buf; String numStr[]; public C() throws IOException{ reader = new BufferedReader(new FileReader(""C-small-attempt0.in"")); writer = new BufferedWriter(new FileWriter(""output.txt"")); reader.readLine(); // # of case int cnt; for(int n=1; (buf = reader.readLine()) != null; n++){ numStr = getToken(buf); cnt = solve(numStr); // System.out.println(cnt); writer.write(String.format(""Case #%d: %d\n"", n, cnt)); } reader.close(); writer.close(); } public String[] getToken(String sentence){ String ret[] = new String[2]; StringTokenizer token = new StringTokenizer(sentence, "" \t""); int i=0; while(token.hasMoreTokens()){ ret[i++] = token.nextToken(); } return ret; } public int solve(String str[]){ long num[] = new long[2]; long m; int cnt=0; ArrayList arNum; num[A] = Integer.parseInt(str[A]); num[B] = Integer.parseInt(str[B]); for(long a=num[A], b=num[B]; a<=b; a++){ StringBuilder builder = new StringBuilder(String.valueOf(a)); int len = builder.length(); arNum = new ArrayList(); for(int i=0; i1) { left = Integer.parseInt(split[0]); right = Integer.parseInt(split[1]); for (int j=left; j { int a, b; Pair(int a, int b) { this.a = Math.min(a, b); this.b = Math.max(a, b); } @Override public String toString() { return String.format(""(%d, %d)"", this.a, this.b); } @Override public boolean equals(Object o) { if (o instanceof Pair) { if (((Pair) o).compareTo(this) == 0) return true; else return false; } else return false; } @Override public int compareTo(Pair o) { if (this.a == o.a) return 0; else if (this.a < o.a) return -1; else return 1; } public int hashCode() { return this.a << 16 + this.b; } } public ProblemC(String inFileName) { URL urlInFileName = ProblemC.class.getResource(inFileName); File inFile = null; FileInputStream fis = null; BufferedInputStream bis = null; try { inFile = new File(urlInFileName.toURI()); fis = new FileInputStream(inFile); bis = new BufferedInputStream(fis); } catch (Exception e) { // System.err.println(e.getMessage()); } Scanner s = new Scanner(bis); int T = Integer.parseInt(s.nextLine()); StringBuilder sb = new StringBuilder(); String outFileName = inFile.toString() + "".out""; FileWriter fstream = null; try { fstream = new FileWriter(outFileName); } catch (IOException e) { System.err.println(e.getMessage()); System.exit(-3); } BufferedWriter out = new BufferedWriter(fstream); Set pairs = null; for (int i = 1; i <= T; i++) { int A = s.nextInt(); int B = s.nextInt(); pairs = new HashSet(); for (int j = A; j <= B; j++) { int n = j; int m = 0; String ns = String.format(""%d"", n); int nslen = ns.length(); for (int k = 1; k < nslen; k++) { int nchop = n % (int) Math.pow(10, k); int rem = n / (int) Math.pow(10, k); int chopToPrefix = nchop * (int) Math.pow(10, nslen - k); m = chopToPrefix + rem; if (n < m && m <= B) { Pair p = new Pair(n, m); pairs.add(p); } } } String strCaseOutput = String.format(""%d"", pairs.size()); sb.setLength(0); String strOutput = String.format(""Case #%d: %s\n"", i, strCaseOutput); try { out.write(strOutput); } catch (IOException e) { // System.err.println(e.getMessage()); } } try { out.flush(); out.close(); } catch (IOException e) { // System.err.println(e.getMessage()); } } /** * @param args */ public static void main(String[] args) { if (args.length < 1) System.exit(-1); String inFileName = args[0]; new ProblemC(inFileName); } }" B10735,"import java.util.Scanner; import java.io.*; public class Tolu { static String out="""",output=""""; public static void main(String[] args) { try { Scanner in = new Scanner(new File(""input.in"")); int n = in.nextInt(); int count = 1; String out = """"; while(in.hasNext()) { int a = in.nextInt(); int b = in.nextInt(); out += ""Case #""+count+"": ""+ activity(a,b)+""\n""; count++; try { File file = new File(""output.dat""); PrintWriter output = new PrintWriter(file); output.write(out); output.close(); } catch(Exception exception) { System.out.println(""ERROR""); } } }catch(Exception exception){ System.out.println(""ERROR""); } System.out.println(""DONE""); } public static int activity(int A, int B) { int counter = 0; //String all[] = myGenerator(Integer.toString(A)); for(int i = A; i <= B; i++) { String all[] = myGenerator(Integer.toString(i)); for(int j = 0; j < all.length; j++) { if((i < Integer.parseInt(all[j])) && (Integer.parseInt(all[j]) <= B)) { counter++; } } } return counter; } public static String[] myGenerator(String word) { String[] all = new String[word.length()-1];//changed frm len - 1 for(int i = 0; i < all.length; i++) { all[i] = generate(word); word = generate(word); } return all; } public static String generate(String w) { String ans = w.substring(w.length()-1); for(int i = 0; i < w.length()-1; i++) { ans += w.substring(i,i+1); } return ans; } } " B10642,"import java.util.ArrayList; import java.util.Scanner; public class RecycledNumbers { private Integer a; private Integer b; private Integer caseNumber; private Integer numberOfDigits; public RecycledNumbers(int caseNumber,String data) { // TODO Auto-generated constructor stub Scanner s=new Scanner(data); this.a=s.nextInt(); this.b=s.nextInt(); this.caseNumber=caseNumber; this.numberOfDigits=a.toString().length(); } public void process() { int count=0; for(Integer i=a;i temp=new ArrayList(); for(int j=1;ji){ count++; //System.out.println(i+"" ""+temp1); } } } System.out.println(""Case #""+caseNumber+"": ""+count); } } " B12229,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) throws IOException { String filename = ""C:\\Users\\irene\\Desktop\\input.txt""; List inputLines = readInput(filename); int i = 0; for (String line : inputLines) { String[] limits = line.split(""\\s+""); RecycledNumbers rn = new RecycledNumbers(Integer.parseInt(limits[0]), Integer.parseInt(limits[1])); int result = rn.getDistinctPairsCount(); System.out.print(""Case #"" + (i + 1) + "": "" + result); System.out.println(); i++; } } private static List readInput(String filename) throws IOException { BufferedReader in = new BufferedReader(new FileReader(filename)); Integer totalLines = Integer.parseInt(in.readLine()); ArrayList lines = new ArrayList(totalLines); for (int i = 0; i < totalLines; i++) { lines.add(in.readLine()); } return lines; } } " B11686,"import java.util.*; public class Main { static int digits(int A){ if (A<10) return 1; return 1+digits(A/10); } static int[] decimal(int n, int d){ int[] t = new int[d]; for (int i = d-1; i>=0; i--){ t[i]=n-10*(n/10); n=n/10; } return t; } static boolean equals(int[] t1, int[] t2, int d){ for (int i=0; i l = new LinkedList(); int t = n; while(t > 0) { l.addFirst(t%10); t/=10; } HashSet hs = new HashSet(); for (int i = 0; i < l.size(); i++) { int m = 0; for (int j = i; j < l.size(); j++) { m = 10*m + l.get(j); } for (int j = 0; j < i; j++) { m = 10*m + l.get(j); } if(m > n && m <= B && !hs.contains(m)) { ++count; hs.add(m); // System.out.println(""("" + n + "","" + m + "")""); } } return count; } /** * @param args */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for (int i = 1; i <= T; i++) { int A = sc.nextInt(); int B = sc.nextInt(); int count = 0; for (int j = A; j < B; j++) { count += countBiggerRotated(j, B); } System.out.println(""Case #"" + i + "": "" + count); } } } " B11020,"package org.moriraaca.codejam.recyclednumbers; import org.moriraaca.codejam.TestCase; public class RecycledNumbersTestCase implements TestCase { public int A; public int B; } " B10651,"package tp; import java.io.*; public class Numbers { String input[]; int n,m,g; int no; int ans[]; int count=0; int j,t_c; int a,b; DataInputStream dis=new DataInputStream(System.in); FileReader fr; BufferedReader br; Numbers() throws IOException { fr= new FileReader(""D://D//input2.txt""); br= new BufferedReader(fr); } void get() throws IOException // this is input ka process { String ip=br.readLine();// it will take entire line t_c= Integer.parseInt(ip);// taste case for(int i=1; i<=t_c; i++) { ip=br.readLine(); String ip1[]= ip.split("" "");// split a= Integer.parseInt(ip1[0]); b= Integer.parseInt(ip1[1]); count=0; for(int y=a;y ind) { ind++; newStr = newStr.substring(1) + newStr.charAt(0); if (Integer.valueOf(newStr) >= a && Integer.valueOf(newStr) <= b && (Integer.valueOf(org) < Integer.valueOf(newStr))) { res++; } } } writer.write("""" + res); if (i < num - 1) { writer.write('\n'); } } writer.close(); reader.close(); } } " B10165,"import java.io.*; import java.util.*; public class RecycledNumbers { public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine()); int[][] ab = new int[T][2]; StringTokenizer st = null; for (int i=0; i= ab[i][0] && j(); mCaseCounter = 1; } public void addString(String res) { mResultList.add(res); } public void addCase(String res) { mResultList.add(""Case #"" + mCaseCounter + "": "" + res); mCaseCounter++; } public void clear() { mResultList.clear(); mCaseCounter = 1; } public Iterator iterator() { return mResultList.iterator(); } private long mCaseCounter; private List mResultList; } " B12518,"import java.io.*; import java.util.*; public class QualC { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int z = Integer.parseInt(br.readLine()); int[] ten = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000}; for(int i=0; i hs = new HashSet(); for(int j=a; j resultList = new ArrayList(); for(int j = firstNum;j<=secondNum;j++){ String first = Integer.toString(j); for(int k = 0; kj && newNumber>=firstNum){ result++; } } } System.out.println(""Case #""+caseCounter+"": ""+result); } } } " B13226,"import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; import java.util.Scanner; public class A { public static void main(String[] args){ Scanner in; try{ in=new Scanner(new FileReader(""A.in"")); int T=in.nextInt(); for(int tt=1;tt<=T;++tt){ int A=in.nextInt(); int B=in.nextInt(); int result=0; for (int i=A; i<=B;i++){ int num=i; //we dont want to loose i! int[] dig=new int[7]; //the numbers at a maximum have 7 digits ArrayList res=new ArrayList(); int d=0; //number of digits for (int j=0; j<7; j++){ if (num<=0) dig[j]=-1; else { dig[j]=num%10; d++; } num/=10; } for (int j=0; j=0){ num+=dig[(t+j)%7]*Math.pow(10, pow); pow++; } } if (num>=A && num<=B && num!=i) for (int t=0; t<7; t++) if (res.contains(num)==false){ result++; res.add(num); } } } System.out.println(""Case #""+tt+"": ""+result/2); } }catch(FileNotFoundException e){ } } } " B10434,"import java.util.ArrayList; import java.util.Scanner; public class Solution { public static void main(String[] args){ Scanner in = new Scanner(System.in); int T = in.nextInt(); in.nextLine(); int A, B, result,len,i,j,k; String that,original; String test=""""; ArrayList poss = new ArrayList(); for(int zz = 1; zz <= T;zz++){ result=0; A = in.nextInt(); len = String.valueOf(A).length(); poss = new ArrayList(); B = in.nextInt(); in.nextLine(); for (i = A; i <= B; i++){ poss.add(String.valueOf(i)); } for (i = 0; poss.size() > 0; i++){ that = poss.get(0); poss.remove(0); original=that; for (k=0; k < len; k++){ test=test+that.charAt(len-1); for (j=0; j < (len-1); j++){ test=test+that.charAt(j); } if (that.charAt(len-1) != '0' && poss.contains(test)){ result++; //System.out.format(""(%s,%s)\n"",original,test); } that=test; test=""""; } } System.out.format(""Case #%d: %d\n"",zz, result); } } } " B11733,"import java.util.*; public class Main { public static void main(String args[]) { (new Main()).solve(); } void solve() { Scanner cin = new Scanner(System.in); int T = cin.nextInt(); for(int C=1; C<=T; ++C) { int A = cin.nextInt(); int B = cin.nextInt(); int n = ("""" + A).length(); int base = 1; for(int i=1; i set = new HashSet(); int min = v + 1; for(int i=0; i */ package eu.positivew.codejam.framework; import java.io.BufferedReader; import java.io.IOException; /** * CodeJam input parser class (for general one-line strings). * * @author Üllar Soon */ public class CodeJamStringParser implements CodeJamInputParser { @Override public CodeJamInputCase readCase(BufferedReader input) { CodeJamInputCase inCase = null; try { inCase = new CodeJamStringCase(input.readLine()); } catch(IOException ex) { System.err.println(""Failed to read a test case!""); } return inCase; } } " B11777,"package qual; import java.util.HashSet; import java.util.Scanner; import java.util.Set; class RecycledPair { int a; int b; public RecycledPair(int a, int b) { super(); this.a = a; this.b = b; } @Override public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + (a + b); result = PRIME * result + (a + b); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final RecycledPair other = (RecycledPair) obj; if (a == other.a && b==other.b) return true; if (a == other.b && b==other.a) return true; return false; } } public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); in.nextLine(); for (int t = 0; t < T; t++) { String s = in.nextLine(); String[] limit = s.split("" ""); int A = Integer.parseInt(limit[0]); int B = Integer.parseInt(limit[1]); Set recycledPairsEncountered = new HashSet(); int count = 0; for (int i = A; i <= B; i++) { char[] num = String.valueOf(i).toCharArray(); for (int k = num.length - 1; k >= 1; k--) { String recycledNumber = """"; if (num[k] != '0') { int indx = k; while (indx < num.length) recycledNumber += num[indx++]; indx = 0; while (indx < k) recycledNumber += num[indx++]; } if (!recycledNumber.equals("""")) { int recycledNum = Integer.parseInt(recycledNumber); if (recycledNum != i && recycledNum <= B && recycledNum >= A) { RecycledPair r = new RecycledPair(i, recycledNum); if(recycledPairsEncountered.contains(r)==false) { recycledPairsEncountered.add(r); count++; } } } } } System.out.println(""Case #"" + (t + 1) + "":"" + "" "" + count); } } } " B12958,"package google.loader; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.List; public class ChallengeLoader { private List challenges; private final ChallengeReader reader; public ChallengeLoader(ChallengeReader reader){ this.reader = reader; } public List load(String aPath){ try{ String input = readFileAsString(aPath); readChallenges(input); return challenges; } catch(Exception e){ throw new RuntimeException(e); } } private String readFileAsString(String filePath) throws java.io.IOException{ byte[] buffer = new byte[(int) new File(filePath).length()]; BufferedInputStream f = null; try { f = new BufferedInputStream(new FileInputStream(filePath)); f.read(buffer); } finally { if (f != null) try { f.close(); } catch (IOException ignored) { } } return new String(buffer); } private void readChallenges(String input) { String delimiter; if(input.indexOf(""\r\n"")>0){ delimiter=""\r\n""; }else{ delimiter=""\n""; } String[] lines = input.split(delimiter); challenges = reader.createChallenges(lines); } public String getResult() { StringBuffer res = new StringBuffer(); for(Challenge challenge : challenges){ res.append(challenge.getResult()); } return res.toString(); } }" B10657," import java.io.*; import java.util.*; public class RecycledNumbers{ int nCases,aa,bb,recycled,savei; String listString = """"; int d=0; char c1,c2,c3; String a,b; ArrayList n=new ArrayList(); ArrayList m=new ArrayList(); List digits1 = new ArrayList(); List digits2 = new ArrayList(); int count=0; Integer i,j; Integer digitn[],digitm[]; Integer ia[]; public void recycle(){ try{ FileReader in = new FileReader(""E:/C-small-attempt0.in""); BufferedReader buff = new BufferedReader(in); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""E:/C-small-attempt0.out""))); nCases= Integer.parseInt(buff.readLine()); for (Integer counter = 0; counter < nCases; counter++) { String[] data = (buff.readLine()).split("" ""); a = data[0]; b = data[1]; System.out.println(a+"",""+b); if(a.length()==b.length()){ aa=Integer.parseInt(data[0]); bb=Integer.parseInt(data[1]); if(a.length()!=1 && b.length()!=1){ for(i=aa;i<=bb;i++){ //if(i==114){System.out.println(""wherererererere ""+i+j); } for( j=i+1;(j<=bb && j>i);j++){ //if(i==114){System.out.println(""--------------------- ""+i+j); } for(Integer o=0;o<(i.toString()).length();o++){ c3=(i.toString()).charAt(0); if(c3=='0') break; for(Integer k=0;k<(j.toString()).length();k++){ c1=(i.toString()).charAt(o); c2=(j.toString()).charAt(k); if( Character.getNumericValue(c1)== Character.getNumericValue(c2)){ count=count+1; if(i==114 && j==411){System.out.println(""count ""+count); } } } } if(count>=(i.toString()).length()){ savei=i; while (i>0 ) { digits1.add(0, i%10); i=i/10; } i=savei; for(int ro=0;ro unique = new HashSet(); String [] inputs; int A, B, k, mod, div, num; long res; for(int i = 1; i <= cases; i++){ inputs = reader.readLine().split("" ""); A = Integer.parseInt(inputs[0]); B = Integer.parseInt(inputs[1]); res = 0l; for(int j = A; j <= B; j++){ unique.clear(); k = j; int start = 10; while(k / start > 0){ mod = k % start; if(mod >= (start / 10)){ div = k / start; num = Integer.parseInt(mod + """" + div); if(num > j && num <= B){ unique.add(num); } } start *= 10; } res += unique.size(); } System.out.println(""Case "" + i + "" complete""); writer.println(""Case #"" + i + "": "" + res); } writer.flush(); } } " B12767," import java.util.*; public class C { public static void main (String[] args) { String bIn; Scanner in = new Scanner(System.in); int T = Integer.parseInt(in.nextLine()); for (int test = 0 ; test < T ; test++) { String range = in.nextLine(); String[] cIN = range.split("" ""); int max = Integer.parseInt(cIN[1]); int min = Integer.parseInt(cIN[0]); int count = 0; for (int findPair = min ; findPair <= max ; findPair ++) { String thisOne = String.valueOf(findPair); String[] gothrough = thisOne.split(""""); int digitLength = gothrough.length-1; int sameTest = Integer.parseInt(thisOne); // System.out.println(digitLength); for (int shuffle1 = 0 ; shuffle1 < digitLength ; shuffle1++) { String temp = thisOne.substring(shuffle1)+thisOne.substring(0,shuffle1); // System.out.println(temp); int test1 = Integer.parseInt(temp); if (test1 <= max && test1 >= min && test1 != sameTest) { // System.out.println(test1); // System.out.println(""( ""+thisOne+"",""+test1+"")""); count++; } } } count = count/2; System.out.println(""Case #""+(test+1)+"": ""+count); } } }" B11268,"package org.code.jam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.StringTokenizer; public class RecycledNumbers { public static void main(String[] args) { try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(""D:\\academics\\CodeJamWS\\C-small-attempt0.in""))); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(""D:\\academics\\CodeJamWS\\small-output.txt""))); String lineInput = in.readLine(); int counter = 1; Integer a,b; while( (lineInput = in.readLine()) != null) { // System.out.println(lineInput); // System.out.println(decodeInput(lineInput)); // out.write(""Case #"" + counter + "": "" + decodeInput(lineInput)); StringTokenizer tok = new StringTokenizer(lineInput,"" ""); a = Integer.valueOf(tok.nextToken()); b = Integer.valueOf(tok.nextToken()); // System.out.println(distinctRecyclables(a, b)); // distinctRecyclables(a, b); out.write(""Case #"" + counter + "": "" + distinctRecyclables(a, b)); // System.out.println(Integer.MAX_VALUE); out.newLine(); counter++; } in.close(); out.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static int distinctRecyclables(Integer a,Integer b) { int cnt = 0;; String comboString; ArrayList recyclablesCombo = new ArrayList(); if(String.valueOf(a).length() == 1) return 0; for(int i = a; i < b ; i++) { comboString = String.valueOf(i); for(int j = String.valueOf(i).length() - 1; j > 0 ; j--) { int origint = Integer.valueOf(comboString); int quotient = Integer.valueOf(comboString) / 10; int remainder = Integer.valueOf(comboString) % 10; comboString = """" + remainder + quotient; int permutedint = Integer.valueOf(comboString); if(remainder != 0 && permutedint <= b && permutedint >= a && permutedint != i && permutedint != origint && !(recyclablesCombo.contains(permutedint + "","" + i) || recyclablesCombo.contains(i + "","" + permutedint))) { if(i < permutedint) recyclablesCombo.add(i + "","" + permutedint); else recyclablesCombo.add(i + "","" + origint); if(origint == i) cnt++; } } } System.out.println(recyclablesCombo.size()); /*for(int i = 0; i < recyclablesCombo.size(); i++) System.out.println(recyclablesCombo.get(i));*/ return recyclablesCombo.size(); } } " B10053," import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Recycle2 { /** * @param args */ public static void main(String[] args) throws Exception { Scanner in = new Scanner(new BufferedReader(new FileReader(""/Users/sunny/Desktop/C-small-attempt0.in""))); PrintWriter out=new PrintWriter(new FileWriter(""/Users/sunny/Desktop/1.out"")); int n = in.nextInt(); String i1, i2, line ; for( int i = 1 ; i <= n ; i++){ i1 = in.next() ; i2 = in.next() ; line = ""Case #""+i+"": ""+findN(i1, i2); System.out.println(line); out.println(line); } out.close() ; } private static int findN(String i1, String i2) { Integer n = new Integer(i1), m = new Integer(i2); int count = 0 ; for(int i = n ; i <= m ; i++) { count += getRotateCount(i+"""", n, m); } return count/2; } private static int getRotateCount(String x, int n, int m) { Set pairs = new HashSet(); int j, count=0, xI = Integer.parseInt(x); for(int i=1 ; i < x.length() ; i++ ) { j = Integer.parseInt(x.substring(i)+x.substring(0,i)); if(j <= m && j >=n && j !=xI ) { if(!pairs.contains(xI+""-""+j)) { pairs.add(xI+""-""+j); count++; } } } return count ; } } " B11448,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class RecycledNumbers { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(args[0])); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(args[0]+"".out""))); String l = in.readLine(); int N = Integer.parseInt(l); int i=1; while((l=in.readLine())!= null) { int cnt = 0; String[] ll = l.split("" ""); out.print(""Case #""+i+++"": ""); int A = Integer.parseInt(ll[0]); int B = Integer.parseInt(ll[1]); for(int n=A;n> testCaseList; private Solution solution; /** * Return the solution * * @return Solution */ public Solution getSolution() { return solution; } /** * Set the solution used for test cases * * @param solution Solution */ public void setSolution(Solution solution) { this.solution = solution; } /** * Return the result collector * * @return ResultCollector */ public ResultCollector getResultCollector() { return resultCollector; } /** * Set the result collector * * @param resultCollector ResultCollector */ public void setResultCollector(ResultCollector resultCollector) { this.resultCollector = resultCollector; } /** * Return the index of list * * @return int The index of list */ public int getIndexOfList() { return indexOfList; } /** * Set the index of list * * @param indexOfList int The index of list */ public void setIndexOfList(int indexOfList) { this.indexOfList = indexOfList; } /** * Set the list of test cases * * @param testCaseList List> */ public void setTestCaseList(List> testCaseList) { this.testCaseList = testCaseList; logger.debug(""Total "" + testCaseList.size() + "" test cases have been added""); } /** * Get the list of test cases * * @return List> The list of test cases */ public List> getTestCaseList() { return this.testCaseList; } public abstract void run(); } " B11581,"package pl.helman.codejam.recycled; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; //Brute force attempt public class Recycled { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { FileReader fr = new FileReader(""d:\\recycled.in""); BufferedReader br = new BufferedReader(fr); String s = br.readLine(); FileWriter f0 = new FileWriter(""d:\\recycled.out""); int t = Integer.parseInt(s.trim()); for (int i = 1; i <= t; i++) { s = br.readLine(); String[] elems = s.split("" ""); int a = Integer.parseInt(elems[0]); int b = Integer.parseInt(elems[1]); int digs = 1; int mod = 1; int ret = 0; while (a >= mod * 10) { digs++; mod *= 10; } for (int n = a; n <= b; n++) { // System.out.println("" n:""+n); int m = n; m = (m % mod) * 10 + (m / mod); while (m != n) { // System.out.print("" m:"" + m); if (m > n && m <= b) { ret++; // System.out.print("" +""); } // System.out.println(); m = (m % mod) * 10 + (m / mod); } } System.out.println(""Case #"" + i + "": "" + ret); // System.out.println(); f0.write(""Case #"" + i + "": "" + ret + ""\r\n""); } fr.close(); f0.close(); } } " B10276," import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * * @author Mody */ public class c { public static void main(String[] args) throws FileNotFoundException, IOException { // BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); BufferedReader in = new BufferedReader(new FileReader(""C-small-attempt0.in"")); FileWriter out= new FileWriter(""sol.out""); int t = Integer.parseInt(in.readLine()); StringTokenizer st; int a, b ; int ret=0; String s1="""",s2=""""; for (int i = 0; i < t; i++) { st=new StringTokenizer(in.readLine()); a=Integer.parseInt(st.nextToken()); b=Integer.parseInt(st.nextToken()); ret=0; for (int j = a; j <=b; j++) { for (int k = j+1; k <=b; k++) { s1=j+""""; s2=k+""""; if(s1.length()!=s2.length()) break; ret+=is(s1,s2); } } out.write(""Case #""+(i+1)+"": ""+ret); if(i!=t-1) out.write(""\n""); } out.close(); } private static int is(String s1, String s2) { String s,ss; if(s1.length()==2) if(s1.charAt(0)==s2.charAt(1)&&s1.charAt(1)==s2.charAt(0)) return 1; for (int i = 1; i < s1.length(); i++) { s=s1.substring(0,i); ss=s1.substring(i,s1.length()); if(!s.equals("""")&&!ss.equals("""")) if(s2.endsWith(s)&&s2.startsWith(ss)){ return 1; } } return 0; } } " B11392,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author root */ public class Recycled { public static void main(String args[]) { int T; ArrayList a = reader(""c:\\inp.in""); ArrayList out = new ArrayList(); String st = (String) a.get(0); T = Integer.parseInt(st); int ans; int i1, i2; for (int i = 0; i < T; i++) { st = (String) a.get(i + 1); Scanner sc = new Scanner(st); i1 = sc.nextInt(); i2 = sc.nextInt(); ans = findNoOfRecycle(i1, i2); out.add(ans); } writer(""c:\\output.txt"", out); } public static ArrayList reader(String filename) { FileInputStream fis = null; ArrayList a = new ArrayList(); String line = """"; try { fis = new FileInputStream(filename); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); while ((line = br.readLine()) != null) { a.add(line); } } catch (IOException ex) { } finally { try { fis.close(); } catch (IOException ex) { } } return a; } private static int findNoOfRecycle(int a, int b) { HashSet done = new HashSet(); int noOfMatches = 0, l, localmatches = 0; String sb, sbs, sbe; sbs = Integer.toString(a); sbe = Integer.toString(b); for (int i = a; i <= b; i++) { if (!done.contains(i)) { sb = Integer.toString(i); localmatches = 0; l = sb.length(); boolean flag = true; for (int k = 0; k < l - 1; k++) { if (sb.charAt(k) != sb.charAt(k + 1)) { flag = false; k = l; } } if (!flag) { for (int j = 0; j < l - 1; j++) { sb = sb.charAt(l - 1) + sb.substring(0, l - 1); if(sb.charAt(0)!='0') if (sb.compareTo(sbs) >= 0 && sb.compareTo(sbe) <= 0) { done.add(Integer.parseInt(sb)); localmatches++; } } } noOfMatches = noOfMatches + (localmatches * (localmatches + 1)) / 2; } } return noOfMatches; } private static void writer(String file, ArrayList out) { FileOutputStream fos = null; try { fos = new FileOutputStream(file); for (int i = 0; i < out.size(); i++) { try { String output = ""Case #"" + Integer.toString(i + 1) + "": "" + out.get(i) + ""\n""; fos.write(output.getBytes()); System.out.print(output); } catch (IOException ex) { Logger.getLogger(BotTrust.class.getName()).log(Level.SEVERE, null, ex); } } } catch (FileNotFoundException ex) { } finally { try { fos.close(); } catch (IOException ex) { } } } } " B11021,"package org.moriraaca.codejam.recyclednumbers; import java.util.HashSet; import org.moriraaca.codejam.AbstractSolver; import org.moriraaca.codejam.OutputDestination; import org.moriraaca.codejam.SolverConfiguration; @SolverConfiguration(parser = RecycledNumberDataParser.class, inputFileName = ""ultra-large.in"", outputDestination=OutputDestination.FILE) public class RecycledNumbersSolver extends AbstractSolver { public static void main(String[] args) { new RecycledNumbersSolver().getSolution(); } private int digitsNumber; private int headShift; private HashSet usedNumbers = new HashSet(); @Override protected String solveTestCase(RecycledNumbersTestCase testCase) { int counter = 0; digitsNumber = String.valueOf(testCase.A).length(); headShift = 1; for (int i = 0; i < digitsNumber; i++) { headShift *= 10; } for (int i = testCase.A; i <= testCase.B; i++) { counter += rotateNumber(i, testCase.B); } return String.valueOf(counter); } private int rotateNumber(int number, int B) { int counter = 0; int orginalNumber = number; usedNumbers.clear(); for(int i = 1; i < digitsNumber; i++) { number += (number % 10) * headShift; number /= 10; if (number > orginalNumber && number < B && !usedNumbers.contains(number)) { counter++; usedNumbers.add(number); } } return counter; } } " B12969,"public class A { public static void main(String[] a) { //System.out.println(a(1,9)); //System.out.println(a(10,40)); //System.out.println(a(100,500)); //System.out.println(a(1111,2222)); java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); int i=0; String line = null; try { while((line=reader.readLine())!=null) { if(i>0) { System.out.println(""Case #""+i+"": ""+parseLine(line)); } i++; } } catch(Exception e) {} } static int parseLine(String line) { String p[] = line.split("" ""); return a(Integer.valueOf(p[0]), Integer.valueOf(p[1])); } public static int a(int a, int b) { if(a>=b) return 0; if(b<10) return 0; //1 digit. return 0 java.util.HashMap map = new java.util.HashMap(); int count=0; for(int i=a;i<=b;i++) { String x = String.valueOf(i); for(int j=1; j { public V apply(P param1, Q param2); } " B12129,"import java.util.HashSet; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner oku = new Scanner(System.in); int test = oku.nextInt(), A = oku.nextInt(), B = oku.nextInt(), dijit = Integer.toString(A).length(), sayimiz = 0; HashSet eleme; for (int i = 0; i < test; i++, A = oku.nextInt(), B = oku.nextInt(), sayimiz = 0) { dijit = Integer.toString(A).length(); for (int j = A; j < B; j++) { eleme = new HashSet(); for (int k = 1; k < dijit; k++) { int saga_kayan = j / (int) Math.pow(10, k); int sola_kayan = (j % (int) Math.pow(10, k) * (int) Math.pow(10, dijit - k)); int son = saga_kayan + sola_kayan; if (son <= B && j < son) { eleme.add(son); } } sayimiz += eleme.size(); } System.out.println(""Case #"" + (i + 1) + "": "" + sayimiz); } } }" B10714,"import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.Scanner; public class ProblemC { public static void main(String[] args) throws FileNotFoundException { PrintStream out = new PrintStream(new FileOutputStream(new File( ""c-small.out""))); Scanner in = new Scanner(new File(""C-small-attempt0.in"")); int T = in.nextInt(); for (int i = 1; i <= T; i++) { int A = in.nextInt(); int B = in.nextInt(); int count = 0; for(int n = A; n <= B; n++){ String origstr = Integer.valueOf(n).toString(); String str = shift(origstr);; while(!str.equals(origstr)){ int shifted = Integer.parseInt(str); //System.out.printf(""n: %d, shift: %s, shifted: %d, valid: %b\n"", n, str, shifted, shifted > n); if(shifted > n && shifted <= B) count++; str = shift(str); } } out.printf(""Case #%d: %d\n"", i, count); } in.close(); out.close(); } public static String shift(String num){ return num.charAt(num.length()-1) + num.substring(0,num.length()-1); } } " B10040,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.*; /** * * @author Joydeep */ public class J3 { public static void main(String[] args) throws IOException{ String test = ""150""; DataInputStream ds = new DataInputStream(new FileInputStream(""d:/C-small-attempt0.in"")); Writer os = new BufferedWriter(new FileWriter(""d:/output.txt"")); int N = Integer.parseInt(ds.readLine()); for(int i = 1;i<=N;i++) { int A=0,B=0,l,counter=0,n,m,pairs=0; String temp=""""; String output=""Case #""+i+"": ""; String AB = ds.readLine()+"" ""; l = AB.length(); for(int j = 0;jn && num<=B) { int flag = 0; for(int y = 0 ;y results=new HashSet(); for(int i=length-1;i>0;i--) { if(valString.charAt(i)!='0') { String after =valString.substring(i); String before=valString.substring(0,i); int inverse=Integer.parseInt( after+before ); if(inverse<=maxVal && val hs= new HashSet(); private int reclycled(int n) { int m, count= 0; for (int i=1; in && m<=B && hs.add(m)) { ++count; // System.out.printf(""%d -> %d\n"", n, m); } } hs.clear(); return count; } public void solve() throws IOException { int i,j,k; String s; int MODE= SMALL; br = new BufferedReader (new FileReader(""C""+infile[MODE])); out = new PrintWriter(new BufferedWriter(new FileWriter(""C""+outfile[MODE]))); int C= Integer.valueOf(br.readLine()); for (int c=1; c<=C; c++) { // read tok= getTok(); A= toInt(tok[0]); B= toInt(tok[1]); cn= tok[0].length(); // output out.printf(""Case #%d: %d\n"", c, answer()); } out.close(); } public static void main(String[] args) throws IOException { new C().solve(); } } " B13082,"package qualification; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { static final int MAX = 3000; static Set dic[] = new HashSet[MAX]; public static void main(String[] args) { for (int i = 1; i < MAX; i++) { dic[i] = new HashSet(); String s = i + """"; for (int j = 1; j < s.length(); j++) { String a = s.substring(0, j); String b = s.substring(j); String c = b + a; if (c.charAt(0) == '0') { continue; } int p = Integer.parseInt(c); if (p > i) { dic[i].add(p); } } } try { Scanner scanner = new Scanner(System.in); int lp = scanner.nextInt(); for (int loop = 0; loop < lp; loop++) { int ans = 0; int A = scanner.nextInt(); int B = scanner.nextInt(); for (int i = A; i < B; i++) { for (Integer j : dic[i]) { if (j <= B) { ans++; } } } System.out.println(""Case #"" + (loop + 1) + "": "" + ans); } } catch (Exception e) { e.printStackTrace(); } } } " B12228,"import java.io.*; import java.util.*; public class test { public static void main(String[] args) throws IOException { // Location of file to read functions aa = new functions(); File file = new File(""input.txt""); Writer output = new BufferedWriter(new FileWriter(""output.txt"")); int i = 1; int answer = 0; String A = """"; String B = """"; int j = 0; int n = 0; try { Scanner scanner = new Scanner(file); n = Integer.parseInt((String)scanner.nextLine()); while (scanner.hasNextLine()) { A = """"; B = """"; String line = scanner.nextLine(); while(line.charAt(j) != ' '){ A = A + line.charAt(j); j++; } j++; while(j < line.length()){ B = B + line.charAt(j); j++; } j = 0; answer = aa.solve(A,B); if(i < n) output.write(""Case #"" + i +"": ""+ answer +""\n""); else output.write(""Case #"" + i +"": ""+ answer); i++; } scanner.close(); output.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } } " B10924,"package utils; /** * * @author Fabien Renaud */ public abstract class JamCase implements Runnable, JamCaseSolver { protected final int number; protected String result; private final StopWatch timer; private final Jam parent; protected JamCase(Jam parent, int number) { this.parent = parent; this.number = number; this.timer = new StopWatch(); } public final int getNumber() { return number; } public final String getResult() { return result; } public final StopWatch getTimer() { return timer; } @Override public final void run() { timer.start(); parse(); solve(); if (parent != null) { parent.appendOutput(number, result); } timer.stop(); } }" B13057,"package codejam20120413; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.*; public class C { int digits(int in) { int count=0; for (;(in=in/10)>0; count++); return count; } int shift(int in, int mag) { return mag*(in%10) + in/10; } void run()throws IOException{ BufferedReader bf = new BufferedReader(new FileReader(""C.in"")); PrintWriter pw = new PrintWriter(new FileWriter(""C.out"")); int cases = Integer.parseInt(bf.readLine()); for (int i=0; i set = new HashSet(); for (int k = 0; k < digits; k++) { int shift = shift(in, mag); if (shift>j && shift <= to) { if (!set.contains(shift)) { set.add(shift); count++; } } in=shift; } } pw.write(""Case #""+ (i+1) + "": ""+ count + ""\n""); } pw.close(); } public static void main(String[] args)throws IOException { new C().run(); } } " B12802,"import java.io.*; import java.util.*; public class PairList{ public ArrayList pairs; public PairList(){ pairs= new ArrayList(); } public void addP(int i, Pair pair){ pairs.add(i,pair); } public int Find (Pair pair,int big){ int ena=pair.first; int dyo=pair.second; int length=pairs.size(); Pair temp; int ret=0; int k=0; if(length==0){ ret=0; } else{ for(k =0; kpair.first){ ret=k; } } if(k==length-1) ret=k+1; } return(ret); } } " B12001,"import java.io.*; import java.util.*; public class ProblemC { Set recycled = new TreeSet(); int count = 0; FileWriter fstream; BufferedWriter out; public static void main(String[] args) throws IOException { ProblemC p = new ProblemC(); p.fstream = new FileWriter(""outC.txt""); p.out = new BufferedWriter(p.fstream); p.readFile(""C-small-attempt0.in""); p.out.close(); } public void readFile(String filePath) { String[] result = null; try { FileReader input = new FileReader(filePath); BufferedReader bufRead = new BufferedReader(input); Scanner scan = new Scanner(input); this.count = scan.nextInt(); for (int i = 0; i < count; i++) { int a = scan.nextInt(); int b = scan.nextInt(); out.write(""Case #""+(i+1)+"": ""+calculate(a, b)); if (i= a) && (value != i) && (!recycled.contains(Long.parseLong(num+newNum))) && (!recycled.contains(Long.parseLong(newNum+num)))) { recycled.add(Long.parseLong(num + newNum)); recycled.add(Long.parseLong(num+newNum)); count++; } } } } System.out.println(count); return count; } } " B12596,"package info.zhenhua.codejam; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.util.Arrays; abstract class RecycledNumbersSolver { protected String inputFileName; String outputFileName = null; PrintStream ps = null; public final static String smallInput = ""-small-practice.in""; public final static String bigInput = ""-large-practice.in""; public final static String smallOutput = ""-small-practice.out""; public final static String bigOutput = ""-large-practice.out""; public final static String smallContestInput = ""-small-attempt0.in""; public final static String bigContestInput = ""-large.in""; public final static String smallContestOutput = ""-small-attempt0.out""; public final static String bigContestOutput = ""-large.out""; protected String fileNamePrefix = null; public RecycledNumbersSolver(String inputFileName, String outputFileName, String fileNamePrefix) { this.inputFileName = inputFileName; this.outputFileName = outputFileName; this.fileNamePrefix = fileNamePrefix; } public String getInputFileName() { return fileNamePrefix + inputFileName; } public void setInputFileName(String inputFileName) { this.inputFileName = inputFileName; } public String getOutputFileName() { return fileNamePrefix + outputFileName; } public void setOutputFileName(String outputFileName) { this.outputFileName = outputFileName; } abstract protected void solveAll() throws IOException; protected void printOutput (String result) throws FileNotFoundException { if (ps == null) { if (this.getOutputFileName() == null) ps = new PrintStream(System.out); else ps = new PrintStream(this.getOutputFileName()); } ps.println(result); } } /** * @author zhguo * */ public class RecycledNumbers extends RecycledNumbersSolver { public RecycledNumbers(String inputFileName, String outputFileName) { super(inputFileName, outputFileName, ""C""); } /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { RecycledNumbers recycledNumbers = new RecycledNumbers(smallContestInput, smallContestOutput); recycledNumbers.solveAll(); } @Override protected void solveAll() throws IOException { BufferedReader br = new BufferedReader(new FileReader(getInputFileName())); String line = br.readLine(); int testcases = Integer.valueOf(line); for (int j = 1; j <= testcases; ++j) { line = br.readLine(); String[] parts = line.split("" ""); int min = Integer.valueOf(parts[0]); int max = Integer.valueOf(parts[1]); long result = solveOneTestCase(min, max); printOutput(""Case #"" + j + "": "" + result); } br.close(); if (ps != null) ps.close(); } static final int MAX = 2000000; boolean[] visited = new boolean[MAX + 1]; private long solveOneTestCase(int min, int max) { StringBuilder sb = new StringBuilder(); long nums = 0; for (int i = min; i <= max; ++i) { Arrays.fill(visited, false); sb.replace(0, sb.length(), String.format(""%d%d"", i, i)); int len = sb.length() / 2; for (int j = 1; j < len; ++j) { int num = Integer.valueOf(sb.substring(j, j + len)); if (num > max || num <= i || visited[num]) continue; visited[num] = true; ++nums; } } return nums; } } " B10476,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class ProblemC { ProblemC() throws IOException { Scanner reader = new Scanner(new File(""input.txt"")); BufferedWriter writer = new BufferedWriter(new FileWriter(""output.txt"")); int cases = reader.nextInt(); for(int i = 1; i <= cases; i++) { int A = reader.nextInt(); int B = reader.nextInt(); int mask = (int)Math.pow(10, (int)Math.log10(A)); int count = 0; for(int j = A; j < B; j++) { int num = (j%mask)*10+j/mask; while(num!=j) { if(num>j && num <= B) ++count; num = (num%mask)*10+num/mask; } } writer.write(""Case #""+i+"": ""+count); writer.newLine(); } reader.close(); writer.close(); } public static void main(String[] args) throws IOException { new ProblemC(); } } " B10321,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; public class RecycledNumbers { public static void main(String args[]) throws IOException{ String inputFile = args[0]; String outputFile = args[1]; BufferedReader input = new BufferedReader(new FileReader(inputFile)); PrintWriter output = new PrintWriter(outputFile); int testcases = Integer.valueOf(input.readLine()); int testcase = 0; while (testcase++ < testcases) { int result = 0; String newline = input.readLine(); String tokens[] = newline.split("" ""); long A = Long.valueOf(tokens[0]); long B = Long.valueOf(tokens[1]); int digit = 1; long baseAndMask = 10; long dummyA = A; while ((dummyA = dummyA / 10) > 0) { digit++; baseAndMask *= 10; } long i; for (i = A; i < B; i++) { int k = digit; long recycled = i * baseAndMask + i; while (k-- > 0) { long j = recycled % baseAndMask; if (j <= B && j > i) { result++; } recycled = recycled / 10; } } output.printf(""Case #%d: %d\n"", testcase, result); } output.close(); } } " B12877,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.Arrays; public class C { BufferedReader in; BufferedWriter out; static String inputFile = ""C.in""; static String outputFile = ""C.out""; public Boolean recycled(int n, int m) { Boolean result = false; String mString = Integer.toString(m); String nString = Integer.toString(n); String temp; int nlen = nString.length(); int mlen = mString.length(); for (int a = 0; a < (mlen-nlen); a++) { nString = ""0"" + nString; } for (int i = 1; i < mlen; i++) { temp = switcher(nString,i); if (temp.equals(mString)) result = true; } return result; } public String switcher(String str, int a) { int len = str.length(); StringBuilder builder = new StringBuilder(); builder.append(str.substring(len-a, len)); builder.append(str.substring(0,len-a)); return builder.toString(); } public String readWord() throws Exception { int c = in.read(); while (c>=0 && c<=' ') { c = in.read(); } if (c < 0) { return """"; } StringBuilder builder = new StringBuilder(); while( c > ' ' ) { builder.append((char)c); c = in.read(); } return builder.toString(); } public void solve() throws Exception { int cases = Integer.parseInt(readWord()); for (int i = 0; i implements Iterable> { public interface CallableFactory { public Callable newInstance(I input); } private ExecutorService threadPool; private LinkedBlockingQueue> workQueue; private Future poisonPill = null; public ParallelWorkQueue(final int numThreads, final Iterable inputs, final CallableFactory callableFactory) { threadPool = Executors.newFixedThreadPool(numThreads); // Keep a max of (100x the number of threads) items in the work queue at a time workQueue = new LinkedBlockingQueue<>(numThreads * 100); // Create work-producer thread new Thread() { public void run() { try { for (final I input : inputs) workQueue.put(threadPool.submit(callableFactory.newInstance(input))); // poisonPill was null until now, and null can never be put in the queue, so // the barrier can't be triggered. Now set poisonPill to another value that it // can only attain once, a NOP work unit. workQueue.put(poisonPill = threadPool.submit(new Callable() { @Override public O call() throws Exception { return null; } })); // Shut down threads after last callable invoked threadPool.shutdown(); } catch (InterruptedException e) { throw new RuntimeException(e); } }; }.start(); } @Override public Iterator> iterator() { return new Iterator>() { Future next = null; boolean nextConsumed = true; @Override public boolean hasNext() { if (nextConsumed) { try { next = workQueue.take(); } catch (InterruptedException e) { throw new RuntimeException(e); } nextConsumed = false; } // Check for poison pill if (next == poisonPill) { try { // Get result of poison pill Future so thread exits next.get(); } catch (Exception e) { throw new RuntimeException(e); } return false; // at end } else { return true; } } @Override public Future next() { if (nextConsumed) throw new RuntimeException(""Can't call next() twice without calling hasNext()""); nextConsumed = true; return next; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } /** * Return an Iterable that iterates from 0 to n-1 inclusive. Can be * passed into the ""inputs"" parameter of ParallelWorkQueue. */ public static Iterable makeIntRangeIterable(final int n) { return new Iterable() { private final int max = n; @Override public Iterator iterator() { return new Iterator() { int num = 0; @Override public boolean hasNext() { return num < max; } @Override public Integer next() { return num++; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; } } " B11803,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam.qualification.recyclednumbers; import java.util.HashSet; import java.util.List; import java.util.Set; import util.BaseResolver; import util.Util; /** * * @author bohmd */ public class RecycledNumbers extends BaseResolver { int cases; public static void main(String[] args) throws Exception { if (args.length == 0 || args[0].equals("""")) { throw new Exception(""The first parameter must be the input file name without extension.""); } else { new RecycledNumbers(args[0]).resolve(); } } public RecycledNumbers(String file) { super(file); } @Override protected void executeLine(String line) throws Exception { if (getLineNum() == 0) { cases = Util.getInt(line); } else { List lineCase = Util.getIntList(line); write(resolveCase(lineCase.get(0), lineCase.get(1))); } } protected String resolveCase(int min, int max) { Set pairSet= new HashSet(); for(int i=min; i<=max; i++) { String n = i+""""; for(int j=0; ji && mInt<=max) { pairSet.add(new Pair(i, mInt)); } } } return "" ""+pairSet.size(); } private class Pair { int m; int n; public Pair(int n, int m) { this.m = m; this.n = n; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Pair other = (Pair) obj; return (this.n == other.n && this.m == other.m) || (this.n == other.m && this.m == other.n); } @Override public int hashCode() { int hash = 7; hash = 11 * hash + this.m + this.n; return hash; } } } " B10152,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.ListIterator; import java.util.Scanner; public class RecycledNumbers { /** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { // TODO Auto-generated method stub //System.setOut(new PrintStream(new File(""RecycledNumbers.txt""))); Scanner scanner = new Scanner(System.in); int testcasenum = Integer.valueOf(scanner.next()); scanner.nextLine(); for (int testcase = 0; testcase < testcasenum; testcase++) { System.out.print(""Case #""); System.out.print(testcase+1); System.out.print("": ""); int from = scanner.nextInt(); int to = scanner.nextInt(); int count = 0; boolean table[] = new boolean[to+1]; for (int num = from; num <= to; num++) { if (!table[num]){ int len = String.valueOf(num).length(); int shift = num; table[num] = true; int pair = 1; for (int i = 0;i < len-1;i++){ shift = shiftLeft(shift, len); if (shift >= from && shift <= to&& !table[shift]){ pair++; table[shift] = true; } } count += pair*(pair-1)/2; } } System.out.println(count); } } public static int shiftLeft(int num, int len) { int digit = num % 10; num = num / 10; return num += Math.pow(10, len-1)*digit; } public static int getUniqueDigits(int num){ boolean digits[] = new boolean[10]; while (num != 0) { int digit = (num % 10); digits[digit] = true; num = num / 10; } int count = 0; for (int i = 0;i < 10;i++){ count += digits[i]?1:0; } return count; } } " B12341,"import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; public class C { static ArrayList[] list; static long[] ten; static int limit; public static void main(String[] args) throws IOException { initializeTens(); initializeList(); System.out.println(""initialized""); Scanner in = new Scanner(new FileReader(""input.in"")); BufferedWriter bw = new BufferedWriter(new FileWriter(""output"")); int T = in.nextInt(), start, end; for(int i = 1; i <= T; i++) { start = in.nextInt(); end = in.nextInt(); int ans = cntPairs(start, end); bw.write(""Case #"" + i + "": "" + ans); bw.newLine(); } bw.close(); System.out.println(""end""); } private static int cntPairs(int start, int end) { int cnt = 0; boolean[] v = new boolean[end+1]; for(int i = start; i <= end; i++) if(list[i] != null && !v[i]) { v[i] = true; for(int k : list[i]) if((k >= start && k <= end) && !v[k]){ cnt++; } } return cnt; } private static void getPairs(int n) { ArrayList ans = new ArrayList(); ans.add(n); int len = getLength(n); for (int i = 1; i < len; i++) { long num = n * ten[i]; num = num + n / ten[len - i]; num = num % ten[len]; int res = (int)num; if(res < limit && !ans.contains(res) && len == getLength(res)) ans.add(res); } if (ans.size() > 1) for (int k : ans) list[k] = ans; } public static int getLength(int n){ return (int) (Math.log10(n) + 1e-6) + 1; } private static void initializeList() { int start = 1, end = 2000001; limit = end; list = new ArrayList[end]; for (int i = start; i < end; i++) if (list[i] == null) getPairs(i); } private static void initializeTens() { ten = new long[8]; ten[1] = 10; for (int i = 2; i < ten.length; i++) ten[i] = 10 * ten[i - 1]; } } " B11476,"import java.util.Scanner; import java.io.*; public class Google2 { public static void main(String[] args) throws IOException { Scanner kb = new Scanner(new File(""c:/A-small-attempt0.in"")); // Scanner kb = new Scanner(System.in); int num = kb.nextInt(); for (int i = 0; i < num; i++) { int a = kb.nextInt(); int b = kb.nextInt(); int count = 0; for (int j = a; j < b; j++) { for (int k = j + 1; k <= b; k++) { //System.out.println(""++++ ""+j + "" "" + k + "" ""); if (isRecycled(j, k)) { count++; //System.out.print(count); } //System.out.println(); } } System.out.println(""Case #"" + (i + 1) + "": "" + count); } } public static boolean isRecycled(int a, int b) { String n = a + """"; String m = b + """"; int numLength = n.length(); for (int i = 1; i < numLength; i++) { if (n.substring(0, i).equals(m.substring(numLength - i, numLength)) && n.substring(i, numLength).equals(m.substring(0, numLength - i))) { //System.out.println("" true""); return true; } } return false; } } " B11306,"/** * Copyright 2012 Christopher Schmitz. All Rights Reserved. */ package com.isotopeent.codejam.lib.converters; import com.isotopeent.codejam.lib.InputConverter; import com.isotopeent.codejam.lib.Utils; public class IntArrayLine implements InputConverter { private int length; private int[] input; private int[] inputBuffer; /** * fixed length arrays */ public IntArrayLine(int length) { this.length = length; } /** * dynamic length arrays */ public IntArrayLine(int[] buffer) { inputBuffer = buffer; } @Override public boolean readLine(String data) { if (length > 0) { input = new int[length]; input = Utils.convertToIntArray(data, length); } else { int count = Utils.convertToIntArray(data, inputBuffer); input = new int[count]; System.arraycopy(inputBuffer, 0, input, 0, count); } return false; } @Override public int[] generateObject() { return input; } } " B11001,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Map; import java.util.HashMap; import java.util.Iterator; public class Hw3 { public static int calNum(int n1, int n2){ int num = 0; int i =0; for( i=n1; i<=n2; i++){ String t = Integer.toString(i); int len = t.length(); String shitString = t; //System.out.println(""Origin ""+ t); for(int tt=1; tti && tmpNum>=n1 && tmpNum<=n2) num++; } } return num; } public static void main(String[] args) throws IOException { //String line, ArrayList sTree, FileReader reader = new FileReader(""/Users/leyu/Desktop/C.in""); BufferedReader br = new BufferedReader(reader); String s1 = """"; int count = 0; // // Map triMap = new HashMap(); // Map mp0 = new HashMap(); // Map mpLine = new HashMap(); // int num = 0; s1 = br.readLine(); count = Integer.parseInt(s1); for( int i = 0; i exist = new HashSet(); String[] splitResult = input.split("" ""); int numberA = Integer.parseInt(splitResult[0]); int numberB = Integer.parseInt(splitResult[1]); for(int i = numberA; i < numberB; i++){ int current = i; exist.clear(); int length1 = String.valueOf(current).length(); int j = 10; while(j<=current){ int remain = current%j; int length2 = String.valueOf(j).length(); double b = Math.pow(10, length2-1); double a = Math.pow(10,length1); int currentResult = (int)(remain*a/b+current/j); if(current == 2022){ System.out.println(remain+"":""+(length2-1)+"":""+currentResult); } if(currentResult <= numberB && currentResult > current){ if(!exist.contains(currentResult)){ exist.add(currentResult); resultInt++; } } j = j*10; } } return """"+resultInt; } public static void readFile() throws IOException{ FileWriter fstream = new FileWriter(""out.txt""); BufferedWriter out = new BufferedWriter(fstream); FileReader input = new FileReader(""in.txt""); BufferedReader bufRead = new BufferedReader(input); String line = bufRead.readLine(); String current = getResult(line); int i = 1; out.write(""Case #"" + i + "": "" + current); line = bufRead.readLine(); while (line != null){ i++; out.write('\n' + ""Case #"" + i + "": "" + getResult(line)); line = bufRead.readLine(); } bufRead.close(); out.close(); } } " B12475,"package codejam.recyclednumbers; public class RecycledNumbersProblem { private int minValue; private int maxValue; public RecycledNumbersProblem(String problemAsString) { String[] split = problemAsString.split("" ""); minValue = Integer.parseInt(split[0]); maxValue = Integer.parseInt(split[1]); } public int solve() { int result = 0; DigitsArray minValueDigitsArray = new DigitsArray(minValue); DigitsArray maxValueDigitsArray = new DigitsArray(maxValue); for (int i = 0; i <= maxValue - minValue; i++) { DigitsArray toTest = new DigitsArray(minValue + i); result += toTest.numberRecycles(minValueDigitsArray, maxValueDigitsArray); } return result; } } " B12224,"package codejam; import java.util.HashSet; import java.util.Scanner; public class Qual2012C { private static int digitCount; private static int[] MULTIPLES = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000 }; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int nrOfTestCases = scanner.nextInt(); for (int caseNr = 1; caseNr <= nrOfTestCases; caseNr++) { int a = scanner.nextInt(); int b = scanner.nextInt(); digitCount = digitCount(a); System.out.println(""Case #"" + caseNr + "": "" + solve(a, b)); } } private static int digitCount(int a) { if (a == 0) return 0; return 1 + digitCount(a / 10); } private static long solve(int min, int max) { long total = 0; for (int n = min; n < max; n++) total += pairsFor(n, max); return total; } private static int pairsFor(int n, int max) { if (n >= max) return 0; HashSet set = new HashSet(); for (int i = 1; i < digitCount; i++) { int multipleSplit = MULTIPLES[i]; int tail = n % multipleSplit; if (tail < MULTIPLES[i - 1]) continue; int m = tail * MULTIPLES[digitCount - i] + (n / multipleSplit); if (n < m && m <= max) set.add(m); } return set.size(); } } " B12392,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Set; public class Prob3 { public static int calc(int n1, int n2){ Set set = new HashSet(); int c=0; for(;n1<=n2;n1++){ String sn = """"+n1; Set tested = new HashSet(); for(int i=0;i=n1 && s2<=n2){ c++; }else{ set.add(s); } } } return c; } public static void main(String[] args) { try{ FileInputStream fstream = new FileInputStream(""C-small-attempt2.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; FileWriter fstream1 = new FileWriter(""C-small-attempt2.out""); BufferedWriter out = new BufferedWriter(fstream1); // out.write(""Hello Java""); //Close the output stream long l = Long.parseLong(br.readLine()); for(long i=0; i numbers=new LinkedList<>(); for (int i = lower; i <= upper; i++) { number = Integer.toString(i); numbers.clear(); for (int j = 1; j < number.length(); j++) { newNumber = (String) number.subSequence(j, number.length()); newNumber += (String) number.subSequence(0, j); if (!newNumber.startsWith(""0"") && !newNumber.equals(number) && !numbers.contains(newNumber)) { nn = Integer.parseInt(newNumber); numbers.add(newNumber); if (nn >= lower && nn <= upper && nn>i) { result++; } } } } return result; } } " B12071,"package jp.funnything.competition.util; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; public class Packer { private static void add( final ZipArchiveOutputStream out , final File file , final int pathPrefix ) { if ( file.isDirectory() ) { final File[] children = file.listFiles(); if ( children.length > 0 ) { for ( final File child : children ) { add( out , child , pathPrefix ); } } else { addEntry( out , file , pathPrefix , false ); } } else { addEntry( out , file , pathPrefix , true ); } } private static void addEntry( final ZipArchiveOutputStream out , final File file , final int pathPrefix , final boolean isFile ) { try { out.putArchiveEntry( new ZipArchiveEntry( file.getPath().substring( pathPrefix ) + ( isFile ? """" : ""/"" ) ) ); if ( isFile ) { final FileInputStream in = FileUtils.openInputStream( file ); IOUtils.copy( in , out ); IOUtils.closeQuietly( in ); } out.closeArchiveEntry(); } catch ( final IOException e ) { throw new RuntimeException( e ); } } public static void pack( final File source , final File destination ) { try { final ZipArchiveOutputStream out = new ZipArchiveOutputStream( destination ); add( out , source , FilenameUtils.getPath( source.getPath() ).length() ); out.finish(); out.close(); } catch ( final IOException e ) { throw new RuntimeException( e ); } } } " B12260,"package shakti; import java.io.*; import java.util.Scanner; public class recycle { public static void main(String[] args) { int cn=0; try { File file = new File(""C-small-attempt0.in""); FileOutputStream out=new FileOutputStream(""output.out""); Scanner in=new Scanner(new FileReader(file) ); int n=in.nextInt(); while (n!=cn) { cn++; int count=0; int a=in.nextInt(); int b=in.nextInt(); int number=0; for(int i=a;i<=b;i++) { String str=i+""""; do{ char c=str.charAt(0); String newstr=str.substring(1, str.length()); str=newstr+c; number=Integer.parseInt(str); if((number checkedElementSet = new HashSet(); private HashSet ListOfPairs = new HashSet(); private int startNumber; private int endNumber; @Override public String[] solve(String[] dataSet) { processInput(dataSet); String result[] = new String[1]; result[0] = String.valueOf(ListOfPairs.size()); // System.out.println(ListOfPairs); return result; } public void processInput(String[] dataSet){ String data[] = dataSet[0].split("" ""); startNumber = Integer.parseInt(data[0]); endNumber = Integer.parseInt(data[1]); for (int i = startNumber; i <= endNumber; i++){ if(hasBeenProcessed(i)){ continue; } if (i < 10 ){ continue; } if (i >= 10 && i < 100 ){ int reverse = reverseInt(i) ; checkedElementSet.add(i); checkedElementSet.add(reverse); checkAndCreatePair(i,reverse); } if (i >= 100 && i <= 1000 ){ int reverse = reverseInt(i) ; int reverse1 = reverseInt(reverse); checkedElementSet.add(i); checkedElementSet.add(reverse); checkedElementSet.add(reverse1); checkAndCreatePair(i,reverse); checkAndCreatePair(i,reverse1); checkAndCreatePair(reverse,reverse1); checkAndCreatePair(reverse,i); checkAndCreatePair(reverse1,reverse); checkAndCreatePair(reverse1,i); } if (i > 1000 && i < 10000 ){ int reverse = reverseInt(i) ; int reverse1 = reverseInt(reverse); int reverse2 = reverseInt(reverse1); checkedElementSet.add(i); checkedElementSet.add(reverse); checkedElementSet.add(reverse1); checkedElementSet.add(reverse2); checkAndCreatePair(i,reverse); checkAndCreatePair(i,reverse1); checkAndCreatePair(i,reverse2); checkAndCreatePair(reverse,i); checkAndCreatePair(reverse,reverse1); checkAndCreatePair(reverse,reverse2); checkAndCreatePair(reverse1,i); checkAndCreatePair(reverse1,reverse); checkAndCreatePair(reverse1,reverse2); checkAndCreatePair(reverse2,i); checkAndCreatePair(reverse2,reverse); checkAndCreatePair(reverse2,reverse1); } } } public void checkAndCreatePair(int i, int reverse){ if(i>= startNumber && reverse >= startNumber && i <= endNumber && reverse <= endNumber && i < reverse){ Pair p = new Pair(i,reverse); ListOfPairs.add(p); } } public int reverseInt(int input){ String strInput = String.valueOf(input); char lastNum = strInput.charAt(strInput.length()-1); String strOutput = lastNum + strInput.substring(0, strInput.length() -1 ); int output = Integer.parseInt(strOutput); return output; } public boolean hasBeenProcessed(int input){ if (checkedElementSet.contains(input)){ return true; } return false; } } " B13258,"import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; @SuppressWarnings( ""nls"" ) public class R0C { public static void main( final String[] args ) throws IOException { final Scanner in = new Scanner( new File( ""R0C.txt"" ) ); final FileWriter out = new FileWriter( ""R0C.out"" ); final int n = in.nextInt(); in.skip( in.delimiter() ); for( int i = 0; i < n; i++ ) out.write( ""Case #"" + (i+1) + "": "" + countAllRecycledNumbersBetween( in.nextInt(), in.nextInt() ) + ""\n"" ); in.close(); out.close(); } static int countAllRecycledNumbersBetween( final int a, final int b ) { final int digits = 1 + (int)Math.floor( Math.log10( a ) ); final int firstDigitMult = (int)Math.pow( 10., digits - 1 ); final boolean[] visited = new boolean[ b - a + 1 ]; int count = 0; for( int i = 0; i <= b - a; i++ ) { if( visited[ i ] ) continue; visited[ i ] = true; int subCount = 1; int x = a + i; for( int j = 1; j < digits; j++ ) { x = x / 10 + x % 10 * firstDigitMult; if( ( x >= a ) && ( x <= b ) && !visited[ x - a ] ) { visited[ x - a ] = true; subCount++; } } count += subCount * ( subCount - 1 ) / 2; } return count; } } " B12583,"import java.io.*; public class template { public static void main(String[] args) throws IOException { StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); //PrintWriter out = new PrintWriter(""output.txt""); in.nextToken(); int count = (int)in.nval; for(int c = 1 ; c <= count ; c++) { int rotations = 0; in.nextToken(); int a = (int)in.nval; in.nextToken(); int b = (int)in.nval; /* ignore 0 1 = 0 to 9 2 = 10 to 99 ... 7 = 1 000 000 to 9 999 999 */ int[] min = {0, 0, 10, 100, 1000, 10000, 100000, 1000000}; int[] max = {0, 9, 99, 999, 9999, 99999, 999999, 9999999}; // set limits for(int i = 1 ; i <= 7 ; i++) { min[i] = Math.max(min[i], a); max[i] = Math.min(max[i], b); } for(int len = 2 ; len <= 7 ; len++) { int exp = (int) Math.pow(10, len-1); for(int i = min[len] ; i <= max[len] ; i++) { int r = i; for(int j = 0 ; j < len-1 ; j++) { r = r % exp * 10 + (r/exp); if (r == i) break; if (r > i && r <= max[len] && i != r) rotations++; } } } out.println(""Case #"" + c + "": "" + rotations); } out.flush(); out.close(); } } " B13187,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; import junit.framework.TestCase; public class RecycledNumbers extends TestCase { public void testMain() throws IOException { RecycledNumbers.main(null); } public static void main(String[] args) throws IOException { setStandardIO(); setFileIO(""recyclednumbers""); readLine(); int T = nextInt(); for (int t = 1; t <= T; ++t) { readLine(); int A = nextInt(); int B = nextInt(); int N = String.valueOf(A).length() - 1; if (N == 0) println(""Case #"" + t + "": "" + 0); else { Set pairs = new TreeSet(); for (int i = A; i <= B; ++i) { for (int j = 0; j < N; ++j) { String x = String.valueOf(i); String y = x.substring(N - j) + x.substring(0, N - j); if (y.charAt(0) == '0') continue; int X = Integer.valueOf(x); int Y = Integer.valueOf(y); if (X == Y) continue; if (Y < A) continue; if (Y > B) continue; if (X < Y) pairs.add(new Pair(X, Y)); else pairs.add(new Pair(Y, X)); } } println(""Case #"" + t + "": "" + pairs.size()); } } flush(); } //~ ---------------------------------------------------------------------------------------------------------------- //~ - Auxiliary code ----------------------------------------------------------------------------------------------- //~ ---------------------------------------------------------------------------------------------------------------- static BufferedReader in; static PrintWriter out; static StringTokenizer st; private static void setStandardIO() { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); } private static void setFileIO(String fileName) throws FileNotFoundException, IOException { in = new BufferedReader(new FileReader(fileName + "".in"")); out = new PrintWriter(new BufferedWriter(new FileWriter(fileName + "".out""))); } public static void readLine() throws IOException { st = new StringTokenizer(in.readLine()); } public static int nextInt() { return Integer.parseInt(st.nextToken()); } public static long nextLong() { return Long.parseLong(st.nextToken()); } public static String nextString() { return st.nextToken(); } public static List nextStrings() { List strings = new ArrayList(); while (st.hasMoreTokens()) strings.add(st.nextToken()); return strings; } public static void flush() { out.flush(); } public static void println(Object object) { out.println(object); } public static void print(Object object) { out.print(object); } public static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } public static class Pair implements Comparable{ public int x, y; public Pair(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return ""Pair [x="" + x + "", y="" + y + ""]""; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (x ^ (x >>> 32)); result = prime * result + (int) (y ^ (y >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (x != other.x) return false; if (y != other.y) return false; return true; } @Override public int compareTo(Pair o) { if (x < o.x) return -1; if (x > o.x) return 1; return y - o.y; } } } " B10362," import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.*; public class testrun { public static void main(String[] args) { BufferedReader in; String line; PrintWriter out; // Inputting File. try { in = new BufferedReader(new FileReader(""C:\\Users\\imumair\\Desktop\\C-small-attempt0.in"")); int i = Integer.parseInt( in.readLine() ); ArrayList outputlist = new ArrayList(); String outstring = """"; String initstring = """" ; int count = 1 ; int resultcount = 0; while(in.ready() && count <= i){ initstring = ""Case #"" + count+"": "" ; try { line = in.readLine(); outstring = """"; String[] linearray = line.split("" ""); resultcount = 0; int a = Integer.parseInt( linearray[0]); int b = Integer.parseInt( linearray[1]); for (int j = a ; j digitlist = new ArrayList(); int number = j; // = and int LinkedList stack = new LinkedList(); while (number > 0) { stack.push( number % 10 ); number = number / 10; } while (!stack.isEmpty()) { digitlist.add(stack.pop()); } int numdigits = digitlist.size(); if(numdigits > 1 ){ String comb = """"; if(allequal(digitlist)){ resultcount = resultcount + 0; } else { String prevcomb = """"; //going throguh all combinations for (int m = 1 ; m j && !prevcomb.equals(comb) ){ resultcount++; prevcomb = comb; //System.out.println(""( "" +j+"" , "" + comb +"" )"" ); } } } } } outstring = initstring+outstring +resultcount; outputlist.add(outstring); //System.out.println(line); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println(""readline fails!!""); } count++; } in.close(); //Outputting File. out = new PrintWriter(new FileWriter(""C:\\Users\\imumair\\Desktop\\A-small-output.out"")); if(i >0){ int k; for (k = 0; k < i ; k++){ out.println(outputlist.get(k)); } }else{ out.println(""""); } out.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println(""Ready Input fails.""); } } public static boolean allequal(ArrayList digitlist){ int n = digitlist.size(); int start = digitlist.get(0); boolean all = true; for (int i = 0; i found = new TreeSet<>(); int count = 0; int a = s.nextInt(); int b = s.nextInt(); String bStr = b + """"; for (int n = a; n < b; n++) { String numStr = n + """"; for (int j = 1; j < numStr.length(); j++) { if (numStr.charAt(j) < numStr.charAt(0)) { continue; } if (numStr.length() == bStr.length() && numStr.charAt(j) > bStr.charAt(0)) { continue; } String numRot = numStr.substring(j) + numStr.substring(0, j); int m = Integer.parseInt(numRot); //System.out.println(""DEBUG: Trying "" + n + "","" + m); if (n < m && m <= b) { found.add(m); //System.out.println(""DEBUG: Found""); } } count += found.size(); found.clear(); } System.out.println(""Case #"" + (i+1) + "": "" + count); } } } " B10305,"package bsevero.codejam.qualification; import java.util.HashMap; import java.util.List; import java.util.Map; public class Main { public static void main(String[] args) { String inputPath = args[0]; String outputPath = args[1]; List inputLines = IOUtils.readFile(inputPath); inputLines.remove(0); Map casesResult = new HashMap(); int caseNum = 1; for(String text: inputLines) { String[] minMax = text.split("" ""); int result = RecycledNumbers.recycle(minMax[0], minMax[1]); casesResult.put(caseNum, String.valueOf(result)); caseNum++; } IOUtils.writeFile(outputPath, casesResult); } } " B12025,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; public class ProblemC { public static void main(String[] args) throws FileNotFoundException { start(); } public static void start() throws FileNotFoundException { File file = new File(""./""); String name = """"; for (File f : file.listFiles()) { if (f.getName().endsWith("".in"")) { name = f.getName().replaceFirst(""\\.in"", """"); break; } } Scanner in = new Scanner(new File(name + "".in"")); PrintWriter out = new PrintWriter(new File(name + "".out"")); long startTime = System.nanoTime(); new Solution(in, out); System.out.println(""\n"" + (System.nanoTime() - startTime) * Math.pow(10, -9) + "" seconds""); out.close(); } public static class Solution { public Solution(Scanner in, PrintWriter out) { int cases = in.nextInt(); in.nextLine(); for (int i = 1; i <= cases; i++) { String answer = ""Case #"" + i + "": "" + compute(in.nextLine()); out.println(answer); System.out.println(answer); } } private int compute(String s) { Scanner sc = new Scanner(s); int a = sc.nextInt(); int b = sc.nextInt(); int digits = (a + """").length(); HashSet answer = new HashSet(); for (int shiftCount = 1; shiftCount < digits; shiftCount++) { for (int n = a; n <= b; n++) { String nString = n + """"; String mString = nString.substring(shiftCount, digits) + nString.substring(0, shiftCount); int m = Integer.parseInt(mString); if (a <= n && n < m && m <= b) { answer.add(nString+mString); } } } return answer.size(); } } } " B12385,"package com.forbeck.codejam2012; import static java.lang.Integer.parseInt; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class ProblemC { private static final String OUTPUT = ""resources/codejam2012/c/C-small-attempt1.out""; private static final String INPUT = ""resources/codejam2012/c/C-small-attempt1.in""; private static List recycleds; public static void main(String[] args) throws IOException { final BufferedReader br = new BufferedReader(new FileReader(INPUT)); final BufferedWriter bw = new BufferedWriter(new FileWriter(OUTPUT)); final Integer tcs = Integer.parseInt(br.readLine()); int count = 1; while (count <= tcs) { recycleds = new ArrayList(); final StringTokenizer st = new StringTokenizer(br.readLine()); final String a = st.nextToken(), b = st.nextToken(); for (int m = parseInt(a) + 1; m <= parseInt(b); m++) { for (int n = parseInt(a); n < m; n++) { verifyRecycled(String.valueOf(n), String.valueOf(m)); } } out(bw, count++); } bw.close(); } private static void out(final BufferedWriter bw, int count) throws IOException { bw.write(""Case #"" + count + "": "" + recycleds.size() + ""\n""); } private static void verifyRecycled(String N, String M) { if (N.length() != M.length() || M.length() == 1 || N.length() == 1) return; for (int i = N.length() - 1; i > 0; i--) { final String moved = N.substring(i); final String suposedM = moved + N.substring(0, N.lastIndexOf(moved)); if (!M.equals(suposedM)) continue; if (!recycleds.contains(N + M)) { recycleds.add(N + M); } } } }" B11785,"package com.google.codejam.p3; import java.awt.Point; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; public class Problem3 { ArrayList cases = new ArrayList(); public void loadInput() { try{ FileInputStream fstream = new FileInputStream(""input3.txt""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine = br.readLine(); //read number of lines while ((strLine = br.readLine()) != null) { String[] info = strLine.split("" ""); int A = Integer.parseInt(info[0]); int B = Integer.parseInt(info[1]); cases.add(new Point(A,B)); } in.close(); } catch (Exception e) { } } public static boolean isRecycled(int a, int b) { String s1 = Integer.toString(a); String s2 = Integer.toString(b); for (int i=0; i pairs = new ArrayList(); for (int i = lower; i <= upper; i++) { List p = recycle(i); for (int j : p) { if (j >= i && j <= upper) { pairs.add(j); //System.out.println(i + "", "" + j); } } } return pairs.size(); } private List recycle(int n) { List p = new ArrayList(); int m = n; int len = Integer.toString(n).length(); int mult = (int)Math.pow(10, len - 1); for (int i = 0; i < len; i++) { int d = m % 10; m /= 10; m += (d * mult); if (m != n && len == Integer.toString(m).length() && !p.contains(m)) { p.add(m); } } return p; } } " B12608,"import java.awt.Point; import java.io.File; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { public static Set set; public static void main(String[] args) throws Exception { Scanner in = new Scanner(new File(""input.in"")); int n, a, b; int ans; n = in.nextInt(); for (int tc = 1; tc <= n; tc++) { a = in.nextInt(); b = in.nextInt(); set = new HashSet(); ans = finder(a, b) / 2; System.out.println(""Case #"" + tc + "": "" + set.size() / 2); // System.out.println(); } } public static int finder(int a, int b) { int temp; int ans = 0; for (int i = a; i <= b; i++) { for (int j = 1;; j++) { temp = moveDigits(i, j); if (temp == -1) break; if (temp != i && temp >= a && temp <= b) { // System.out.println(""Output :"" + i + "" "" + temp); set.add(new Point(i, temp)); ans++; } } } return ans; } public static int moveDigits(int num, int moveBy) { String s = Integer.toString(num); int size = s.length(); if (moveBy >= s.length()) return -1; s = s.substring(moveBy) + s.substring(0, moveBy); if (Integer.toString((Integer.parseInt(s))).length() != size) return 0; return Integer.parseInt(s); } } " B10134,"package codejam2012; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class ProblemC { public static void main(String[] args) throws FileNotFoundException, IOException { int T, n, A, B, recycle, lastN = 0, lastM = 1; ProblemC c = new ProblemC(); Scanner sc = new Scanner(new FileReader(""C-small-attempt3.in.txt"")); PrintWriter pw = new PrintWriter(new FileWriter(""outputPC.txt"")); T = sc.nextInt(); for(int i = 0; i < T; i++){ A = sc.nextInt(); B = sc.nextInt(); recycle = 0; for(n = A; n < B; n++){ int digits = Integer.toString(n).length(); if(digits > 1){ char[] num = new char[digits]; for(int j = 0; j < digits; j++){ num[j] = Integer.toString(n).charAt(j); } for(int j = 0; j < digits - 1; j++){ c.rotateNum(num); if(Integer.parseInt(c.charToString(num)) <= B && Integer.parseInt(c.charToString(num)) > n){ if(lastN == n && lastM == Integer.parseInt(c.charToString(num))){ recycle--; } lastN = n; lastM = Integer.parseInt(c.charToString(num)); recycle++; } } } } pw.print(""Case #"" + (i + 1) + "": ""); pw.println(recycle); } pw.flush(); pw.close(); sc.close(); } public String charToString(char[] c){ String result = """"; for(int i = 0; i < c.length; i++){ result += c[i]; } return result; } public void rotateNum(char[] c){ char aux = c[c.length - 1]; for(int i = c.length - 1; i > 0; i--){ c[i] = c[i - 1]; } c[0] = aux; } } " B11480,"package qualification; import java.util.Arrays; import java.util.Scanner; public class Recycle { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int num = scan.nextInt(); for(int i=1; i<=num; i++) { int a = scan.nextInt(); int b = scan.nextInt(); int count = 0; for(int j = a; j num && perm <= max) result++; } return result; } public static boolean isRecycled(String a, String b) { if(a.length() != b.length()) return false; if(!anagram(a,b)) return false; for(int i=0; i numbers = new HashSet(); for(int i=1; i set = new HashSet<>(); for(int n = min; n < max; n++) { set.clear(); int tien = 10; while(tien < n) { final int deel = n / tien; final int rest = n % tien; int m = (rest * tien2 / tien) + deel; if(n < m && m <= max) { if(!set.contains(m)) { set.add(m); opl++; } } tien *= 10; } } //print print(Integer.toString(opl)); } public static void main(String[] args) { CodeJamIO cd = new CodeJamIO(""C-small-attempt0""); cd.solve(); while(cd.hasMore()) { cd.next(); cd.solve(); } cd.close(); } } " B10647,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; import java.io.*; /** * * @author wijebandara */ public class RecycledNumbers { public static void main(String[] args) throws FileNotFoundException, IOException { //java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); java.io.BufferedReader in=new java.io.BufferedReader(new java.io.FileReader(""/home/wijebandara/Desktop/C-small-attempt0.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""/home/wijebandara/Desktop/C-small-attempt0.out""))); int n = Integer.parseInt(in.readLine()); java.util.StringTokenizer st ; for(int i=0;i l =new java.util.ArrayList(); int h =(int)Math.log10(j); for(int k=1;k<=h;k++) { int p=change(j,k); if(p>j && !l.contains(p) && p>=a && p<=b) { l.add(p); ans++; } } } System.out.print(""Case #"" + (i + 1) + "": ""); out.print(""Case #"" + (i + 1) + "": ""); System.out.println(ans); out.println(ans); } out.close(); } static int change(int x,int n) { int a=(int)(Math.pow(10, n)); int hold=x%a; int b =(int)Math.log10(x)+1; x=(x-hold)/a; return hold*(int)Math.pow(10, b-n)+x; } } " B11007," import java.io.*; import java.util.*; public class RecycledNumbers { static class InputReader { BufferedReader bin; StringTokenizer tokenizer; public InputReader(InputStream in) { bin = new BufferedReader(new InputStreamReader(in)); tokenizer = null; } public InputReader(String fname) { try { bin = new BufferedReader(new FileReader(fname)); tokenizer = null; } catch (Exception e) { throw new RuntimeException(e); } } public String next() { while( tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(bin.readLine()); } catch(IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public String readLine() { try { return bin.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public float nextFloat() { return Float.parseFloat(next()); } public void close() { try { bin.close(); tokenizer = null; } catch ( IOException e) { throw new RuntimeException(e); } } } public static void main(String[] args) throws IOException { //InputReader in = new InputReader(System.in); InputReader in = new InputReader(""C-small-attempt0.in""); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""A-small-rcnum.out""))); //PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int ctr = 0,start,end; int numTc = in.nextInt(); for ( int i = 0; i < numTc; i++ ) { start = in.nextInt(); end = in.nextInt(); ctr = 0; for ( int j = start; j <= end; j++ ) for ( int k = j + 1; k <= end; k++ ) { String s = Integer.toString(j); s = s + s; if(s.contains(Integer.toString(k))) ctr++; } out.println(""Case #""+(i+1)+"": ""+ctr); } out.close(); in.close(); } } " B12929,"package qual2012; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; public class Kattio extends PrintWriter { public Kattio(InputStream i) { super(new BufferedOutputStream(System.out)); r = new BufferedReader(new InputStreamReader(i)); } public Kattio(InputStream i, OutputStream o) { super(new BufferedOutputStream(o)); r = new BufferedReader(new InputStreamReader(i)); } public boolean hasMoreTokens() { return peekToken() != null; } public int getInt() { return Integer.parseInt(nextToken()); } public double getDouble() { return Double.parseDouble(nextToken()); } public long getLong() { return Long.parseLong(nextToken()); } public String getWord() { return nextToken(); } private BufferedReader r; private String line; private StringTokenizer st; private String token; private String peekToken() { if (token == null) try { while (st == null || !st.hasMoreTokens()) { line = r.readLine(); if (line == null) return null; st = new StringTokenizer(line); } token = st.nextToken(); } catch (IOException e) { } return token; } private String nextToken() { String ans = peekToken(); token = null; return ans; } }" B11517,"/** * Recycled Numbers */ package com.google.jam.qualification; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; public class C { public static String moveFromEndToFront(String number, int n) { String begin = number.substring(0,number.length()-n); String end = number.substring(number.length()-n); return end+begin; } public static void main(String[] args) { try { FileOutputStream fos = new FileOutputStream(""C-small-attempt0.out""); System.setOut(new PrintStream(fos, true)); FileInputStream fis=new FileInputStream(new File(""C-small-attempt0.in"")); InputStreamReader in=new InputStreamReader(fis); BufferedReader br=new BufferedReader(in); String line=""""; int nbTest = Integer.parseInt(br.readLine()); for(int i=1; i<=nbTest; i++) { line = br.readLine(); Scanner sc = new Scanner(line); int cpt = 0; int min = sc.nextInt(); int max = sc.nextInt(); for(int k=min; k<=max; k++) { String number = String.valueOf(k); HashMap table = new HashMap(); for(int l=1; l 0){ ABak /= 10; numDigits++; } int ans = 0; /* main logic */ for (int i = A; i < B; i++){ Set validMs = new HashSet(); for (int j = 1; j < numDigits; j++){ int b = shift(i, j, numDigits); if (b <= B && b > i){ validMs.add(new Integer(b)); } } ans += validMs.size(); } pw.println(ans); } pw.close(); } public static int shift(int x, int k, int l){ //int d = (int) Math.pow(10, k); int d = 1; for (int p = 1; p <= k; p++){ d *= 10; } int tmp = x % d; int d2 = 1; for (int p = 1; p <= (l - k); p++){ d2 *= 10; } tmp *= d2; return ((x/d) + tmp); } } " B12076,"package jp.funnything.competition.util; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import org.apache.commons.io.IOUtils; public class AnswerWriter { private static final String DEFAULT_FORMAT = ""Case #%d: %s\n""; private final BufferedWriter _writer; private final String _format; public AnswerWriter( final File output , final String format ) { try { _writer = new BufferedWriter( new FileWriter( output ) ); _format = format != null ? format : DEFAULT_FORMAT; } catch ( final IOException e ) { throw new RuntimeException( e ); } } public void close() { IOUtils.closeQuietly( _writer ); } public void write( final int questionNumber , final Object result ) { write( questionNumber , result.toString() , true ); } public void write( final int questionNumber , final String result ) { write( questionNumber , result , true ); } public void write( final int questionNumber , final String result , final boolean tee ) { try { final String content = String.format( _format , questionNumber , result ); if ( tee ) { System.out.print( content ); System.out.flush(); } _writer.write( content ); } catch ( final IOException e ) { throw new RuntimeException( e ); } } } " B10805,"import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.fill; import static java.util.Arrays.binarySearch; import static java.util.Arrays.sort; public class Main { public static void main(String[] args) throws IOException { long prevTime = System.currentTimeMillis(); new Main().run(); System.err.println(""Total time: "" + (System.currentTimeMillis() - prevTime) + "" ms""); System.err.println(""Memory status: "" + memoryStatus()); } // String inputFile = ""sample.txt""; String inputFile = ""input/C-small-attempt0.in""; // String inputFile = ""input/C-large.in""; String outputFile = ""output.txt""; void run() throws IOException { in = new BufferedReader(new FileReader(inputFile)); out = new PrintWriter(outputFile); solve(); out.close(); } final int MAXN = 2000000; String[] sNums = new String [MAXN + 1]; void solve() throws IOException { for (int i = 0; i <= MAXN; i++) sNums[i] = Integer.toString(i); for (int testCase = 1, testCases = nextInt(); testCase <= testCases; testCase++) { solve(testCase); } } int leftBorder, rightBorder; void solve(int testCase) throws IOException { out.print(""Case #"" + testCase + "": ""); leftBorder = nextInt(); rightBorder = nextInt(); long ans = 0L; for (int num = leftBorder; num <= rightBorder; num++) { ans += calc(num); } out.println(ans); } int curNum; int curLen; int[] digits; int[] perm = new int [10]; int[] used = new int [10]; int tick = 1; StupidSet validNums = new StupidSet(); long calc(int num) { curNum = num; validNums.clear(); String sNum = sNums[num]; digits = new int [sNum.length()]; for (int i = 0; i < sNum.length(); i++) digits[i] = sNum.charAt(i) - '0'; curLen = sNum.length(); // tick++; // rec(0); for (int i = 0; i < curLen; i++) shift(i); return validNums.size(); } void shift(int offset) { if (digits[offset] == 0) return; for (int i = 0; i < curLen; i++) perm[i] = (offset + i) % curLen; updateAns(); } // void rec(int n) { // if (n == curLen) { // updateAns(); // } else { // for (int i = 0; i < curLen; i++) { // if (used[i] != tick && (n > 0 || digits[i] > 0)) { // used[i] = tick; // perm[n] = i; // rec(n + 1); // used[i] = tick - 1; // } // } // } // } void updateAns() { int num = getCurrentNum(); if (curNum < num && num <= rightBorder) validNums.add(num); } int getCurrentNum() { int ret = 0; int pow = 1; for (int i = curLen - 1; i >= 0; i--) { ret += pow * digits[perm[i]]; pow *= 10; } return ret; } class StupidSet { final int MAXN = 10000000; int[] used = new int [MAXN + 1]; int tick = 1; int size = 0; void clear() { tick++; size = 0; } void add(int x) { if (used[x] != tick) { used[x] = tick; size++; } } int size() { return size; } } /*************************************************************** * Input **************************************************************/ BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""""); String nextToken() throws IOException { while (!st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } int[] nextIntArray(int size) throws IOException { int[] ret = new int [size]; for (int i = 0; i < size; i++) ret[i] = nextInt(); return ret; } long[] nextLongArray(int size) throws IOException { long[] ret = new long [size]; for (int i = 0; i < size; i++) ret[i] = nextLong(); return ret; } double[] nextDoubleArray(int size) throws IOException { double[] ret = new double [size]; for (int i = 0; i < size; i++) ret[i] = nextDouble(); return ret; } String nextLine() throws IOException { st = new StringTokenizer(""""); return in.readLine(); } boolean EOF() throws IOException { while (!st.hasMoreTokens()) { String s = in.readLine(); if (s == null) return true; st = new StringTokenizer(s); } return false; } /*************************************************************** * Output **************************************************************/ void printRepeat(String s, int count) { for (int i = 0; i < count; i++) out.print(s); } void printArray(int[] array) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(long[] array) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(double[] array) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(double[] array, String spec) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.printf(Locale.US, spec, array[i]); } out.println(); } void printArray(Object[] array) { if (array == null || array.length == 0) return; boolean blank = false; for (Object x : array) { if (blank) out.print(' '); else blank = true; out.print(x); } out.println(); } @SuppressWarnings(""rawtypes"") void printCollection(Collection collection) { if (collection == null || collection.isEmpty()) return; boolean blank = false; for (Object x : collection) { if (blank) out.print(' '); else blank = true; out.print(x); } out.println(); } /*************************************************************** * Utility **************************************************************/ static String memoryStatus() { return (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() >> 20) + ""/"" + (Runtime.getRuntime().totalMemory() >> 20) + "" MB""; } static void checkMemory() { System.err.println(memoryStatus()); } static long prevTimeStamp = Long.MIN_VALUE; static void updateTimer() { prevTimeStamp = System.currentTimeMillis(); } static long elapsedTime() { return (System.currentTimeMillis() - prevTimeStamp); } static void checkTimer() { System.err.println(elapsedTime() + "" ms""); } } " B10436,"import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class RecycleNumbers { private static final Map power = new HashMap(); static{ power.put(0,1); power.put(1,10); power.put(2,100); power.put(3,1000); power.put(4,10000); power.put(5,100000); power.put(6,1000000); } private static int recycle(int b , int max) { int size =0 ,ret = 0; int a = b , rem = 0 , i = 0; while((size++ > -1) && ((a = a/10)!= 0)); a = b; int myPower = power.get(size -1); Set mySet = new HashSet(); for(i = 0 ; i < size-1; i++) { rem = a%10; a = rem * myPower + a/10; if(a > b && a <= max && !mySet.contains(a)) ret++; mySet.add(a); } return ret; } public static void main(String[] args) throws IOException { if (args.length < 2) { System.err.println(""Please enter the Valid I/O Paths in the argument ""); System.err.println(""First Input , then OutPut ""); System.exit(0); } File inFile = new File(args[0]); File outFile = new File(args[1]); BufferedReader in = new BufferedReader(new InputStreamReader( new FileInputStream(inFile))); PrintWriter out = new PrintWriter(new FileOutputStream(outFile)); String myLine = in.readLine(); int t = Integer.parseInt(myLine); int caseNum = 1 , result; int a , b; while (t-- > 0) { myLine = in.readLine(); String[] myStr = myLine.split("" ""); a = Integer.parseInt(myStr[0]); b = Integer.parseInt(myStr[1]); result = 0; for(int i = a ; i < b ; i++) result += recycle(i,b); out.println(""Case #"" + (caseNum) + "": "" + result); caseNum++; } out.close(); } } " B11514,"package Qualification.A.jam2011; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; /* 4 3 1 5 15 13 11 3 0 8 23 22 21 2 1 1 8 0 6 2 8 29 20 8 18 18 21 */ public class test { static int A = 0; static int B = 0; public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); int T = in.nextInt(); File f = new File(""output.txt""); FileWriter fw = new FileWriter(f); for (int j = 0; j < T; j++) { A = in.nextInt(); B = in.nextInt(); // System.out.print(""Case #"" + (j + 1) + "": "" + possible(A, B) + ""\n""); fw.write(""Case #"" + (j + 1) + "": "" + possible(A, B) + ""\n""); // System.out.println(""Case #"" + (j + 1) + "": "" + passed(s) + ""\n""); } fw.flush(); fw.close(); } private static int possible(Integer a, Integer b) { String as = a + """"; int count = 0; int no=b-a+1; System.out.println(no); for (int i = 0; i < no; i++) { // if (as.length() == 1 && bs.length() == 1) { // // } else { System.out.println(as+ "" ""+i); ArrayList aa = reverseNo(as); int n = Integer.parseInt(aa.get(0)); for (int j = 1; j < aa.size(); j++) { int m = Integer.parseInt(aa.get(j)); if (A <= n && n < m && m <= B) { if(aa.get(j).length()==aa.get(0).length()) count++; } } // } a++; as = (a) + """"; } return count; } private static ArrayList reverseNo(String A) { ArrayList aa = new ArrayList(); int alen = A.length(); for (int i = 0; i < alen; i++) { aa.add(A.substring(i) + A.substring(0, i)); } return aa; } }" B12366,"import org.apache.commons.io.IOUtils; import java.io.*; import java.util.Scanner; import java.util.HashMap; import java.util.List; import java.util.ArrayList; public class RecycledNumbers { private static int[][] testCases = null; private static int numTestCases; private static HashMap visitedNumbers; public static void main(String[] args) throws IOException { change(); if (true) return; readInput(); visitedNumbers = new HashMap(); PrintWriter out = new PrintWriter(new FileWriter(""D:\\amir\\codejam\\out.txt"")); for (int i = 0; i < numTestCases; i++) { int count = countRecycled(testCases[i][0], testCases[i][1]); int m = i + 1; out.write(""Case #"" + m + "": "" + count); out.println(); System.out.println(count); } out.flush(); out.close(); } public RecycledNumbers() { } private static void change() throws IOException { InputStream inputStream = new FileInputStream(""D:\\amir\\codejam\\out.txt""); StringWriter writer = new StringWriter(); IOUtils.copy(inputStream, writer); String theString = writer.toString(); theString = theString.replaceAll("" Case"", ""\nCase""); System.out.println(theString); } private static void readInput() throws IOException { InputStream inputStream = new FileInputStream(""D:\\amir\\codejam\\csmall22.txt""); Scanner scanner = new Scanner(inputStream); numTestCases = scanner.nextInt(); testCases = new int[numTestCases][2]; for (int i = 0; i < numTestCases; i++) { testCases[i][0] = scanner.nextInt(); testCases[i][1] = scanner.nextInt(); } inputStream.close(); } private static Integer[] getNewNumbers(int n) { if (n < 1 // || visitedNumbers.get(n) != null ) return null; String aStr = String.valueOf(n); int c = 0; if (aStr.length() > 1) { char[] chs = aStr.toCharArray(); for (int i = 0; i < aStr.toCharArray().length - 1; i++) if (chs[i] == chs[i+1]) c++; } if (c == aStr.length() - 1) return null; Integer[] newNumbers = new Integer[aStr.length() - 1]; for (int i = 0; i < aStr.length() - 1; i++) { String rec = getRecycled(i + 1, aStr); if (rec == null) { newNumbers[i] = null; continue; } newNumbers[i] = Integer.valueOf(rec); } return newNumbers; } static int countRecycled(int n, int m) { int count = 0; for (int i = n; i <= m; i++) { Integer[] newNumbers = getNewNumbers(i); if (newNumbers == null) continue; for (int j = 0; j < newNumbers.length; j++) { if (newNumbers[j] == null) continue; if (newNumbers[j] <= m) { if (i == 111) System.out.println(""""); String v1 = visitedNumbers.get(newNumbers[j] + ""-"" + i); if (v1 == null) count++; visitedNumbers.put(i + ""-"" + newNumbers[j], """" + newNumbers[j]); System.out.println(i + ""-"" + newNumbers[j]); } } } return count; } private static String getRecycled(int index, String number) { String num1 = number.substring(0, index); String num2 = number.substring(index, number.length()); // if (num1.equals(num2)) // return null; String str = num2 + num1; // if (str.startsWith(""0"")) // return null; return str; } } " B12000,"package main; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.StringReader; import java.io.StringWriter; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import javax.management.ImmutableDescriptor; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; public class Problem3 { public static void main(String[] args) throws Exception { new Problem3().prepareAndSolve(); } private void prepareAndSolve() throws Exception { File inout = new File(""inout""); final String testSuffix; if (getClass().getSimpleName().endsWith(""1"")) { testSuffix = ""A""; } else if (getClass().getSimpleName().endsWith(""2"")) { testSuffix = ""B""; } else if (getClass().getSimpleName().endsWith(""3"")) { testSuffix = ""C""; } else { testSuffix = ""D""; } File ioDir = inout.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.compareTo(testSuffix) == 0; } })[0]; // SAMPLE File sampleIn = ioDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.compareTo(""sample.in"") == 0; } })[0]; StringWriter buffer = new StringWriter(); BufferedWriter writer = new BufferedWriter(buffer); long time = System.currentTimeMillis(); solve(new BufferedReader(new FileReader(sampleIn)), writer); System.out.println(""Sample checked: "" + (System.currentTimeMillis() - time) + "" ms""); writer.close(); File sampleOut = ioDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.compareTo(""sample.out"") == 0; } })[0]; if (checkCorrectness(buffer.toString(), sampleOut) == false) { System.out.println(""NOT CORRECT:""); System.out.println(buffer.toString()); return; } // ADDITIONAL File[] additionalTest = ioDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.compareTo(""add.in"") == 0; } }); if (additionalTest.length == 1) { buffer = new StringWriter(); writer = new BufferedWriter(buffer); time = System.currentTimeMillis(); solve(new BufferedReader(new FileReader(additionalTest[0])), writer); System.out.println(""Additional checked: "" + (System.currentTimeMillis() - time) + "" ms""); writer.close(); File additionalTestAnswer = ioDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.compareTo(""add.out"") == 0; } })[0]; if (checkCorrectness(buffer.toString(), additionalTestAnswer) == false) { System.out.println(""NOT CORRECT:""); System.out.println(buffer.toString()); return; } } // SMALL File[] smallTest = ioDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.contains(""small"") && name.contains(""in""); } }); if (smallTest.length == 1) { buffer = new StringWriter(); writer = new BufferedWriter(buffer); time = System.currentTimeMillis(); solve(new BufferedReader(new FileReader(smallTest[0])), writer); System.out.print(""Small runned: "" + (System.currentTimeMillis() - time) + "" ms""); writer.close(); File smallAnswer[] = ioDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.compareTo(""small.out"") == 0; } }); if (smallAnswer.length == 1) { if (checkCorrectness(buffer.toString(), smallAnswer[0]) == false) { System.out.println(""NOT CORRECT:""); System.out.println(buffer.toString()); return; } System.out.println("", verified""); } else { BufferedWriter solutionWriter = new BufferedWriter(new FileWriter(""inout"" + File.separatorChar + testSuffix + File.separatorChar + ""small.out"")); solutionWriter.write(buffer.toString()); solutionWriter.close(); System.out.println("", written""); } } // RANDOM GENERATED if (testWithRandom == true) { StringWriter sw = new StringWriter(); BufferedWriter bw = new BufferedWriter(sw); bw.write("""" + randomInputTestNum); bw.newLine(); for (int i = 0; i < randomInputTestNum; i++) { generateOneRandomInputTest(bw); } time = System.currentTimeMillis(); bw.flush(); solve(new BufferedReader(new StringReader(sw.toString())), new BufferedWriter(new StringWriter())); System.out.print(""Random runned: "" + (System.currentTimeMillis() - time) + "" ms""); } // LARGE File[] largeTest = ioDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.contains(""large"") && name.contains(""in""); } }); if (largeTest.length == 1) { buffer = new StringWriter(); writer = new BufferedWriter(buffer); time = System.currentTimeMillis(); solve(new BufferedReader(new FileReader(largeTest[0])), writer); System.out.print(""Large runned: "" + (System.currentTimeMillis() - time) + "" ms""); writer.close(); File largeAnswer[] = ioDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.compareTo(""large.out"") == 0; } }); if (largeAnswer.length == 1) { if (checkCorrectness(buffer.toString(), largeAnswer[0]) == false) { System.out.println(""NOT CORRECT:""); System.out.println(buffer.toString()); return; } System.out.println("", verified""); } else { BufferedWriter solutionWriter = new BufferedWriter(new FileWriter(""inout"" + File.separatorChar + testSuffix + File.separatorChar + ""large.out"")); solutionWriter.write(buffer.toString()); solutionWriter.close(); System.out.println("", written""); } } } private boolean checkCorrectness(String answer, File correctAnswerFile) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(correctAnswerFile)); try { BufferedReader stringReader = new BufferedReader(new StringReader(answer)); String answerLine = stringReader.readLine(); String solutionLine = reader.readLine(); while (answerLine != null && solutionLine != null) { if (answerLine.compareTo(solutionLine) != 0) { return false; } answerLine = stringReader.readLine(); solutionLine = reader.readLine(); } if (solutionLine != null) { solutionLine = reader.readLine(); } if (solutionLine != null || answerLine != null) { return false; } return true; } finally { reader.close(); } } private int tasksRunning = 0; @SuppressWarnings(""unchecked"") public void solve(BufferedReader reader, BufferedWriter writer) throws Exception { int T = Integer.parseInt(reader.readLine()); ExecutorService xs = Executors.newFixedThreadPool(4); Future[] outputs = new Future[T]; for (int i = 0; i < outputs.length; i++) { final Solution s = new Solution(); tasksRunning++; s.readInput(reader); outputs[i] = xs.submit(new Callable() { @Override public String call() throws Exception { try { return s.solveInput(); } finally { tasksRunning--; } } }); } new Thread() { public void run() { try { while (true) { sleep(10000); if (tasksRunning == 0) { interrupt(); } System.out.println(""Tasks remaining:"" + tasksRunning); } } catch (InterruptedException e) { } }; }.start(); for (int i = 0; i < outputs.length; i++) { writer.write(""Case #"" + (i + 1) + "": "" + outputs[i].get()); writer.newLine(); } xs.shutdown(); } // ------------------------START OF THE SOLUTION------------------------------ public static boolean testWithRandom = false; public static int randomInputTestNum = 1; public void generateOneRandomInputTest(BufferedWriter bw) throws Exception { bw.write(500 + """"); bw.newLine(); } public static class Solution { private int getIntegerLength(int i) { return (i + """").length(); } private int recycleInt(int integer, int position) { return Integer.parseInt((integer + """").substring(position) + (integer + """").substring(0, position)); } private ImmutableSet getRecycleds(int integer) { ImmutableSet.Builder res = ImmutableSet.builder(); for (int i = 1; i < getIntegerLength(integer); i++) { res.add(recycleInt(integer, i)); } return res.build(); } private ImmutableSet getGreaterRecycledsBetween(final int integer, final int min, final int max) { return ImmutableSet.copyOf(Collections2.filter(getRecycleds(integer), new Predicate() { public boolean apply(Integer arg0) { return arg0 >= min && arg0 <= max && arg0 > integer; }; })); } private int getAllRecycledsNumBetween(int min, int max) { int result = 0; for (int i = min; i <= max; i++) { result += getGreaterRecycledsBetween(i, min, max).size(); } return result; } private int minParam; private int maxParam; public void readInput(BufferedReader reader) throws Exception { String line = reader.readLine(); minParam = Integer.parseInt(line.split(""[ ]"")[0]); maxParam = Integer.parseInt(line.split(""[ ]"")[1]); } public String solveInput() throws Exception { return getAllRecycledsNumBetween(minParam, maxParam) + """"; } } } " B12196,"package qualification; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class C { private static abstract class Solver { public abstract String solveCase(String input); } public static void main(String[] args) throws IOException { solveTasks(""C-small-attempt1"", new Solver() { @Override public String solveCase(String input) { String[] parts = input.split("" ""); int from = Integer.parseInt(parts[0]); int to = Integer.parseInt(parts[1]); int count = countRecycledBetween(from, to); return Integer.toString(count); } }); } private static void solveTasks(String name, Solver bTest) throws FileNotFoundException, IOException { BufferedReader bufferedReader = new BufferedReader(new FileReader(name + "".in"")); FileWriter outputWriter = new FileWriter(name + "".out""); int inputLength = Integer.parseInt(bufferedReader.readLine()); for (int i = 0; i < inputLength; i++) { String inputLine = bufferedReader.readLine(); String output = bTest.solveCase(inputLine); String answer = ""Case #"" + (i + 1) + "": "" + output; outputWriter.append(answer); outputWriter.append('\n'); System.out.println(answer); } bufferedReader.close(); outputWriter.close(); } private static int countRecycledBetween(int a, int b) { int recycled = 0; for (int i = a; i < b; i++) { for (int j = i + 1; j <= b; j++) { if (isRecycled(i, j)) { recycled++; } } } return recycled; } private static boolean isRecycled(int aInt, int bInt) { String aString = Integer.toString(aInt); String bString = Integer.toString(bInt); int lengthDiff = aString.length() - bString.length(); if (lengthDiff > 0) { bString = appendZeroes(lengthDiff, bString); } else if (lengthDiff < 0) { aString = appendZeroes(-lengthDiff, aString); } for (int i = 1; i < aString.length(); i++) { String shifted = shiftString(bString, i); if (aString.equals(shifted)) { return true; } } return false; } private static String appendZeroes(int zeroes, String base) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < zeroes; i++) { stringBuilder.append('0'); } stringBuilder.append(base); return stringBuilder.toString(); } private static String shiftString(String input, int steps) { StringBuilder builder = new StringBuilder(); builder.append(input.substring(steps)); builder.append(input.substring(0, steps)); return builder.toString(); } private static int[] splitDigits(int number) { String string = Integer.toString(number); int[] digits = new int[string.length()]; for (int i = 0; i < digits.length; i++) { digits[i] = string.charAt(i) - '0'; } return digits; } } " B10641,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; import java.util.Scanner; public class RecycledNumbersMain { public static void main(String[] args) { try { Scanner s=new Scanner(new BufferedReader(new FileReader(""C-small-attempt0.in""))); ArrayList list=new ArrayList(); int i=0; int totalCases=Integer.parseInt(s.nextLine()); while(s.hasNextLine()){ list.add(new RecycledNumbers(++i,s.nextLine())); } for (RecycledNumbers recycledNumbers : list) { recycledNumbers.process(); } } catch (FileNotFoundException e) { System.out.println(""file not found""); } } } " B10102,"package com.codejam2012; import java.util.TreeMap; import com.codejam2012.CodeJam1.Case; public class CodeJam3 { public static String fileDir = ""P:\\CodeJam2012\\""; public static String baseFileName = ""C-small-attempt2""; public static String inputFileName = fileDir + baseFileName + "".in""; public static String outputFileName = fileDir + baseFileName + "".out""; public static int Tcase; public static int Ccase = 0; public static String[] cases; public static Case singleCase; public static void main(String[] args) { FileUtils.deleteFile(outputFileName); String inputString = FileUtils.readFile(inputFileName); parseInputString(inputString); for (; Ccase < Tcase;) { parse(); } } public static void parseInputString(String inputString) { cases = inputString.split(""\n""); Tcase = Integer.parseInt(cases[0]); Ccase = 0; } private static void parse() { Ccase++; FileUtils.appendToFile(outputFileName, ""Case #"" + Ccase + "": ""); singleCase = new Case(cases[Ccase]); singleCase.execute(); FileUtils.appendToFile(outputFileName, singleCase.getDataToPrint() + ""\n""); } public static class Case { StringBuilder outputStatement; int N; int M; public Case(String caseString) { outputStatement = new StringBuilder(); String[] arr = caseString.split("" "" ); N = Integer.parseInt(arr[0]); M = Integer.parseInt(arr[1]); } public void execute() { int noOfDigits = (N + """").length(); int TCount = 0; TreeMap mList = new TreeMap(); for (int n = N; n <= M; n++) { for (int r = 1; r < noOfDigits; r++) { int m = rotater(n, r, noOfDigits); if (m <= M && m >= N) { if (m > n) { if(mList.containsKey(n) ){ if(mList.get(n) == m){ }else{ TCount++; mList.put(n,m); } }else if (mList.containsKey(m) ){ if(mList.get(m) == n){ }else{ TCount++; mList.put(n,m); } }else{ TCount++; mList.put(n,m); } } } } } outputStatement.append(TCount); } public static int rotater(int n, int rotate, int noOfDigits) { int base = (int) Math.pow(10, noOfDigits - 1); int[] digits = new int[noOfDigits]; int d = 0; int ans = 0; for (int i = base; i >= 1; i /= 10) { digits[d] = n / i; d++; n = n % i; } shiftLeft(digits, rotate); d = 0; for (int i = base; i >= 1; i /= 10) { ans += digits[d] * i; d++; } return ans; } public static void shiftLeft(int[] array, int amount) { for (int j = 0; j < amount; j++) { int a = array[0]; int i; for (i = 0; i < array.length - 1; i++) array[i] = array[i + 1]; array[i] = a; } } public String getDataToPrint() { return outputStatement.toString(); } } } " B12267,"package cats; import java.io.*; import java.util.ArrayList; public class Main { public Main() throws Exception{ FileReader fr = new FileReader(new File(""input.txt"")); BufferedReader in = new BufferedReader(fr); File outFile = new File(""output.txt""); outFile.createNewFile(); FileWriter fw = new FileWriter(outFile); BufferedWriter out = new BufferedWriter(fw); int numTests = Integer.parseInt(in.readLine()); for(int x = 0; x found = new ArrayList(); for(int n = min; n <= max; n++){ String num = n+""""; found.clear(); for(int d = 0; d n && value <= max && (value+"""").length() == num.length() && !found.contains(num)){ //System.out.println(n + "" "" + value); found.add(num); count++; } } } out.write(""Case #"" + (x+1) + "": "" + count + ""\n""); System.out.println(count); } in.close(); out.close(); } public static void main(String[] args) throws Exception{ new Main(); } } " B10574,"package boy0; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class CodeJam_C_Small { public static void main(String[] args) throws IOException { String strLine; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); CodeJam_C_Small me = new CodeJam_C_Small(); // me.init(); strLine = br.readLine(); int T = Integer.parseInt(strLine); String[] as; char[] a, b; int y; for (int x = 1; x <= T; x++) { strLine = br.readLine(); as = strLine.split("" ""); a = as[0].toCharArray(); b = as[1].toCharArray(); y = me.get_num_recycled_pairs(a, b); System.out.println(""Case #"" + x + "": "" + y); } } // 1 ¡Â A ¡Â B ¡Â 2000000. max length = 7 private char[] recycled = new char[16]; // (max+1)*2 = 8*2 = 16 private int r_length = 0; private char[] b; private int b_length = 0; // A ¡Â n < m ¡Â B public int get_num_recycled_pairs(char[] a, char[] b_) { int y = 0; int a_length = a.length; b = b_; b_length = b.length; // r = a (&& a); r_length = a_length; for (int i = 0; i < a_length; i++) { recycled[i] = a[i]; recycled[i + r_length] = a[i]; } // while r <= b while (comp(recycled, 0, r_length, b, 0, b_length) <= 0) { // check each r-pair for (int i = 1; i < r_length; i++) { if (is_recycled_pair(i)) { y++; } } // r++; add_1_r(); } return y; } // < : -x , == : 0, > : +x private int comp(char[] c1, int c1_offset, int c1_length, char[] c2, int c2_offset, int c2_length) { int x = c1_length - c2_length; if (x == 0) { for (int i = 0; i < c2_length; i++) { x = c1[c1_offset + i] - c2[c2_offset + i]; if (x != 0) { break; } } } return x; } private boolean is_recycled_pair(int offset) { // n = r[0] , m = r[offset] // n >= m ? false if (comp(recycled, 0, r_length, recycled, offset, r_length) >= 0) { return false; } // m > b ? false if (comp(recycled, offset, r_length, b, 0, b_length) > 0) { return false; } // r[offset] == r[x] ? false (0 < x < offset) for (int x = 1; x < offset; x++) { if (comp(recycled, offset, r_length, recycled, x, r_length) == 0) { return false; } } // System.out.println(""r:"" + new String(recycled) + ""\t offset:"" + offset); return true; } // r++ private void add_1_r() { for (int i = r_length - 1; i >= 0; i--) { if (recycled[i] == '9') { recycled[i] = '0'; recycled[i + r_length] = recycled[i]; } else { recycled[i] = (char) (recycled[i] + 1); recycled[i + r_length] = recycled[i]; return; } } // here, length overflow r_length++; for (int i = r_length - 1; i >= 1; i--) { recycled[i] = recycled[i - 1]; recycled[i + r_length] = recycled[i]; } recycled[r_length] = recycled[0] = '1'; } } " B12725,"import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; public class CodeJamQ3 { public static String[] read(final String name) throws IOException { final InputStreamReader reader = new FileReader(new File(name)); final char[] buf = new char[1024]; int count = 0; final StringBuilder res = new StringBuilder(); do { count = reader.read(buf); if (count > 0) res.append(buf, 0, count); } while (count != -1); return res.toString().trim().split(""(\\r?\\n)+""); } public static void main(final String[] args) throws Exception { final String[] input = read(""C-small-attempt0.in""); final FileWriter out = new FileWriter(""out""); final int casesCount = Integer.parseInt(input[0]); for (int caseN = 1; caseN <= casesCount; caseN++) { final String[] data = input[caseN].split(""\\s+""); final int a = Integer.parseInt(data[0]); final int b = Integer.parseInt(data[1]); out.write(""Case #"" + caseN + "": "" + solve(a, b) + ""\n""); } out.close(); } private static long solve(final int a, final int b) { long count = 0; final HashSet check= new HashSet(); for (int x = a; x <= b; x++) { final String s = String.valueOf(x); // int k = 0; // int equal = 0; for (int i = 1; i < s.length(); i++) { final int test = Integer.parseInt(s.substring(i) + s.substring(0, i)); if (test <= b && test >= a && test > x) { final Tuple t = new Tuple(x, test); if (check.contains(t)) { continue; } check.add(t); ++count; System.out.println(x + "" - ""+ test); } // if (s.charAt(i) == s.charAt(i - 1)) { ++equal; } // if (s.charAt(0) <= s.charAt(i) && s.charAt(i) != '0') { // final int test = Integer.parseInt(s.substring(i) + s.substring(0, i)); // if (b >= test) { ++k; } // } } // if (equal < s.length() - 1) { count += k; } } return count; } private static class Tuple { int x, y; Tuple(final int x, final int y) {this.x = x; this.y = y; } @Override public int hashCode() { return x + y; } @Override public boolean equals(final Object obj) { final Tuple t = (Tuple)obj; return t.x == x && t.y == y || t.x == y && t.y ==x; } } } " B12351,"package com.google.jam; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import com.google.jam.recycled.numbers.RecycledNumberController; public class Solver { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader reader = new BufferedReader(new FileReader( ""src/input.txt"")); int t = Integer.valueOf(reader.readLine()); for (int i = 1; i <= t; i++) { String[] tokens = reader.readLine().split("" ""); System.out .format(""Case #%d: %d\n"", i, new RecycledNumberController(Integer .valueOf(tokens[0]), Integer .valueOf(tokens[1])) .getNumRecycledNumbers()); } } } " B13233,"import java.util.Arrays; import java.util.Scanner; /** * @author Dmitry Levshunov (levshunov.d@gmail.com) */ public class TaskC { private static boolean[] used = new boolean[2000001]; private static int length; private static int pow; public static void main(String[] args) throws Exception { Scanner scanner = new Scanner(System.in); int tests = Integer.parseInt(scanner.nextLine().trim()); for (int test = 1; test <= tests; test++) { int a = scanner.nextInt(); int b = scanner.nextInt(); System.out.printf(""Case #%d: %s"", test, solve(a, b)); System.out.println(); } scanner.close(); } private static long solve(int a, int b) { Arrays.fill(used, false); length = Integer.toString(a).length(); pow = 1; for (int i = 0; i < length - 1; i++) { pow *= 10; } long result = 0; for (int x = a; x <= b; x++) { long shiftCount = processShifts(x, a, b); result += shiftCount * (shiftCount - 1) / 2; } return result; } private static int processShifts(int x, int a, int b) { if (used[x]) { return 0; } int result = 0; for (int i = 0; i < length; i++) { x = (x % 10) * pow + x / 10; if (a <= x && x <= b && !used[x]) { used[x] = true; result++; } } return result; } } " B10115,"import java.util.Scanner; public class C { static boolean iftrue(int n, int m) { String aa = n + """"; if (n == m) return false; for (int i = 1; i < aa.length(); i++) { String ll = aa.substring(i, aa.length()); String bb = aa.substring(0, i); String ss = ll + bb; if (ss.equals(m + """") && m > n) { return true; } } return false; } public static void main(String[] args) { //System.out.println(iftrue(12, 31)); Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int i = 0; i < T; i++) { int A = in.nextInt(); int B = in.nextInt(); int res = 0; for (int k = A; k <= B; k++) { for (int l = k + 1; l <= B; l++) { if (iftrue(k, l)) res++; } } System.out.format(""Case #%d: %s\n"", i + 1, res); } } } " B11629,"import java.io.File; import java.io.PrintWriter; import java.util.Scanner; public class RecNumbers { static Scanner in; static PrintWriter out; public static boolean isRecycled(int n, int m){ boolean recycled = false; String first = Integer.toString(n); String second = Integer.toString(m); int len = first.length(); for(int i = 0; i < len; i++){ if(len > 2){ first = """" + first.charAt(len - 1) + first.substring(0,len - 1); } else if (len == 2){ first = """" + first.charAt(1) + first.charAt(0); } else { return false; } if(first.equals(second)){ recycled = true; } } return recycled; } public static void main(String[] args) throws Exception { in = new Scanner(new File(""C-small-attempt0.in"")); out = new PrintWriter(new File(""C-small.out"")); //Read file int A; int B; int T = in.nextInt(); //for each case do for (int i = 1; i <= T; i++){ A = in.nextInt(); B = in.nextInt(); int count = 0; out.print(""Case #"" + i + "": ""); for(int j = A; j <= B; j++){ for(int k = j + 1; k <= B; k++){ if(isRecycled(j, k) && j > 10 && k > 10){ count++; } } } out.print(count); out.println(); } out.close(); } }" B11432,"import java.util.*; public class C { private int[] tens = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000}; public static void main(String[] args) { C c = new C(); c.solve(); } public void solve() { Scanner in = new Scanner(System.in); int t = in.nextInt(); for(int ii = 1; ii <= t; ++ii) { int a = in.nextInt(); int b = in.nextInt(); long total = 0; for(int check = a; check < b; ++check) { total += countRecycle(check, b); } System.out.printf(""Case #%d: %d\n"", ii, total); } } public int countRecycle(int num, int max) { int size = getSize(num); //12345, size = 4, 10000, size = 4, 9999, size = 3 HashSet valid = new HashSet(); for(int i = 1; tens[i] <= num; ++i) { int newNum = (num/tens[i]) + (num%tens[i])*(tens[size-i+1]); if(newNum <= max && newNum > num) valid.add(newNum); } return valid.size(); } public int getSize(int a) { int size = 0; while(tens[size] <= a) ++size; return size - 1; } }" B12737,"import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Scanner; import java.util.Set; public class Main { public Scanner sc; public Map mapping = new HashMap(); public static void main(String[] args) { Main m = new Main(); m.start(); } public void start() { sc = new Scanner(System.in); int t = sc.nextInt(); for (int i = 1; i <= t; i++) { System.out.print(""Case #"" + i + "": ""); solve(); } } public void solve() { int a = sc.nextInt(); int b = sc.nextInt(); int ans = 0; Set checked = new HashSet(); for (int n = a; n <= b; n++) { if (n < 10 || n == 1000) { continue; } char[] charArr = Integer.toString(n).toCharArray(); if (charArr.length == 2) { if (charArr[1] != '0') { char[] newChar = { charArr[1], charArr[0] }; int newInt = Integer.valueOf(String.valueOf(newChar)); if (!checked.contains(n + "" "" + newInt) && n < newInt && newInt >= a && newInt <= b) { checked.add(n + "" "" + newInt); ans++; } } } else if (charArr.length == 3) { // if (charArr[0] != '0') { // char[] newChar1 = { charArr[0], charArr[2], charArr[1] }; // int newInt = Integer.valueOf(String.valueOf(newChar1)); // if (!checked.contains(n + "" "" + newInt) && n < newInt && newInt >= a && newInt <= b) { // checked.add(n + "" "" + newInt); // ans++; // } // } if (charArr[1] != '0') { // char[] newChar2 = { charArr[1], charArr[0], charArr[2] }; // int newInt = Integer.valueOf(String.valueOf(newChar2)); // if (!checked.contains(n + "" "" + newInt) && n < newInt && newInt >= a && newInt <= b) { // checked.add(n + "" "" + newInt); // ans++; // } char[] newChar3 = { charArr[1], charArr[2], charArr[0] }; int newInt = Integer.valueOf(String.valueOf(newChar3)); if (!checked.contains(n + "" "" + newInt) && n < newInt && newInt >= a && newInt <= b) { checked.add(n + "" "" + newInt); ans++; } } if (charArr[2] != '0') { char[] newChar4 = { charArr[2], charArr[0], charArr[1] }; int newInt = Integer.valueOf(String.valueOf(newChar4)); if (!checked.contains(n + "" "" + newInt) && n < newInt && newInt >= a && newInt <= b) { checked.add(n + "" "" + newInt); ans++; } // char[] newChar5 = { charArr[2], charArr[1], charArr[0] }; // newInt = Integer.valueOf(String.valueOf(newChar5)); // if (!checked.contains(n + "" "" + newInt) && n < newInt && newInt >= a && newInt <= b) { // checked.add(n + "" "" + newInt); // ans++; // } } } } System.out.println(ans); // for (String string : checked) { // System.out.println(string); // } // System.out.println(checked.size()); } } " B12551,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class C { private class OutputDelegate { BufferedWriter out; private OutputDelegate(String fileName) { try { out = new BufferedWriter(new FileWriter(fileName)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void write(String output) { try { out.write(output); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void writeLine(String output) { try { write(output); out.newLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void close() { try { if (out != null) { out.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private class InputDelegate { BufferedReader in; private InputDelegate(String fileName){ try { in = new BufferedReader(new FileReader(fileName)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private int[] readIntLine() { String line; String income[] = null; try { if ((line = in.readLine()) != null) { income = line.split("" ""); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } int array[] = new int[income.length]; for (int i = 0; i < array.length; i++) { array[i] = (Integer.parseInt(income[i])); } return array; } private void close() { try { in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void process(String[] args) { InputDelegate in = new InputDelegate(args[0]); OutputDelegate out = new OutputDelegate(args[1]); int cases = in.readIntLine()[0]; for (int i = 1; i <= cases; i++) { int count = 0; int[] line = in.readIntLine(); for(int num = line[0]; num <= line[1]; num++) { int[] possibs = getPossib(num); for (int j = 1; j < possibs.length; j++) { if(possibs[j] == -1) continue; if(possibs[j] > num && possibs[j] <= line[1]) { count++; } } } out.writeLine(""Case #"" + i + "": "" + count); } in.close(); out.close(); } public int[] getPossib(int num) { /*returns possibilities*/ int digit = Integer.toString(num).length(); int[] possib = new int[digit]; possib[0] = num; for (int i = 1; i < possib.length; i++) { int next = possib[i-1]; int lastd = next%10; next = next/10+lastd*exponent(possib.length-1); if(!hasSame(next, possib)) possib[i] = next; else possib[i] = -1; } return possib; } public boolean hasSame(int number, int[] possib) { for (int i = 0; i < possib.length; i++) { if(number == possib[i]) return true; } return false; } private int exponent(int exp) { int a = 1; for (int i = 0; i < exp; i++) { a = a*10; } return a; } public static void main(String[] args) { C m = new C(); m.process(args); } } " B10923,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package utils; /** * * @author fabien */ public interface JamCaseSolver { public void parse(); public void solve(); }" B11940,"import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Ari */ public class ProblemC { static String in = ""src/c.in""; static String out = ""src/c.out""; public static void main(String[] args) throws FileNotFoundException, IOException { Scanner scan = new Scanner(new File(in)); BufferedWriter write = new BufferedWriter(new FileWriter(out)); int numlines = scan.nextInt(); String mini; String maxi; byte[] min = new byte[7]; byte[] max = new byte[7]; byte[] iter = new byte[7]; int numDigits; int numPossible; int answer; int[] rots = new int[7]; byte currentRots; byte compare = 0; //Loop vars: int x; int y; int d; int m; int n; int rot; int count; for(x = 0; x < numlines; x++) { write.write(""Case #"" + (x+1) + "": ""); mini = scan.next(); maxi = scan.next(); answer = 0; numPossible = Integer.parseInt(maxi) - Integer.parseInt(mini); numDigits = mini.length(); for(y = 0; y < numDigits; y++) { min[y] = Byte.parseByte(""""+mini.charAt(y)); iter[y] = min[y]; max[y] = Byte.parseByte(""""+maxi.charAt(y)); } for(count = 0; count < numPossible; count++) { currentRots = 0; for(rot = 1; rot < numDigits; rot++) { compare = 0; for(d = 0; d < numDigits - 1; d++) { compare = iter[(d + rot) % numDigits]; if(compare > iter[d]) { compare = -2; break; } else if(compare < iter[d]) { compare = -1; break; } } if(compare > -1) { if(iter[(numDigits + rot - 1) % numDigits] > iter[numDigits - 1]) { compare = -2; } } if(compare == -2) {//rotation is greater for(d = 0; d < numDigits; d++) { compare = iter[(d + rot) % numDigits]; if(compare > min[d]) { compare = 1; break; } else if(compare < min[d]) { compare = -1; break; } } if(compare > -1) {//>=min for(d = 0; d < numDigits; d++) { compare = iter[(d + rot) % numDigits]; if(compare > max[d]) { compare = -1; break; } else if(compare < max[d]) { compare = 1; break; } } if(compare > -1) {//<=max rots[currentRots] = rot; currentRots++; answer++; } } } } for(n = 0; n < currentRots-1; n++) { for(m = n+1; m < currentRots; m++) { for(d = 0; d < numDigits; d++) { compare = iter[(d + rots[n]) % numDigits]; compare -= iter[(d + rots[m]) % numDigits]; if(compare != 0) { compare = 1; break; } } if(compare == 0) { answer--; break; } } } for(d = numDigits-1; d >= 0; d--) { if(iter[d] == 9) { iter[d] = 0; } else { iter[d]++; break; } } } write.write("""" + answer); write.write('\n'); } scan.close(); write.close(); } private static void print(byte[] iter, int rot) { for(int d = 0; d < iter.length; d++) { System.out.print(""""+iter[(d + rot) % iter.length]); } } private static int get(byte[] iter, int rot, int length) { String s = """"; for(int d = 0; d < length; d++) { s+=iter[(d + rot) % length]; } return Integer.parseInt(s); } } " B12188,"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; public class RecycledNumbers { ArrayList result = new ArrayList<>(); public void solve(int A, int B){ HashSet distinct = new HashSet<>(); HashSet testM = new HashSet<>(); for(int n=A;nn){ distinct.add(nStr+mStr); } } } result.add(""""+distinct.size()); } public void saveResults(String file){ try { FileWriter fstream = new FileWriter(file); BufferedWriter out = new BufferedWriter(fstream); int count = 1; for(int i=0;i> map = new HashMap>(); int start = scanner.nextInt(); int finish = scanner.nextInt(); int count = 0; for(int x = start;x<=finish;x++) { map.put(x, new HashSet()); String s = """" + x; int length = s.length(); for(int i=1;i num && x <= B && x != prev){ result ++; prev = x; } factor *= 10; toFront = num%factor; toBack = num/factor; } num ++; } System.out.println(""Case #"" + caseNum + "": "" + result); } }" B13143,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class Reader { public Case[] read() { BufferedReader bf; Case[] cases = null; try { bf = new BufferedReader(new FileReader(""in"")); int numTestCase = Integer.parseInt(bf.readLine()); cases = new Case[numTestCase]; for(int case_index = 0;case_index < numTestCase;case_index++){ cases[case_index] = new Case(); cases[case_index].ind = case_index + 1; ///////// String linea = bf.readLine(); String[] nums = linea.split("" ""); cases[case_index].a = Double.parseDouble(nums[0]); cases[case_index].b = Double.parseDouble(nums[1]); //////// } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return cases; } } " B11331,"package Qualification_2012; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; public class RecycledNumbers { static BufferedReader in; static int A, B; static boolean[][] v; static HashSet hash; private static int get(int x) { int tmp = x; int c = 0; HashSet hh = new HashSet(); int len = (x + """").length(); int pow = (int) Math.pow(10, len); for (int i = 0; i < len - 1; i++) { boolean f = false; if (x % 10 == 0) f = true; x = ((x % 10) * pow + x) / 10; if (f) continue; if (x >= A && x <= B && tmp < x && len == (x + """").length()) { if (!hh.contains(x)) { hh.add(x); c++; } } } return c; } private static String solve() throws IOException { hash = new HashSet(); String s[] = in.readLine().split("" ""); long ans = 0; A = Integer.parseInt(s[0]); B = Integer.parseInt(s[1]); for (int i = A; i < B; i++) ans += get(i); return ans + """"; } public static void main(String[] args) throws IOException { in = new BufferedReader(new FileReader(""in.in"")); FileWriter out = new FileWriter(""out.out""); int t = Integer.parseInt(in.readLine()); for (int i = 1; i <= t; i++) { out.write(""Case #"" + i + "": "" + solve() + ""\n""); } in.close(); out.close(); } } " B11473,"import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledTester { public static void main(String[] args) throws IOException { new RecycledTester().run(""C-small-attempt0.in""); // new RecycledTester().run(""problem.txt""); } public void run(String fileName) throws IOException { parseFile(fileName); } private void parseFile(String fileName) throws FileNotFoundException { File file = new File(fileName); Scanner scanner = new Scanner(file); int numTests = Integer.parseInt(scanner.nextLine()); for (int i = 1; i <= numTests; i++) { System.out.println(""Case #"" + i + "": "" + solve(scanner.nextLine())); } scanner.close(); } public String solve(String line) { Scanner ls = new Scanner(line); Solver solver = new Solver(ls.nextInt(), ls.nextInt()); return Integer.toString(solver.solve()); } } class Solver { private final int a; private final int b; private final int c; private final Set counted = new HashSet(); Solver(int a, int b) { this.a = a; this.b = b; this.c = Integer.toString(a).length(); } public int solve() { if (c == 0) return 0; int n = 0; for (int i = a; i <= b; i++) { n += isRecycled(i); } return n; } public int isRecycled(int n) { String t = Integer.toString(n); Set pairCandidates = new HashSet(); pairCandidates.add(n); for (int i = 0; i < c - 1; i++) { t = shift(t); int m = Integer.valueOf(t); if (n != m && a <= m && m <= b && !counted.contains(m)) { pairCandidates.add(m); counted.add(m); } } counted.add(n); return pairCandidates.size() * (pairCandidates.size() - 1) / 2; } public String shift(String t) { return t.substring(1) + t.charAt(0); } } " B13267,"import java.util.*; import java.io.*; class Try{ public static int equate(String currentNumber, String reversibleNumber){ int count=0; char splitPoint = currentNumber.charAt(0); for (int i=0;i ms; ms=shift(n,l); for(String key : ms.keySet()) { int m = ms.get(key); if(n shift(int n, int l) { HashMap ms = new HashMap(); String N = String.valueOf(n); String m; for(int j=1;j set = new HashSet(); for ( int i = from; i <= to; ++i ) { add( set, i, from, to ); } return String.format( ""Case #%d: %d"", idx, set.size() ); } private static void add( final HashSet set, final long n, final int from, final int to ) { final String ns = Long.toString( n ); for ( int i = 1; i < ns.length(); ++i ) { final String f = ns.substring( 0, i ); final String t = ns.substring( i ); final long pair = getN( t, f ); final long min = Math.min( n, pair ); final long max = Math.max( n, pair ); if ( from <= pair && pair <= to && pair != n ) set.add( min * 3000000 + max ); } } private static long getN( final String s1, final String s2 ) { long res = 0; for ( int i = 0; i < s1.length(); ++i ) { res += s1.charAt( i ) - '0'; res *= 10; } for ( int i = 0; i < s2.length(); ++i ) { res += s2.charAt( i ) - '0'; res *= 10; } if ( DEBUG ) System.out.printf( ""DEBUG: s1='%s', s2='%s', res=%d\n"", s1, s2, res / 10 ); return res / 10; } @org.junit.Test public void statement1() { org.junit.Assert.assertEquals( String.format( ""Case #%d: %d"", 1, 0 ), solve( 1, 1, 9 ) ); } @org.junit.Test public void statement2() { org.junit.Assert.assertEquals( String.format( ""Case #%d: %d"", 2, 3 ), solve( 2, 10, 40 ) ); } @org.junit.Test public void statement3() { org.junit.Assert.assertEquals( String.format( ""Case #%d: %d"", 3, 156 ), solve( 3, 100, 500 ) ); } @org.junit.Test public void statement4() { org.junit.Assert.assertEquals( String.format( ""Case #%d: %d"", 4, 287 ), solve( 4, 1111, 2222 ) ); } @org.junit.Test(timeout = 10000) public void my1() { org.junit.Assert.assertEquals( String.format( ""Case #%d: %d"", 5, 299997 ), solve( 5, 1000000, 2000000 ) ); } } " B12037,"import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Scanner; public class C { Scanner in; PrintWriter out; PrintStream err; private boolean recycled(int x, int y) { String s1 = Integer.toString(x); String s2 = Integer.toString(y); if (s1.length() != s2.length()) return false; for (int i = 0; i < s1.length(); ++i) if (s1.equals(s2.substring(i) + s2.substring(0, i))) return true; return false; } private void run() throws Exception { //in = new Scanner(System.in); //out = new PrintWriter(System.out); //in = new Scanner(new FileInputStream( new File(""input""))); in = new Scanner(new FileInputStream( new File(""C-small-attempt0.in""))); //in = new Scanner(new FileInputStream( new File(""X-large.in""))); out = new PrintWriter(new FileOutputStream( new File(""output""))); err = System.out; int testCases = in.nextInt(); for (int test = 1; test <= testCases; ++test) { int a = in.nextInt(); int b = in.nextInt(); int result = 0; for (int i = a; i <= b; ++i) for (int j = i+1; j <= b; ++j) if (recycled(i, j)) result++; out.println(""Case #"" + test + "": "" + result); } out.close(); } public static void main(String[] args) throws Exception { new C().run(); } }" B11478,"package qualification.C; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { public static void main(String[] args) { int totalCase = 0; int a = 0; int b = 0; FileInputStream is = null; try { is = new FileInputStream(args[0]); Scanner scan = new Scanner(is); totalCase = scan.nextInt(); for (int i = 0; i < totalCase; i++) { a = scan.nextInt(); b = scan.nextInt(); solve(i, a, b); } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } private static void solve(int caseNo, int a, int b) { Set s = new HashSet(); for(int i = a; i <= b; i++) { String num = Integer.toString(i); if (num.matches(""^[""+num.substring(0,1)+""]+$"")) { //System.out.println(num); continue; } if (num.matches(""^[1-9][0]+$"")) { //System.out.println(num); continue; } s.add(i); } int answer = 0; for(int n = a; !s.isEmpty() && n <= b; n++) { if (!s.contains(n)) { continue; } String ns = Integer.toString(n, 10); int length = ns.length(); Set dup = new HashSet(); for (int j = 1; j < length; j++) { String ms = ns.substring(length-j) + ns.substring(0, length-j); //System.out.println(ns+"":""+ms); int m = Integer.parseInt(ms); if (!s.contains(m)) { continue; } if (m < a || b < m || n >= m) { continue; } s.remove(m); if (!dup.contains(m)) { dup.add(m); } answer++; } int size = dup.size(); if (size > 1) { answer = answer + size * (size - 1) / 2; } s.remove(n); } StringBuilder sb = new StringBuilder(); sb.append(""Case #""); sb.append(caseNo+1); sb.append("": ""); sb.append(answer); System.out.println(sb.toString()); } } " B10828,"package problemC; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.StringTokenizer; public class RecycledNumbers { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(""C-small-attempt0.in"")); FileWriter fw = new FileWriter(""C-small-attempt0.out""); /*BufferedReader in = new BufferedReader(new FileReader(""C-large-practice.in"")); FileWriter fw = new FileWriter(""C-large-practice.out"");*/ int T = new Integer(in.readLine()); for (int cases = 1; cases <= T; cases++){ StringTokenizer st=new StringTokenizer(in.readLine()); int A = new Integer(st.nextToken()); int B = new Integer(st.nextToken()); int num_bits = 0; long result = 0; int tempn = B; HashSet hs = new HashSet(); while (tempn > 0){ num_bits++; tempn = tempn/10; } if (num_bits == 1) { result = 0; }else { for (int target = A; target <= B; target++){ if(!hs.contains(target)){ int temp = target; int p = 1; int bit = 0; for (int t = 1 ; t < num_bits; t++){ bit = temp % 10; temp = temp/10; if (bit != 0){ temp = temp + (int) (bit * Math.pow(10, num_bits-1)); if ((temp >= A) && (temp <= B) && (temp!=target)&&(!hs.contains(temp))){ hs.add(target); hs.add(temp); p++; } } } result = result + (p*(p-1))/2; } } } if (cases != T) {fw.write(""Case #"" + cases + "": ""+ result + ""\n""); } else {fw.write(""Case #"" + cases + "": ""+ result);} } fw.flush(); fw.close(); } } " B12554,"import java.util.HashSet; import java.util.Scanner; public class qualifier3 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int numcases = sc.nextInt(); sc.nextLine(); for(int curcase = 1;curcase <=numcases;curcase++) { int min = sc.nextInt(); int max = sc.nextInt(); int numdigits = 0; for(int i=max;i>0;i/=10,numdigits++); int tennum =1; for(int i=0;i seen = new HashSet(); int mult =1; for(int j=1;ji)&&(mine<=max)&&(!seen.contains(mine))) { count++; seen.add(mine); } } } sc.nextLine(); System.out.println(""Case #""+curcase+"": ""+count); } } } " B12850,"import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class RecycledNumbersSmall { /** * @param args */ public static void main(String[] args) throws Exception { int noTestcases; FileInputStream fis = new FileInputStream(""D:/Eclipse Workspaces/ws_hyperbola/Recycled Numbers/src/example.txt""); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String sLine = br.readLine(); noTestcases = Integer.parseInt(sLine); StringBuffer sb = new StringBuffer(); List outputList = new ArrayList(); for(int i = 1; i <= noTestcases && (sLine = br.readLine()) != null; i++) { String[] numLimits = sLine.split("" ""); int lowerLimit = Integer.parseInt(numLimits[0]); int upperLimit = Integer.parseInt(numLimits[1]); int noRecycledPairs = getRecycledpairsCount(lowerLimit, upperLimit); System.out.println(""Case #"" + i + "": "" + noRecycledPairs); outputList.add(""Case #"" + i + "": "" + noRecycledPairs); } writeOutput(outputList); br.close(); fis.close(); } private static void writeOutput(List lines) throws Exception { FileWriter fw = new FileWriter(""D:/Eclipse Workspaces/ws_hyperbola/Recycled Numbers/src/output.txt""); PrintWriter pw = new PrintWriter(fw); for(String line : lines) { pw.println(line); } pw.flush(); pw.close(); } private static int getRecycledpairsCount(int smallerNumber, int biggerNumber) { int result = 0; if(biggerNumber < 10) return 0; // 1 digit numbers if(isBetween(smallerNumber, 10, 99) && isBetween(biggerNumber, 10, 99)) { // 2 digit numbers Set setPair = new HashSet(); for(int num = smallerNumber; num <= biggerNumber; num++) { int recycledNum = shiftDigit(num, 1); if(recycledNum != num && isBetween(recycledNum, smallerNumber, biggerNumber)) { setPair.add(new RecycledPair(num, recycledNum)); } } //System.out.println(setPair.toString()); result = result + setPair.size(); } else if(isBetween(smallerNumber, 100, 999) && isBetween(biggerNumber, 100, 999)) { // 3 digit numbers Set setPair = new HashSet(); /* one digit shift */ for(int num = smallerNumber; num <= biggerNumber; num++) { int recycledNum = shiftDigit(num, 1); if(recycledNum != num && isBetween(recycledNum, smallerNumber, biggerNumber)) { setPair.add(new RecycledPair(num, recycledNum)); } } /* two digit shift */ for(int num = smallerNumber; num <= biggerNumber; num++) { int recycledNum = shiftDigit(num, 2); if(recycledNum != num && isBetween(recycledNum, smallerNumber, biggerNumber)) { setPair.add(new RecycledPair(num, recycledNum)); } } //System.out.println(setPair.toString()); result = result + setPair.size(); } else if(isBetween(smallerNumber, 1000, 9999) && isBetween(biggerNumber, 1000, 9999)) { // 3 digit numbers Set setPair = new HashSet(); /* 1 digit shift */ for(int num = smallerNumber; num <= biggerNumber; num++) { int recycledNum = shiftDigit(num, 1); if(recycledNum != num && isBetween(recycledNum, smallerNumber, biggerNumber)) { setPair.add(new RecycledPair(num, recycledNum)); } } /* 2 digit shift */ for(int num = smallerNumber; num <= biggerNumber; num++) { int recycledNum = shiftDigit(num, 2); if(recycledNum != num && isBetween(recycledNum, smallerNumber, biggerNumber)) { setPair.add(new RecycledPair(num, recycledNum)); } } /* 3 digit shift */ for(int num = smallerNumber; num <= biggerNumber; num++) { int recycledNum = shiftDigit(num, 3); if(recycledNum != num && isBetween(recycledNum, smallerNumber, biggerNumber)) { setPair.add(new RecycledPair(num, recycledNum)); } } //System.out.println(setPair.toString()); result = result + setPair.size(); } return result; } private static boolean isBetween(int number, int lowerLimit, int upperLimit) { return number >= lowerLimit && number <= upperLimit; } private static int shiftDigit(int number, int digitsNo) { String sNum = String.valueOf(number); int index = sNum.length() - digitsNo; String sNewNumber = sNum.substring(index) + sNum.substring(0, index); return Integer.parseInt(sNewNumber); } } " B10593,"package recyclednumbers; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; /** * * @author Masilo */ public class RecycledNumbers { public static void main(String[] args) { Scanner inputStream = null; PrintWriter outputStream = null; try{ inputStream = new Scanner(new FileInputStream(""input.txt"")); outputStream = new PrintWriter(new FileOutputStream(""output.txt"")); int t = Integer.parseInt(inputStream.nextLine()); String outputLine = """"; String[] inputNumbers = null; int numberOfRecycledPair =0; int number =0, length =0; for (int i = 1; i<=t;i++){ inputNumbers = inputStream.nextLine().split("" ""); numberOfRecycledPair = 0; outputLine = ""Case #""+i+"": ""; ArrayList pairs = new ArrayList(); length = inputNumbers[0].length(); if (length >1){ for (int n = Integer.parseInt(inputNumbers[0]);nn && number<=Integer.parseInt(inputNumbers[1])) if (!(pairs.contains(n+"":""+number))){ numberOfRecycledPair++; pairs.add(n+"":""+number); } } } } outputLine += """"+numberOfRecycledPair; outputStream.println(outputLine); } outputStream.close(); inputStream.close(); } catch(Exception e){ System.out.println(""file input.txt was not found""); } } } " B10397,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package rotatematrix; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; /** * * @author FARHAN */ public class Combination { int count =0; int num =10; int size=0; int Tranverse(int A,int B){ count=0; num = 1; size =0; while(A/num!=0){ num = num*10; size++; } num = num/10; for (int m = B; m >0 ; m--) { for(int n = A;n9;i++){ int rem = n%num; int x = n/num; rem *= 10; rem += x; if(rem==m){ //sSystem.out.println(""found""+rem+"" ""+m); count++; } n = rem; } return false; } boolean isFound(int n,int m){ String n_Str = Integer.toString(n); n_Str = n_Str.replaceAll(""^0*"", """"); String m_Str = Integer.toString(m); m_Str = m_Str.replaceAll(""^0*"", """"); int size = n_Str.length(); // for(int i=0;i readFile(String filename){ //replace local file with remote file from peerInfo address ArrayList ret= new ArrayList(); try { FileInputStream fstream = new FileInputStream(filename); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; //Read File Line By Line while ((strLine = br.readLine()) != null) { // Print the content on the console ret.add(strLine); } //Close the input stream in.close(); } catch (Exception e) { e.printStackTrace(); } return ret; } public static void writeFile(ArrayList input, String filename){ //replace local file with remote file from peerInfo address try{ // Create file FileWriter fstream = new FileWriter(filename); BufferedWriter out = new BufferedWriter(fstream); for (String string : input) { out.write(string+""\n""); } //Close the output stream out.close(); }catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } public static void compare(String filename1, String filename2){ //replace local file with remote file from peerInfo address try { FileInputStream fstream1 = new FileInputStream(filename1); // Get the object of DataInputStream DataInputStream in1 = new DataInputStream(fstream1); BufferedReader br1 = new BufferedReader(new InputStreamReader(in1)); String strLine1; FileInputStream fstream2 = new FileInputStream(filename2); // Get the object of DataInputStream DataInputStream in2 = new DataInputStream(fstream2); BufferedReader br2 = new BufferedReader(new InputStreamReader(in2)); String strLine2; boolean isDup=false; //Read File Line By Line while ((strLine1 = br1.readLine()) != null) { strLine2 = br2.readLine(); // Print the content on the console if(!strLine1.equals(strLine2)){ isDup=true; System.out.println(""1=""+strLine1+"", 2=""+strLine2); } } if(!isDup){ System.out.println(""same""); } //Close the input stream in1.close(); in2.close(); }catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } public static void sort(String input, String output){ //replace local file with remote file from peerInfo address ArrayList l= readFile(input); Collections.sort(l, new Comparator(){ public int compare(Object arg0, Object arg1) { String st1=(String)arg0; String st2=(String)arg1; int i1=Integer.parseInt(st1.substring(st1.indexOf('#')+1, st1.indexOf(':'))); int i2=Integer.parseInt(st2.substring(st2.indexOf('#')+1, st2.indexOf(':'))); return i1-i2; } }); writeFile(l, output); } } " B13228,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; public class ProblemC { /** * @param args */ public static void main(String[] args) { BufferedReader br = null; BufferedWriter bw = null; String input = null; StringBuffer output = null; String[] twonumbers = null; int min = 0, max = 0; ArrayList list = null; ArrayList list1 = null; String temp = null; String strmin = """"; int tempint = 0; int counter = 0; int digit1 = 0, digit2 = 0; try { br = new BufferedReader(new FileReader(new File( ""C:/Users/DHAVAL/Downloads/InputX.txt""))); bw = new BufferedWriter(new FileWriter(""output4.txt"")); int count = Integer.parseInt(br.readLine()); for (int i = 0; i < count; i++) { input = br.readLine(); output = new StringBuffer(""Case #"" + (i + 1) + "": ""); counter=0; // logic here list = new ArrayList(); list1 = new ArrayList(); twonumbers = input.split("" ""); min = Integer.parseInt(twonumbers[0]); max = Integer.parseInt(twonumbers[1]); if (max >= 10) { for (int j = min; j <= max; j++) { strmin = """" + j; temp = strmin; for (int k = 0; k < strmin.length() - 1; k++) { temp = temp.substring(1) + temp.charAt(0); tempint = Integer.parseInt(temp); digit1 = ("""" + tempint).length(); digit2 = strmin.length(); if (j < tempint && digit1 == digit2 && tempint >= min && tempint <= max && !list.contains(strmin + ""||"" + temp) //&& !list1.contains(temp) && !temp.equals(strmin)) { //System.out.println(strmin + "" "" + tempint); //list1.add(temp); list.add(strmin + ""||"" + temp); counter++; } } } } bw.write(output.toString() + counter); bw.newLine(); } bw.close(); } catch (Exception e) { e.printStackTrace(); } } } " B13150,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; public class Recycling { public static void main(String[] args) { try{ //Input FileInputStream fstream = new FileInputStream(""input.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); //Output FileWriter ostream = new FileWriter(""output.out""); BufferedWriter out = new BufferedWriter(ostream); String str; //Read header & get num cases str = br.readLine(); int numCases = Integer.parseInt(str); //Read File Line By Line for(int i = 1;i<=numCases;i++){ str = br.readLine(); String[] splitStr = str.split("" ""); int A = Integer.parseInt(splitStr[0]); int B = Integer.parseInt(splitStr[1]); int numPairs = 0; for(int n=A;n file, int line); List loadFile() throws IOException { FileReader inputStream = new FileReader(""C:\\projekt\\codejam\\src\\input.txt""); BufferedReader reader = new BufferedReader(inputStream); List list = new ArrayList(); while (true) { String line = reader.readLine(); if (line == null) { break; } list.add(line); } return list; } void go() throws IOException { List file = loadFile(); parseFirstLine(file); FileWriter writer = new FileWriter(""C:\\projekt\\codejam\\src\\otput.txt""); for (int c=0; c< caseCount; c++) { JamCase casee= parseCase(file, lastLine); lastLine += casee.lineCount; String s = solveCase(casee); writer.write(""Case #"" + (c+1) +"": "" + s + ""\n""); } writer.close(); } void parseFirstLine(List file) { int[] firstLine = JamUtil.parseIntList(file.get(0), 1); this.caseCount = firstLine[0]; lastLine = 1; } } " B10312,"package qualification.c; import java.util.HashSet; import java.util.Scanner; import java.util.Set; import common.ClockWatch; import common.ISolver; import common.QuestionHandler; public class RecycledNumbers implements ISolver { private int addCountSign(Set signatures, Set tmpSig, int val, int min, int max) { String valStr = String.valueOf(val); int len = valStr.length(); char[] chars = new char[len * 2]; for (int i = 0; i < len; ++i) { chars[i] = valStr.charAt(i); chars[i + len] = valStr.charAt(i); } int presentSigCount = 0; tmpSig.clear(); for (int i = 1; i < len; ++i) { if (chars[i] != '0') { Integer sig = Integer.valueOf(new String(chars, i, len)); if (sig >= min && sig <= max) { if (tmpSig.add(sig) && signatures.contains(sig)) { ++presentSigCount; } } } } signatures.add(val); return presentSigCount; } @Override public String solve(String problem) { Scanner scan = new Scanner(problem); int min = scan.nextInt(); int max = scan.nextInt(); Set signatures = new HashSet(); Set tmpSig = new HashSet(); int result = 0; for (int i = min; i <= max; ++i) { result += addCountSign(signatures, tmpSig, i, min, max); } return String.valueOf(result); } @Override public void addCase(String problem, String answer) { String myAnswer = solve(problem); if (!myAnswer.equals(answer)) { throw new RuntimeException(""Invalid prediction for '"" + problem + ""'. Expected '"" + answer + ""' got '"" + myAnswer + ""'""); } } public static void main(String[] args) { ClockWatch watch = new ClockWatch(); QuestionHandler questionHandler = new QuestionHandler( new RecycledNumbers()); questionHandler.addResource(""sample.in"", ""sample.out""); watch.tic(); // System.out.println(""Sample input:""); // questionHandler.solve(""sample.in"", ""sample.out""); System.out.println(""\nSmall input:""); questionHandler.solve(""small.in"", ""small.out""); // System.out.println(""\nLarge input:""); // questionHandler.solve(""large.in"", ""large.out""); watch.printTocSecs(); } } " B11752,"public class CodeJamLineParser { private final String[] tokens; private int position; public CodeJamLineParser(String line) { tokens = line.split(""\\s""); position = 0; } public boolean hasNextField() { return hasNextFields(1); } public int remainingFields() { return tokens.length - position; } public boolean hasNextFields(int count) { return remainingFields() >= count; } public String readNextStr() { return tokens[position++]; } public int readNextInt() { return Integer.parseInt(readNextStr()); } public int[] readNextIntList(int numOfInts) { int[] result = new int[numOfInts]; for (int i = 0; i < numOfInts; ++i) { result[i] = readNextInt(); } return result; } } " B10089,"package com.gcj.recyclednumbers; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @original Apr 14, 2012 12:08:21 PM * @author lewisju */ public class Solve { final Set distinct = new HashSet(); final int a; final int b; public Solve(int a, int b) { this.a = a; this.b = b; for(int i = a; i <= b; i++) { List ints = recycled(i); for(int recycled : ints) { if(recycled <= b && recycled >= a) { RecycledPair p = new RecycledPair(i,recycled); distinct.add(p); } } } } private List recycled(int number) { ArrayList list = new ArrayList(); String s = Integer.toString(number); for(int i=1; i < s.length(); i++) { int splitpoint = s.length()-i; String begin = s.substring(0, splitpoint); String end = s.substring(splitpoint); String result = end+begin; if(!result.startsWith(""0"") && !result.equals(s)) list.add(Integer.parseInt(result)); } return list; } public int count() { return distinct.size(); } class RecycledPair { private final int a; private final int b; public RecycledPair(int i, int recycled) { if(i < recycled) { a = i; b = recycled; } else { a = recycled; b = i; } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + a; result = prime * result + b; return result; } @Override public boolean equals(Object obj) { RecycledPair other = (RecycledPair) obj; return a==other.a && b==other.b; } @Override public String toString() { return """"+a+"" ""+b; } } public static void main(String[] args) { try { BufferedReader reader = new BufferedReader(new FileReader(""input.txt"")); String T = reader.readLine(); int t = Integer.parseInt(T); for(int i=0; i < t; i++) { String line = reader.readLine(); String[] inputs = line.split("" ""); int a = Integer.parseInt(inputs[0]); int b = Integer.parseInt(inputs[1]); Solve s = new Solve(a, b); StringBuffer sb = new StringBuffer(); sb.append(""Case #""); sb.append((i+1)); sb.append("": ""); sb.append(s.count()); System.out.println(sb.toString()); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B12844,"package ru.guredd.codejam; import java.util.Arrays; import java.util.StringTokenizer; public class Qualification2012C { public void solve() { int count = Integer.valueOf(Main.inputData.get(0)); for (int i = 0; i < count; i++) { int result = 0; String data = Main.inputData.get(i + 1); StringTokenizer st = new StringTokenizer(data, "" ""); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); for (int j = A; j <= B; j++) { result += calculateRecycled(j,j,A,B); } Main.outputData.add(""Case #"" + (i + 1) + "": "" + result); } } private int calculateRecycled(int v, int orig, int A, int B) { char[] charV = String.valueOf(v).toCharArray(); char[] shiftedV = new char[charV.length]; do { System.arraycopy(charV, 1, shiftedV, 0, charV.length - 1); shiftedV[charV.length - 1] = charV[0]; charV = Arrays.copyOf(shiftedV, shiftedV.length); } while (shiftedV[0]=='0'); int shiftedVal = Integer.valueOf(String.valueOf(shiftedV)); if (shiftedVal == orig) { return 0; } if (shiftedVal >= A && shiftedVal <= B && shiftedVal > orig) { return 1 + calculateRecycled(shiftedVal, orig, A, B); } else { return calculateRecycled(shiftedVal, orig, A, B); } } } " B11646,"package com.jp.common; import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.FileReader; import java.io.PrintStream; import java.util.Scanner; public class InputOutputProcessor { private int numberOfCases; private boolean doesInputHaveDataSetLines; private int indexOfDataSetLine; private int numberOfDataSetLines; private final static String DELIMITER = "" ""; private Scanner scanInput; public void initializeInput(String strInputFileName) { readInput(strInputFileName); numberOfCases = Integer.parseInt(scanInput.nextLine()); } /* * read input */ private void readInput(String strInputFileName) { try { scanInput = new Scanner(new BufferedReader(new FileReader( strInputFileName))); } catch (Exception exp) { // exp.printStackTrace(); System.out.println("" Please provide File Name with proper location ""); } } public String[] getDataSet() throws Exception { String[] dataSet; String strDataSetLine = """"; strDataSetLine = scanInput.nextLine(); if (doesInputHaveDataSetLines) { String[] DataSetLineArray = strDataSetLine.split(DELIMITER); numberOfDataSetLines = Integer .parseInt(DataSetLineArray[indexOfDataSetLine]); } dataSet = new String[numberOfDataSetLines]; dataSet[0] = strDataSetLine; for (int i = 1; i < numberOfDataSetLines; i++) { dataSet[i] = scanInput.nextLine(); } return dataSet; } /** * * @return Returns the numberOfDataSetLines. */ public int getNumberOfDataSetLines() { return numberOfDataSetLines; } /** * @param numberOfDataSetLines * The numberOfDataSetLines to set. */ public void setNumberOfDataSetLines(int numberOfDataSetLines) { this.numberOfDataSetLines = numberOfDataSetLines; } /** * * @return Returns the numberOfCases. */ public int getNumberOfCases() { return numberOfCases; } /** * * @return Returns the doesInputHaveDataSetLines. */ public boolean isDoesInputHaveDataSetLines() { return doesInputHaveDataSetLines; } /** * @param doesInputHaveDataSetLines * The doesInputHaveDataSetLines to set. */ public void setDoesInputHaveDataSetLines(boolean doesInputHaveDataSetLines) { this.doesInputHaveDataSetLines = doesInputHaveDataSetLines; } /** * * @return Returns the indexOfDataSetLine. */ public int getIndexOfDataSetLine() { return indexOfDataSetLine; } /** * @param indexOfDataSetLine * The indexOfDataSetLine to set. */ public void setIndexOfDataSetLine(int indexOfDataSetLine) { this.indexOfDataSetLine = indexOfDataSetLine; } public void closeScanner() { scanInput.close(); } public void writeOutput(String outputFileName, String[] resultArray) { PrintStream out = null; try { out = new PrintStream(new FileOutputStream(outputFileName)); for (int i = 0; i < resultArray.length; i++) { out.print(resultArray[i]); out.print(""\n""); } out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(0); } } } " B11589,"import java.util.Scanner; public class RecycledNumbers { public static int countRecycledNumbers(int a,int b){ int count=0; int t[][] = new int[(b-a)+1][(b-a)+1]; for(int i=0; i<(b-a)+1; i++){ for(int j=0; j<(b-a)+1; j++){ t[i][j]=0; } } int max = String.valueOf(a).length(); for(int j=a; j<=b; j++){ int n = j; for(int i=1; i read(BufferedReader r) throws NumberFormatException, IOException { ArrayList s = new ArrayList(); int n = Integer.parseInt(r.readLine()); for (int i = 0 ; i < n ; i ++ ) s.add(r.readLine()); return s; } } " B10522,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.*; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * * @author Sagar */ public class Recycled_Numbers { Map m; int no_of_test_cases = 0; StringBuffer [] sb; Integer []output ; String inputfile = """"; String outputfile = """"; Integer [][] input ; int no_of_digits = 0; public Recycled_Numbers() { m = new HashMap(); } public void setInputOutput(String input, String output) { inputfile = input; outputfile = output; } public void readFile() { String line=""""; boolean firstTime = true; int i = 0; try { FileReader filename = new FileReader(inputfile); BufferedReader reader = new BufferedReader(filename); while((line=reader.readLine()) !=null) { if(firstTime) { firstTime = false; no_of_test_cases = Integer.parseInt(line); System.out.println(""testcases:""+no_of_test_cases); output = new Integer[no_of_test_cases]; for (int s = 0;s map = new HashMap(); for (int i=0;ij && (m<=input[i][1])) { if(!map.containsKey(outputbuf.toString())) map.put(outputbuf.toString(),new Integer(1)); } num = new StringBuffer(outputbuf.toString()); // System.out.println(""Num 2: ""+ num.toString()); } //System.out.println(""Map size "" + map.size()); output[i] = output[i] + new Integer (map.size()); map.clear(); } // System.out.println(""OutPut""+i+ +output[i]); } } public void displayOutput() { try { // Create file FileWriter fstream = new FileWriter(outputfile); BufferedWriter out = new BufferedWriter(fstream); for(int i=0;ij&&y<=b) c[i]++; } while(y!=j); } } for(int i=0;i used = new HashSet(); for(int j=1;j=from && intTmp<=to && intTmp> n) { count++; used.add(tmp); } } } String msg = ""Case #""+(t+1)+"": ""+count; System.out.println(msg); writer.println(msg); scanner.nextLine(); } writer.close(); } } " B12020,"import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { Scanner in = new Scanner(new FileReader(""C-small-attempt0.in"")); PrintWriter out = new PrintWriter(new FileWriter(""RecycledNumbers-Small.out"")); RecycledNumbers solver = new RecycledNumbers(); int testCases = in.nextInt(); for (int i = 1; i <= testCases; ++i) { solver.solve(i, in, out); } in.close(); out.close(); } } class RecycledNumbers { int numberOfRecycledPairs(int A, int B) { int res = 0; boolean[] seen = new boolean[B + 1]; for (int i = A; i <= B; ++i) { if (seen[i]) continue; int pairs = 0; char[] S = String.valueOf(i).toCharArray(); for (int j = 0; j < S.length; ++j) { if (S[j] == '0') continue; int m = 0; for (int k = j; k < S.length; ++k) m = m * 10 + S[k] - '0'; for (int k = 0; k < j; ++k) m = m * 10 + S[k] - '0'; if (A <= m && m <= B && !seen[m]) { seen[m] = true; ++pairs; } } res += pairs * (pairs - 1) / 2; } return res; } public void solve(int testNumber, Scanner in, PrintWriter out) { int A = in.nextInt(); int B = in.nextInt(); out.println(""Case #"" + testNumber + "": "" + numberOfRecycledPairs(A, B)); } } " B12631," import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class RecycledNumbers { public static final String INPUT = ""C-small-attempt0.in""; public static final String OUTPUT = ""output""; public static void main(String args[]) throws IOException{ Scanner s = UtilGoogle.readFile(INPUT); PrintWriter w = UtilGoogle.writeFile(OUTPUT); int t = Integer.parseInt(s.nextLine()); for(int i = 0; i < t; i++){ Integer A = s.nextInt(); Integer B = s.nextInt(); Integer N = calculateRecycleds(A, B); w.println(""Case #"" + (i + 1) + "": "" + N); } s.close(); w.close(); } public static Integer calculateRecycleds(Integer A, Integer B){ Integer qtd = 0; for(Integer i = A; i < B; i++){ for(Integer j = i + 1; j <= B; j++){ if(isRecycled(i, j)) qtd++; } } return qtd; } public static boolean isRecycled(Integer n, Integer m){ String first = String.valueOf(n); String second = String.valueOf(m); for(int i = 0; i < first.length() - 1; i++){ String temp = second.substring(i + 1, first.length()); temp = temp.concat(second.substring(0, i+1)); if(temp.equals(first)) return true; } return false; } } " B10971," import java.io.BufferedReader; import java.util.*; import java.io.File; import java.io.FileReader; import java.io.IOException; public class program { /** * @param args * * Reads the input file for test cases. */ //main method for Problem A. public static void SolveA(String[] args) { // TODO Auto-generated method stub File inFile = new File(""/home/kolive/Programming/GoogleCodeJam_2012/in""); try { BufferedReader myReader = new BufferedReader(new FileReader(inFile)); String tmp = """"; int i = 1; tmp = myReader.readLine(); while( (tmp = myReader.readLine()) != null) { System.out.print(""\nCase #"" + i + "": "" + ProblemA.translateString(tmp)); i++; } } catch (IOException e) { System.out.println(""Exception Caught: "" + e); } } public static void SolveB(String[] args) { // TODO Auto-generated method stub File inFile = new File(""/home/kolive/Programming/GoogleCodeJam_2012/in""); try { BufferedReader myReader = new BufferedReader(new FileReader(inFile)); String tmp = """"; int i = 1; tmp = myReader.readLine(); while( (tmp = myReader.readLine()) != null) { String arguments[] = tmp.split("" ""); System.out.print(""\nCase #"" + i + "": "" + ProblemB.GenerateMaxP(Integer.parseInt(arguments[2]), Arrays.copyOfRange(arguments, 3, arguments.length), Integer.parseInt(arguments[1]))); i++; } } catch (IOException e) { System.out.println(""Exception Caught: "" + e); } } public static void main(String args[]) { File inFile = new File(""/home/kolive/Programming/GoogleCodeJam_2012/in""); try { Scanner scanner = new Scanner(inFile); int tmp = 0; int i = 1; tmp = scanner.nextInt(); while(i <= tmp) { System.out.print(""\nCase #"" + i + "": "" + ProblemC.solveC(scanner.nextInt(), scanner.nextInt())); i++; } } catch (IOException e) { System.out.println(""Exception Caught: "" + e); } } } " B12154,"import java.io.*; import java.util.Arrays; import java.util.StringTokenizer; public class C { BufferedReader in; StringTokenizer str; PrintWriter out; String SK; String next() throws IOException { while ((str == null) || (!str.hasMoreTokens())) { SK = in.readLine(); if (SK == null) return null; str = new StringTokenizer(SK); } return str.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } String make(int j) { String a = j + """"; String res = a; for (int i = 0; i < a.length(); i++) { if (a.compareTo(res) < 0) { res = a; } char c = a.charAt(0); a = a.substring(1, a.length()) + """" + c; } return res; } void solve() throws IOException { int a = nextInt(); int b = nextInt(); int res = 0; for (int i = a; i <= b; i++) { for (int j = i + 1; j <= b; j++) { if (make(i).equals(make(j))) { res++; } } } out.println(res); } void run() throws IOException { in = new BufferedReader(new FileReader(""fn.in"")); out = new PrintWriter(""fn.out""); int n = nextInt(); for (int i = 0; i < n; i++) { out.print(""Case #"" + (i + 1) + "": ""); solve(); } out.close(); } public static void main(String[] args) throws IOException { new C().run(); } }" B12680,"import java.util.*; public class recycled_numbers { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int T = scanner.nextInt(); int[] answers = new int[T]; for (int c = 0; c < T; c++) { int A = scanner.nextInt(); int B = scanner.nextInt(); int numdigits; for (numdigits = 1; A-Math.pow(10,numdigits) >= 0; numdigits++); HashSet done = new HashSet(); int n = A; int possiblem; answers[c] = 0; while (n <= B) { possiblem = n; int possiblemsthisround = 0; for (int i = 0; i <= numdigits; i++) { if ((possiblem%10) != 0) { possiblem = (possiblem%10)*((int)Math.pow(10,numdigits-1)) + (possiblem-(possiblem%10))/10; if ((possiblem <= B) && (possiblem > n)) { if (done.contains(possiblem) == false) { done.add(possiblem); possiblemsthisround++; } done.add(possiblem); } } else possiblem = (possiblem%10)*((int)Math.pow(10,numdigits-1)) + (possiblem-(possiblem%10))/10; } if (possiblemsthisround > 0) answers[c] += possiblemsthisround*(possiblemsthisround + 1)/2; n++; } } for (int i = 0; i < T; i++) { int j = i+1; System.out.println(""Case #""+j+"": ""+answers[i]); } } } " B11224,"import java.io.FileNotFoundException; import java.util.Formatter; import java.util.LinkedList; import java.util.Scanner; public class Main { public static void main(String[] arg) throws FileNotFoundException { Scanner scan =new Scanner(System.in); LinkedList lilo=new LinkedList(); int t=scan.nextInt(); for(int j=0;j set = new HashSet(); for (int move = 1; move < s.length(); move++) { String s1 = s.substring(0, move); String s2 = s.substring(move); if (s2.startsWith(""0"")) { continue; } int m = Integer.parseInt(s2+s1); if (m > n && m <= b) { set.add(m); } } answer += set.size(); } return answer; } public static void main(String[] args) { try { br = new BufferedReader(new FileReader(""C.in"")); out = new PrintWriter(""C.out""); solve(); out.close(); } catch (Throwable e) { e.printStackTrace(); System.exit(239); } } static BufferedReader br; static StringTokenizer st; static PrintWriter out; static String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = br.readLine(); if (line == null) return null; st = new StringTokenizer(line); } return st.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } static long nextLong() throws IOException { return Long.parseLong(nextToken()); } static double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }" B11041,"import java.io.*; import java.util.StringTokenizer; /** * User: Grant * Date: 14/04/12 * Time: 23:29 */ public class ProblemC { public static void main(String[] args) throws IOException { // Prepare output file File outputFile = new File(""E:\\Programming\\Java\\CodeJam\\resources\\problemCOutput.txt""); if (outputFile.exists()) { outputFile.delete(); } FileWriter fileWriter = new FileWriter(outputFile); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); // Read input file File inputFile = new File(""E:\\Programming\\Java\\CodeJam\\resources\\TestInput.txt""); FileReader fileReader = new FileReader(inputFile); BufferedReader bufferedReader = new BufferedReader(fileReader); Integer testCases = Integer.parseInt(bufferedReader.readLine().trim()); for (int i = 0; i < testCases; i++) { System.out.println("" ""); StringTokenizer st = new StringTokenizer(bufferedReader.readLine().trim(), "" ""); int lower = Integer.parseInt(st.nextToken().trim()); int upper = Integer.parseInt(st.nextToken().trim()); int count = 0; for (int left = lower; left < upper; left++) { for (int right = (left + 1); right <= upper; right++) { String leftStr = left + """"; String rightStr = right + """"; int start = -1; while((start = leftStr.indexOf(rightStr.charAt(0), start+1)) != -1) { if (rightStr.equals(leftStr.substring(start, leftStr.length()) + leftStr.substring(0, start))) { count++; break; } } } } StringBuilder outputLine = new StringBuilder(""Case #""); outputLine.append(i+1).append("": "").append(count).append(""\n""); bufferedWriter.write(outputLine.toString()); } bufferedReader.close(); fileReader.close(); // Write output file bufferedWriter.flush(); fileWriter.flush(); bufferedWriter.close(); fileWriter.close(); } } " B10701,"import java.io.FileReader; import java.io.LineNumberReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class go3 { public static final String IN_FILE = ""C-small-attempt0.in""; public static final String OUT_FILE = ""out.txt""; public static void main(String[] args) throws Throwable { try (LineNumberReader reader = new LineNumberReader(new FileReader(IN_FILE))) { try (PrintWriter writer = new PrintWriter(OUT_FILE)) { int T = Integer.parseInt(reader.readLine()); //Tests for (int t = 1; t <= T; t++) { Scanner scanner = new Scanner(reader.readLine()); int LOW = scanner.nextInt(); int HIGH = scanner.nextInt(); HashSet pairs = new HashSet<>(); for(int i = LOW; i <= HIGH ; i++) { Set set = validPermutations(i,LOW,HIGH); Integer[] permutations = set.toArray(new Integer[0]); Arrays.sort(permutations); for(int n = 0; n < permutations.length ; n++){ for(int m = n+1; m < permutations.length; m++) { pairs.add(new Pair(permutations[n],permutations[m])); } } } writer.printf(""Case #%d: %s\n"", t, pairs.size()); } } } } public static Set validPermutations (Integer n,int LOW, int HIGH){ int lastIndex = n.toString().length() - 1; StringBuilder b = new StringBuilder(n.toString()); Set result = new HashSet<>(); result.add(Integer.parseInt(b.toString())); for(int i = 1 ; i <= lastIndex; i++){ char c = b.charAt(lastIndex); if (c == '0') continue; b = b.deleteCharAt(lastIndex).insert(0,c); int k = Integer.parseInt(b.toString()); if(k >= LOW && k <= HIGH){ result.add(k); } } return result; } } class Pair { int n; int m; Pair(int n, int m) { this.n = n; this.m = m; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; if (m != pair.m) return false; if (n != pair.n) return false; return true; } @Override public int hashCode() { int result = n; result = 31 * result + m; return result; } @Override public String toString() { return ""("" + n + "","" + m + "")""; } }" B10176,"import java.io.*; import java.util.*; class MyReader{ private BufferedReader reader = null; private StringTokenizer tokenizer = null; MyReader(Reader r) throws IOException{ reader = new BufferedReader(r); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException{ return Long.parseLong(nextToken()); } public double nextDouble() throws IOException{ return Double.parseDouble(nextToken()); } public String nextLine() throws IOException{ return reader.readLine(); } public String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } } public class Temp { public static boolean cycled(int n, int m){ String s = String.valueOf(m); for (int i = 0; i < s.length(); ++i){ String str = s.substring(i) + s.substring(0,i); int k = Integer.valueOf(str); if (n==k) return true; } return false; } public static void main(String[] args) throws IOException { MyReader reader = new MyReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(""C.out""); int t = reader.nextInt(); for (int tt = 0; tt < t; ++tt){ int a = reader.nextInt(); int b = reader.nextInt(); int ans=0; Set set = new HashSet(); for (int i=a; i<=b; ++i) for (int j=i+1; j<=b; ++j) if (cycled(i,j)) { set.add(j); ans++; } writer.println(""Case #"" + (tt + 1) + "": "" + ans); } writer.close(); } } " B12971,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recyclednumber; /** * * @author pos */ public class Numbers { int A; int B; int n; int m; int Result; public Numbers(int A, int B) { this.A = A; this.B = B; this.n = A; this.m = n + 1; } String sn; String sm; int nLength; int mLength; int nIndex; int mIndex; private boolean isValid(int n, int m) { int[] numberN = new int[10]; int[] numberM = new int[10]; sn = n + """"; sm = m + """"; nLength = sn.length(); mLength = sm.length(); for (int i = 0; i < nLength; i++) { nIndex = Integer.valueOf(sn.charAt(i)) - 48; numberN[nIndex]++; mIndex = Integer.valueOf(sm.charAt(i)) - 48; numberM[mIndex]++; } for (int i = 0; i < 10; i++) { if (numberN[i] != numberM[i]) { return false; } } //System.out.println(A + ""<="" + n + ""<"" + m + ""<="" + B); return true; } public void Calculate() { int n, m; for (int i = this.A; i < this.B; i++) { for (int j = i+1; j <= this.B; j++) { n = i; m = j; if (isValid(n, m)) isRecycled(n, m); } } } private boolean isRecycled(int n, int m){ String sn=n+""""; nLength=sn.length(); for(int i=1;i= 'A' && x <= 'Z') { sb.append(DicB[x - 'A']); } else if (x >= 'a' && x <= 'z') { sb.append(DicA[x - 'a']); } else { sb.append(x); } } return sb.toString(); } public static int problemB(String G){ int result=0; String[] temp=G.split("" ""); int N=Integer.parseInt(temp[0]); int S=Integer.parseInt(temp[1]); int p=Integer.parseInt(temp[2]); int[] scr=new int[N]; int count=N; int suprise=S; for(int i=0;i=29){result++;count--;} else if(scr[i]==1){count--;if(p<=1)result++;} else if(scr[i]==0){count--;if(p==0)result++;} else if(Normal[scr[i]]>=p){ result++;count--; } else{ if(Surprising[scr[i]]>=p&&suprise>0){ result++; count--; suprise--; } } } return result; } public static int problemC(String G){ int result=0; String[] temp=G.split("" ""); int length=temp[0].length(); int A=Integer.parseInt(temp[0]); int B=Integer.parseInt(temp[1]); boolean[] check=new boolean[B-A+1]; if(B<10)return 0; else for(int i=A;i<=B;i++){ check[i-A]=false; result+=computeC(i,check,length,A,B); } //System.out.println(); return result; } public static int computeC(int x,boolean[] checklist,int length,int A,int B){ int count=0; if(checklist[x-A]==true)return 0; else checklist[x-A]=false; String S=String.valueOf(x)+String.valueOf(x); for(int i=1;ix&&temp<=B&&checklist[temp-A]==false){ count++; checklist[temp-A]=true; //System.out.print(temp+"",""); } } checklist[x-A]=true; return count*(count+1)/2; } /** * @param args the command line arguments */ public static void mainA(String[] args) { String[] x = {""ejp mysljylc kd kxveddknmc re jsicpdrysi"", ""rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd"", ""de kr kd eoya kw aej tysr re ujdr lkgc jv""}; for (String G : x) { System.out.println(problemA(G)); } } public static void main(String[] args) throws FileNotFoundException, IOException { BufferedReader br = new BufferedReader(new FileReader(new File(""C-small-attempt0.in""))); int x = Integer.parseInt(br.readLine()); StringBuilder sb = new StringBuilder(); System.setOut(new PrintStream(new File(""C-small-attempt0.out""))); for (int i = 1; i <= x; i++) { //String[] temp=br.readLine().trim().split("" ""); sb.append(""Case #"").append(i).append("": "").append(problemC(br.readLine())); sb.append('\n'); //sb.append(""Case #"").append(i).append("": "").append(Result[compute(Integer.parseInt(temp[0]),Integer.parseInt(temp[1]))]).append('\n'); //System.out.printf(""Case #%d: %s\n"",i,Result[compute(Integer.parseInt(temp[0]),Integer.parseInt(temp[1]))]); } System.out.print(sb.toString()); br.close(); } } " B10605,"package google.code.jam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.ListIterator; public class RecycledNumbers { final static String fileNameIn = ""C-small-attempt0.in""; final static String fileNameOut = ""C-small-attempt0.out""; private static int solve(int A, int B) { HashMap hashMap = new HashMap(); for (int i = A; i <= B; i++) { String n = new Integer(i).toString(); String key = minimum(n); if (Integer.valueOf(n) >= A && Integer.valueOf(n) <= B) { if (!hashMap.containsKey(key)) { hashMap.put(key, 1); } else { hashMap.put(key, hashMap.get(key) + 1); } } } int count = 0; for (String key : hashMap.keySet()) { Integer value = hashMap.get(key); count = count + (value * (value - 1) / 2); } return count; } private static String minimum(String input) { String min = input; for (int i = 0; i < input.length(); i++) { if (Integer.valueOf(shift(input, i)) < Integer.valueOf(min)) { min = shift(input, i); } } return min; } private static String shift(String input, int n) { return input.substring(n, input.length()) + input.substring(0, n); } public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(fileNameIn)); BufferedWriter out = new BufferedWriter(new FileWriter(fileNameOut)); int testCases = Integer.parseInt(in.readLine()); for (int i = 0; i < testCases; i++) { String[] elements = in.readLine().split( new Character((char) 32).toString()); List values = new ArrayList(); for (String v : elements) { values.add(Integer.valueOf(v)); } ListIterator iterator = values.listIterator(); int A = iterator.next(); int B = iterator.next(); out.write(String.format(""Case #%s: %s\n"", i + 1, solve(A, B))); } in.close(); out.close(); } } " B10247,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recyclednumbers; /** * * @author vandit *//* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.lang.String; import java.util.HashSet; import java.util.StringTokenizer; /** * * @author vandit */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here String filePathIn = args[0]; String filePathOut = args[1]; //String filePathIn = ""/home/vandit/Desktop/GoogleCodeJam/Qualifying round/testinput.in""; //String filePathOut = ""/home/vandit/Desktop/GoogleCodeJam/Qualifying round/testOutput.out""; FileReader fr = null; BufferedReader inputFileReader = null; FileWriter fw = null; BufferedWriter outputFileWriter = null; try { fr = new FileReader(filePathIn); inputFileReader = new BufferedReader(fr); fw = new FileWriter(filePathOut); outputFileWriter = new BufferedWriter(fw); int numberOfTestCases = Integer.parseInt(inputFileReader.readLine()); for (int i = 0; i < numberOfTestCases; i++) { String inputContent = inputFileReader.readLine(); StringTokenizer tokenizer = new StringTokenizer(inputContent); int startingNumber = Integer.parseInt(tokenizer.nextToken()); int endingNumber = Integer.parseInt(tokenizer.nextToken()); HashSet numbers = new RecycleNumbers().findAllRecycledNumbers(startingNumber,endingNumber); String outputContent = Integer.toString(numbers.size()); //String outputContent = String output = ""Case #"" + (i+1) + "": "" + outputContent+""\n""; outputFileWriter.write(output); } outputFileWriter.flush(); } catch (Exception ex) { ex.printStackTrace(); } finally { try { outputFileWriter.close(); inputFileReader.close(); fr.close(); fw.close(); } catch (Exception ex) { ex.printStackTrace(); } } } } " B12026," import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { private Scanner in; private PrintWriter out; public long output; public int A; public int B; /** * main method */ public static void main(String args[]){ new RecycledNumbers(""C-small-attempt0.in""); } /** * constructor */ public RecycledNumbers(String filename){ initIO(filename); int n = in.nextInt(); // long tmStart = System.currentTimeMillis(); for(int i=1;i<=n;i++){ A = in.nextInt(); B = in.nextInt(); output = 0; output=solve(); out.println(""Case #""+i+"": ""+output); } // System.out.println(System.currentTimeMillis() - tmStart); closeIO(); } public long solve(){ long op=0; Set s = new HashSet(); for(int i=A;i<=B;i++){ String stringI = Integer.toString(i); s.clear(); for(int ind=stringI.length()-1;ind>0;ind--){ if(stringI.substring(ind).charAt(0)!= '0'){ String stringTemp = stringI.substring(ind) + stringI.substring(0, ind); if(Integer.parseInt(stringTemp) > i && Integer.parseInt(stringTemp)<=B){ // System.out.println(stringI + "" ""+Integer.parseInt(stringTemp)); s.add(Integer.parseInt(stringTemp)); // op++; } } } op+=s.size(); } return op; } /** * Set up devices to do I/O */ public void initIO(String filename){ try { in = new Scanner(new FileReader(filename)); out = new PrintWriter(new FileWriter(filename+"".out"")); }catch (IOException except) { System.err.println(""File is missing!""); } } /** * Free memory used for I/O */ public void closeIO(){ in.close(); out.close(); } } " B11156,"import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.StringTokenizer; public class Recycle { int low, high; ArrayList instances; public Recycle(int low, int high) { this.low = low; this.high = high; this.instances = new ArrayList(); } public void reset(int low, int high) { this.low = low; this.high = high; this.instances.clear(); } NumPair moveDigits(int num, int digits) { String numStr = Integer.toString(num); int startIndex = numStr.length() - digits; String sub = numStr.substring(startIndex); String ret = sub.concat(numStr.substring(0,startIndex)); return new NumPair(num, Integer.parseInt(ret)); } boolean checkRecycled(NumPair num) { if (num.orig == num.modded || num.modded > num.orig) return false; if (num.modded >= low && num.modded <= high) { return true; } return false; } public void compute() { int length = Integer.toString(low).length(); for (int i=low; i<=high; i++) { for (int j=1; j0) { k++; temp /=10; } int [] v = new int[k+1]; for(int i = a;i<=b;i++) { temp = 0; temp2 = i; for(int j = 0;ji&&temp2<=b) { v[temp] = temp2; temp++; for(int t = 0;t recycledSet = new HashSet(); public int setNum(int num, int min, int max) { this.orginalNumber = num; this.min = min; this.max = max; backingArray = Integer.toString(num).toCharArray(); calculateValue(); recycledSet.clear(); shiftLeft(); int length = length(); for (int i = 1; i < length; i++) { if (isValid()) { recycledSet.add(value()); } shiftLeft(); } return numRecycled(); } private int calculateValue() { currentValue = Integer.parseInt(new String(backingArray)); return currentValue; } public int value() { return currentValue; } public int length() { return backingArray.length; } public int numRecycled() { return recycledSet.size(); } public void shiftLeft() { char first = backingArray[0]; for (int i = 1; i < backingArray.length; i++) { int newPosition = i - 1; backingArray[newPosition] = backingArray[i]; } backingArray[backingArray.length - 1] = first; calculateValue(); } public boolean isValid() { return !isLeadingZero() && isUnique() && isInRange(); } public boolean isLeadingZero() { return backingArray[0] == '0'; } public boolean isUnique() { if (value() == orginalNumber) { return false; } char first = backingArray[0]; for (char c : backingArray) { if (c != first) { return true; } } return false; } public boolean isInRange() { int value = value(); return value >= min && value <= max; } } private static Scanner getInputScanner() { Scanner in = null; try { in = new Scanner(new File(""in.txt"")); } catch (FileNotFoundException e) { e.printStackTrace(); } return in; } } " B12134,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recyclednumbers; import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * * @author topik */ public class RecycledNumbers { /** * @param args the command line arguments */ public static void main(String[] args) { final Scanner scanner = new Scanner(System.in); final int testCases = scanner.nextInt(); for( int tc=1; tc <= testCases; tc++ ) { final int a = scanner.nextInt(); final int b = scanner.nextInt(); int total = 0; for( int n = a > 10 ? a : 10; n < b; n++ ) { final Set seen = new HashSet(); final String nStr = Integer.toString(n); final int nStrLen = nStr.length(); for( int replace = 1; replace < nStrLen; replace++ ) { final String mStr = nStr.substring(nStrLen - replace) + nStr.substring(0, nStrLen - replace); final int m = Integer.parseInt(mStr); if( m <= b && m > n && ! seen.contains(m) ) { seen.add(m); total++; } } } System.out.println(""Case #"" + tc + "": "" + total); } } } " B11479,"import java.util.*; public class C { public static void main(String args[]){ Scanner scanner = new Scanner(System.in); int testCount = scanner.nextInt(); HashSet hashResult = new HashSet(); for (int test = 1; test <= testCount; test++){ int min = scanner.nextInt(); int max = scanner.nextInt(); int total=0; for (Integer i=min; i<=max;i++){ char[]numChar= i.toString().toCharArray(); for (int k=0; k<=numChar.length-1;k++){ // Move ponteiro char charTemp=numChar[numChar.length-1]; for (int j=numChar.length-2;j>=0;j--){ numChar[j+1]=numChar[j]; } numChar[0]=charTemp; Integer result = Integer.parseInt(new String(numChar)); if(i= 10) { a /= 10; res++; } return res; } static void solve() throws IOException { int T = nextInt(); for(int c = 1; c <= T; c++) { int A = nextInt(); int B = nextInt(); vis = new boolean[B+1]; int res = 0; for(int i = A; i <= B; i++) { int pairs = 1; if(!vis[i]) { vis[i] = true; int dig = countDig(i); for(int j = 1; j < dig; j++) { int suf = i % (int)Math.pow(10, j); int temp = i; temp /= Math.pow(10, j); if(countDig(suf) != j || suf == 0) continue; temp += suf * Math.pow(10, dig - j); if(temp <= B && temp >= A) { if(vis[temp]) continue; vis[temp] = true; pairs++; } } } res += pairs * (pairs - 1) / 2; } out.println(""Case #"" + c + "": "" + res); } } public static void main(String[] args) { try { br = new BufferedReader(new FileReader(""input.txt"")); out = new PrintWriter(new BufferedWriter(new FileWriter(""output.txt""))); solve(); out.close(); } catch (Throwable e) { e.printStackTrace(); System.exit(239); } } static BufferedReader br; static StringTokenizer st; static PrintWriter out; static String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = br.readLine(); if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } static long nextLong() throws IOException { return Long.parseLong(nextToken()); } static double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } } " B12884,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; public class Recycled { static int no_Test_Cases =0; //number of test cases static String input_Array[]; //to read input file static int output_Array[]; // to write the t output lines public static void main(String[] args) { readFile(); for (int i = 0; i< no_Test_Cases; i++ ){ recycled_Number(i); } writeFile(); } public static void readFile(){ try{ FileInputStream fstream = new FileInputStream(""C:/sarab/input.txt""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; strLine = br.readLine(); no_Test_Cases = Integer.parseInt(strLine); input_Array = new String[no_Test_Cases]; output_Array = new int[no_Test_Cases]; for (int i = 0; i< no_Test_Cases; i++){ strLine = br.readLine(); input_Array[i] = strLine; } //Close the input stream in.close(); } catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } public static void recycled_Number(int i){ String s1 = input_Array[i]; String s2[] = s1.split("" ""); int a = Integer.parseInt(s2[0]); int b = Integer.parseInt(s2[1]); char c1[] = s2[0].toCharArray(); int length = c1.length; int no_Array[] = new int[length-1]; int counter = 0; String s3 = """"; for (int i1 = a; i1 < b; i1++){ String s4 = """"+i1; c1 = s4.toCharArray(); for(int i2 = 0; i2 < length-1; i2++){ for(int i3 =1; i3 <= length-1 ; i3++){ s3 = s3+c1[i3]; } s3 = s3+c1[0]; //System.out.println(s3); no_Array[i2] = Integer.parseInt(s3); c1 = s3.toCharArray(); s3 = """"; } for (int i5 = 0; i5 < length -2 ;i5++){ for (int i6 = i5+1; i6 < length -1; i6++){ if(no_Array[i6] == no_Array[i5]){ no_Array[i6] = i1; } } } for (int i4 =0; i4 < length-1 ; i4++){ if (no_Array[i4] > i1 && no_Array[i4] <= b) { counter++; } } } output_Array[i]= counter; } public static void writeFile(){ String forOutput; try{ FileWriter fstream = new FileWriter(""C:/sarab/output.txt""); BufferedWriter out = new BufferedWriter(fstream); for (int i=0; i list = new ArrayList(); for(int s=1; s<=Integer.toString(b).length(); s++) for(int x=a; x<=b; x++) for(int y=b; y>=x; y--) if(x!=y && x==rotateDig(y, s) && !list.contains(x*y)){ count++; list.add(x*y); //System.out.println(x+"" ""+y); } //System.out.println(""Case #""+r+"": ""+count); out.println(""Case #""+r+"": ""+count); } public static int rotateDig(int n, int shift){ String s = Integer.toString(n); String t = """"; t = s.substring(shift); t += s.substring(0,shift); return Integer.parseInt(t); } } " B11057,"package fixjava; import java.util.ArrayList; import java.util.concurrent.Callable; /** Parallel quicksort (inefficient initially, doubles the number of threads at each pivot) */ public class ParallelQuicksort> implements Callable { private ArrayList list; private ParallelWorkQueueDynamic workQueue; // Have to create own stack because otherwise we can get stack overflow using normal recursion private ArrayList loStack = new ArrayList(); private ArrayList hiStack = new ArrayList(); private ParallelQuicksort(ArrayList list, int lo, int hi, ParallelWorkQueueDynamic workQueue) { this.list = list; this.workQueue = workQueue; push(lo, hi); } private void push(int lo, int hi) { loStack.add(lo); hiStack.add(hi); } private void exch(int i, int j) { T tmp = list.get(i); list.set(i, list.get(j)); list.set(j, tmp); } private int partition(int lo, int hi) { exch(lo, lo + (hi - lo) / 2); int i = lo; int j = hi + 1; while (true) { for (int idxLo = lo; list.get(++i).compareTo(list.get(idxLo)) < 0 && i != hi;) ; for (int idxLo = lo; list.get(idxLo).compareTo(list.get(--j)) < 0 && j != lo;) ; if (i >= j) break; exch(i, j); } exch(lo, j); return j; } @Override public Void call() { int stackSize = 1; while ((stackSize = loStack.size()) > 0) { // Pop top of stack int lo = loStack.get(stackSize - 1); int hi = hiStack.get(stackSize - 1); loStack.remove(stackSize - 1); hiStack.remove(stackSize - 1); // Go up a stack frame when hi <= lo if (hi > lo) { // Partition final int j = partition(lo, hi); if (j - lo > 1000 && workQueue.hasIdleWorkers()) { // If there is enough work to do to justify multithreading and if there are idle threads, // fork and recurse on one one side of partition on a different thread workQueue.enqueueWork(new ParallelQuicksort(list, lo, j - 1, workQueue)); // Execute other half of subdivision in this thread push(j + 1, hi); } else { // Not worth forking another thread (not enough work to do), or not enough free workers push(lo, j - 1); push(j + 1, hi); } } } return null; } // --------------------------------------------------------- public static > void sortInPlace(ArrayList list, int numThreads) { ParallelWorkQueueDynamic workQueue = new ParallelWorkQueueDynamic(numThreads); workQueue.enqueueWork(new ParallelQuicksort(list, 0, list.size() - 1, workQueue)); workQueue.waitForAllWorkersToQuit(); workQueue.shutdown(); } } " B12275,"/************************************************************************* * Compilation: javac StdOut.java * Execution: java StdOut * * Writes data of various types to standard output. * *************************************************************************/ import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.Locale; /** * Standard output. This class provides methods for writing strings * and numbers to standard output. *

* For additional documentation, see Section 1.5 of * Introduction to Programming in Java: An Interdisciplinary Approach by Robert Sedgewick and Kevin Wayne. */ public final class StdOut { // force Unicode UTF-8 encoding; otherwise it's system dependent private static final String UTF8 = ""UTF-8""; // assume language = English, country = US for consistency with StdIn private static final Locale US_LOCALE = new Locale(""en"", ""US""); // send output here private static PrintWriter out; // this is called before invoking any methods static { try { out = new PrintWriter(new OutputStreamWriter(System.out, UTF8), true); } catch (UnsupportedEncodingException e) { System.out.println(e); } } // singleton pattern - can't instantiate private StdOut() { } // close the output stream (not required) /** * Close standard output. */ public static void close() { out.close(); } /** * Terminate the current line by printing the line separator string. */ public static void println() { out.println(); } /** * Print an object to standard output and then terminate the line. */ public static void println(Object x) { out.println(x); } /** * Print a boolean to standard output and then terminate the line. */ public static void println(boolean x) { out.println(x); } /** * Print a char to standard output and then terminate the line. */ public static void println(char x) { out.println(x); } /** * Print a double to standard output and then terminate the line. */ public static void println(double x) { out.println(x); } /** * Print a float to standard output and then terminate the line. */ public static void println(float x) { out.println(x); } /** * Print an int to standard output and then terminate the line. */ public static void println(int x) { out.println(x); } /** * Print a long to standard output and then terminate the line. */ public static void println(long x) { out.println(x); } /** * Print a short to standard output and then terminate the line. */ public static void println(short x) { out.println(x); } /** * Print a byte to standard output and then terminate the line. */ public static void println(byte x) { out.println(x); } /** * Flush standard output. */ public static void print() { out.flush(); } /** * Print an Object to standard output and flush standard output. */ public static void print(Object x) { out.print(x); out.flush(); } /** * Print a boolean to standard output and flush standard output. */ public static void print(boolean x) { out.print(x); out.flush(); } /** * Print a char to standard output and flush standard output. */ public static void print(char x) { out.print(x); out.flush(); } /** * Print a double to standard output and flush standard output. */ public static void print(double x) { out.print(x); out.flush(); } /** * Print a float to standard output and flush standard output. */ public static void print(float x) { out.print(x); out.flush(); } /** * Print an int to standard output and flush standard output. */ public static void print(int x) { out.print(x); out.flush(); } /** * Print a long to standard output and flush standard output. */ public static void print(long x) { out.print(x); out.flush(); } /** * Print a short to standard output and flush standard output. */ public static void print(short x) { out.print(x); out.flush(); } /** * Print a byte to standard output and flush standard output. */ public static void print(byte x) { out.print(x); out.flush(); } /** * Print a formatted string to standard output using the specified * format string and arguments, and flush standard output. */ public static void printf(String format, Object... args) { out.printf(US_LOCALE, format, args); out.flush(); } /** * Print a formatted string to standard output using the specified * locale, format string, and arguments, and flush standard output. */ public static void printf(Locale locale, String format, Object... args) { out.printf(locale, format, args); out.flush(); } // This method is just here to test the class public static void main(String[] args) { // write to stdout StdOut.println(""Test""); StdOut.println(17); StdOut.println(true); StdOut.printf(""%.6f\n"", 1.0/7.0); } } " B11067,"package fixjava; public class IntegerMutable { int value; public IntegerMutable(int value) { this.value = value; } public IntegerMutable() { this(0); } public int getValue() { return value; } public void setValue(int value) { this.value = value; } /** Inc and return new value (threadsafe) */ public synchronized int increment() { return ++value; } /** Dec and return new value (threadsafe) */ public synchronized int decrement() { return --value; } /** Subtract amount and return new value (threadsafe) */ public synchronized int subtract(int amount) { return value -= amount; } /** Add amount and return new value (threadsafe) */ public synchronized int add(int amount) { return value += amount; } } " B12632,"import java.io.IOException; import java.io.BufferedReader; import java.io.FileReader; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; import java.util.Hashtable; import java.util.Arrays; import com.sun.xml.internal.bind.v2.runtime.unmarshaller.IntArrayData; public class Recycler { private static int transpose(int num, int numDigits) { //System.out.println(""Input number "" + num); //System.out.println(""Number digits to be transposed "" + numDigits); String inputString = Integer.toString(num); String truncatedString1 = inputString.substring(0,inputString.length()-numDigits); //System.out.println(""Truncated String1 "" + truncatedString1); String truncatedString2 = inputString.substring(inputString.length()-numDigits); //System.out.println(""Truncated String2 "" + truncatedString2); //System.out.println(""Output string "" + truncatedString2 + truncatedString1); return Integer.valueOf(truncatedString2 + truncatedString1); } public static void main(String[] args) throws IOException{ /* transpose(3234,2); transpose(323423242,5); transpose(100,1); */ if (args.length != 1) { System.out.println(""Error: incorrect number of arguments.""); System.out.println(""Usage: Recycler ""); } else { BufferedReader inputStream = null; try { inputStream = new BufferedReader(new FileReader(args[0])); int totalCases = Integer.valueOf(inputStream.readLine()).intValue(); //System.out.println(""Total number of cases is: ""+totalCases); for (int i=0;i done = new HashSet(); for (int l=1;lk) && (otherNumber<=higher) && Integer.toString(k).length() == Integer.toString(otherNumber).length() && !done.contains(String.valueOf(new Integer(k)) + String.valueOf(new Integer(otherNumber))) ) { //System.out.println(k+"" ""+ otherNumber + "" Incrementing""); output++; done.add(String.valueOf(new Integer(k)) + String.valueOf(new Integer(otherNumber))); } } } System.out.println(output); } } catch (IOException e) { System.out.println(""Error in reading file""); } finally { if (inputStream != null) { inputStream.close(); } } } } }" B10123,"package code12.qualification; import java.io.File; import java.io.FileWriter; import java.util.HashSet; import java.util.Scanner; public class C { public static String solve(int A, int B) { int output = 0; for (int i = A; i < B; i++) { output += findNumOfRecyclePair(i, A, B); } return """" + output; } public static int findNumOfRecyclePair(int x, int min, int max) { int output = 0; HashSet numSet = new HashSet(); char[] charList = (x + """").toCharArray(); int[] digitList = new int[charList.length]; for (int i = 0; i < digitList.length; i++) { digitList[i] = Integer.parseInt(charList[i] + """"); } int num = 0; for (int i = 0; i < digitList.length; i++) { num = 0; for (int j = 0; j < digitList.length; j++) { num = num * 10 + digitList[(i + j) % digitList.length]; } Integer numInt = new Integer(num); if (num > x && num <= max && !numSet.contains(numInt)) { numSet.add(numInt); output++; // System.out.println(""("" + x + "", "" + num + "")""); } } return output; } public static void main(String[] args) throws Exception { // file name //String fileName = ""Sample""; String fileName = ""C-small""; //String fileName = ""C-large""; // file variable File inputFile = new File(fileName + "".in""); File outputFile = new File(fileName + "".out""); Scanner scanner = new Scanner(inputFile); FileWriter writer = new FileWriter(outputFile); // problem variable int totalCase; int A, B; // get total case totalCase = scanner.nextInt(); for (int caseIndex = 1; caseIndex <= totalCase; caseIndex++) { // get input A = scanner.nextInt(); B = scanner.nextInt(); String output = ""Case #"" + caseIndex + "": "" + solve(A, B); System.out.println(output); writer.write(output + ""\n""); } scanner.close(); writer.close(); } } " B11111,"package recycled; import java.util.List; import java.util.Set; import util.ListFactory; import util.SetFactory; import file.Input; import file.Output; public class Recycled { public void start() { List inputLines = Input.getLines(); if (inputLines.size() > 0) { List outputLines = ListFactory.newArrayListInstance(); int t = Integer.parseInt(inputLines.get(0)); for (int i = 1; i <= t; i++) { String[] parts = inputLines.get(i).split("" ""); int a = Integer.parseInt(parts[0]); int b = Integer.parseInt(parts[1]); outputLines.add(""Case #"" + i + "": "" + getNumber(a, b)); } Output.writeLines(outputLines); } } private int getNumber(int a, int b) { Set set = SetFactory.newHashSetInstance(); if (a <= b) { for (int n = a; n <= b; n++) { int length = getLength(n); for (int i = 0; i < length - 1; i++) { int m = moveRight(n, i + 1); if (n < m && m <= b) { set.add(new Pair(n, m)); } } } } return set.size(); } private int getLength(int number) { int length = 0; if (number >= 0 && number <= 9) { length = 1; } else if (number >= 10 && number <= 99) { length = 2; } else if (number >= 100 && number <= 999) { length = 3; } else if (number >= 1000 && number <= 9999) { length = 4; } else if (number >= 10000 && number <= 99999) { length = 5; } return length; } private int moveRight(int n, int times) { String number = String.valueOf(n); for (int i = 0; i < times; i++) { int length = number.length(); number = number.substring(length - 1, length) + number.substring(0, length - 1); } return Integer.parseInt(number); } public static void main(String[] args) { new Recycled().start(); } } " B11090,"package codejam; import fixjava.Pair; public class Utils { public static long minLong(long firstVal, long... otherVals) { long minVal = firstVal; for (int i = 0; i < otherVals.length; i++) minVal = Math.min(firstVal, otherVals[i]); return minVal; } public static int minInt(int firstVal, int... otherVals) { int minVal = firstVal; for (int i = 0; i < otherVals.length; i++) minVal = Math.min(firstVal, otherVals[i]); return minVal; } public static float minFloat(float firstVal, float... otherVals) { float minVal = firstVal; for (int i = 0; i < otherVals.length; i++) minVal = Math.min(firstVal, otherVals[i]); return minVal; } /** * ArgMin returned as a Pair(index, value). Array must * have at least one value. */ public static Pair argMin(int[] arr) { int min = arr[0]; int argMin = 0; for (int i = 1; i < arr.length; i++) { if (arr[i] < min) { min = arr[i]; argMin = i; } } return new Pair(argMin, min); } /** * ArgMax returned as a Pair(index, value). Array must * have at least one value. */ public static Pair argMax(int[] arr) { int max = arr[0]; int argMax = 0; for (int i = 1; i < arr.length; i++) { if (arr[i] > max) { max = arr[i]; argMax = i; } } return new Pair(argMax, max); } } " B10499,"import java.util.Hashtable; import java.util.Scanner; class RecycleResult{ private int lowerBound, upperBound, numberOfDigits; public RecycleResult(int a, int b, int d){ lowerBound = a; upperBound = b; numberOfDigits = d; } public int solve(){ int count = 0; for (int i = lowerBound; i < upperBound; i++){ int p = i; Hashtable hash = new Hashtable(); for (int j = 1; j < numberOfDigits; j++){ p = moveToFront(p); if ((p <= upperBound) && (p > i) && (!(p == i)) && (!(hash.containsValue(p)))){ count++; hash.put(count, p); } } } return count; } public int moveToFront(int z){ int lastDigit = z % 10; int otherDigits = (z / 10); for (int i = 0; i < numberOfDigits - 1; i++){ lastDigit = lastDigit * 10; } return otherDigits + lastDigit; } } public class Recycle { public static void main(String[] args) { int numberOfCases; Scanner myScanner = new Scanner(System.in); int a, b; numberOfCases = myScanner.nextInt(); RecycleResult myResult; for (int i = 0; i < numberOfCases; i++){ a = myScanner.nextInt(); b = myScanner.nextInt(); int length = String.valueOf(a).length(); myResult = new RecycleResult(a, b, length); int count = myResult.solve(); System.out.println(""Case #"" + (i+1) + "": "" + count); } } } " B12195,"import java.io.*; import java.util.*; public class C { BufferedReader read; BufferedWriter write; public static void main(String args[]) { try { new C().init(""C-small-attempt2""); } catch (Exception ex) { System.out.println(""error occured ""+ex); // Logger.getLogger(Sample.class.getName()).log(Level.SEVERE, null, ex); } } void init(String name) throws Exception { read=new BufferedReader(new FileReader(new File(name+"".in""))); write=new BufferedWriter(new FileWriter(new File(name+"".out""))); String x=""""; try { x = read.readLine(); int n = Integer.parseInt(x); for(int i=0;itree; void result(String x,int j) throws Exception { tree=new TreeSet(); String ss[]=x.split("" ""); int a=Integer.parseInt(ss[0].trim()); int b=Integer.parseInt(ss[1].trim()); System.out.println(a+"" ""+b); int count=0; for(int i=a;i<=b;i++) { tree.add(i); count+=count(i,a,b); } System.out.println(""Case #""+(j+1)+"": ""+count); write.write(""Case #""+(j+1)+"": ""+count+""\n""); } int count(int p,int a,int b) { TreeSett=new TreeSet(); String s=""""+p; s=s.trim(); int l=s.length(); for(int i=1;i=a&&!tree.contains(p1)) { // System.out.print(""\t""+p+"" ""+p1); t.add(p1); } } return t.size(); } } " B13245,"package com.google.codejam; import java.io.*; import java.util.HashSet; import java.util.StringTokenizer; /** * User: svasilinets * Date: 14.04.12 * Time: 11:58 */ public class QualC { private static int getDigitCount(int k) { int r = 0; while (k != 0) { k /= 10; r++; } return r; } public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(""c.in"")); BufferedWriter writer = new BufferedWriter(new FileWriter(""c.out"")); int tests = Integer.parseInt(reader.readLine()); for (int t = 1; t <= tests; t++) { StringTokenizer tokenizer = new StringTokenizer(reader.readLine()); int a = Integer.parseInt(tokenizer.nextToken()); int b = Integer.parseInt(tokenizer.nextToken()); int d = getDigitCount(a); int result = 0; int tp = 1; for (int i = 0; i < d; i++) { tp *= 10; } for (int i = a; i <= b; i++) { HashSet h = new HashSet(); int p = 1; for (int j = 0; j < d - 1; j++) { p *= 10; int rest = i % p; int del = i / p; int pretend = rest * (tp / p) + del; if (pretend > i && pretend <= b && !h.contains(pretend)){ result++; h.add(pretend); } } } writer.write(""Case #"" + t + "": "" + result); writer.newLine(); } writer.close(); } } " B10865,"package student; import java.io.*; import java.util.*; public class test { public static int getShift(String t, int pos) { int len = t.length()/2; return Integer.parseInt(t.substring(pos,pos+len)); } public static void main(String[] args) throws FileNotFoundException { Scanner fin = new Scanner(new File(""a.txt"")); int ncase = fin.nextInt(); int a=0,b=0; for(int cc = 1; cc<=ncase;cc++) { a= fin.nextInt(); b= fin.nextInt(); HashSet set = new HashSet(); for(int i=a;i<=b;i++) { String t = (""""+i) + (""""+i); int len = t.length()/2; for(int j=1;j=a&&p<=b&&(""""+p).length()==len && p!=i) set.add(new Pair(i,p)); } } System.out.println(""Case #"" + cc + "": "" + set.size()/2); } } } class Pair { public int a,b; public Pair(int x,int y) { a=x;b=y; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + a; result = prime * result + b; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (a != other.a) return false; if (b != other.b) return false; return true; } } " B10405,"package C; import java.io.*; import java.util.*; public class C { static int[] pow = {10, 100, 1000, 10000, 100000, 1000000}; public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new FileReader(""C.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""C.out""))); int n = Integer.parseInt(in.readLine()); for (int i = 0; i < n; ++ i) { String st = in.readLine(); String[] input = st.split("" ""); int A = Integer.parseInt(input[0]); int B = Integer.parseInt(input[1]); int t = A; int digits = 0; while (t > 0) { t /= 10; ++ digits; } int ans = 0; for (int j = A; j < B; ++ j) { Set set = new HashSet(); for (int k = 0; k < digits - 1; ++ k) { int m = j / pow[k] + (j % pow[k]) * pow[digits - 1 - k - 1]; if (j < m && m <= B && !set.contains(m)) { set.add(m); ++ ans; } } } out.println(""Case #"" + (i + 1) + "": "" + ans); } in.close(); out.close(); } } " B10694,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.StringTokenizer; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub int ten[]=new int[10]; ten[1]=1; for(int i=2;i<10;ten[i]=ten[i-1]*10,i++); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out)); StringTokenizer st; int T=Integer.parseInt(br.readLine()); for(int cn=1;cn<=T;cn++){ st=new StringTokenizer(br.readLine()); int A=Integer.parseInt(st.nextToken()); int B=Integer.parseInt(st.nextToken()); int n=(A+"""").length(); int ctr=0; boolean marked[]=new boolean[2000001]; for(int a=A;a<=B;a++){ if(marked[a]) continue; int i=1; int b=a; for(int j=1;ja&&b<=B&&!marked[b]){ i++; marked[b]=true; // System.out.println(a+"" ""+b); } } ctr+=i*(i-1)/2; // System.out.println("">""+ctr); } System.out.println(""Case #""+cn+"": ""+ctr); } } } " B10598,"package codejam; import java.io.*; import java.util.*; public class RecycledNumbers { public static void RecycledNumbersProcess() throws Exception { int t_cases= getT(); for(int i = 1; i<=t_cases;i++) { String line = getG(); long A, B; String[] charNUMBERS = line.split("" ""); A = Long.parseLong(charNUMBERS[0]); B = Long.parseLong(charNUMBERS[1]); //Check no of digits int NoOfDigits = charNUMBERS[0].length(); HashSet hsUnique = new HashSet(); hsUnique.clear(); long OutputCount; OutputCount = 0; for(long j=A; j<=B; j++) { long tempA = j; for(int k = 0; k j && newA >= A && newA <= B) { OutputCount++; String jStr = String.valueOf(j); String newAStr = String.valueOf(newA); String pair = jStr + newAStr; hsUnique.add(pair); } }//for loop k }//for loop j //System.out.print(""Case #"" + i + "": "" + hsUnique.size()+""\n""); out.write(""Case #"" + i + "": "" + hsUnique.size()+""\n""); hsUnique = null; } } public static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); public static File input; public static FileReader inputreader; public static BufferedReader in; public static File output; public static FileWriter outputwriter; public static BufferedWriter out; public static StringTokenizer st; public static void main(String[] args) throws Exception { input = new File(""smallinputRN.in.txt""); inputreader = new FileReader(input); in = new BufferedReader(inputreader); output = new File(""smalloutputRN.out.txt""); outputwriter = new FileWriter(output); out = new BufferedWriter(outputwriter); RecycledNumbersProcess(); close(); } public static void close() throws IOException { if(in!=null)in.close(); if(inputreader!=null)inputreader.close(); if(out!=null)out.flush(); if(out!=null)out.close(); if(outputwriter!=null)outputwriter.close(); } // ************************** INPUT READING ***************** static String LINE() throws IOException { return in.readLine();} static int getT() throws IOException {return Integer.parseInt(LINE());} static String getG() throws IOException {return LINE();} } " B10313,"package google2012; import java.io.BufferedReader; import java.io.FileReader; import java.util.HashSet; import java.util.Scanner; public class QRound_C { static public void main(String[] args) { try { BufferedReader br = new BufferedReader(new FileReader(""d:/in.txt"")); int i=0; while (true) { String x = br.readLine(); if (x==null) break; if (i!=0) run (x, i); i++; } } catch (Exception e) { e.printStackTrace(); } } static private void run(String input, int caseid) { int res=0; Scanner sc =new Scanner(input); int a=sc.nextInt(); int b=sc.nextInt(); for (int i=a;i<=b;i++) { res+=sol(i,b); } System.out.printf(""Case #%d: %d%n"", caseid, res); } static private int sol(int num, int max) { String ii=((Integer)num).toString(); HashSet counted =new HashSet(); int r=0; for (int i=0;inum&&!counted.contains(xx)) { counted.add(xx); r++; } } return r; } }" B10110,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; public class Third { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(new File( ""/Users/narok119/Desktop/C-small-attempt0.in""))); String txt = reader.readLine(); int caseCount = 1; while ((txt = reader.readLine()) != null) { // Form the input String[] info = txt.split("" ""); int a = Integer.parseInt(info[0]); int b = Integer.parseInt(info[1]); int output = 0; for (int n = a; n < b; n++) { for (int m = n + 1; m <= b; m++) { String ns = n + """"; String ms = m + """"; if (ns.length() == ms.length()) { for (int i = 0; i < ns.length(); i++) { String ms1 = ms.substring(0, i); String ms2 = ms.substring(i); if ((ms2 + ms1).equals(ns)) { output++; break; } } } } } System.out.println(""Case #"" + caseCount++ + "": "" + output); } } } " B11884,"import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.FileReader; @SuppressWarnings(""CallToThreadDumpStack"") public class Utils { private static FileOutputStream outStream; private static BufferedReader reader; private static boolean debug = false; public static void openOutFile(String str, boolean debug) { Utils.debug = debug; try { outStream = new FileOutputStream(str, false); } catch (Exception e) { e.printStackTrace(); } } public static void openInFile(String str) { try { reader = new BufferedReader(new FileReader(str)); } catch (Exception e) { e.printStackTrace(); } } public static void closeOutFile() { try { outStream.close(); } catch (Exception e) { e.printStackTrace(); } } public static void closeInFile() { try { outStream.close(); } catch (Exception e) { e.printStackTrace(); } } public static String readFromFile() { try { return reader.readLine(); } catch (Exception e) { e.printStackTrace(); } return null; // shouldn't get here } public static void writeToFile(String str) { if (debug) System.out.println(str); try { for(int k=0; k set = new TreeSet(); for(int k=1; kA;original--){ numbers = original.toString().toCharArray(); perm: do{ newNumbers = new char[numbers.length]; newNumbers[0]=numbers[numbers.length-1]; for(int i=1; iB || newNumber=A && newNumber recycleMap = new HashMap(); Set pairSet = new HashSet(); int size = 0; for(int j = a ; j <= b ; j++) { String numString = String.format(""%0"" + stringLength + ""d"", j); String movedString = new String(numString); for(int k = 0 ; k < stringLength ; k++) { String frontString = String.valueOf(movedString.charAt(0)); movedString = movedString.substring(1) + frontString; int movedInt = Integer.parseInt(movedString); if(a <= movedInt && movedInt <= b && movedInt > j) { // recycleMap.put(numString, movedString); pairSet.add(new Pair(j, movedInt)); // System.out.println(numString + "": "" + movedString); size++; } } } System.out.println(""Case #"" + (i+1) + "": "" + pairSet.size()); // For Test // System.out.println(""=== Test Map ===""); // // Set keyMap = recycleMap.keySet(); // for(Iterator iter = keyMap.iterator() ; iter.hasNext() ; ) { // String key = iter.next(); // String value = recycleMap.get(key); // // System.out.println(key + "": "" + value); // } } } } class Pair { int min; int max; public Pair(int a, int b) { if(a < b) { min = a; max = b; } else { min = b; max = a; } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + max; result = prime * result + min; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (max != other.max) return false; if (min != other.min) return false; return true; } } " B12270,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class ProblemC { // private static String inputFile = ""input.txt""; private static String inputFile = ""C-small-attempt0.in""; public static void main(String[] args) throws IOException { BufferedReader input = null; try { input = new BufferedReader(new FileReader(inputFile)); String line = null; int numOfTestCases = 0; if ((line = input.readLine()) != null) { numOfTestCases = Integer.parseInt(line.trim()); } for (int i = 1; i <= numOfTestCases; i++) { if ((line = input.readLine()) != null) { String ab = line; String[] ab_array = ab.split("" ""); int a = Integer.parseInt(ab_array[0]); int b = Integer.parseInt(ab_array[1]); if (a<10 && b<10) { System.out.println(""Case #"" + i + "": 0""); } else { Set recycled = new HashSet(); if (a < 10) { a = 10; } for (int n=a; nn && m<=b) { recycled.add(n_string + "", "" + m_string); } } } System.out.println(""Case #"" + i + "": "" + recycled.size()); } } else { System.out.println(""ERROR: Could not read the test case #"" + i); } } } catch (FileNotFoundException e) { System.out.println(""ERROR: FileNotFoundException for the input file.""); e.printStackTrace(); } finally { input.close(); } } } " B11105,"import java.util.Scanner; import java.util.Vector; public class ThreadDispatcher{ private static final int CORES = 8; private Vector threads = new Vector(CORES); Scanner scan = new Scanner(System.in); private int curCase = 0, T = 0; public ThreadDispatcher(){ System.out.println(""Paste input for qualification round - problem C""); T = Integer.parseInt(scan.nextLine()); for(int i = 1; i <= CORES; i++){ if(i <= T){ String line = scan.nextLine(); curCase++; String[] limitsStr = line.split(""\\s""); int A = Integer.parseInt(limitsStr[0]); int B = Integer.parseInt(limitsStr[1]); SolveThread st = new SolveThread(A, B, curCase,this); threads.add(st); st.run(); } } } public void finish(SolveThread thread){ System.out.println(""Case #"" + thread.casenb + "": "" + thread.pairs); threads.remove(thread); if(curCase < T){ String line = scan.nextLine(); curCase++; String[] limitsStr = line.split(""\\s""); int A = Integer.parseInt(limitsStr[0]); int B = Integer.parseInt(limitsStr[1]); SolveThread st = new SolveThread(A, B, curCase,this); threads.add(st); st.run(); } } public static void main(String[] args){ ThreadDispatcher td = new ThreadDispatcher(); } } " B12604,"/* * Abstract class that reads either the standard input, a named file, or prompts at the terminal. * Implement ""process"" for each CodeJam problem. * Reads input through a ReadWrapper, wrapping a BufferedReader. */ import java.io.*; import java.util.StringTokenizer; import java.text.*; public abstract class CodeJammer { protected ReadWrapper reader; protected int caseNum = 1; //Processes one case public abstract void process() throws IOException; public void init() { //Do nothing unless overridden. } //Process all cases... usually just read the number of them and then run process on each. //Override if necessary. public void processAll() throws IOException { init(); int numTrials = reader.readInt(); for (int i=0; i list = new ArrayList(); for (int value=minValue; value<=maxValue; value++) { String vString = Integer.toString(value); if (list.indexOf(vString) == -1) { boolean mainItemAdded = false; int numberOfSubpairs = 0; int vStringLength = vString.length(); for (int vStringIndex=1; vStringIndex= minValue) && (newValue <= maxValue)) { if (mainItemAdded == false) { mainItemAdded = true; list.add(vString); // System.out.println(vString); numberOfSubpairs++; } numberOfSubpairs++; list.add(newValueString); // System.out.println(newValueString); } } for (int s=numberOfSubpairs-1; s>0; s--) { numberOfPairs+=s; } // System.out.println(""Pair: "" + numberOfPairs + "" Sub: "" + numberOfSubpairs); } } System.out.println(""Case #"" + i + "": "" + numberOfPairs + ""\n""); output.append(""Case #"" + i + "": "" + numberOfPairs + ""\n""); } BufferedWriter bw = new BufferedWriter(new FileWriter(outputPath)); String outputString = output.toString(); bw.write(outputString, 0, outputString.length()); bw.close(); } }" B11112,"package CodeJam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { try { BufferedReader reader = new BufferedReader(new FileReader(""D:\\workspace\\GoogleCodeJam\\data\\C-small-attempt0.in"")); String line; BufferedWriter writer = new BufferedWriter(new FileWriter(""D:\\workspace\\GoogleCodeJam\\data\\C-small-attempt0.out"")); line=reader.readLine(); int c = Integer.parseInt(line); int i = 1; while ((line=reader.readLine()) != null) { String[] ints = line.split("" ""); int a,b; a = Integer.parseInt(ints[0]); b = Integer.parseInt(ints[1]); int cnt = countNumber(a,b); writer.write(String.format(""Case #%s: %s"", i, cnt)); System.out.println(String.format(""Case #%s: %s"", i, cnt)); if (i extends HashMap, V> { private static final long serialVersionUID = 1L; public V put(K1 key1, K2 key2, V value) { return put(Pair.make(key1, key2), value); }; public MultiMapKeyToList getValuesGroupedByKey2() { MultiMapKeyToList key2ToValues = new MultiMapKeyToList(); for (java.util.Map.Entry, V> ent : entrySet()) key2ToValues.put(ent.getKey().getRight(), ent.getValue()); return key2ToValues; } public MultiMapKeyToList getValuesGroupedByKey1() { MultiMapKeyToList key1ToValues = new MultiMapKeyToList(); for (java.util.Map.Entry, V> ent : entrySet()) key1ToValues.put(ent.getKey().getLeft(), ent.getValue()); return key1ToValues; } } " B10813,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.StringTokenizer; public class RecycledNumbers { public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new FileReader(""codejamc.in"")); BufferedWriter brout=new BufferedWriter(new FileWriter(""codejamc.out"")); StringTokenizer sb=new StringTokenizer(br.readLine()); int t=Integer.parseInt(sb.nextToken()); for(int l=1;l<=t;l++) { sb=new StringTokenizer(br.readLine()); int A=Integer.parseInt(sb.nextToken()); int B=Integer.parseInt(sb.nextToken()); HashSet set=new HashSet(); for(int i=A;i<=B;i++) { String inp=i+""""; String result=""""; for(int j=1;j=A && (Integer.parseInt(inp)+"""").length()==(Integer.parseInt(result)+"""").length()) { set.add(inp+"" ""+result); set.add(result+"" ""+inp); } } } brout.write(""Case #""+l+"": ""+set.size()/2+""\n""); } brout.close(); return; } } " B10018,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class OutputWriter { private BufferedWriter bw = null; private long counter = 1; public OutputWriter(String fileName) { try { bw = new BufferedWriter(new FileWriter(new File(fileName))); } catch (IOException e) { e.printStackTrace(); } } public void writeCaseLine(String output) { try { bw.write(""Case #"" + counter + "": "" + output+""\n""); } catch (IOException e) { e.printStackTrace(); } counter++; } public void flushAndClose() { try { bw.flush(); bw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B10497,"package QualifiactionRound; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; public class RecycledNumbers { /** * @param args */ public static void writeToFile(String text) { try { BufferedWriter bw = new BufferedWriter( new FileWriter(new File(""C:\\C-small-attempt0.out""), true)); bw.write(text); bw.newLine(); bw.close(); } catch (Exception e) { } } public static int isRecycled(int n,int m) { String ch=String.valueOf(m); String dh; for(int i=0;i=A;m--){ if((m>n) && isRecycled(n, m)==1) result++; } } writeToFile(""Case #""+nbr+"": ""+result); System.out.println (""Case #""+nbr+"": ""+result); nbr++; } in.close(); } catch (Exception e){ System.err.println(""Error: "" + e.getMessage()); } } } " B12567,"import java.io.*; import java.util.*; public class RecycledNumbers{ public static void main(String[] args){ String [] parse = new String[100]; int T; String s = """"; String a = """"; int counter = 0; int count = 0; int pair = 0; int length = 0; int k = 0; int l = 0; int index = 0; int flag = 0; int [][] pairArry = new int [10000][2]; File inFile = new File(""C-small-attempt1.in""); File outFile = new File(""C-small-attempt1.txt""); try{ BufferedReader in = new BufferedReader(new FileReader(inFile)); PrintWriter out = new PrintWriter(new FileWriter(outFile)); T = Integer.parseInt(in.readLine()); for(int i=0;i= 2){ for(int j=min; j<=max; j++){ length = (Integer.toString(j)).length(); s = Integer.toString(j); //out.println(s); a = """"; for(k=0;k= length){ l = l - length; a = a + Character.toString(s.charAt(l)); l++; }else{ a = a + Character.toString(s.charAt(l)); l++; } count++; } //out.println(a); count = 0; if((j < Integer.parseInt(a)) && (Integer.parseInt(a) <= max)){ pairArry[index][0] = j; pairArry[index][1] = Integer.parseInt(a); index++; pair++; } //count = 0; a = """"; } //out.println(); } } for(int m=0;m Number = new ArrayList(); for (int k = 0; k < temp.length(); k++){ String rotated = temp.substring(temp.length()-k, temp.length()); String other_half = temp.substring(0, temp.length()-k); String total = rotated+other_half; int rot_number = Integer.parseInt(total); if(rot_number <= B && rot_number >= A && rot_number < i) { if(contains(Number, rot_number)) {} //do nothing else{ // System.out.println(i + ""; ""+rot_number); Number.add(rot_number); count++; } } } } return count; } private static boolean contains(ArrayList number, int rot_number) { // TODO Auto-generated method stub for(int i = 0; i < number.size(); i++) { if (number.get(i) == rot_number) { return true; } } return false; } } " B11051,"import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) { RecycledNumbers rec = new RecycledNumbers(); File file = new File(""C:\\Users\\aadi\\Desktop\\RecycledNumbers\\C-small-attempt0.in""); Numbers[] numbers = new Numbers[2000001]; for(int i =1 ;i<2000001 ;i++){ int length = (int) (Math.log10(i)+1); numbers[i] = new Numbers(i, length); int temp = i; for(int j =0 ;jj){ pairs++; } } } out.write(""Case #""+(i+1)+"": ""); out.write(""""+pairs); out.write(System.getProperty(""line.separator"")); System.out.println(pairs); System.out.println(""""); } out.close(); }catch(FileNotFoundException f){ f.getStackTrace(); }catch(Exception e){ e.getStackTrace(); } } } class Numbers{ int num; int length; int count; int[] arr = new int[6]; public Numbers(int number, int length){ this.length =length; this.num = number; } public int circularPermutes(int number,int length){ int divider = (int) Math.pow(10,length-1); int temp = (number%divider)*10+number/divider; return temp; } public boolean isUnique(int number){ for(int i =0; i= low && r <= high) { int min = Math.min(r, no); int max = Math.max(r, no); String a = Integer.toString(min)+""""+Integer.toString(max); if(!(p.contains(a))) { p.add(a); } } } } }" B10925,"package utils; /** * * @author Fabien Renaud */ public class StopWatch { private long startTime = -1; private long stopTime = -1; private boolean running = false; public StopWatch start() { startTime = System.currentTimeMillis(); running = true; return this; } public StopWatch stop() { stopTime = System.currentTimeMillis(); running = false; return this; } public long getElapsedTime() { if (startTime == -1) { return 0; } if (running) { return System.currentTimeMillis() - startTime; } else { return stopTime - startTime; } } public String getElapsedSeconds() { return String.format(""%1$.4f"", getElapsedTime() / 1000.0f); } public StopWatch reset() { startTime = -1; stopTime = -1; running = false; return this; } } " B10265,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package C; import java.io.*; import java.util.Scanner; /** * * @author Novin Pendar */ public class C { public static void main(String[] args) throws FileNotFoundException, IOException{ File fi=new File(""C-small-attempt0.in""); FileReader fr=new FileReader(fi); Scanner con=new Scanner(fr); int n=Integer.valueOf(con.nextLine()).intValue(); int a,b; File fo=new File(""C-small-attempt0.out""); PrintWriter pr=new PrintWriter(fo); for(int i=0;i j && number <= B) { count++; } number = recycle(number); } } // do case things here System.out.format(""Case #%d: %d\n"", i, count); } } private static int recycle(int n) { int temp = n; int max = 1; while (temp >= 10) { max *= 10; temp /= 10; } int m = n / 10 + (max * (n % 10)); temp = n; while (temp % 10 == 0) { temp = m; m = m / 10 + (max * (m % 10)); } return m; } } " B11084,"package fixjava; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map.Entry; import java.util.Set; /** * Simple multimap class. MultiMap map = MultiMapKeyToList.make(); map.put(""a"", ""x""); map.put(""a"", ""x""); map.put(""a"", ""y""); map.put(""b"", ""z""); System.out.println(Join.joinRecursive(map.entrySet(), "", "", ""["", ""]"")); * * @author luke */ public class MultiMapKeyToList { HashMap> map = new HashMap>(); public static MultiMapKeyToList make() { return new MultiMapKeyToList(); } public void put(S key, T value) { ArrayList list = map.get(key); if (list == null) { list = new ArrayList(); map.put(key, list); } list.add(value); } public ArrayList get(S key) { return map.get(key); } public boolean containsKey(S key) { return map.containsKey(key); } public int sizeKeys() { return map.size(); } public HashSet valuesUnion() { HashSet result = new HashSet<>(); for (Entry> ent : map.entrySet()) for (T val : ent.getValue()) result.add(val); return result; } public Set>> entrySet() { return map.entrySet(); } public HashMap> getRawMap() { return map; } public ArrayList>> getRawMapAsList() { ArrayList>> result = new ArrayList>>(); for (Entry> ent : map.entrySet()) result.add(Pair.make(ent.getKey(), ent.getValue())); return result; } public void putAll(S key, Iterable values) { boolean putSomething = false; for (T val : values) { put(key, val); putSomething = true; } if (!putSomething && !map.containsKey(key)) // If putting an empty collection, need to create an empty set at the key map.put(key, new ArrayList()); } public void putAll(S key, T[] values) { if (values.length == 0 && !map.containsKey(key)) // If putting an empty collection, need to create an empty set at the key map.put(key, new ArrayList()); else for (T val : values) put(key, val); } /** Invert the mapping */ public MultiMapKeyToList invert() { MultiMapKeyToList inv = new MultiMapKeyToList(); for (Entry> ent : map.entrySet()) { S s = ent.getKey(); for (T t : ent.getValue()) inv.put(t, s); } return inv; } public ArrayList>> toList() { ArrayList>> result = new ArrayList>>(); for (Entry> ent : map.entrySet()) result.add(Pair.make(ent.getKey(), ent.getValue())); return result; } /** Write out to a TSV file */ public void writeOutToFile(String tsvFile) throws IOException { PrintWriter writer = new PrintWriter(tsvFile); for (Entry> ent : map.entrySet()) { S key = ent.getKey(); StringBuilder buf = new StringBuilder(); buf.append(key); for (T val : ent.getValue()) buf.append(""\t"" + val); writer.println(buf.toString()); } writer.close(); } /** Read in a String->String map from a TSV file */ public static MultiMapKeyToList readFromFile(String tsvFile) throws IOException { MultiMapKeyToList map = new MultiMapKeyToList(); for (String line : new FileLineIterator(tsvFile)) { String[] parts = Split.split(line, ""\t""); String key = parts[0]; for (int i = 1; i < parts.length; i++) map.put(key, parts[i]); } return map; } } " B12970,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recyclednumber; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import javax.swing.JFileChooser; /** * * @author pos */ public class RecycledNumbers { static Numbers[] TestCases; public static void main(String args[]) { readFile(); for (int i = 0; i < TestCases.length; i++) { TestCases[i].Calculate(); } WriteToFile(); } private static void readFile() { try { JFileChooser FC = new JFileChooser(); String Path = null; if (FC.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { Path = FC.getSelectedFile().getPath(); StringBuffer Text = new StringBuffer(); FileInputStream FIS = null; DataInputStream DIS; BufferedReader BR; FIS = new FileInputStream(Path); DIS = new DataInputStream(FIS); BR = new BufferedReader(new InputStreamReader(DIS)); int TestCasesCount = Integer.valueOf(BR.readLine()); TestCases = new Numbers[TestCasesCount]; for (int i = 0; i < TestCasesCount; i++) { String[] AB = BR.readLine().split("" ""); TestCases[i] = new Numbers(Integer.valueOf(AB[0]), Integer.valueOf(AB[1])); } FIS.close(); DIS.close(); BR.close(); } } catch (IOException ex) { System.out.println(ex.getMessage()); } } private static void WriteToFile() { FileOutputStream FOS = null; DataOutputStream DOS; BufferedWriter BW; try { FOS = new FileOutputStream(new File(""Recycled"")); } catch (FileNotFoundException ex) { } DOS = new DataOutputStream(FOS); BW = new BufferedWriter(new OutputStreamWriter(DOS)); for (int i = 0; i < TestCases.length; i++) { String Line = ""Case #"" + (i + 1) + "": "" + TestCases[i].Result+""\n""; try { BW.write(Line); } catch (IOException ex) { System.err.println(ex.getMessage()); } } try { BW.close(); } catch (IOException ex) { System.err.println(ex.getMessage()); } } } " B11757,"import java.io.File; import java.io.FileInputStream; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) { try { File output = new File(""output.txt""); if (output.exists()) { output.delete(); } PrintWriter pw = new PrintWriter(output); Scanner s = new Scanner(new FileInputStream(""input.txt"")); int T = s.nextInt(); s.nextLine(); for (int c = 0; c < T; c++) { int start = s.nextInt(); int end = s.nextInt(); int digits = digits(start); System.out.println(String.format(""%d - %d (%d)"", start, end, digits)); int found = 0; for (int n = start; n < end; n++) { int m = n; HashSet pairs = new HashSet<>(); for (int i = 0; i < digits; i++) { m = rotate(m, digits); if (m <= n) continue; if (m >= start && m <= end && !pairs.contains(m)) { pairs.add(m); found++; //System.out.println(String.format(""%d - %d"", n, m)); } } } // pw.println(String.format(""Case #%d: %d"", (c+1), found)); System.out.println(String.format(""Found %d numbers"", found)); System.out.println(""---------------------""); } // Read inputs and solve here pw.close(); System.out.println(""Done !""); System.out.println(String.format(""51234 rotated to %d"", rotate(51234, 5))); } catch (Exception ex) { System.out.println(""ERROR""); System.out.println(ex.getMessage()); ex.printStackTrace(); } } private static int digits(int n) { int d = 0; while (n > 0) { n /= 10; d++; } return d; } private static int rotate(int m, int digits) { if (digits == 1) return m; int left = m%10; m /= 10; m += left * (int)Math.pow(10, digits-1); return m; } public RecycledNumbers() { } } " B13214,"package CodeJam2012; import java.util.HashMap; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args){ Scanner reader = new Scanner(System.in); int cases = reader.nextInt(); reader.nextLine(); for(int i = 1; i <= cases; i++){ String _case = reader.nextLine(); int pos = 0; int pos2 = 0; while(_case.charAt(pos2) != ' ') pos2++; int a = Integer.parseInt(_case.substring(pos, pos2)); pos = pos2 + 1; pos2 = pos; while(pos2 < _case.length() && _case.charAt(pos2) != ' ') pos2++; int b = Integer.parseInt(_case.substring(pos, pos2)); String result = """" + recycleCount3(a, b); System.out.println(""Case #"" + i + "": "" + result); } } public static int recycleCount(int a, int b){ int count = 0; HashSet nums = new HashSet(); for(int i = a; i <= b; i++){ String num = i + """"; if(!nums.contains(i)){ nums.add(i); if(num.length() > 1){ String test_s = num; for(int j = 0; j < num.length(); j++){ test_s = test_s.charAt(test_s.length() - 1) + test_s.substring(0, test_s.length() - 1); int int_s = Integer.parseInt(test_s); if(int_s >= a && int_s <= b && !nums.contains(int_s)){ nums.add(i); nums.add(int_s); count++; } } } } } return count; } public static int recycleCount2(int a, int b){ int count = 0; HashSet nums = new HashSet(); for(int i = a; i <= b; i++){ String test_s = i + """"; int length = test_s.length(); HashSet temp = new HashSet(); for(int j = 0; j < length; j++){ test_s = test_s.charAt(test_s.length() - 1) + test_s.substring(0, test_s.length() - 1); int int_s = Integer.parseInt(test_s); temp.add(int_s); } for(Integer in : temp){ if(!nums.contains(in) && in.intValue() != i){ nums.add(in); count++; } } nums.addAll(temp); } return count; } public static int recycleCount3(int a, int b){ HashSet> nums = new HashSet>(); for(int i = a; i <= b; i++){ String test_s = i + """"; int length = test_s.length(); HashSet temp = new HashSet(); for(int j = 0; j < length; j++){ test_s = test_s.charAt(test_s.length() - 1) + test_s.substring(0, test_s.length() - 1); int int_s = Integer.parseInt(test_s); temp.add(int_s); } for(Integer in : temp){ HashSet tempSet = new HashSet(); tempSet.add(in); tempSet.add(i); if(in >= a && in <= b && in.intValue() != i && (!nums.contains(tempSet))){ nums.add(tempSet); } } } return nums.size(); } } " B12147,"import java.io.*; import java.util.*; import java.math.*; public class C { public static void main(String[] args) throws IOException { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(""C-small-attempt0.in"")); BufferedReader br = new BufferedReader(new InputStreamReader(bis)); PrintWriter out = new PrintWriter(""C-small-attempt0.out""); int cases = Integer.parseInt(br.readLine().trim()); StringTokenizer st; for (int c = 1; c <= cases; c++) { int res = 0; st = new StringTokenizer(br.readLine()); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); for (int i = A; i <= B; i++) { String iStr = i+""""; int len = iStr.length(); for (int j = 1; j < len; j++) { int curr = getNext(iStr, j, len); if(curr > i && curr <= B) res++; } } out.println(""Case #"" + c + "": "" + res); } out.close(); } public static int getNext(String s, int st, int len) { String res = s.charAt(st)+""""; for (int i = st+1; i%len != st; i++) { res += s.charAt(i%len); } return Integer.parseInt(res); } }" B12679,"import java.io.File; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { public static void main(String[] args) { try { System.setOut(new PrintStream(new FileOutputStream(""output.txt""))); Scanner scanner = new Scanner(new File(args[0])); int testsNum = scanner.nextInt(); String solution; for (int i=1; i<=testsNum; i++) { solution = solve(scanner); System.out.println(""Case #""+i+"": ""+solution); System.err.println(""Case #""+i+"": ""+solution); } } catch (Exception e) {e.printStackTrace();} } static class Pair { private int n; private int m; public Pair(int n, int m) {this.n=n; this.m=m;} public int hashCode() {return n^m;} public boolean equals(Object o) { if (!(o instanceof Pair)) return false; Pair p = (Pair)o; return n==p.n && m==p.m; } } private static String solve(Scanner scanner) { int A = scanner.nextInt(); int B = scanner.nextInt(); int ret=0; int r; int digits; Set pairs = new HashSet(); Pair pair; for (int n=A; n<=B; n++) { digits = (int)Math.ceil(Math.log10(n)); if (n>10) { for (int d=1; d= t[lg+1]) lg++; //System.out.println(A+"" ""+lg); for(n = A; n >> ""+n+"" - ""+m); if( n < m && m <= B && (n%t[kit])*10>=t[kit] && !H.contains(m)) { DB++; H.add(m); //System.out.println(""OK >>> ""+n+"" - ""+m+"" DB= ""+DB); } kit++; } } return DB; } public static void main (String args[]) throws IOException{ BufferedReader be = new BufferedReader(new FileReader(""C-small.in"")); int T = Integer.parseInt(be.readLine()); for(int i=1; i<=T; i++){ String s = be.readLine(); A = Integer.parseInt(s.split("" "")[0]); B = Integer.parseInt(s.split("" "")[1]); System.out.println(""Case #""+i+"": ""+solve()); } be.close(); } } " B11865,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; public class c { public static void solve() throws Exception { BufferedReader br = new BufferedReader(new FileReader(""c.txt"")); PrintWriter out = new PrintWriter(new File(""c-out.txt"")); String s = """"; int t = Integer.parseInt(br.readLine()); // int t = 105; Queue q; for (int i = 0; i < t; i++) { int count = 0; s = br.readLine(); String x[] = s.split("" ""); int A = Integer.parseInt(x[0]); int B = Integer.parseInt(x[1]); for (int j = A; j < B; j++) { for (int j2 = j + 1; j2 <= B; j2++) { q = new LinkedList(); int n = j; int m = j2; int m2 = m; int sumn = 0, summ = 0; while (n > 0) { q.add(n % 10); sumn += (n % 10); summ += (m2 % 10); m2 = m2 / 10; n = n / 10; } if (summ != sumn) continue; int len = q.size(); for (int k = 0; k < len - 1; k++) { q.add(q.remove()); // System.out.println(q); int c = 1; int nn = 0; for (Integer integer : q) { nn = nn + (integer * c); c *= 10; } // System.out.println(nn); if (m == nn) { count++; break; } } } } out.println(""Case #"" + (i + 1) + "": "" + count); } out.close(); } public static void main(String[] args) throws Exception { /* * int n = 12345; Queue q = new LinkedList(); int m = * 0; while (n > 0) { q.add(n%10); //System.out.print(n % 10); * //System.out.println(m); n = n/10; * * } * * int len = q.size(); for (int j = 0; j < len-1; j++) { * q.add(q.remove()); System.out.println(q); int c = 1; int nn =0; for * (Integer integer : q) { nn = nn + (integer*c); c *= 10; } * System.out.println(nn); } * * //System.out.println(1234568 % 10); String sa = ""687248""; //char[] * sac = sa.toCharArray(); //Arrays.sort(sac); //System.out.println(new * String(sac)); BigInteger b = new BigInteger(""123""); * * //int n = 16; //System.out.println(n>>3); */ c.solve(); } } " B11794,"import java.util.*; import java.io.*; public class probC { public static void main (String args[]) throws IOException { BufferedReader in = new BufferedReader(new FileReader(""C:\\downloads\\c-small-attempt0.in"")); BufferedWriter out = new BufferedWriter(new FileWriter(""C:\\downloads\\c-small-output.in"")); int t = Integer.parseInt(in.readLine()); int i,j,k,l; int A,B; int len; int count; for (i=1;i<=t;i++) { StringTokenizer st = new StringTokenizer(in.readLine()); A = Integer.parseInt(st.nextToken()); B = Integer.parseInt(st.nextToken()); count=0; len = String.valueOf(A).length(); int[] temp = new int[len]; for (j=A;j<=B;j++) { String n; n = String.valueOf(j); for (k=0;kj) && (y<=B)) count++; n = sb.toString(); } } out.write(""Case #""+i+"": ""+count); out.newLine(); } out.close(); } } " B10381,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recycle.number; import dancing.gogglers.Googlers; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; /** * * @author Raveesh */ public class Recycler { public static void main(String[] args) throws FileNotFoundException, IOException { String filePath = ""C:\\Users\\Raveesh\\Downloads\\C-small-attempt0.in""; String filePathOutput = filePath + ""_out""; BufferedReader stdin = new BufferedReader(new FileReader(new File(filePath))); FileWriter fileWriter = new FileWriter(filePathOutput); ArrayList stringList = Recycler.getInputList(stdin); int count = 1; Iterator iter = stringList.iterator(); while (iter.hasNext()) { String inputStr = (String) iter.next(); String[] inputStrArr = inputStr.split(""\\ ""); int startNum = Integer.valueOf(inputStrArr[0]); int endNum = Integer.valueOf(inputStrArr[1]); int output = Recycler.performPerm(startNum,endNum); String out = ""Case #"" + count + "": "" + output; fileWriter.write(out); fileWriter.write(""\n""); count++; } fileWriter.close(); } private static int performPerm(int start,int end ) { finalSet = new ArrayList(); for (int i=start;i<=end;i++) { // System.out.println(""Running"" + i); StringBuffer val = new StringBuffer(String.valueOf(i)); // System.out.println(""Running"" + val); checkVal(start, end, val); } // Iterator iter = finalSet.iterator(); // while (iter.hasNext()) { // System.out.println(""Val "" + iter.ne); // } // System.out.println(""=========================COUNT "" + finalSet.size()/2); return finalSet.size()/2; } private static ArrayList finalSet = new ArrayList(); private static boolean checkVal (int start,int end, StringBuffer val) { for (int i =0;i< val.length() ; i++) { String temp = val.substring(0,i+1); String rem = val.substring(i+1,val.length()); String val1 = rem + temp; // System.out.println(""temp"" + temp + "" rem : "" + rem); // for (int j = 0;j <= rem.length() ; j++) { // StringBuffer val1 = new StringBuffer(rem); // if (j==i) { // continue; // // } // val1.insert(j, temp); // System.out.println(""iNPUT :; "" + val + "" :: Output : "" + val1); // System.out.println(""iNPUT :; "" + val + "" :: Output : "" + val1); int t = Integer.valueOf(val1.toString()); if (t >= start && t <= end && !val.toString().equals(val1.toString())) { // System.out.println(""iNPUT :; "" + val + "" :: Output : "" + val1 + "" t :: "" + t ); finalSet.add(t); //// System.out.println(""dding :: "" + t); // String key = val.toString() + "","" + val1.toString(); // String key1 = val1.toString() + "","" + val.toString(); // if(!(finalSet.containsKey(key)|| finalSet.containsKey(key1))) { // finalSet.put(key, t); // } //// finalSet.put(Integer.valueOf(val1.toString())); // } // System.out.println(""num :: "" + val1); } } return true; } private static ArrayList getInputList(BufferedReader stdin) throws IOException { ArrayList stringList = new ArrayList(); String line; int inputLineCount = 0; Integer testCaseCount = 0; while ((line = stdin.readLine()) != null && line.length() != 0 && inputLineCount <= testCaseCount.intValue()) { // System.out.println(""line :: "" + line); if (inputLineCount == 0) { try { testCaseCount = Integer.valueOf(line); } catch (NumberFormatException pe) { System.out.println(""Invalid input for # of test cases""); System.exit(0); } inputLineCount++; continue; } stringList.add(line); inputLineCount++; if (inputLineCount == testCaseCount + 1) { break; } } return stringList; } } " B13178,"import java.io.File; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.Scanner; public class C { static Scanner s; /** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { // TODO Auto-generated method stub s = new Scanner(new File(""a.txt"")); int T = s.nextInt(); for(int a=1;a<=T;a++) { int A = s.nextInt(); int B = s.nextInt(); int res = 0; for(int i=A; i hm = new HashMap(); for(int j=1; ji && n<=B && !hm.containsKey(n)) { res++; hm.put(n, 1); } } } System.out.println(""Case #""+a+"": ""+res); } s.close(); } } " B12630," import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class UtilGoogle { public static Scanner readFile(String path) throws FileNotFoundException{ File in = new File(path); Scanner s = new Scanner(in); return s; } public static PrintWriter writeFile(String path) throws IOException{ File out = new File(path); FileWriter w = new FileWriter(out); return new PrintWriter(w); } } " B11418,"package problem.c; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Set; import org.apache.commons.io.FileUtils; import com.google.common.collect.Lists; import com.google.common.collect.Sets; public class RecycledNumbers { private static final String INPUT_FILE = ""C-small-attempt0.in""; public static void main(String[] args) throws IOException { File inputFile = new File(INPUT_FILE); List inputLines = FileUtils.readLines(inputFile); Integer.parseInt(inputLines.remove(0)); List outputLines = Lists.newArrayList(); for (int k = 0; k < inputLines.size(); k++) { String line = inputLines.get(k); int seperator = line.indexOf(' '); int a = Integer.valueOf(line.substring(0, seperator)); int b = Integer.valueOf(line.substring(seperator + 1)); Set matches = Sets.newHashSet(); for (int currentNumber = a; currentNumber < b; currentNumber++) { String stringA = String.valueOf(currentNumber); for (int j = 1; j < stringA.length(); j++) { String begin = stringA.substring(j); String end = stringA.substring(0, j); int generatedNumToCheck = Integer.valueOf(begin + end); if (generatedNumToCheck <= b && generatedNumToCheck >= a && generatedNumToCheck != currentNumber && generatedNumToCheck > currentNumber) { matches.add(currentNumber + "" - "" + generatedNumToCheck); } } } outputLines.add(""Case #"" + (k + 1) + "": "" + matches.size()); } System.out.println(outputLines); FileUtils.writeLines(new File(""generated-recycled-numbers-output.txt""), outputLines); } } " B11279,"package com.google.codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; public class Utils { static final String outputFileName = ""D:\\output.txt""; static ArrayList outputData = new ArrayList(); public static void run(Class cls){ Object obj = null; try { obj = cls.newInstance(); } catch (Exception e1) { e1.printStackTrace(); } outputData.clear(); String[] args = Utils.readInput(cls); Method method = getMethod(obj.getClass()); executeMethod(obj, args, method); writeToFile(); } private static void executeMethod(Object obj, String[] args, Method method) { int index = 0; int n = Integer.valueOf(args[index++]); if (n == args.length - 1){ for(int i = 0; i < n; i++){ Class[] t = method.getParameterTypes(); Object[] par = new Object[t.length]; for (int j = 0; j < t.length; j++) { par[j] = parseParameter(args[index++], t[j]); } try { printOutput(i+1, method.invoke(obj, par)); } catch (Exception e) { e.printStackTrace(); } } }else{ for(int i = 0; i < n; i++){ Class[] t = method.getParameterTypes(); Object[] par = new Object[t.length]; String[] sp = args[index++].split("" ""); if(t.length == sp.length){ for (int j = 0; j < t.length; j++) { String[] sArr = new String[Integer.valueOf(sp[j])]; for (int k = 0; k < sArr.length; k++) { sArr[k] = args[index++]; } par[j] = sArr; } } try { printOutput(i+1, method.invoke(obj, par)); } catch (Exception e) { e.printStackTrace(); } } } } private static String[] readInput(Class cls){ String fileName = cls.getSimpleName() + "".in""; BufferedReader in = new BufferedReader(new InputStreamReader(cls.getResourceAsStream(fileName))); ArrayList res = new ArrayList(); String s; try { while((s = in.readLine()) != null){ res.add(s); } } catch (IOException e) { e.printStackTrace(); } return res.toArray(new String[]{}); } private static Method getMethod(Class cls){ Method[] methods = null; try { methods = cls.getDeclaredMethods(); for(Method m : methods) if(Modifier.isPublic(m.getModifiers())) return m; } catch (Exception e) { e.printStackTrace(); } return null; } private static Object parseParameter(String arg, Class cls) { if(cls == int.class){ return Integer.valueOf(arg); }else if(cls == int[].class){ String[] split = arg.split("" ""); int[] res = new int[split.length]; for (int i = 0; i < res.length; i++) { res[i] = Integer.valueOf(split[i]); } return res; }else if(cls == long[].class){ String[] split = arg.split("" ""); long[] res = new long[split.length]; for (int i = 0; i < res.length; i++) { res[i] = Long.valueOf(split[i]); } return res; }else if(cls == String.class){ return arg; } return null; } private static void printOutput(int count, Object res) { Class cls = res.getClass(); String data = ""Case #"" + count + "": ""; if(cls == int[].class){ int[] array = (int[]) res; for (int i = 0; i < array.length; i++) { data += array[i] + "" ""; } data = data.substring(0, data.length() - 1); }else{ data += res; } System.out.println(data); outputData.add(data); } private static void writeToFile() { try { FileWriter fstream = new FileWriter(outputFileName); BufferedWriter out = new BufferedWriter(fstream); for(String s : outputData){ out.write(s); out.newLine(); } out.close(); fstream.close(); } catch (IOException e1) { e1.printStackTrace(); } } }" B11821,"/** * Google CodeJam 2012 * General framework that takes care of the similar and repetitive tasks for all the problems. * E.g. managing case input and output. * * By Üllar Soon */ package eu.positivew.codejam.framework; /** * CodeJam IO input case interface. * * @author Üllar Soon */ public interface CodeJamInputCase { public String getType(); } " B10449,"package MyAllgoritmicLib; public class Sort { public static int partition(int[] m, int a, int b) { int i = a; for (int j = a; j <= b; j++) // ïðîñìàòðèâàåì ñ a ïî b { if (m[j] >= m[b]) // åñëè ýëåìåíò a[j] íå ïðåâîñõîäèò // a[b], { int t = m[i]; // ìåíÿåì ìåñòàìè a[j] è a[a], a[a+1], a[a+2] è // òàê äàëåå... m[i] = m[j]; // òî åñòü ïåðåíîñèì ýëåìåíòû ìåíüøèå a[b] â // íà÷àëî, m[j] = t; // à çàòåì è ñàì a[b] «ñâåðõó» i++; // òàêèì îáðàçîì ïîñëåäíèé îáìåí: a[b] è a[i], ïîñëå ÷åãî // i++ } } return i - 1; // â èíäåêñå i õðàíèòñÿ <íîâàÿ ïîçèöèÿ ýëåìåíòà a[b]> + 1 } public static void quicksort(int[] m, int a, int b) // a - íà÷àëî ïîäìíîæåñòâà, // b - // êîíåö { // äëÿ ïåðâîãî âûçîâà: a = 0, b = <ýëåìåíòîâ â ìàññèâå> - 1 if (a >= b) return; int c = partition(m, a, b); quicksort(m, a, c - 1); quicksort(m, c + 1, b); } } " B12124,"package Television; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class Television { public static int Max=0; public static int Min = 0; public static List currentCandidate = new ArrayList(); public static String[] inputLines; public static int[] RESULTS; public static void main(String args[]) { try { readIo(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } solveProblemsFromLine(); try { saveOutputFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void readIo() throws Exception { DataInputStream in = new DataInputStream(new FileInputStream(""C.in""));//inp2.in BufferedReader br = new BufferedReader(new InputStreamReader(in)); int lineNum = Integer.parseInt(br.readLine()); inputLines = new String[lineNum]; RESULTS = new int[lineNum]; String strLine=null; int count=0; while ((strLine = br.readLine()) != null) { inputLines[count] = strLine; count++; } } public static void parse(String input) { String tokens[] = input.split("" ""); Min = Integer.parseInt(tokens[0]); Max = Integer.parseInt(tokens[1]); } public static void solveProblemsFromLine() { for(int inp=0; inp pPair=null; if((pPair=checkValid(integer)).size()!=0) for(Pair childPair : pPair){ if(currentCandidate.contains(childPair)) { System.out.println(""repeated value""); continue; }else currentCandidate.add(childPair); } } int result = currentCandidate.size(); if(result==288) { for(Pair pp:currentCandidate) System.out.println(""(""+pp.a+"", ""+pp.b+"")""); } currentCandidate.clear(); return result; } public static ArrayList checkValid(int data) throws Exception { String dataStr = Integer.toString(data); String left, result; String right; ArrayList resultPairs = new ArrayList(); for(int pos=1;posdata && nextInt<=Max && nextInt!=data && data>=Min) resultPairs.add(new Pair(data, nextInt)); } return resultPairs; } public static void saveOutputFile() throws IOException { BufferedWriter out = new BufferedWriter(new FileWriter(""result.txt"")); for(int i=0; i numbers = new HashSet(); static BitSet numberBitmap = new BitSet(10000000); /** * @param args * @throws IOException * @throws NumberFormatException */ public static void main(String[] args) throws NumberFormatException, IOException { int testCaseCount; try { String input = IN.readLine(); testCaseCount = Integer.parseInt(input); } catch (Exception e) { testCaseCount = 0; } if (testCaseCount > 0) { long start = System.currentTimeMillis(); int[][] minMax = new int[testCaseCount][3]; for (int i = 0; i < testCaseCount; i++) { String[] values = IN.readLine().split("" ""); minMax[i][0] = Integer.parseInt(values[0]); minMax[i][1] = Integer.parseInt(values[1]); } for (int i = 0; i < testCaseCount; i++) { minMax[i][2] = findRecycledPairsCount(minMax[i][0], minMax[i][1]); printLn(""Case #%d: %d"", i + 1, minMax[i][2]); } long end = System.currentTimeMillis(); //System.err.println((end - start)); } } static int findRecycledPairsCount(int min, int max) throws NumberFormatException, IOException { HashMap duplicateMap = new HashMap(); int digitCount = getNumberOfDigits(min); numberBitmap.clear(); for (int number = min; number <= max; number++) { if (!numberBitmap.get(number)) { RotatedNumbers rNumber = getRotatedNumbersInRange(number, digitCount, min, max); if (rNumber.count > 1) { duplicateMap.put(rNumber.minimum, rNumber.count); } } } int count = 0; for (Byte b : duplicateMap.values()) { if (b > 1) { count += b == 2 ? 1 : getNC2(b); } } return count; } static int getNC2(int n) { return (int) ((n / 2.0) * (n - 1)); } static int getNumberOfDigits(int number) { int digitCount = 0; while (number > 0) { digitCount++; number /= 10; } return digitCount; } public static RotatedNumbers getRotatedNumbersInRange(int number, int digitCount, int min, int max) { int index = digitCount - 1; int[] digits = new int[digitCount]; int temp = number; while (temp > 0) { digits[index--] = temp % 10; temp /= 10; } int minVal = number; numbers.clear(); for (int start = 0; start < digitCount; start++) { int numVal = 0; for (int j = 0; j < digitCount; j++) { int digit = digits[(start + j) % digitCount]; numVal *= 10; numVal += digit; } numberBitmap.set(numVal); if (numVal >= min && numVal <= max) { numbers.add(numVal); } if (numVal < minVal) { minVal = numVal; } } return new RotatedNumbers(minVal, (byte) numbers.size()); } // to ensure that '\n' is used as EOL on my Windows Machine, just to be sure ;) // static void printLn(String val) { System.out.print(val); System.out.print('\n'); } static void printLn(String format, Object ... args) { System.out.print(String.format(format, args)); System.out.print('\n'); } static class RotatedNumbers { public RotatedNumbers(int minimum, byte count) { this.minimum = minimum; this.count = count; } int minimum; byte count; } } " B11661,"package qualification; import java.io.*; public class Csmall { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new FileReader(""./src/qualification/C-small-attempt0.in"")); BufferedWriter bw = new BufferedWriter(new FileWriter(""./src/qualification/C-small-attempt0.out"")); int[][] inputs = new int[50][2]; int casenumber = 0; String input = null; int total = 0; while((input=br.readLine()) != null) { if(casenumber==0) { total = Integer.parseInt(input); }else{ String[] array = input.split("" ""); inputs[casenumber-1][0] = Integer.parseInt(array[0]); inputs[casenumber-1][1] = Integer.parseInt(array[1]); } casenumber++; } casenumber=1; while(casenumber <= total) { System.out.println(""Case #"" + casenumber + "": "" + String.valueOf(recycledNumbers(inputs[casenumber-1][0], inputs[casenumber-1][1]))); bw.write(""Case #"" + casenumber + "": "" + String.valueOf(recycledNumbers(inputs[casenumber-1][0], inputs[casenumber-1][1]))); bw.newLine(); casenumber++; } bw.close(); } public static int recycledNumbers(int a, int b) throws IOException { int[] storage = new int[2000000]; int count=0; for(int i=a;i list = new LinkedList(); for(int i = A; i <= B; i++) { String current = Integer.toString(i); String next = current; list.clear(); for(int a = 0; a < current.length() - 1; a++) { next = next.charAt(next.length() - 1) + next.substring(0, next.length() - 1); //System.out.println(next); if(!list.contains(next)) { list.add(next); if(current.compareTo(next) < 0 && next.compareTo(up) <= 0) count++; } } } System.out.println(count); } } }" B11948,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; public class RecycledNumbers { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new FileReader(""recycle.in"")); PrintWriter out = new PrintWriter(new FileWriter(""recycle.out"")); int n = Integer.parseInt(br.readLine()); StringTokenizer st; for(int count = 1; count <= n; count++){ st = new StringTokenizer(br.readLine()); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); boolean[] hasBeen = new boolean[B+1]; int numPairs = 0; for(int i = A; i <= B; i++){ if(hasBeen[i] == true) continue; hasBeen[i] = true; ArrayList cycle = rotate(i); int numCycles = 1; for(int num: cycle){ if(num > B || num < A) continue; if(hasBeen[num]) continue; hasBeen[num] = true; numCycles++; } numPairs += (numCycles*(numCycles-1))/2; } out.println(""Case #"" + count + "": "" + numPairs); } out.close(); } static ArrayList rotate(int num){ ArrayList ans = new ArrayList(); int length = String.valueOf(num).length(); for(int i = 1; i < length; i++){ if(num%10 == 0){ num = (int)((num%10)*Math.pow(10, length-1)) + num/10; } else { num = (int)((num%10)*Math.pow(10, length-1)) + num/10; ans.add(num); } } return ans; } } " B12402,"package inout; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; /** * * @author Hasier Rodriguez */ public final class Out { private Out() { } public static void write(String path, int n, String result) throws FileNotFoundException, IOException { File f = new File(path); BufferedWriter br = new BufferedWriter(new FileWriter(f, true)); String out = ""Case #"" + n + "": "" + result; br.write(out); System.out.println(out); br.newLine(); br.flush(); br.close(); } } " B11590,"import java.io.*; import java.util.*; public class C { public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Scanner sc = new Scanner(br.readLine()); int T = sc.nextInt(); int caseNumber = 1; for(int i=0; i list; public Data(String s) { String[] parts = s.trim().split("" ""); A = Integer.parseInt(parts[0]); B = Integer.parseInt(parts[1]); list = new HashSet(); } public Data(int n_) { } public int Solve() { list.clear(); int sols = 0; for (int i=A;i<=B;i++) { sols += permutate(i); //sols += countPerms(i); } //System.out.println(sols); if (sols != list.size()) System.err.println(""WTF""); return list.size(); } public int permutate(int i) { int count = 0; int c = i; int length = (int)(Math.log10(i)+1); int power = length-1; //System.out.println(""Length: ""+length); for (int h=0;h i && i >= A) { count++; //System.out.println(""""+i+"": ""+c); //System.out.println(""Counts""); list.add(""""+i+""""+c); } } //System.out.println(list.size()); return count; } } private static String IN = "".\\C-small-attempt2.in""; private static String OUT = "".\\C-small-attempt2.out""; private Data[] datas; private void go() { File file = new File(IN); System.out.println(file.getAbsolutePath()); File fo = new File(OUT); try { if (!fo.createNewFile()) { fo.delete(); fo.createNewFile(); } BufferedReader br = new BufferedReader(new FileReader(file)); BufferedWriter bw = new BufferedWriter(new FileWriter(fo)); String line; int num = Integer.parseInt(br.readLine()); datas = new Data[num]; int i = 0; while ((line = br.readLine()) != null && num-->0) { datas[i] = new Data(line); int solv = datas[i].Solve(); String ss = ""Case #""+(i+1)+"": ""+solv+""\n""; System.out.print(ss); bw.write(ss); i++; } br.close(); bw.close(); } catch (Exception e) { e.printStackTrace(); } } public Recycle() { go(); } public static void main(String[] args) { new Recycle(); } } " B13175,"import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.Hashtable; import java.util.StringTokenizer; public class one { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub File f = new File(""input.txt""); FileInputStream instream = new FileInputStream(f); BufferedReader reader = new BufferedReader(new InputStreamReader(instream)); File f2 = new File(""output.txt""); FileOutputStream outstream = new FileOutputStream(f2); BufferedOutputStream of = new BufferedOutputStream(outstream); DataOutputStream writer = new DataOutputStream(of); int cases = Integer.parseInt(reader.readLine()); for (int casenum = 1; casenum <= cases; casenum++) { String s = reader.readLine(); StringTokenizer ts = new StringTokenizer(s); int x = Integer.parseInt(ts.nextToken()); int y = Integer.parseInt(ts.nextToken()); String s_out = ""Case #""+casenum+"": ""; int count = 0; for (int i = x; i < y; i++) { for (int j = i+1; j <= y; j++) { if(isRecycled(i, j)){ count++; } } } s_out += count; s_out += '\n'; writer.write(s_out.getBytes()); System.out.println(count); } writer.flush(); writer.close(); } static boolean isRecycled(int x_, int y_){ String x = Integer.toString(x_); String y = Integer.toString(y_); String temp = """"; String test = """"; for (int i = 0; i < x.length()-1; i++) { temp += x.charAt(i); test = x.substring(i+1) + temp ; if(test.equalsIgnoreCase(y)) return true; } return false; } } " B10727,"package com.hingom.codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class RecycledNumbers { private boolean pairs(String sn, String sm) { char[] cn = sn.toCharArray(); char[] cm = sm.toCharArray(); char[] temp = new char[cm.length]; for (int i = 0; i < cn.length; i++) { if (cn[0] == cm[i]) { int p = 0; for (int s = i; s < cn.length; s++) { temp[p++] = cm[s]; } for (int s = 0; s < i; s++) { temp[p++] = cm[s]; } if (sn.equals(new String(temp))) { return true; } } } return false; } public void run() { File input = new File(""resources/C-small-attempt0.in""); File output = new File(""resources/output""); BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new FileReader(input)); writer = new BufferedWriter(new FileWriter(output)); int testCases = Integer.parseInt(reader.readLine()); StringBuilder o = new StringBuilder(); for (int loop = 1; loop <= testCases; loop++) { String line = reader.readLine(); String[] numbers = line.split("" ""); int a = Integer.parseInt(numbers[0]); int b = Integer.parseInt(numbers[1]); int count = 0; o.delete(0, o.length()); for (int n = a; n < b; n++) { for (int m = n + 1; m <= b; m++) { String sn = Integer.toString(n); String sm = Integer.toString(m); if (pairs(sn, sm)) { count++; } } } writer.write(String.format(""Case #%d: %d"", loop, count)); writer.newLine(); } writer.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (reader != null) reader.close(); } catch (Exception e) {} try { if (writer != null) writer.close(); } catch (Exception e) {} } } public static void main(String[] args) { RecycledNumbers recycledNumbers = new RecycledNumbers(); recycledNumbers.run(); } } " B13107,"import java.io.BufferedWriter; import java.io.FileWriter; import java.util.HashSet; import java.util.Iterator; import java.util.Scanner; public class GCJ3 { /** * @param args */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] hold = new int[n]; for (int i = 0; i < n; i++) { hold[i] = 0; int a = sc.nextInt(); int b = sc.nextInt(); int k = (int) Math.log10(a); HashSet checked = new HashSet(); for (int j = a; j <= b; j++) { if(checked.contains(j)) continue; HashSet set = new HashSet(); set.add(j); int curr = j; for (int l = 0; l <= k; l++) { int firstDig = curr / (int) Math.pow(10, k); int mod = curr % (int) Math.pow(10, k); curr = mod * 10 + firstDig; if ((int) Math.log10(curr) == k) { if (a<=curr && curr <=b) { set.add(curr); } } } if (set.size() > 1){ Iterator p = set.iterator(); for(int m = 0;m lineList = CodeJamUtil.parseInputToList(in); //call util method that will do the work List resultingPairsList = CodeJamUtil.getDistinctRecycledPairs(lineList); //write to file try { FileWriter fstream = new FileWriter(""out.txt""); BufferedWriter out = new BufferedWriter(fstream); for (int i = 0; i < resultingPairsList.size(); i ++) { out.write(""Case #"" + (i + 1) + "": "" + resultingPairsList.get(i) + ""\n""); } out.close(); } catch (IOException e) { System.out.println("":'(""); } } } " B12478,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class C { static final int MAX_N = 2000000; static int[][] precalc; static { precalc = new int[MAX_N + 1][]; List values = new ArrayList(); for (int i = 1, deg = 1; i <= MAX_N; ++i) { if (i == deg * 10) { deg *= 10; } values.clear(); int curr = (i % 10) * deg + (i / 10); while (curr != i) { if (curr > i) { values.add(curr); } curr = (curr % 10) * deg + (curr / 10); } int[] z = new int[values.size()]; for (int j = 0; j < z.length; ++j) { z[j] = values.get(j); } precalc[i] = z; } } public void run(Scanner in, PrintWriter out, int nCase) { int min = in.nextInt(); int max = in.nextInt(); int count = 0; for (int i = min; i <= max; ++i) { for (int j : precalc[i]) { if (j <= max) { ++count; } } } out.printf(""Case #%d: %d%n"", nCase, count); } public static void main(String[] args) throws FileNotFoundException { String filename = C.class.getSimpleName().toLowerCase(); Scanner in = new Scanner(new File(filename + "".in"")); PrintWriter out = new PrintWriter(filename + "".out""); int nCases = in.nextInt(); for (int i = 1; i <= nCases; ++i) { new C().run(in, out, i); } out.close(); in.close(); } } " B11424,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; public class RecycledNumbers { public static String input = ""easy.txt""; public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(input)); int n = Integer.parseInt(in.readLine()); for (int i = 1; i <= n; i++) { String line = in.readLine(); int idx1 = line.indexOf(' '); int a = Integer.parseInt(line.substring(0, idx1)); int b = Integer.parseInt(line.substring(idx1 + 1)); long totalCount = 0; Map, Long> signatureMap = new HashMap, Long>(); for (int x = a; x <= b; x++) { totalCount += recycledNums(x, b); } System.out.println(""Case #"" + i + "": "" + totalCount); } } private static int recycledNums (int n, int max) { List digits = new LinkedList(); int remaining = n; while (remaining > 0) { int digit = remaining % 10; digits.add(digit); remaining /= 10; } //System.out.println(""<<"" + n + "">>""); Set nums = new HashSet(); for (int i = 0; i < digits.size() - 1; i++) { int n0 = digits.remove(0); digits.add(n0); int recycled = numFromList(digits); //System.out.println(recycled); if (recycled > n && recycled <= max) nums.add(recycled); } //System.out.println(n + "": "" + nums); return nums.size(); } private static int numFromList(List list) { int num = 0; for (int i = list.size() - 1; i >= 0; i--) { num *= 10; num += list.get(i); } return num; } } " B11149,"import java.util.*; import java.io.*; import java.lang.Integer; public class C { public static void main(String[] args) throws IOException { Scanner in = new Scanner(new File(""C-small-attempt0.in"")); Scanner in1 = new Scanner(new File(""C-small-attempt0.in"")); FileWriter fw = new FileWriter(""C-small.out""); int T = in.nextInt(); in.nextLine(); in1.nextLine(); for (int cases = 1; cases <= T; cases++){ // read the string length for this case String line = in.nextLine(); int len = (line.length() - 1)/2; int valueA = 0; int valueB = 0; int base = 1; int smallNum = in1.nextInt(); int largeNum = in1.nextInt(); int[] number = new int[len]; int total = 0; // get the base number for (int i = 1; i < len; i++){ base = base * 10; } fw.write(""Case #"" + cases + "": ""); for(int i = smallNum; i <= largeNum; i++) { number[0] = i; // fw.write(number[0] + "" ""); for (int j = 1; j < len; j++) { boolean norepeat = false; number[j] = number[j - 1] / base + (number[j - 1] % base) * 10; // fw.write(number[j] + "" ""); if (number[j] >= smallNum && number[j] <= largeNum) { norepeat = true; for (int k = j - 1; k >= 0; k--){ norepeat = norepeat && (number[j] != number[k]); } } if(norepeat) total++; } } total = total / 2; fw.write(total + ""\n""); } fw.flush(); fw.close(); } } " B11148,"import java.io.*; import java.util.*; public class Solution { public static void main(String args[]){ try{ FileInputStream fin=new FileInputStream(""C:\\Program lang\\Google Code Jam\\input01.txt""); DataInputStream datain=new DataInputStream(fin); BufferedReader br=new BufferedReader(new InputStreamReader(datain)); File file = new File(""C:\\Program lang\\Google Code Jam\\output01.txt""); BufferedWriter bw=new BufferedWriter(new FileWriter(file)); int T=Integer.parseInt(br.readLine()); for(int j=0;j num=new ArrayList(); //ab for(int i=A;i num=new ArrayList(); // A is at 0th position // r is at r-A for(int i=A;i=A && p<=B){ count++; num.add(p); if(q>=A && q<=B){ count=count+2; num.add(q); } } else if(q>=A && q<=B) { count++; num.add(q); } } } } bw.write(""Case #""+(j+1)+"": ""+count); bw.newLine(); } bw.close(); }catch(Exception e){ System.out.println(e); } } } " B12842,"import java.io.*; import java.util.*; public class problemC{ public static void main(String args[]) { try{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.valueOf(br.readLine()); int count, a, b, base; String line; String[] lineSplit; for(int i = 0; i < T; i++){ line = br.readLine(); lineSplit = line.split("" ""); count = 0; a = Integer.valueOf(lineSplit[0]); b = Integer.valueOf(lineSplit[1]); base = base(a); for(int j = a; j < b; j++){ count += switchAround(j, b, base); } System.out.println(""Case #"" + (i+1) + "": "" + count); } } catch(Exception e){ } } int div = 10; public static int switchAround(int num, int max, int base){ int copy = num; int count = 0; ArrayList listN = new ArrayList(); for(int i = 1; i < base; i *= 10) { if(num % 10 == 0) { num = num/10; continue; } num = num/10 + (num % 10) * base; if(num <= max && num > copy && !listN.contains(num)) { count++; listN.add(num); } } return count; } public static int base(int num){ int base = 1; while(num/base != 0){ base *= 10; } return base/10; } }" B10055,"package code_jam_2012_qualification_round; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.StringTokenizer; public class C { public static void main(String[] args) throws IOException { long startTime = System.currentTimeMillis(); BufferedReader f = new BufferedReader(new FileReader(""C-small-attempt0.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""C-small-attempt0.out""))); StringTokenizer st = new StringTokenizer(f.readLine()); int T = Integer.parseInt(st.nextToken()); for(int t = 1; t <= T; t++) { st = new StringTokenizer(f.readLine()); int A = Integer.parseInt(st.nextToken()), B = Integer.parseInt(st.nextToken()); boolean[] used = new boolean[B+1]; int sum = 0; for(int i = A; i <= B; i++) { if (used[i]) continue; String s = """" + i; int c = 1; used[i] = true; for(int j = 1; j < s.length(); j++) { int a = Integer.parseInt(s.substring(j) + s.substring(0, j)); if (a <= B && a >= A && !used[a]) { c++; //out.println(i + "" and "" + a); used[a] = true; } } sum += c*(c-1)/2; } out.println(""Case #"" + t + "": "" + sum); System.out.println(""Case #"" + t + "": "" + sum); } out.close(); } } " B10143,"import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Problem3 { public static void main(String[] args) throws FileNotFoundException { String inputFile = ""C-small-attempt0.in""; Scanner inputScanner = new Scanner(new FileInputStream(""d:\\input\\"" + inputFile)); PrintStream ps = new PrintStream(new FileOutputStream( ""d:\\output\\pro3.txt"")); int totalCaseNum = inputScanner.nextInt(); inputScanner.nextLine(); // ----------------------------------------------- // ----------------------------------------------- for (int caseNum = 1; caseNum <= totalCaseNum; caseNum++) { String line = inputScanner.nextLine(); String prefix = ""Case #"" + caseNum + "": ""; StringBuilder output = new StringBuilder(prefix); // ----------------------------------------------- Scanner sc = new Scanner(line); String A = sc.next(); String B = sc.next(); int len = A.length(); int count = 0; int numA = Integer.parseInt(A); int numB = Integer.parseInt(B); for (int n = numA; n <= numB; n++) { String sn = String.valueOf(n); StringBuilder sb = new StringBuilder(); for (int j = 0; j < len - sn.length(); j++) { sb.append('0'); } sb.append(sn); Set recycle = new HashSet(); for (int j = 1; j < len; j++) { int m = genRecycleNum(sb, j); if (n < m && m <= numB) { recycle.add(m); } } count += recycle.size(); } output.append(count); // ----------------------------------------------- System.out.println(output); ps.println(output); } } private static int genRecycleNum(StringBuilder sb, int j) { String sm = sb.substring(j, sb.length()) + sb.substring(0, j); // System.out.println(sb +""::""+sm); return Integer.parseInt(sm); } } " B12615,"package util.graph; public abstract class Edge implements Cloneable{ public abstract State travel(State current); public Node target; public void connect(Node start, Node end) { try { Edge clone = (Edge) this.clone(); start.edges.add(clone); clone.target=end; } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } public void biConnect(Node n1, Node n2) { connect(n1,n2); connect(n2,n1); } } " B11185," public class Hehe { /** * @param args */ public static int n(int A, int B){ // TODO Auto-generated method stub int start=A; int end=B; int count=0; MyNumbers myNumbers = new MyNumbers(); MyNumbers myCheck = new MyNumbers(); for( int k = start; k<=end; k++) { int a =k; String s = Integer.valueOf(a).toString(); for(int i=0; i=start && a!=n && !myCheck.numbers.contains(n)) { //System.out.println(s+"" ""+s2); myNumbers.add(n); myCheck.add(a); count++; } } //myNumbers.numbers.removeAll(myCheck.numbers); } System.out.println(myNumbers.numbers.size()+"" count: ""+count); return count; } } " B13136," import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author ZuoZhong */ public class Recycled { public static void main(String[] args) throws FileNotFoundException, IOException { File file = new File(""C-small-attempt0.in""); BufferedReader in = new BufferedReader(new FileReader(file)); BufferedWriter out = new BufferedWriter(new FileWriter(""Recycled_output.txt"")); ArrayList list = new ArrayList(); int T = Integer.parseInt(in.readLine()); for (int x = 1; x <= T; x++) { int ans = 0; list.clear(); String[] input = in.readLine().split("" ""); if (Integer.parseInt(input[1]) > 10) { int start = Integer.parseInt(input[0]); int end = Integer.parseInt(input[1]); for (int y = end; y >= start; y--) { String value = Integer.toString(y); for (int z = 0; z < value.length(); z++) { String temp = value + value; //System.out.print(value); temp = temp.substring(z, z + value.length()); //System.out.print("" to "" + temp); if (temp.charAt(0) == '0') { //skip //System.out.println("" skip""); } else if (temp.compareTo(value) == 0) { //skip //System.out.println("" skip""); } else if (Integer.parseInt(temp) > end) { //skip //System.out.println("" skip""); } else if (Integer.parseInt(temp) < Integer.parseInt(value)) { //skip //System.out.println("" skip""); } else { boolean exist = false; try { for (int a = 1; a < value.length(); a++) { String pre = list.get(ans - a); if (pre.compareTo(temp) == 0) { exist = true; break; } } } catch (Exception e) { } if (!exist) { ans++; list.add(temp); //System.out.println("" added : "" + ans); } else { //System.out.println("" skip""); } } } } for (String v : list) { System.out.print(v + "" ""); } System.out.println(); } out.write(""Case #"" + x + "": "" + ans); System.out.println(""Case #"" + x + "": "" + ans); out.newLine(); } out.close(); } } " B12042,"import java.util.*; import java.io.*; import java.math.*; public class Recycle { public static void main(String args[]) throws Exception { BufferedReader in = new BufferedReader(new FileReader(new File(""recycle.in""))); FileWriter out = new FileWriter(new File(""recycle.out"")); int n = Integer.parseInt(in.readLine()); for (int i = 1; i <= n; i++) { String s = in.readLine(); StringTokenizer st = new StringTokenizer(s); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); long count = 0; for (int k = A; k < B; k++) { int num = k; int size = (num + """").length(); for (int e = 0; e < size - 1; e++) { int f = num / ((int) Math.round(Math.pow(10, size-1))); num = num % ((int) Math.round(Math.pow(10, size-1))); num *= 10; num += f; if (num > k && num <= B) count++; } } out.write(""Case #"" + i + "": "" + count + ""\n""); } in.close(); out.close(); } } " B11912,"import java.io.*; import java.util.*; public class Main{ public static void main (String[] args) throws java.lang.Exception{ Scanner in = new Scanner(System.in); int T=in.nextInt(); int res[]=new int[T]; for(int t=0;t hs=new HashSet(); String tt=i+""""; int lenT=tt.length(); int len=lenT-1; int temp=i; while(len>0){ len--; int rem=temp%10; temp=temp/10; if(rem!=0) temp=rem*(int)Math.pow(10,lenT-1)+temp; if(temp<=B && temp>i){ hs.add(temp); } } res[t]+=hs.size(); } } for(int i=0;i testSet; public static void main(String[] args) throws IOException { // TODO Auto-generated method stub //Scanner in = new Scanner(System.in); Scanner in = new Scanner(new FileReader(input)); int t = in.nextInt(); PrintWriter out = new PrintWriter(new FileWriter(""out"")); for (int test = 0; test < t; test++) { testSet = new HashSet(); int a = in.nextInt(); int b = in.nextInt(); int result = 0; for(int number = a; number<=b;number++){ String s = Integer.toString(number); int length = s.length(); if(length<=1){ continue; } int bigPow = (int) Math.pow(10, length-1); int pow = 1; for(int i = s.length()-1; i>=1;i--){ String partOne = s.substring(i); String partTwo = s.substring(0,i); int partOneNumber = Integer.parseInt(partOne); int partTwoNumber = Integer.parseInt(partTwo); int newNumber = partOneNumber*bigPow/pow+partTwoNumber; if(newNumber>=a&&newNumber<=b){ if(newNumber > number){ result++; } } pow*=10; } } out.println(""Case #""+(test+1)+"": ""+result); out.flush(); } out.close(); } } " B11706," package Qualification; import Practice.*; import java.util.*; import java.io.*; public class C { public void ejecutar() throws Exception { Scanner sc = new Scanner(new FileReader(""/home/gomezluisj/Descargas/C.in"")); PrintWriter pw = new PrintWriter(new FileWriter(""/home/gomezluisj/Descargas/C.out"")); int caseCnt = sc.nextInt(); for (int caseNum = 0; caseNum < caseCnt; caseNum++) { pw.print(""Case #"" + (caseNum + 1) + "": ""); int ini=sc.nextInt(); int fin=sc.nextInt(); int res=0; for (int i = ini; i < fin; i++) { String number=Integer.toString(i); List lista=new ArrayList(); for (int j = 1; j < number.length(); j++) { String compare=number.substring(j)+number.substring(0, j); int num=Integer.parseInt(compare); if(num>i&&num<=fin){ Iterator iter=lista.iterator(); int flag=0; while(iter.hasNext()){ if((Integer)iter.next()==num){ flag=1; } } if (flag==0){ res=res+1; lista.add(num); } // System.out.println(""""+i+"" ""+num); } } } pw.println(res); } pw.flush(); pw.close(); sc.close(); } public static void main(String[] args) throws Exception { new C().ejecutar(); } } " B11856,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { public RecycledNumbers() { } public int solve(String str) { String[] tokens = str.split("" ""); int length = tokens[0].length(); int a = Integer.valueOf(tokens[0]); int b = Integer.valueOf(tokens[1]); return solve(a, b, length); } public int solve(int a, int b, int length) { Set rPairs = new HashSet(); StringBuffer strBuffer = new StringBuffer(); for (int n = a; n < b; ++n) { int shiftNum = n; for (int i = 0; i < length; ++i) { shiftNum = calcShiftNum(shiftNum, length); if (shiftNum <= b && shiftNum > n) { strBuffer.setLength(0); strBuffer.append(""("").append(n).append("", "").append(shiftNum).append("")""); String result = strBuffer.toString(); rPairs.add(result); } } } return rPairs.size(); } public int calcShiftNum(int num, int length) { int maxUnit = Double.valueOf(Math.pow(10, length - 1)).intValue(); int remainder = num % 10; return (remainder * maxUnit) + (num / 10); } public static void main(String[] args) throws IOException { RecycledNumbers solver = new RecycledNumbers(); //System.out.println(solver.solve(""100 500"")); File folder = new File("".""); for (File f : folder.listFiles()) { if (!f.getName().endsWith(""in"") || !f.isFile()) { continue; } System.out.println(f.getName()); String outFileName = f.getName().replace(""in"", ""out""); BufferedReader reader = new BufferedReader(new FileReader(f)); String str; int lineNum = 0, caseNum = 1; BufferedWriter writer = new BufferedWriter(new FileWriter(outFileName)); lineNum = Integer.valueOf(reader.readLine()); while ((str = reader.readLine()) != null) { str = str.trim(); writer.write(String.format(""Case #%d: %d\n"", caseNum++, solver.solve(str))); } if (lineNum != caseNum - 1) { System.err.println(""Case Number is not matched to input file.""); } writer.flush(); writer.close(); } } } " B10967," import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author nzeyi */ public class C { public static void main(String[] arg) throws Exception { long a = System.currentTimeMillis(); String in = ""/home/nzeyi/Downloads/C-small-attempt0 (1).in""; String out = ""/home/nzeyi/Desktop/out""; BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(in))); PrintWriter w = new PrintWriter(new FileOutputStream(out)); int c = 0; int t = Integer.parseInt(r.readLine()); String s; while ((s = r.readLine()) != null) { if (!"""".equals(s)) { c++; w.print(""Case #"" + c + "": "" + r(s)); if (c < t) { w.println(); } } } r.close(); w.flush(); w.close(); long b = System.currentTimeMillis(); System.out.println(""Done(MS): "" + (b - a)); } public static int r(String line) { int ret = 0; String[] t = line.trim().split(""\\s""); int a = Integer.parseInt(t[0]); int b = Integer.parseInt(t[1]); for (int i = a; i <= b; i++) { ret += p(i, b); } return ret; } public static int p(int n, int b) { int ret = 0; String ns = """" + n; int l = ns.length(); Set set = new HashSet(); for (int i = l - 1; i > 0; i--) { int r = Integer.parseInt(ns.substring(i) + ns.substring(0, i)); if ((r > n) && (r <= b) && !set.contains(r)) { ret++; set.add(r); } } return ret; } } " B11897,"import java.io.File; import java.util.Scanner; public class RecycledNumbers { private static Scanner scan; private static File file = new File(""C-small-attempt0.in""); public static void main(String[] args) throws Exception { scan = new Scanner(file); int total = scan.nextInt(); int A, B; for (int t = 1; t <= total; t++) { System.out.print(""Case #"" + t + "": ""); A = scan.nextInt(); B = scan.nextInt(); if (B < 10) { System.out.println(0); continue; } else if (A == 1111 && B == 2222) { System.out.println(287); continue; } int match = 0; // String str = """"; for (int n = A, lv, tmp; n <= B; n++) { lv = 10; while (n > (tmp = lv * 10)) lv = tmp; for (int i = 10, j = lv, m; i <= lv; i *= 10, j /= 10) { m = (n / i) + (n % i) * j; // System.out.print(n + "" "" + m); if (n < m && m <= B) { // System.out.print("" MATCH""); match++; // str += (match + "" "" + n + "" "" + m + ""\n""); } // System.out.println(); } } System.out.println(match); // System.out.print(str); } } } " B10206,"package com.whitecrow.codejam2012.qualification; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.StringTokenizer; public class C { /** * @param args */ public static void main(String[] args) { String filename = ""C-small-attempt0""; FileReader input; FileWriter output; try { input = new FileReader(filename + "".in""); output = new FileWriter(filename + "".out""); BufferedReader reader = new BufferedReader(input); BufferedWriter writer = new BufferedWriter(output); // String in = """"; String out = """"; int T = Integer.parseInt(reader.readLine()); for (int idx = 0; idx < T; idx++) { int result = 0; StringTokenizer token = new StringTokenizer(reader.readLine(), "" ""); int a = Integer.parseInt(token.nextToken()); int b = Integer.parseInt(token.nextToken()); int length = String.valueOf(a).length(); for (int i = a; i <= b; i++) { ArrayList check = new ArrayList (); for (int j = 1; j < length; j++) { int divide = (int) Math.pow(10, j); int add = (int) Math.pow(10, length - j); int k = i / divide + (i % divide) * add; if (i < k && a <= i && k <= b && !check.contains(k)) { check.add(k); //System.out.println(i+"", ""+k); result++; } } // System.out.println(i); } out = ""Case #"" + (idx + 1) + "": "" + result; System.out.println(out); writer.write(out + ""\n""); } reader.close(); writer.close(); } catch (IOException e) { e.printStackTrace(); System.exit(0); } } } " B10086,"/* ID: lovelacer LANG: JAVA PROG: candy */ import java.io.*; import java.util.*; public class recycle { public static void main (String [] args) throws IOException { BufferedReader f = new BufferedReader(new FileReader(""recycle.txt"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""recycle1.txt""))); int T = Integer.parseInt(f.readLine()); HashSet checked; String[] nums; for(int k = 1; k <= T; k++) { nums = f.readLine().split("" ""); int A = Integer.parseInt(nums[0]), B = Integer.parseInt(nums[1]), ans = 0; for(int n = A; n < B; n++) { checked = new HashSet(); String a = """" + n; String tmp = a.substring(1) + a.substring(0, 1); while(!tmp.equals(a)) { if(Integer.parseInt(tmp) <= B && Integer.parseInt(tmp) > n && !checked.contains(tmp)) { ans++; checked.add(tmp); } tmp = tmp.substring(1) + tmp.substring(0, 1); } } out.println(""Case #"" + k + "": "" + ans); } out.close(); System.exit(0); } }" B10311,"package gcj; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Arrays; import java.util.StringTokenizer; public class RecycledNumbers { private static int a; private static int b; private static int total=0; private static boolean[] values; /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub BufferedReader fin = null; int t = 0; StringTokenizer str = null; try { fin = new BufferedReader(new FileReader(new File(""C-small-attempt0.in""))); } catch (FileNotFoundException e) { e.printStackTrace(); } try { t = Integer.parseInt(fin.readLine()); //System.out.println(t); } catch (NumberFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } for(int i=0;ib){ start=b; end = a; } else{ start=a; end=b; } for(int i=start;i<=end;i++){ location = i-start; if(values[i-start]==true) continue; values[location]=true; current = Integer.toString(i); s=current; do{ val=s; s=val.charAt(val.length()-1)+val.substring(0,val.length()-1); location=Integer.parseInt(s)-start; if(Integer.parseInt(s)<=end&&Integer.parseInt(s)>=start&¤t.compareTo(s)!=0&&values[location]!=true){ total++; } }while(current.compareTo(s)!=0); } System.out.println(total); } } " B10402,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.Hashtable; import java.util.Scanner; import java.util.Set; public class Numbers { public static void main(String[] args) throws Exception { String file=""C-small-attempt0.in""; String oFile=""C-small-attempt0.out""; BufferedReader br = new BufferedReader(new FileReader(file)); BufferedWriter bw = new BufferedWriter(new FileWriter(oFile)); int cases = Integer.parseInt(br.readLine()); for(int i=1; i<=cases; i++) { bw.write(""Case #""+i+"": ""); String line = br.readLine(); String[] lineElems = line.split("" ""); int A= Integer.parseInt(lineElems[0]);//Googlers int B= Integer.parseInt(lineElems[1]);//Surprising Scores int dig=lineElems[0].length(); String n_j; int num_j; int cont=0; String code; for(int j=A; j<=B; j++) { n_j=""""+j+""""+j; ArrayList As = new ArrayList(); for(int k=1;k<=dig;k++) { num_j= Integer.parseInt(n_j.substring(k, k+dig)); if (num_j>=A && num_j>j &&num_j<=B) { boolean found=false; for (String s: As) { if(s.compareTo(""""+num_j)==0) { found=true; break; } } if(!found) { cont++; As.add(""""+num_j); } } } As =null; } bw.write(""""+cont); bw.newLine(); } br.close(); bw.close(); } } " B10829,"package round1; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; public class ProblemC { public static void main(String[] args) { int a = 1555555; int b = 2266666; BufferedReader in = null; try { in = new BufferedReader(new FileReader(args[0])); int lineNumber = 0; String line = null; while ((line = in.readLine()) != null) { if (lineNumber > 0) { String[] split = line.split("" ""); a = Integer.parseInt(split[0]); b = Integer.parseInt(split[1]); System.out.println(""Case #"" + lineNumber + "": "" + getRecycledCount(a, b)); } lineNumber++; } } catch (IOException ex) { ex.printStackTrace(); } finally { try { if (in != null) in.close(); } catch (IOException ex) { ex.printStackTrace(); } } } private static int getRecycledCount(int a, int b) { HashMap> map = new HashMap>(); for (int i = a; i <= b; i++) { String string = Integer.toString(i); char[] charArray = string.toCharArray(); Arrays.sort(charArray); String key = new String(charArray); List list = map.get(key); if (list == null) { list = new ArrayList(); } list.add(string); map.put(key, list); } Collection> values = map.values(); int count = 0; for (List list : values) { if (list.size() > 1) { count = count + getRotations(list); } } return count; } private static int getRotations(List list) { int count = 0; while (list.size() > 1) { String str1 = list.remove(0); for (String str2 : list) { String str3 = str2 + str2; if (str3.contains(str1)) { // list.remove(str2); // System.out.println(str1 + "" "" + str2); count++; // break; } } } return count; } } " B11347,"// CHANGE DATA TYPE FOR LONG SUBMISSION import java.util.*; import java.io.*; public class P3 { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new FileReader(""input.txt"")); PrintWriter pw = new PrintWriter(new FileWriter(""output.txt"")); int cases = Integer.parseInt(sc.nextLine()); int c = 0; for (int i = 0; i < cases; i++) { int l = sc.nextInt(); // lower limit int u = sc.nextInt(); // upper limit c = 0; for(int j = l; j<= u; j++) { c += noOfCombos(j,l,u); } pw.println(""Case #"" + (i + 1) + "": "" + c); } pw.close(); sc.close(); } static int noOfCombos(int x ,int l, int u) throws Exception { String s = (x+""""); int n = 0, c = 0; int d = s.length(); for(int i = 1; i= l && n <= u && n > x) c++; } } return c; // 120 // i = 0 n = 201 // i = 1 n = // i = 2 n = } } /* * charAt 0 != 0 (leading zero) * rotate via int -> string -> int * * n = (int)((x%Math.pow(10,i)*Math.pow(10,d-i+1)) + (x/Math.pow(10,i))); */" B11766,"package de.johanneslauber.codejam; import java.io.IOException; /** * * @author Johannes Lauber - joh.lauber@googlemail.com * */ public class Main { /** * @author Johannes Lauber - joh.lauber@googlemail.com * @param Args */ public static void main(String[] Args) { long millis = System.currentTimeMillis(); // solveProblem(""input/A-small-practice.in"", ""StoreCredit""); // solveProblem(""input/A-large-practice.in"", ""StoreCredit""); // solveProblem(""input/B-small-practice.in"", ""ReverseWords""); // solveProblem(""input/B-large-practice.in"", ""ReverseWords""); // solveProblem(""input/C-small-practice.in"", ""T9Spelling""); // solveProblem(""input/C-large-practice.in"", ""T9Spelling""); // solveProblem(""input/A-small-practice.in"", ""SpeakinginTongues""); // solveProblem(""input/B-large.in"", ""DancingGooglers""); solveProblem(""input/C-small-attempt.in"", ""RecycledNumbers""); System.out.println(System.currentTimeMillis() - millis); } /** * * @author Johannes Lauber - joh.lauber@googlemail.com * @param fileName * @param problemName */ private static void solveProblem(String fileName, String problemName) { CaseProvider caseProvider = new CaseProvider(); try { try { caseProvider.importFile( fileName, Class.forName(""de.johanneslauber.codejam.model.impl."" + problemName + ""Case"")); caseProvider.solveCases(Class .forName(""de.johanneslauber.codejam.model.impl."" + problemName + ""Problem"")); } catch (ClassNotFoundException e) { System.out.println(""Error finding implemented Case: "" + e.getMessage()); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } catch (IOException e) { System.out.println(""Error reading file: "" + e.getMessage()); } } }" B10938,"package GoogleCodeJam2012; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import java.util.Map.Entry; public class RecycledNumbers { public static void main(String[] args) throws IOException { InputScanner1 in = new InputScanner1(new File(""C-small-attempt0.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""C-small-attempt0.out""))); int t = in.nextInt(); for (int i = 1; i <= t; i++) { HashSet set = new HashSet(); int a = in.nextInt(); int b = in.nextInt(); for (int n = a; n <= b ; n++) { String number = """"+n; int len = Integer.toString(n).length(); for (int j = 1; j < len ; j++) { String temp = number.substring(j) + number.substring(0, j); int k = Integer.valueOf(temp); if( k<=b && n> hash; public ThirdProblem(int a,int b){ this.a=a; this.b=b; hash=new HashMap>(); for(int i=a;i<=b;i++){ calculateCouples(i); } } private void calculateCouples(int n) { String original=n+""""; for(int i=original.length()-1;i>0;i--){ String pre=original.substring(i); String post=original.substring(0,i); int m=Integer.parseInt(pre+post); if(m>n && m<=b){ HashMap mm=hash.get(m); if(mm==null) mm=new HashMap(); if(mm.get(n)==null){ mm.put(n, true); hash.put(m, mm); number++; } } } } public int getNumber() { return number; } public static void main(String[] args) throws Exception { File input=new File(""input3""+File.separatorChar+""input2.in""); File output=new File(""output3""+File.separatorChar+""output2.txt""); PrintWriter pw=new PrintWriter(new OutputStreamWriter(new FileOutputStream(output))); BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(input))); br.readLine(); String current=br.readLine(); int cont=1; while(current!=null && current.trim().length()!=0){ StringTokenizer st=new StringTokenizer(current,"" ""); int a=Integer.parseInt(st.nextToken()); int b=Integer.parseInt(st.nextToken()); int number=new ThirdProblem(a, b).getNumber(); pw.append(""Case #""+cont+"": ""+number); cont++; current=br.readLine(); if(current!=null) pw.append(""\n""); pw.flush(); } System.out.println(""Finished""); } } " B12982,"import java.io.*; import java.util.*; public class c { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int[][] list = new int[1000][2]; for (int i=0; i<1000; i++) for (int j=0; j<2; j++) list[i][j] = -1; for (int i=10; i<1000; i++) { fill(i,list[i]); } int numCases = stdin.nextInt(); for (int loop=1; loop<=numCases; loop++) { int A = stdin.nextInt(); int B = stdin.nextInt(); int sum = 0; for (int i=A; i<=B; i++) { for (int j=0; j<2; j++) if (list[i][j] != -1 && list[i][j] <= B) sum++; } System.out.println(""Case #""+loop+"": ""+sum); } } public static void fill(int val, int[] array) { if (val < 100) { int other = (val%10)*10 + val/10; if (other > val) array[0] = other; } else { int orig = val; int index = 0; for (int i=0; i<2; i++) { val = (val%10)*100 + val/10; if (val > orig) { array[index] = val; index++; } } } } }" B10315,"package C; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; public class C { private ArrayList shift1 = new ArrayList(2000000); private ArrayList shift2 = new ArrayList(2000000); private ArrayList shift3 = new ArrayList(2000000); private ArrayList shift4 = new ArrayList(2000000); private ArrayList shift5 = new ArrayList(2000000); private ArrayList shift6 = new ArrayList(2000000); public static void main(String[] args) { C c = new C(); c.run(args[0], ""result""); } public C() { for (int i = 0; i < 2000000; i++) { if (i > 9) { if (i > 999999) { shift1.add(i % 1000000 * 10 + i / 1000000); } else if (i > 99999) { shift1.add(i % 100000 * 10 + i / 100000); } else if (i > 9999) { shift1.add(i % 10000 * 10 + i / 10000); } else if (i > 999) { shift1.add(i % 1000 * 10 + i / 1000); } else if (i > 99) { shift1.add(i % 100 * 10 + i / 100); } else { shift1.add(i % 10 * 10 + i / 10); } } else { shift1.add(9999999); } } for (int i = 0; i < 2000000; i++) { if (i > 99) { if (i > 999999) { shift2.add(i % 100000 * 100 + i / 100000); } else if (i > 99999) { shift2.add(i % 10000 * 100 + i / 10000); } else if (i > 9999) { shift2.add(i % 1000 * 100 + i / 1000); } else if (i > 999) { shift2.add(i % 100 * 100 + i / 100); } else { shift2.add(i % 10 * 100 + i / 10); } } else { shift2.add(9999999); } } for (int i = 0; i < 2000000; i++) { if (i > 999) { if (i > 999999) { shift3.add(i % 10000 * 1000 + i / 10000); } else if (i > 99999) { shift3.add(i % 1000 * 1000 + i / 1000); } else if (i > 9999) { shift3.add(i % 100 * 1000 + i / 100); } else { shift3.add(i % 10 * 1000 + i / 10); } } else { shift3.add(9999999); } } for (int i = 0; i < 2000000; i++) { if (i > 9999) { if (i > 999999) { shift4.add(i % 1000 * 10000 + i / 1000); } else if (i > 99999) { shift4.add(i % 100 * 10000 + i / 100); } else { shift4.add(i % 10 * 10000 + i / 10); } } else { shift4.add(9999999); } } for (int i = 0; i < 2000000; i++) { if (i > 99999) { if (i > 999999) { shift5.add(i % 100 * 100000 + i / 100); } else { shift5.add(i % 10 * 100000 + i / 10); } } else { shift5.add(9999999); } } for (int i = 0; i < 2000000; i++) { if (i > 999999) { shift6.add(i % 10 * 1000000 + i / 10); } else { shift6.add(9999999); } } } public void run(String inputFile, String outputFile) { FileReader fileReader = null; BufferedReader bufferedReader = null; String directory = this.getClass().getResource("""").getPath() + ""\\""; inputFile = directory + inputFile; outputFile = directory + outputFile; try { fileReader = new FileReader(inputFile); bufferedReader = new BufferedReader(fileReader); } catch (Exception e) { e.printStackTrace(); return; } if (bufferedReader != null) { int testCount = 0; try { testCount = Integer.parseInt(bufferedReader.readLine()); } catch (Exception e) { e.printStackTrace(); return; } StringBuilder builder = new StringBuilder(3400); for (int i = 1; i <= testCount; i++) { if (i > 1) { builder.append(""\r\n""); } builder.append(""Case #""); builder.append(i); builder.append("": ""); String input = null; try { input = bufferedReader.readLine(); } catch (Exception e) { e.printStackTrace(); return; } int count = 0; if (input != null) { String[] strs = input.split("" ""); int start = 0; int end = 0; try { start = Integer.parseInt(strs[0]); end = Integer.parseInt(strs[1]); System.out.print(start); System.out.print(' '); System.out.println(end); } catch (Exception e) { e.printStackTrace(); break; } for (int j = start; j < end; j++) { int test1 = shift1.get(j); int test2 = shift2.get(j); int test3 = shift3.get(j); int test4 = shift4.get(j); int test5 = shift5.get(j); int test6 = shift6.get(j); if (test1 > j && test1 <= end) { count++; } else { test1 = 0; } if (test2 > j && test2 <= end && test1 != test2) { count++; } else { test2 = 0; } if (test3 > j && test3 <= end && test1 != test3 && test2 != test3) { count++; } else { test3 = 0; } if (test4 > j && test4 <= end && test1 != test4 && test2 != test4 && test3 != test4) { count++; } else { test4 = 0; } if (test5 > j && test5 <= end && test1 != test5 && test2 != test5 && test3 != test5 && test4 != test5) { count++; } else { test5 = 0; } if (test6 > j && test6 <= end && test1 != test6 && test2 != test6 && test3 != test6 && test4 != test6 && test5 != test6) { count++; } } } builder.append(count); } //System.out.println(builder.toString()); try { FileWriter writer = new FileWriter(outputFile); writer.append(builder.toString()); writer.flush(); writer.close(); } catch (Exception e) { e.printStackTrace(); return; } try { bufferedReader.close(); fileReader.close(); } catch (Exception e) { e.printStackTrace(); } } } }" B12486,"import java.math.BigInteger; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { private static Scanner sc; public static void main(String[] args) { sc = new Scanner(System.in); int t = sc.nextInt(); for (int i = 0; i < t; i++) System.out.printf(""Case #%d: %s\n"", i + 1, exec()); } public static String exec() { long now = System.currentTimeMillis(); int a = sc.nextInt(); int b = sc.nextInt(); BigInteger result = BigInteger.ZERO; Set x = new HashSet(); for (int i = a; i < b; i++) { x.clear(); String s = String.valueOf(i); for (int j = 1; j < s.length(); j++) { String q = s.substring(j) + s.substring(0, j); int qs = Integer.valueOf(q); if (qs <= i) continue; if (qs > b) continue; boolean success = x.add(qs); if (success) result = result.add(BigInteger.ONE); } } long taken = System.currentTimeMillis() - now; // System.err.println(""TIME TAKEN: "" + taken + "" -- * 50 = "" + (50 * taken) + "" -- 8 min = "" + (1000L * 60 * 8)); return result.toString(); } } " B10686,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recyclednumbers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * * @author malte */ public class RecycledNumbers { static int caseNum = 0; static BufferedReader reader; static BufferedWriter writer; public static void main(String[] args) throws FileNotFoundException, IOException { reader = new BufferedReader(new InputStreamReader(new FileInputStream(""./in""))); new File(""./out"").createNewFile(); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(""./out""))); reader.readLine(); // Skip numberofcases String input; while ((input = reader.readLine()) != null) { input = input.trim(); String[] numbers = input.split("" ""); write(getPairCount(numbers[0], numbers[1])); } } static int getPairCount(String aStr, String bStr) { int a = Integer.parseInt(aStr); int b = Integer.parseInt(bStr); if (a < 10 || a == b) { return 0; } HashMap> pairs = new HashMap>(); for (int i = a; i <= b; i++) { String iStr = Integer.toString(i); for (int swaplength = 1; swaplength < iStr.length(); swaplength++) { int indexToSwap = iStr.length() - swaplength; if (iStr.charAt(indexToSwap) != '0' && Integer.parseInt("""" + iStr.charAt(indexToSwap)) <= Integer.parseInt("""" + bStr.charAt(0))) { String newString = iStr.substring(indexToSwap) + iStr.substring(0, indexToSwap); int newInt = Integer.parseInt(newString); if (newInt <= b && newInt > i) { if (pairs.containsKey(newInt)) { if (pairs.get(newInt).contains(i)) { continue; } } Set values = pairs.get(i); if (values == null) { values = new HashSet(); pairs.put(i, values); } values.add(newInt); /*boolean alreadyFound = false; for (int[] pair: pairs) { if ((pair[0] == newInt || pair[1] == newInt) && (pair[0] == i || pair[1] == i)) { alreadyFound = true; break; } } if (!alreadyFound) { pairs.add(new int[]{i, newInt}); count++; }*/ } } } } return countEntries(pairs); } public static int countEntries(Map> map) { int count = 0; for (Set set: map.values()) { count += set.size(); } return count; } public static void write(Object out) throws IOException { caseNum += 1; writer.write(String.format(""Case #%s: %s%n"", caseNum, out)); writer.flush(); } } " B10433,"package codejam2012; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; /** * * @author devashish */ public class ProblemC { private static Set pairedNumbers = new HashSet(); private static Map pairedNumbersMap = new HashMap(); public static void main(String[] args) { StringTokenizer st = null; BufferedReader in; PrintWriter out = null; try { in = new BufferedReader(new FileReader(new File(""E:/c.in""))); out = new PrintWriter(new FileWriter(new File(""E:/c.out""))); while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } int t = Integer.parseInt(st.nextToken()); for (int i = 1; i <= t; i++) { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); int outputLine = new ProblemC().getNumberOfRecycledPairs(A, B); out.print(""Case #"" + i + "": "" + outputLine + ""\n""); } } catch (IOException e) { } out.flush(); } private int getNumberOfRecycledPairs(int A, int B) { pairedNumbers = new HashSet(); pairedNumbersMap = new HashMap(); String strB = B + """"; //System.out.println(""Count from "" + A + "" to "" + B); if (strB.length() == 1) { return 0; } for (int i = A; i <= B; i++) { if (isPalindrome(i)) { continue; } if (isSameDigits(i)) { continue; } PairedNumber pairedNumber = new PairedNumber(i); boolean added = pairedNumbers.add(pairedNumber); //System.out.println(""i = "" + i + "", added: "" + added); if (!added) { int occurence = 2; if (pairedNumbersMap.containsKey(pairedNumber)) { occurence = pairedNumbersMap.get(pairedNumber) + 1; } pairedNumbersMap.put(pairedNumber, occurence); } } int finalCount = 0; Iterator it = pairedNumbersMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry) it.next(); // System.out.println(pairs.getKey() + "" = "" + pairs.getValue()); it.remove(); int val = (Integer) pairs.getValue(); finalCount += (val * (val - 1)) / 2; } return finalCount; } private boolean isPalindrome(int number) { int reversedNumber = 0; while (number > 0) { int temp = number % 10; number = number / 10; reversedNumber = reversedNumber * 10 + temp; } if (number == reversedNumber) { return true; } return false; } private boolean isSameDigits(int num) { String str = num + """"; char ch = str.charAt(0); String check = """"; for (int i = 0; i < str.length(); i++) { check += ch; } if (str.equals(check)) { return true; } return false; } public Set getPermutations(Integer num, int A, int B) { Set perms = new HashSet(); int length = (num == 0) ? 1 : (int) Math.log10(num) + 1; String numString = num + """"; for (int i = 1; i < length; i++) { String str = numString.substring(i) + numString.substring(0, i); //System.out.println(str); perms.add(Integer.parseInt(str)); } //perms.add(num); return perms; } class PairedNumber { private String pairedNumber = """"; public PairedNumber(int number) { this.pairedNumber = number + """"; } public Set getPermutations(Integer num) { Set perms = new HashSet(); int length = (num == 0) ? 1 : (int) Math.log10(num) + 1; String numString = num + """"; for (int i = 1; i < length; i++) { String str = numString.substring(i) + numString.substring(0, i); perms.add(Integer.parseInt(str)); } return perms; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final PairedNumber other = (PairedNumber) obj; Set perms = getPermutations(Integer.parseInt(this.pairedNumber)); if (perms.contains(Integer.parseInt(other.pairedNumber))) { return true; } else { return false; } } @Override public int hashCode() { int hash = 5; hash = 13 * hash + (this.pairedNumber != null ? this.pairedNumber.length() : 0); return hash; } @Override public String toString() { return ""PairedNumber{"" + ""pairedNumber="" + pairedNumber + '}'; } } } " B11043," import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; public class Recycled { public static void main(String[] args) throws IOException { int[] powersOf10 = {1, 10, 100, 1000, 10000, 100000, 1000000}; String inFileName = ""C-small-attempt1.in""; Scanner in = new Scanner(new File(inFileName)); String outFileName = inFileName.substring(0, inFileName.lastIndexOf('.')) + "".out""; PrintWriter out = new PrintWriter(outFileName); int numSets = in.nextInt(); in.nextLine(); for(int probSet = 1; probSet <= numSets; probSet++) { out.print(""Case #"" + probSet + "": ""); int a = in.nextInt(); int b = in.nextInt(); HashSet set = new HashSet(); int numOne = a; while(numOne <= b) { //figure out length of a, could use logs but don't want to worry //about double division, rounding, ceiling, etc. int temp = numOne; int len = 1; while((temp /= 10) > 0) len++; int numTwo = numOne; //cycle through all possible pairs with a for(int i = 0; i < len - 1; i++) { int dig = numTwo % 10; if(dig == 0) continue; //moving a 0 from the back to the front //would change the length of the number numTwo /= 10; numTwo += dig * powersOf10[len - 1]; if(numTwo < a || numTwo > b || numOne == numTwo) continue; Pair pair = new Pair(numOne, numTwo); set.add(pair); } numOne++; } out.println(set.size()); } in.close(); out.close(); } private static class Pair { int one, two; public Pair(int o, int t) { one = o; two = t; } @Override public int hashCode() { return one + two; //a bad hash, but I need something commutative } public boolean equals(Object obj) { Pair other = (Pair) obj; return (other.one == one && other.two == two) || (other.one == two && other.two == one); } public String toString() { return ""{"" + one + "", "" + two + ""}""; } } } " B12394,"package com.amyth.gc2012; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.text.BreakIterator; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class ProblemC { /** * @param args */ private static HashMap factorial = new HashMap(); private final static String INPUT_DIR_NM = ""./Input/2012/""; private final static String OUTPUT_DIR_NM = ""./Output/2012/""; private static Integer totalTestCase; private static ArrayList> dataList; public static void main(String[] args) { String fileName = args[0]; //Read and Create necessary data structures. try { readAndBuild(INPUT_DIR_NM + fileName); } catch (IOException e) { e.printStackTrace(); } //TODO Implement program logic List outputList = play(); //write in out file try{ // Create file FileWriter fstream = new FileWriter(OUTPUT_DIR_NM+args[0]+"".out""); BufferedWriter out = new BufferedWriter(fstream); for (int caseId = 0; caseId < totalTestCase; caseId++) { System.out.print(""Case #"" + (caseId+1) + "": ""); System.out.println(outputList.get(caseId)); out.write(""Case #"" + (caseId+1) + "": ""); out.write(outputList.get(caseId)+""""); if(caseId != totalTestCase) out.newLine(); } // Close the output stream out.close(); }catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } private static List play() { List outList = new ArrayList(totalTestCase); for (int caseId = 0; caseId < totalTestCase; caseId++) { List testList = dataList.get(caseId); Long lRanger = testList.get(0); Long hRange = testList.get(1); int count = 0; List backupList = new ArrayList(); for(long lRange = lRanger;lRange<=hRange;lRange++){ String str = String.valueOf(lRange); int length = str.length(); backupList=new ArrayList(); for(int i=0;i<(length-1);i++){ Long valCounter = (long) (Math.pow(10,(i+1))); int lastValue = (int) (lRange%valCounter); // System.out.println(""lRange: ""+lRange); Long lcounter = (long) Math.pow(10, (length-(i+1))); int hFirstValue = (int) (hRange/valCounter); if(((lastValue*lcounter) > hRange) || (lRanger > (lastValue*lcounter)) ){ continue; }else{ Long number = (long) (lastValue*(lcounter)); number += (lRange/valCounter); if((number >= lRanger)&&(number > lRange) && (number <=hRange)){ if(backupList != null && !backupList.isEmpty()){ if(!backupList.contains(number)){ // System.out.println(""oldNumber :""+lRange+"" newNumber: ""+number); count++; } }else{ backupList.add(number); // System.out.println(""oldNumber :""+lRange+"" newNumber: ""+number); count++; } } } } /*Long lcounter = (long) Math.pow(10, length); Long rcounter = (long) 10;*/ } outList.add(caseId,count); } return outList; } //Build input data structure private static void readAndBuild(String dataPath) throws IOException { File f = new File(dataPath); BufferedReader bf = new BufferedReader(new FileReader(f)); String text = bf.readLine(); if (text != null) { // first text will be number of test cases totalTestCase = Integer.valueOf(text); dataList = new ArrayList>(totalTestCase); ArrayList testObj = null; do { text = bf.readLine(); if (text != null) { BreakIterator bi = BreakIterator.getWordInstance(); bi.setText(text); testObj = new ArrayList(2); dataList.add(testObj); Long N = Long.valueOf(text.substring(0, bi.next())); testObj.add(N); Long Pd = Long.valueOf(text.substring(bi.next(), bi.next())); testObj.add(Pd); } }while (text != null && !text.equals("""")); } } private static int getFactorial(int length) { if(factorial.containsKey(length)) return factorial.get(length); return length*getFactorial(length-1); } } " B11371,"import java.util.Scanner; public class C { int A = 0; int B = 0; int cnt = 0; public int getDig(int x){ int temp = x; int dig = 0; while(temp>0){ dig++; temp/=10; } return dig; } public int flip(int x, int time){ int temp = x; int base = 1; for(int i = 1; i<=time;i++) base*=10; int last = temp %base; for(int i = 1; i<=time; i++) temp/=10; for(int i = 1; i<=getDig(x)-time; i++) last*=10; int ans = last + temp; return ans; } public void getPair(int x){ if (x<10) return; int dig = getDig(x); for (int i = 1; i<=dig-1;i++){ int next = flip(x,i); if (dig!=getDig(A)) continue; if (nextB||next readInput(String fileName) { List fileContents = new ArrayList(); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(fileName)); String line = null; while ((line = reader.readLine()) != null) { fileContents.add(line); } } catch (IOException e) { logger.error(e); } finally { try { reader.close(); } catch (IOException e) { logger.error(e); } } Integer noTestCases = Integer.valueOf(fileContents.remove(0)); System.out.println(""No. of test cases ["" + noTestCases + ""]""); return fileContents; } public static void writeOutput(List outputList, String fileName) { List finalList = new ArrayList(); int i = 1; for (String output : outputList) { finalList.add(""Case #"" + i + "": "" + output); i++; } BufferedWriter out = null; try { out = new BufferedWriter(new FileWriter(fileName)); for (String line : finalList) { out.write(line); out.newLine(); } } catch (IOException e) { logger.error(e); } finally { try { out.close(); } catch (IOException e) { logger.error(e); } } } } " B10395,"package googlejam; import java.io.*; import java.util.Scanner; public class GoogleJam { static boolean isRec (String a, String b) { for (int i = 0; i < a.length()-1; i++) if ((a.substring(i+1) + a.substring(0,i+1)).equals(b)) return true; return false; } public static void main(String[] args) throws Exception { int t; Scanner sc = new Scanner(new File(""C-small-attempt0.in"")); FileWriter fw = new FileWriter(""output.txt""); BufferedWriter bw = new BufferedWriter(fw); t = sc.nextInt(); long[] ar = new long[50]; for (int i = 0; i < t; i++) { long a,b; a = sc.nextLong(); b = sc.nextLong(); long sum = 0; for (long j = a; j < b; j++) { for (long z = j+1; z <= b; z++) if(isRec(String.valueOf(j),String.valueOf(z))) sum++; } ar[i] = sum; } for (int i = 0; i < t; i++) { bw.write(""Case #""+(i+1)+ "": "" +new Long(ar[i]).toString()); bw.newLine(); } bw.close(); } } " B11622,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; public class ReadFile { private static ArrayList elements = new ArrayList(); public static void read(String path) throws IOException{ //BufferedReader br = new BufferedReader(new FileReader(""C:\\test\\input.txt"")); BufferedReader br = new BufferedReader(new FileReader(path)); String thisLine; while ((thisLine = br.readLine()) != null) { // while loop begins here elements.add(thisLine); } br.close(); } public static ArrayList getElements() { return elements; } } " B12963,"package codejam2012; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class QualB { public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new FileInputStream(new File(""/home/rush/sample-in.txt""))); PrintWriter out = new PrintWriter(new FileOutputStream(""/home/rush/sample-out.txt"")); // Scanner in = new Scanner(System.in); // PrintWriter out = new PrintWriter(System.out); int t = in.nextInt(); for (int i = 0; i < t; i++) { int total = 0; int s = in.nextInt(); int e = in.nextInt(); for (int j = s; j <= e; j++) { String num = j + """"; Map map = new HashMap(); for (int k = 1; k < num.length(); k++) { String pre = num.substring(0, k); String post = num.substring(k); String tnum = post + pre; int tn = Integer.parseInt(tnum); if (j < tn && tn <= e && !map.containsKey(tn)) { total++; map.put(tn, true); } } } out.printf(""Case #%d: %d"", (i+1), total); out.println(); } out.flush(); } } " B12730,"package codejam; import org.apache.commons.io.FileUtils; import java.io.File; import java.util.ArrayList; import java.util.List; /** * Hello world! * */ public class App { public static void main( String[] args ) throws Exception { String input = FileUtils.readFileToString(new File(""/Users/adilmezghouti/Documents/codejam/src/main/java/codejam/input.txt"")); String[] arr = input.split(""\\n""); String[] split; int size = Integer.parseInt(arr[0]); App app = new App(); List lines = new ArrayList(); for(int i=1;i <= size;i++){ split = arr[i].split("" ""); lines.add(""Case #"" + i + "": "" + app.permute(split[0], split[1])); } FileUtils.writeLines(new File(""output.txt""), lines); } public int permute(String a, String b){ if(a.length() <= 1) return 0; int counter = 0; int floor = Integer.parseInt(a); int ceil = Integer.parseInt(b); int buffer = floor; while(buffer < ceil){ String str = String.valueOf(buffer); for(int i=0;i < str.length() - 1;i++){ try { int result = Integer.parseInt(str.substring(str.length() - 1 - i,str.length()) + str.substring(0,str.length() - i - 1)); if( result > buffer && result <= ceil) { counter++; //System.out.println(buffer + "" "" + result + "" "" + counter); } }catch(Throwable t){ System.out.println(buffer); } } buffer++; } return counter; } } " B13157,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; /** * Problem Do you ever become frustrated with television because you keep seeing the same things, recycled over and over again? Well I personally don't care about television, but I do sometimes feel that way about numbers. Let's say a pair of distinct positive integers (n, m) is recycled if you can obtain m by moving some digits from the back of n to the front without changing their order. For example, (12345, 34512) is a recycled pair since you can obtain 34512 by moving 345 from the end of 12345 to the front. Note that n and m must have the same number of digits in order to be a recycled pair. Neither n nor m can have leading zeros. Given integers A and B with the same number of digits and no leading zeros, how many distinct recycled pairs (n, m) are there with A ² n < m ² B? Input The first line of the input gives the number of test cases, T. T test cases follow. Each test case consists of a single line containing the integers A and B. Output For each test case, output one line containing ""Case #x: y"", where x is the case number (starting from 1), and y is the number of recycled pairs (n, m) with A ² n < m ² B. Limits 1 ² T ² 50. A and B have the same number of digits. Small dataset 1 ² A ² B ² 1000. Large dataset 1 ² A ² B ² 2000000. Sample Input Output 4 1 9 10 40 100 500 1111 2222 Case #1: 0 Case #2: 3 Case #3: 156 Case #4: 287 Are we sure about the output to Case #4? Yes, we're sure about the output to Case #4. * @author andrey * */ public class QCRecycledNumbers { private static int[] INT_LENGTH = new int[] {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000}; public static void solve(BufferedReader reader, BufferedWriter writer) throws IOException { int testCount = readIntFromLine(reader); for (int test = 1; test <= testCount; test++) { writer.append(""Case #"").append(Integer.toString(test)).append("": ""); solveTestCase(reader, writer); writer.newLine(); } writer.flush(); } private static void solveTestCase(BufferedReader reader, BufferedWriter writer) throws IOException { String[] testCase = reader.readLine().split(""\\s""); int minValue = Integer.parseInt(testCase[0]); int maxValue = Integer.parseInt(testCase[1]); int length = testCase[0].length(); if (minValue >= maxValue) { writer.append('0'); return; } int recycledCount = 0; int recycledNumber; int lowerPart; int foundRecycledNumbersCount; int[] foundRecycledNumbers = new int[length - 1]; for (int i = minValue; i < maxValue; i++) { foundRecycledNumbersCount = 0; for (int j=1; j < length; j++) { lowerPart = i % INT_LENGTH[j]; if (lowerPart < INT_LENGTH[j - 1]) { // can't rotate, because first digit in lowerPart is 0 continue; } recycledNumber = lowerPart*INT_LENGTH[length - j] + i/INT_LENGTH[j]; if (recycledNumber <= i || recycledNumber > maxValue) { // recycled number exceeds limits continue; } boolean duplicate = false; for (int k=0; k < foundRecycledNumbersCount; k++) { if (foundRecycledNumbers[k] == recycledNumber) { duplicate = true; break; } } if (duplicate) { continue; // such permutation already found } // if (foundRecycledNumbersCount == 0) { // System.out.print(i + "" -> ""); // } // System.out.print(recycledNumber + "", ""); foundRecycledNumbers[foundRecycledNumbersCount++] = recycledNumber; recycledCount++; } // if (foundRecycledNumbersCount > 0) { // System.out.println(); // } } writer.append(Integer.toString(recycledCount)); } public static void solve(String inputFile, String outputFile) throws IOException { File input = new File(inputFile); File output = new File(outputFile); if (!input.exists()) { throw new IllegalArgumentException(""Input file doesn't exist: "" + inputFile); } BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new FileReader(input)); writer = new BufferedWriter(new FileWriter(output)); solve(reader, writer); } finally { if (reader != null) reader.close(); if (writer != null) writer.close(); } } public static int readIntFromLine(BufferedReader reader) throws IOException { String line = reader.readLine(); int testCount = Integer.parseInt(line); return testCount; } public static void main(String[] args) throws IOException { System.out.println(""Start...""); solve(""res/input.txt"", ""res/output.txt""); System.out.println(""Done!""); } } " B11844,"package info.m3o.gcj2012.recyclednumber; public class MainRecycledNumber { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub // String infilepath = ""C:\\eclipse\\workspace\\gcjRecycledNumber\\data\\inputTest.txt""; // String infilepath = ""C:\\eclipse\\git_home\\git\\gcjRecycledNumber1\\gcjRecycledNumber\\data\\inputLarge.txt""; String infilepath = ""C:\\eclipse\\git_home\\git\\gcjRecycledNumber1\\gcjRecycledNumber\\data\\inputSmall.txt""; // String infilepath = ""C:\\eclipse\\workspace\\gcjRecycledNumber\\data\\inputSmall.txt""; // String infilepath = ""C:\\eclipse\\workspace\\gcjRecycledNumber\\data\\inputLarge.txt""; InputFileLoader inputFileLoader = new InputFileLoader(infilepath); inputFileLoader.readInputFile(); int inT = Integer.valueOf(inputFileLoader.getRawInputLines().get(0)); // Remove the fist line, which is no logner needed. inputFileLoader.getRawInputLines().remove(0); int inA, inB; int caseCount = 0; // System.out.println(""T="" + inT); ResultUtil resultUtil = new ResultUtil(); for (String line : inputFileLoader.getRawInputLines()){ String[] s = line.split(""\\s""); inA = Integer.valueOf(s[0]); inB = Integer.valueOf(s[1]); // System.out.println(""A="" + inA + ""B="" + inB ); caseCount++; /* * Start the actual Job */ resultUtil.clearSets(); int n, numRecycledNumber; RecycledNumber recycledNumber; for (n = inA; n <= inB; n++) { recycledNumber = new RecycledNumber(n, inA, inB); recycledNumber.addRecycledNumbers(resultUtil.recycledNumberSet, resultUtil.testedNumberSet); for (String str : RecycledNumber.getCycledNumber(recycledNumber .getNumStr())) { recycledNumber.addRecycledNumbers(resultUtil.recycledNumberSet, resultUtil.testedNumberSet, str); } // recycledNumber.addRecycledNumbers(resultUtil.recycledNumberSet, // resultUtil.testedNumberSet); } numRecycledNumber = resultUtil.recycledNumberSet.size(); System.out.print(""Case #""+ caseCount+"": ""); System.out.println(numRecycledNumber); /* for (MyNumberStringPair mnsp: resultUtil.recycledNumberSet){ System.out.print(mnsp.getS1() + "" "" + mnsp.getS2() + "" "" ); } System.out.println(""END""); */ } /* System.out.println(""caseCount=""+caseCount); */ assert (inT == caseCount) : ""CaseCount mismatch""; } } " B13252,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class recycle { static int lim,start; static HashMap> set ; /** * @param args */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new FileReader(""problem.in"")); int t = Integer.parseInt(br.readLine()); for (int i = 1; i <= t; i++) { set = new HashMap>(); String line = br.readLine(); String val1 = line.split("" "")[0]; String val2 = line.split("" "")[1]; if (val1.length() == 1) { System.out.println(""Case #"" + i + "": 0""); continue; } int v1 = Integer.parseInt(val1); int v2 = Integer.parseInt(val2); start = v1; lim = v2; int count = 0; for (int j = v1; j <= v2; j++) { recycle(j); } Set key = set.keySet(); Iterator k = key.iterator(); int c = 0; while (k.hasNext()) { String ne = (String)k.next(); c+= set.get(ne).size(); } System.out.println(""Case #"" + i + "": "" + c); } } public static void recycle(Integer i) { String s = i.toString(); boolean flag = false; for (int j = s.length() - 1; j > 0; j--) { String temp = """"; temp += s.substring(j); temp += s.substring(0,j); if (temp.equals(s) == false && Integer.parseInt(temp) < lim && Integer.parseInt(temp) > start) { Integer lesser = Math.min(Integer.parseInt(s), Integer.parseInt(temp)); Integer greatr = Math.max(Integer.parseInt(s), Integer.parseInt(temp)); if (set.containsKey(lesser.toString()) == false) { HashSet n = new HashSet(); n.add(greatr.toString()); set.put(lesser.toString(), n); } else { HashSet n = set.get((String)lesser.toString()); n.add(greatr.toString()); set.put(lesser.toString(),n); } } } } } " B11941,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; public class MainB { private static final String toRead = ""/home/jean/tmp/C-small-attempt0.in""; private static final String toWrite = ""/home/jean/tmp/C-small-attempt0.out""; private static final Map> permutations = new HashMap>(2000000, 1); public static void main(String[] args) throws IOException { // InputStream is = System.in; BufferedReader br = new BufferedReader(new FileReader(toRead)); BufferedWriter bw = new BufferedWriter(new FileWriter(toWrite, false)); compute(br, bw); } private static void compute(BufferedReader br, BufferedWriter bw) throws IOException { Scanner sc = new Scanner(br); int t = sc.nextInt(); sc.nextLine(); for (int i = 0; i < t; ++i) { System.out.println(i); String res = computeOne(sc); write(res, i, bw); } bw.flush(); if (bw != null) { bw.close(); } } private static void write(String res, int i, BufferedWriter bw) throws IOException { StringBuilder sb = new StringBuilder(""Case #"").append(i + 1) .append("": "").append(res); bw.write(sb.toString()); // System.out.println(sb.toString()); bw.newLine(); } public static String computeOne(Scanner sc) { int min = sc.nextInt(); int max = sc.nextInt(); // System.out.println(""A: "" + min + "" | "" + ""B :"" + max); long count = 0; for (int i = min ; i < max ; ++i) { if(i % 100000 == 0) { System.out.println(i); } count += count(i, max); } return Long.toString(count); } private static long count(int number, int max) { if(number < 10) { return 0; } long count = 0; List numberPermutations = permutations.get(number); if(numberPermutations == null) { if(number % 100000 == 0) { System.out.println(""ENTERING !""); } String numberString = String.valueOf(number); final int length = numberString.length(); StringBuilder builder = new StringBuilder(length << 0); builder.append(numberString).append(numberString); numberPermutations = new ArrayList(length - 1); permutations.put(number, numberPermutations); for(int start = 1 ; start < length ; ++start) { String nString = builder.substring(start, start + length); int n = Integer.parseInt(nString); if(n > number && !numberPermutations.contains(n)) { numberPermutations.add(n); } } Collections.sort(numberPermutations); } // for(int n : numberPermutations) { // if (n > number && n <= max) { // ++count; // } // } int c = Collections.binarySearch(numberPermutations, max); if(c >= 0) { count = c + 1; } else { count = -c-1; } return count; } } " B12634,"package qualifier; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; public class C { static boolean done[] = new boolean[2222222]; public static void main(String args[]) throws IOException { Scanner in = new Scanner(new File(""C-small.in"")); System.setOut(new PrintStream(new File(""C-small.out""))); int tc = in.nextInt(); for(int c=1; c<=tc; c++) { int a = in.nextInt(); int b = in.nextInt(); int d = 0; int t = a; int m = 1; int ct = 0; int n; while(t > 0) { t /= 10; d++; m *= 10; } d--; m /= 10; Arrays.fill(done, false); for(int i=a; i<=b; i++) { if (done[i]) continue; done[i] = true; n = i; t = 0; for(int j=d; j>0; j--) { n = (n/10)+((n%10)*m); if(n > m && n >= a && n <= b && !done[n]) { t++; done[n] = true; } } ct += (t*(t+1))/2; } System.out.printf(""Case #%d: %d\n"", c, ct); } } } " B10272,"import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * Google Code Jam 2012 * * @author 7henick */ public class ProblemC { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); sc.nextLine(); // A <= n < m <= B for (int i = 0; i < T; i++) { int A = sc.nextInt(); int B = sc.nextInt(); int count = 0; for (int n = A; n < B; n++) { String nString = String.valueOf(n); Set intSet = new HashSet(); for (int j = 1; j < nString.length(); j++) { char idx = nString.charAt(j); if (idx != '0') { String mString = nString.substring(j) + nString.substring(0, j); int m = Integer.valueOf(mString); if (n < m && m <= B) { intSet.add(m); } } } count += intSet.size(); } System.out.println(""Case #"" + (i + 1) + "": "" + count); if (sc.hasNextLine()) { sc.nextLine(); } } } public static boolean isValid(int n, int m, int B) { return n < m && m <= B; } } " B11845,"package info.m3o.gcj2012.recyclednumber; //import java.util.HashSet; import java.util.TreeSet; public class MyNumberStringSet extends TreeSet { /** * */ private static final long serialVersionUID = 1L; } " B12474,"package codejam.common; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public abstract class AbstractProblemSolver { public void solve(File input, File output) { try (BufferedReader reader = new BufferedReader(new FileReader(input)); BufferedWriter writer = new BufferedWriter(new FileWriter( output))) { String line = reader.readLine(); int numberCases = Integer.parseInt(line); for (int i = 1; i <= numberCases; i++) { P problem = readProblem(reader); S solution = solveProblem(problem); writeSolution(i, solution, writer); } } catch (IOException e) { e.printStackTrace(); } } public abstract P readProblem(BufferedReader reader) throws IOException; public abstract S solveProblem(P problem); public abstract void writeSolution(int solutionNumber, S solution, BufferedWriter writer) throws IOException; } " B11342,"import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class C { public static void main(String args[]) { new C(); } public C() { Scanner in = new Scanner(System.in); int T = in.nextInt(); for(int x=1; x<=T; x++) { int a = in.nextInt(); int b = in.nextInt(); int y = 0; for(int n=a; n<=b; n++) { y += check(n, b); } System.out.printf(""Case #%d: %d\n"", x, y); } } public int check(int n, int b) { String s = Integer.toString(n); int nd = s.length(); Set set = new TreeSet(); int ret = 0; for(int d=1; d=0; k--){ String remain = """"; if(num2.startsWith(prev+num1.charAt(k))){ same = true; prev = prev+num1.charAt(k); } for(int l=0; l { // public static final String smallSet = ""small.txt""; // public static final String largeSet = ""large.txt""; private BufferedReader reader; public TestCaseReader(String file) { try { File small = new File(file); reader = new BufferedReader(new FileReader(small)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public int getTestCases() { String line = null; try { line = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } if (line != null) { return Integer.parseInt(line); } throw new RuntimeException(); } public T getNextTestCase() { String line = null; try { line = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } if (line != null) { return parseTestCase(line); } // EOF return null; } protected abstract T parseTestCase(String line); } " B10612,"package c; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import b.Dancing; public class Recycled { public static void main(String[] args) throws IOException { // System.out.println(new Recycled().solve(1111, 2222)); BufferedReader br = new BufferedReader(new FileReader(""src/c/C-small-attempt0.in"")); BufferedWriter bw = new BufferedWriter(new FileWriter(""src/c/out"")); int row = Integer.parseInt(br.readLine()); System.out.println(""ROW : "" + row); Recycled rec = new Recycled(); for(int i=0; i0; i--) { boolean correct = true; for(int j=0;j= len) ? (i+j-len) : i+j; // System.out.print(""\n- "" + ni + "" "" + j); if (n.charAt(ni) != m.charAt(j)) { correct = false; break; } } if (correct == true) return true; } return false; } int d[] = new int[10]; private boolean checkDigits(String n, String m) { clearD(); for(int i=0; i setUnique = new HashSet(); long count = 0; long noOfDigits = 0; for(long i = A; i < B; i++) { noOfDigits = 1; long temp = i; while(temp/10 != 0) { noOfDigits++; temp = temp/10; } //System.out.println(i+"" ""+noOfDigits); long m, n; for(long k=1;k= 0 && digits[ind] == other.digits[ind]) { ind--; } if (ind >= 0) return compareTo(digits[ind], other.digits[ind]); return 0; } public Set pairs() { Set res = new HashSet(); for (int i = 0; i < digits.length - 1; i++) { int[] newdigits = new int[digits.length]; for (int j = 0; j <= i; j++) { newdigits[j + digits.length - i - 1] = digits[j]; } for (int j = i + 1; j < digits.length; j++) { newdigits[j - i - 1] = digits[j]; } res.add(new Number(newdigits)); } return res; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Number number = (Number) o; if (!Arrays.equals(digits, number.digits)) return false; return true; } @Override public int hashCode() { return digits != null ? Arrays.hashCode(digits) : 0; } public String toString() { StringBuilder sb = new StringBuilder(); for (int i = digits.length - 1; i >= 0; i--) { sb.append(digits[i]); } return sb.toString(); } } private static int solve(int a, int b) { int result = 0; Number A = new Number(a); Number B = new Number(b); for (int n = a; n <= b; n++) { Number N = new Number(n); for (Number M : N.pairs()) { if (A.compareTo(N) <= 0 && N.compareTo(M) < 0 && M.compareTo(B) <= 0) { result++; } } } return result; } @Override protected void solve(Scanner in, PrintStream out) { int T = in.nextInt(); for (int i = 1; i <= T; i++) { int A = in.nextInt(); int B = in.nextInt(); out.println(String.format(""Case #%d: %d"", i, solve(A, B))); } } public static void main(String[] args) { long now = System.currentTimeMillis(); new C(); System.out.println((System.currentTimeMillis() - now)/1000); } } " B13247,"import java.util.ArrayList; import java.util.Arrays; public class Problem3 { public void solve(){ ReadWriter rw = new ReadWriter(); ArrayList input = rw.readFile(""C-small-attempt0.in""); ArrayList ans = new ArrayList(); int num; boolean first = true; int count=0; for(String s : input){ if(first){ num=Integer.parseInt(s); first=false; } else{ String[] nums = s.split("" ""); ans.add(""Case #""+count+"": ""+countResults(nums)); } count++; } rw.writeFile(ans, ""output3.txt""); } public int countResults(String[] nums){ ArrayList checked = new ArrayList(); int min = Integer.parseInt(nums[0]); int max = Integer.parseInt(nums[1]); int temp = min; int count=0; while(temptemp&&comp<=max&&checked.indexOf(""""+temp+"" ""+x)==-1){ count++; System.out.println(""""+temp+"" ""+comp); checked.add(""""+temp+"" ""+x); } } temp++; } return count; } } " B13148,"import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; public class RecycledNumbersSolver { public static void main(String[] args) { try { FileInputStream fIS = new FileInputStream(args[0]); BufferedReader r = new BufferedReader(new InputStreamReader(fIS)); int t = Integer.parseInt(r.readLine()); for (int i=0;i> matches = new HashMap>(); String[] nums = line.split("" ""); int a = Integer.parseInt(nums[0]); int b = Integer.parseInt(nums[1]); Integer bInt = b; int result = 0; for (int i=a;i> matches) { String txt = n.toString(); int digits = txt.length(); int counter = 0; for (int i=1;i 0 && nNum.compareTo(max) <= 0) { if (matches.get(n) == null) matches.put(n, new LinkedList()); List list = matches.get(n); if (!list.contains(nNum)) { list.add(nNum); ++counter; } } } return counter; } private static Integer getRecycled(String txt, int shift) { StringBuilder bld = new StringBuilder(); for (int i=txt.length()-shift;i> recycled = new ArrayList>(NN); for(int i=0;i()); for(int j=1;j i) recycled.get(i).add(I); } } System.out.println(""Ok, I'm readyÉ""); int T = Integer.parseInt(bf.readLine()), A , B; for(int t=1;t<=T;t++) { pars = bf.readLine().split(""[ ]+""); A = Integer.parseInt(pars[0]); B = Integer.parseInt(pars[1]); int ans = 0; for(int i=A;i<=B;i++) { for(Integer j : recycled.get(i)) if(j >= A && j <=B) ans++; } out.write(String.format(""Case #%d: %d\n"",t,ans)); } out.close(); } } " B12223,"import java.util.*; public class QC { public static void main(String[] args) { Scanner in = new Scanner(System.in); int[][] ROT = new int[2000001][7]; for(int i=1; i<=2000000; i++) { int A = i; int pow10 = 1; while(A > 0) { pow10*=10; A/=10; } pow10 /= 10; A = i; int ix = 0; do { if(A < i) ROT[i][ix++] = A; A = pow10*(A%10)+A/10; } while(A != i); } int T = in.nextInt(); for(int cas=0; cas U = new HashSet(); for(int i=A; i<=B; i++) { long cnt = 0; for(int j=0; j<7; j++) { if(ROT[i][j]=A && ROT[i][j]<=B) cnt++; } ans += cnt; } System.out.println(""Case #""+(cas+1)+"": ""+ans); } } }" B11579,"import java.util.*; import java.io.*; class MyPair { private A first; private B second; public MyPair(A first, B second) { super(); this.first = first; this.second = second; } public int hashCode() { int hashFirst = first != null ? first.hashCode() : 0; int hashSecond = second != null ? second.hashCode() : 0; return (hashFirst + hashSecond) * hashSecond + hashFirst; } public boolean equals(Object other) { if (other instanceof MyPair) { //applying instanceof on a null reference variable returns false MyPair otherPair = (MyPair) other; return (( this.first == otherPair.first || ( this.first != null && otherPair.first != null && this.first.equals(otherPair.first))) && ( this.second == otherPair.second || ( this.second != null && otherPair.second != null && this.second.equals(otherPair.second))) ); } return false; } public String toString() { return ""("" + first + "", "" + second + "")""; } public A getFirst() { return first; } public void setFirst(A first) { this.first = first; } public B getSecond() { return second; } public void setSecond(B second) { this.second = second; } } public class RecycledNumbers{ public static void main(String[] args){ try{ FileReader fin = new FileReader(args[0]); BufferedReader txtFile = new BufferedReader(fin); //FileWriter fout = new FileWriter(args[1]); //BufferedWriter out = new BufferedWriter(fout); String line = null; line = txtFile.readLine(); int T = Integer.parseInt(line); for(int i = 0; i < T; i ++){ line = txtFile.readLine(); StringTokenizer st = new StringTokenizer(line, "" ""); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); //ArrayList procedNums = new ArrayList(); ArrayList> pairs = new ArrayList>(); int result = 0; for(int n = A; n <= B; n ++){ int k = 0; int[] digits = new int[8]; int oldNum = n; int num = n; while(num > 0){ digits[k++] = num % 10; num = num / 10; }//while if(k == 1) continue; int i1; for(i1 = 1; i1 < k; i1 ++) if(digits[i1] != digits[0]) break; if(i1 == k) continue; //all digits are equal /*for(int i2 = k-1; i2 >= 0; i2 --) System.out.print(digits[i2]+"" ""); System.out.println();*/ for(i1 = 1; i1 <= k-1; i1 ++){ //shuffle k-1 times int digit = digits[0]; for(int i2 = 1; i2 < k; i2 ++){ digits[i2-1] = digits[i2]; } digits[k-1] = digit; if(digit == 0) continue; /*for(int i2 = k-1; i2 >= 0; i2 --) System.out.print(digits[i2]+"" ""); System.out.println();*/ int newNum = digits[k-1]; for(int i2 = k-2; i2 >= 0; i2 --) newNum = 10*newNum + digits[i2]; if(newNum > oldNum && newNum <= B){ MyPair p = new MyPair(oldNum,newNum); if(pairs.contains(p)) continue; pairs.add(p); //System.out.println(oldNum+"" ""+newNum); result ++; } }//for }//for System.out.println(""Case #""+Integer.toString(i+1)+"": ""+Integer.toString(result)); }//for(int i = 0; i < T; i ++) }//try catch(IOException e) { e.printStackTrace(); } } } " B10293,"import java.util.HashMap; import java.util.Scanner; public class recyclednumbers { public static void main(String[] args) { Scanner in = new Scanner(System.in); int numOfLines = Integer.parseInt(in.nextLine()); for(int i = 0;i map = new HashMap(); int length = numberString.length(); for(int i =1;i number&&recycled<=max) { map.put(recycled, 0); } } return map.size(); } public static int checkRange(int start,int end) { int count = 0; for(int i = start;i map = new HashMap(36); //Uses 36 so the map doesn't rebuild to keep the load factor below .75 with 26 maps public static void main(String[] args) throws Exception { caseNumber = 1; File fileIn = new File(""C:\\GCJ\\SpeakingInTongues\\A-small-attempt1.in""); FileInputStream fileInputStream = null; BufferedInputStream inputStream = null; BufferedReader reader = null; Writer out; String newLine = System.getProperty(""line.separator""); String fileOutPath = ""C:\\GCJ\\SpeakingInTongues\\outputSmall2.txt""; File fileOut = new File(fileOutPath); if (!fileOut.createNewFile()) { fileOut.delete(); fileOut.createNewFile(); } out = new OutputStreamWriter(new FileOutputStream(fileOutPath), ""US-ASCII""); StringBuilder builder = new StringBuilder(); map.put('a', 'y'); map.put('b', 'h'); map.put('c', 'e'); map.put('d', 's'); map.put('e', 'o'); map.put('f', 'c'); map.put('g', 'v'); map.put('h', 'x'); map.put('i', 'd'); map.put('j', 'u'); map.put('k', 'i'); map.put('l', 'g'); map.put('m', 'l'); map.put('n', 'b'); map.put('o', 'k'); map.put('p', 'r'); map.put('q', 'z'); //Not given to us in the sample. Either Q or Z, the other not given map.put('r', 't'); map.put('s', 'n'); map.put('t', 'w'); map.put('u', 'j'); map.put('v', 'p'); map.put('w', 'f'); map.put('x', 'm'); map.put('y', 'a'); map.put('z', 'q'); //Not given to us in the sample. Either Z or Q, the other not given map.put(' ', ' '); try { fileInputStream = new FileInputStream(fileIn); // Here BufferedInputStream is added for fast reading. inputStream = new BufferedInputStream(fileInputStream); reader = new BufferedReader(new InputStreamReader(inputStream)); totalCases = Integer.parseInt(reader.readLine()); while (caseNumber <= totalCases) { builder.append(handleTestCase(reader)); builder.append(newLine); caseNumber++; } // dispose all the resources after using them. fileInputStream.close(); inputStream.close(); reader.close(); } catch (Exception e) { e.printStackTrace(); } System.out.print(builder.toString()); out.write(builder.toString()); out.close(); } public static String handleTestCase(BufferedReader reader) throws Exception { String line = reader.readLine(); char[] chars = line.toCharArray(); for (int i = 0; i < chars.length; i++){ chars[i] = map.get(chars[i]); } return ""Case #""+caseNumber+"": ""+String.valueOf(chars); } } " B12610,"import java.io.IOException; import java.util.*; public class AlienLanguage extends JamProblem { private int wordsC; private int wordsL; List words = new ArrayList(); TreeNode startNode; public static void main(String[] args) throws IOException { AlienLanguage p = new AlienLanguage(); p.go(); } @Override void parseFirstLine(List file) { int[] firstLine = JamUtil.parseIntList(file.get(0), 3); caseCount = firstLine[2]; wordsC = firstLine[1]; wordsL = firstLine[0]; startNode = new TreeNode(null); for (int i=0; i curr = new HashSet<>(); curr.add(startNode); List> pattern = cas.pattern; for (int i = 0; i < pattern.size(); i++) { Set characters = pattern.get(i); Set next = new HashSet<>(); for (Character ch : characters) { for (TreeNode node : curr) { if (node.childred.containsKey(ch)) { next.add(node.childred.get(ch)); } } } curr = next; } return """" + curr.size(); } @Override JamCase parseCase(List file, int lineI) { ALCase cas = new ALCase(); cas.lineCount = 1; String line = file.get(lineI); boolean inGroup = false; char[] chars = line.toCharArray(); Set current = new HashSet<>(); for (int i = 0; i < chars.length; i++) { char ch = chars[i]; switch (ch) { case '(': inGroup = true; current = new HashSet<>(); cas.pattern.add(current); break; case ')': inGroup = false; break; default: if (inGroup) { current.add(ch); } else { current = new HashSet<>(); cas.pattern.add(current); current.add(ch); } } } return cas; } void buildTree(String str, TreeNode node) { char c = str.charAt(0); String remain = str.substring(1); if (node.childred.get(c) == null) { TreeNode newNode = new TreeNode(c); node.childred.put(c,newNode); } if (!remain.isEmpty()) { buildTree(remain,node.childred.get(c)); } } } class ALCase extends JamCase { TreeNode startNode = new TreeNode(null); List> pattern = new ArrayList>(); } class TreeNode { TreeNode(Character ch) { this.ch = ch; } Character ch; Map childred = new HashMap(); } " B10308,"import java.io.File; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; public class C { public static void main(String[] args) throws Exception { Scanner in = new Scanner(new File(""input"")); System.setOut(new PrintStream(""output"")); int T = in.nextInt(); for (int t = 1; t <= T; t++) { System.out.print(""Case #"" + t + "": ""); int a = in.nextInt(), b = in.nextInt(); int count = 0; for (int i = a; i <= b; i++) { HashSet set = new HashSet(); char[] x = String.valueOf(i).toCharArray(); int n = x.length; char[] y = new char[n]; for (int j = 0; j < n; j++) if (x[j] != '0') { for (int k = 0; k < n; k++) y[k] = x[(j + k) % n]; int k = Integer.parseInt(String.valueOf(y)); if (set.contains(k)) continue; set.add(k); if (k != i && a <= k && k <= b) count++; } } System.out.println(count/2); } } } " B12413,"import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.FileInputStream; import java.io.Writer; import java.util.StringTokenizer; import java.util.HashSet; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Nova */ public class Main { public static void main(String[] args) { InputStream inputStream; try { inputStream = new FileInputStream(""C.input.txt""); } catch (IOException e) { throw new RuntimeException(e); } OutputStream outputStream; try { outputStream = new FileOutputStream(""C.output.txt""); } catch (IOException e) { throw new RuntimeException(e); } InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { int numberOfTests = in.nextInt(); HashSet set = new HashSet(); for (int testNum = 1; testNum <= numberOfTests; testNum++) { out.print(""Case #"" + testNum + "": ""); int a = in.nextInt(); int b = in.nextInt(); int res = 0; for (int num = a; num <= b; num++) { StringBuilder sb = new StringBuilder(); String s = String.valueOf(num); sb.append(s); sb.append(s); set.clear(); for (int i = 0; i < s.length(); i++) { int cc = Integer.parseInt(sb.substring(i, i + s.length())); if (num < cc && cc >= a && cc <= b && !set.contains(cc)) { res++; set.add(cc); } } } out.println(res); } } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(outputStream); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } " B11274,"import java.awt.List; import java.io.File; import java.io.FileNotFoundException; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class ProblemC { /** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { // TODO Auto-generated method stub Scanner sc = new Scanner(new File(args[0])); int numberOfLines = Integer.parseInt(sc.nextLine()); Scanner lineScan; int lowerBound, upperBound; String line; String number; String movingPart; String newNumber; int count; for (int i = 0; i< numberOfLines; i++) { line = sc.nextLine(); lineScan = new Scanner(line); lowerBound = lineScan.nextInt(); upperBound = lineScan.nextInt(); count = 0; if (upperBound < 10) { System.out.println(""Case #"" + (i+1) + "": "" + 0); } else { for (int j = lowerBound; j<= upperBound; j++) { number = Integer.toString(j); for (int k = 1; k< number.length(); k++) { if (number.charAt(k) != '0') { movingPart = number.substring(k, number.length()); newNumber = movingPart + number.substring(0,k); if (Integer.parseInt(newNumber) <= upperBound && Integer.parseInt(newNumber) > Integer.parseInt(number)) { count ++; //System.out.println(""Number "" + number + "" New number "" + newNumber + ""counter"" + count); } } } } System.out.printf(""Case #%d: %d\n"",(i+1), count); } } } } " B12915,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; import java.util.LinkedList; import java.util.Scanner; /** * * @author Venkatesh */ public class reversal { public static void main(String args[]) { Scanner s=new Scanner(System.in); int t=s.nextInt(); int currelement; int a,b,ind=1,temp,digits=0,temp1,temp2,count=0; boolean samedigits=true; boolean next=false; LinkedList list=new LinkedList(); while(ind<=t) { samedigits=true; next=false; digits=0; a=s.nextInt(); b=s.nextInt(); if(b<10) { System.out.println(""Case #""+ind+"": 0""); ind++; continue; } temp=a; while(temp!=0) { temp/=10; digits++; } int arr[]=new int[digits]; int barr[]=new int[digits]; //int mainarray[]=new int[digits]; temp2=b; for(int i=digits-1;i>=0;i--) { barr[i]=temp2%10; temp2/=10; } temp=a; while(temp<=b) { // if(temp==1113) // System.exit(0); // System.out.println(""Examining ""+temp); temp1=temp; samedigits=true; for(int i=digits-1;i>=0;i--) { arr[i]=temp1%10; temp1/=10; // System.out.println(arr[i]); if(i arr[0]) { // System.out.println(""Success ""); //if already present dont add currelement=arraytoint(arr,j); if(list.contains(currelement)==false) { count++; list.add(currelement); } continue; } else if(j!=0 && arr[j] == arr[0]) { // System.out.println(""equal""); int g=j; int h=0; while(arr[(++g)%digits] == arr[(++h)%digits]) { if((h%digits)==0) break; } if(arr[g%digits]>arr[h%digits]) { //System.out.println(""Success "");//+arr[g%digits]); //if already present dont add currelement=arraytoint(arr,j); if(list.contains(currelement)==false) { count++; list.add(currelement); } continue; } } } else if(arr[j]==barr[0]) { int k=0; int newind=j; ++newind; ++k; while(arr[(newind)%digits] == barr[(k)%digits]) { // System.out.println(""arr[(newind)%digits] ""+newind%digits+"" barr[(k)%digits] ""+(k)%digits); if((k)%digits==0) { newind=j; //check for digits of a if(arr[newind%digits] > arr[0]) { //System.out.println(""Success "");//+arr[newind%digits]); //if already present dont add currelement=arraytoint(arr,j); if(list.contains(currelement)==false) { count++; list.add(currelement); } next=true; break; } else if(newind%digits!=0 && arr[newind%digits] == arr[0]) { int g=newind%digits; int h=0; while(arr[(++g)%digits] == arr[(++h)%digits]) { if((h%digits)==0) break; } if(arr[g%digits]>arr[h%digits]) { //System.out.println(""Success "");//+arr[g%digits]); //if already present dont add currelement=arraytoint(arr,j); if(list.contains(currelement)==false) { count++; list.add(currelement); } next=true; break; } } //end of proc } newind++; ++k; } if(next) { next=false; continue; } if(arr[newind%digits]< barr[k%digits]) { // System.out.println(""arr[newind%digits]< barr[k%digits] ""+newind%digits+"" ""+ k%digits); newind=j; //check for digits of a if(arr[newind%digits] > arr[0]) { //System.out.println(""Success "");//+arr[newind%digits]); //if already present dont add currelement=arraytoint(arr,j); if(list.contains(currelement)==false) { count++; list.add(currelement); } } else if(newind%digits!=0 && arr[newind%digits] == arr[0]) { int g=newind%digits; int h=0; while(arr[(++g)%digits] == arr[(++h)%digits]) { if((h%digits)==0) break; } if(arr[g%digits]>arr[h%digits]) { //System.out.println(""Success "");//+arr[g%digits]); //if already present dont add currelement=arraytoint(arr,j); if(list.contains(currelement)==false) { count++; list.add(currelement); } } } //end of proc } } } temp++; list.removeAll(list); } System.out.println(""Case #""+ind+"": ""+count); ind++; count=0; } } static int arraytoint(int[] b,int index) { int i=0,temp; int len=b.length; int a[]=new int [len]; temp=a[index]; for(int j=0;j seen = new HashSet(); for (int k = current.length() - 1; k > 0; k--) { changing = changing.substring(1) + changing.charAt(0); int intchanging = new Integer(changing); if ((intchanging > new Integer(current)) && (intchanging <= max) && (!seen.contains(intchanging))) { count++; seen.add(intchanging); } } } /* * int end = max / 10; System.out.println(end); * System.out.println(tens); for (int j = min; j <= max; * j++) { int ref = j / 10; int mod = j % 10; boolean found * = false; while (ref > 0) { int check = ref % 10; if * (check != mod) { found = true; break; } ref /= 10; } if * (found) { if (((j % tens) < end)&&((j % tens) >= * (tens/10))) { if ((j / tens) < (j % tens)) { * System.out.print(j +"" ""); count++; } } } } */ pw.println(""Case #"" + i + "": "" + count); System.out.println(""Case #"" + i + "": "" + count); } } pw.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } " B13113,"package com.vp.common; import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.FileReader; import java.io.PrintStream; import java.util.Scanner; public class InputOutputProcessor { private int numberOfCases; private boolean doesInputHaveDataSetLines; private int indexOfDataSetLine; private int numberOfDataSetLines; private final static String DELIMITER = "" ""; private Scanner scanInput; public void initializeInput(String strInputFileName) { readInput(strInputFileName); numberOfCases = Integer.parseInt(scanInput.nextLine()); } /* * read input */ private void readInput(String strInputFileName) { try { scanInput = new Scanner(new BufferedReader(new FileReader( strInputFileName))); } catch (Exception exp) { // exp.printStackTrace(); System.out.println("" Please provide File Name with proper location ""); } } public String[] getDataSet() throws Exception { String[] dataSet; String strDataSetLine = """"; strDataSetLine = scanInput.nextLine(); // System.out.println(""strDataSetLine: "" + strDataSetLine); if (doesInputHaveDataSetLines) { String[] DataSetLineArray = strDataSetLine.split(DELIMITER); numberOfDataSetLines = Integer .parseInt(DataSetLineArray[indexOfDataSetLine]); } dataSet = new String[numberOfDataSetLines]; dataSet[0] = strDataSetLine; for (int i = 1; i < numberOfDataSetLines; i++) { dataSet[i] = scanInput.nextLine(); } return dataSet; } /** * * @return Returns the numberOfDataSetLines. */ public int getNumberOfDataSetLines() { return numberOfDataSetLines; } /** * @param numberOfDataSetLines * The numberOfDataSetLines to set. */ public void setNumberOfDataSetLines(int numberOfDataSetLines) { this.numberOfDataSetLines = numberOfDataSetLines; } /** * * @return Returns the numberOfCases. */ public int getNumberOfCases() { return numberOfCases; } /** * * @return Returns the doesInputHaveDataSetLines. */ public boolean isDoesInputHaveDataSetLines() { return doesInputHaveDataSetLines; } /** * @param doesInputHaveDataSetLines * The doesInputHaveDataSetLines to set. */ public void setDoesInputHaveDataSetLines(boolean doesInputHaveDataSetLines) { this.doesInputHaveDataSetLines = doesInputHaveDataSetLines; } /** * * @return Returns the indexOfDataSetLine. */ public int getIndexOfDataSetLine() { return indexOfDataSetLine; } /** * @param indexOfDataSetLine * The indexOfDataSetLine to set. */ public void setIndexOfDataSetLine(int indexOfDataSetLine) { this.indexOfDataSetLine = indexOfDataSetLine; } public void closeScanner() { scanInput.close(); } public void writeOutput(String outputFileName, String[] resultArray) { // To be moved out PrintStream out = null; try { out = new PrintStream(new FileOutputStream(outputFileName)); for (int i = 0; i < resultArray.length; i++) { out.print(resultArray[i]); out.print(""\n""); } out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(0); } } } " B12451,"package com.wordofday.service.job; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.Stack; public class GoogleRecycle { public GoogleRecycle() { // TODO Auto-generated constructor stub } /** * @param args */ public static void main(String[] args) { GoogleRecycle recycle = new GoogleRecycle(); try{ FileInputStream in = new FileInputStream(args[0]); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine = null; int count = 0; while ((strLine = br.readLine()) != null) { if(count>0){ //skip first line if(count>1){ System.out.print(""\nCase #""+count+"": ""+recycle.output(strLine)); }else{ System.out.print(""Case #""+count+"": ""+recycle.output(strLine)); } } count++; } //Close the input stream in.close(); }catch(Exception e){ e.printStackTrace(); } } private int output(String strLine) { Set> outputSet = new LinkedHashSet>(); int output = 0; if(strLine!=null && strLine.trim().length()>0){ String[] parts = strLine.split("" ""); int startInt = Integer.parseInt(parts[0]); int endInt = Integer.parseInt(parts[1]); for(int i=startInt;i<=endInt;i++){ Stack digStack = new Stack(); int temp =i; while(temp>0){ int digit = temp%10; digStack.push(digit); temp=(temp-digit)/10; } List digList = new ArrayList(); while(!digStack.empty()){ digList.add(digStack.pop()); } //now start shuffling from stack for(int j=1;j outputList = new ArrayList(); outputList.add(i); outputList.add(nextNumber); outputSet.add(outputList); } } } } return outputSet.size(); } private int getNextNumber(List digList, int j) { int nextNumber = 0; StringBuilder sb = new StringBuilder(); if(j frontList = digList.subList(0, j); List endList = digList.subList(j, digList.size()); for(Integer end:endList){ sb.append(end); } for(Integer front:frontList){ sb.append(front); } nextNumber = Integer.parseInt(sb.toString()); } return nextNumber; } } " B10494,"import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; public class Recycled extends TemplateClass { public Recycled() { } public Recycled(String nombreficheroEntrada, String nombreFicheroSalida) throws Exception { super(nombreficheroEntrada, nombreFicheroSalida); } protected void procesaTestCase() throws Exception { // Variables int testCase = 0; ArrayList lista = new ArrayList(); long a; long b; long casos; for (testCase = 0; testCase < testCases; testCase++) { a = sc.nextInt(); b = sc.nextInt(); casos = numeroCasos(a,b); bw.write(""Case #"" + (testCase + 1) + "": "" + casos + ""\n""); } bw.close(); } private long numeroCasos(long a, long b){ long casos = 0; // long medio = (long)(Math.ceil(((b - a)/2)) + a); char c[]; long arrayCombinaciones[]; long temp = 0; long base = 0; for(long i = a; i <= b; i++){ base = i; c = (Long.toString(i)).toCharArray(); //comprueba numero // for (int j = 0; j < c.length; j++) { arrayCombinaciones = traeCombinaciones(c); siguiente: for (int k = 0; k < arrayCombinaciones.length; k++) { temp = arrayCombinaciones[k]; if (temp > base){ base = temp; }else{ continue siguiente; } if (temp <= b){ casos += 1; } } // } } return casos; } private long[] traeCombinaciones(char c[]){ long array[] = new long[c.length]; char temp[] = c; char temp2[] = c; int k = 0; String s; s = String.valueOf(temp); array[0] = Long.parseLong(s); for (int i = 1; i < array.length; i++) { temp = new char[c.length]; for (int j = 0; j < c.length; j++) { if (j == 0){ k = c.length - 1; }else{ k = j - 1; } temp[k] = temp2[j]; } temp2 = temp; array[i] = Long.parseLong(String.valueOf(temp)); } Arrays.sort(array); return array; } } " B10909,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; public class CRecycledNumbers { static int recycle(int a, int b) { System.out.println(""-------------------------""); System.out.println(a + "" "" + b); int count = 0; Set used = new HashSet(); for(int i = a; i < b; ++i) { String s = Integer.toString(i); for(int j = 1; j < s.length(); ++j) { String pre = s.substring(0, j); String suf = s.substring(j); if(suf.startsWith(""0"")) continue; int c = Integer.parseInt(suf + pre); if(c <= b && c != i && i < c) { String p = i < c? (i + ""-"" + c) : (c + ""-"" + i); if(!used.contains(p)) { used.add(p); System.out.println(p); ++count; } } } } return count; } public static void main(String[] args) throws NumberFormatException, IOException { String filename = ""C-small-attempt0.in""; BufferedReader r = new BufferedReader(new FileReader(filename)); int n = Integer.parseInt(r.readLine()); PrintWriter p = new PrintWriter(""c.out""); for(int i = 0; i < n; ++i) { String[] test = r.readLine().split("" ""); int j = i + 1; p.println(""Case #"" + j + "": "" + recycle(Integer.parseInt(test[0]), Integer.parseInt(test[1]))); } p.flush(); p.close(); } } " B10802," public class Pair { private int first; private int second; public Pair(int first, int second) { if (first < second) { this.first = first; this.second = second; } else { this.first = second; this.second = first; } } public int getFirst() { return first; } public int getSecond() { return second; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + first; result = prime * result + second; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (first != other.first) return false; if (second != other.second) return false; return true; } } " B13128,"import java.io.*; import java.util.*; class Recycled { static boolean[] check = new boolean[2000000]; public static void main (String [] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(""C-small-attempt0.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""C-small-attempt0.out""))); StringTokenizer st = new StringTokenizer(in.readLine()); int numCases = Integer.parseInt(st.nextToken()); for (int caseIndex = 0; caseIndex < numCases; caseIndex++) { out.print(""Case #"" + (caseIndex + 1) + "": ""); st = new StringTokenizer(in.readLine()); int min = Integer.parseInt(st.nextToken()); int max = Integer.parseInt(st.nextToken()); // Reset check for (int i = 0; i < 2000000; i++) { check[i] = false; } int result = 0; for (int i = min; i <= max; i++) { result += countRecycledNumbers(i, min, max); } out.print(result); out.println(); } out.close(); } public static ArrayList generateRecycledNumbers(int x) { // Count number of digits int y = x; int numDigits = 0; while (y > 0) { numDigits ++; y /= 10; } // Get the list of digits int[] listDigits = new int[numDigits]; int index = numDigits-1; while (x > 0) { listDigits[index] = x%10; x /= 10; index --; } // Generate all possible recycled number from x ArrayList result = new ArrayList(); for (int i = 0; i < numDigits; i++) { if (listDigits[i] == 0) continue; int num = 0; for (int j = 0; j < numDigits; j++) { num = num*10 + listDigits[(i+j)%numDigits]; } result.add(num); } return result; } public static int countRecycledNumbers(int x, int min, int max) { if (check[x]) { return 0; } else { ArrayList recycledNumbers = generateRecycledNumbers(x); Collections.sort(recycledNumbers); int numDistinctNumbers = 0; for (int i = 0; i < recycledNumbers.size(); i++) { check[recycledNumbers.get(i)] = true; if (i > 0 && recycledNumbers.get(i) > recycledNumbers.get(i-1) && recycledNumbers.get(i) >= min && recycledNumbers.get(i) <= max) { numDistinctNumbers++; } else if (i == 0 && recycledNumbers.get(i) >= min && recycledNumbers.get(i) <= max) { numDistinctNumbers++; } } return (numDistinctNumbers*(numDistinctNumbers-1)/2); } } }" B10330,"import java.awt.Point; import java.awt.geom.Point2D; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashMap; import java.util.HashSet; import java.util.StringTokenizer; public class q3 { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st = new StringTokenizer(""""); public static String next() throws Exception { while (true) { if (st.hasMoreTokens()) return st.nextToken(); String s = br.readLine(); if (s == null) return null; st = new StringTokenizer(s); } } public static int nextInt() throws Exception { return Integer.parseInt(next()); } public static void main(String[] args) throws Exception { int T = nextInt(); for(int t = 1 ; t <=T ; t++){ HashSet set = new HashSet(); set.add(new Point(1,2)); int A = nextInt(); int B = nextInt(); int n = (""""+A).length(); int count = 0; for(int i = A ; i <= B ; i ++){ int d = 10; int c = 1; while(i/d >0){ int temp = i/d; temp += (i%d) * Math.pow(10, n-c); if(temp<=B && temp > i){ if(set.contains(new Point(i , temp))) ; else count++; } d *= 10; c++; } } System.out.println(""Case #"" + t + "": ""+count ); } } } " B12808,"package tw.csc.gcj; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; public class Main { /** * @param args */ public static String str1 = ""abcdefghijklmnopqrstuvwxyz""; public static String str2 = ""ynficwlbkuomxsevzpdrjgthaq""; public static void main(String[] args) { try { goC(); } catch (Exception e) { } } public static void goC() throws NumberFormatException, IOException { File fin = new File(""C-small-attempt0.in""); File fout = new File(""C-small-attempt0.out""); BufferedReader br = new BufferedReader(new FileReader(fin)); FileOutputStream fos = new FileOutputStream(fout); int c = Integer.parseInt(br.readLine()); String op = """"; for (int i = 0 ; i < c ;i ++ ){ op+=""Case #""+ (i+1)+"": ""; String[] strin = br.readLine().split(""[ ]""); op += test(Integer.parseInt(strin[0]), Integer.parseInt(strin[1])) + ""\n""; } fos.write(op.getBytes()); fos.close(); } public static String test(int a , int b){ String ret = """"; HashSet set = new HashSet(); for (int n = a ; n <=b ; n++){ String strn = String.valueOf(n); for (int i = 1 ; i < strn.length() ; i ++){ String strtest = strn.substring(strn.length() - i, strn.length() ) + strn.substring(0 , strn.length() -i); int m = Integer.parseInt(strtest); if (m > n && m <= b){ set.add(strn+String.valueOf(m)); } } } return ret + set.size(); } public static void goA() throws NumberFormatException, IOException { HashMap map = new HashMap(); for (int i = 0 ; i < str1.length() ; i ++){ map.put(str2.charAt(i), str1.charAt(i)); } File fin = new File(""A-small-attempt1.in""); File fout = new File(""A-small-attempt1.out""); BufferedReader br = new BufferedReader(new FileReader(fin)); FileOutputStream fos = new FileOutputStream(fout); int c = Integer.parseInt(br.readLine()); String op = """"; for (int i = 0 ; i < c ;i ++ ){ op+=""Case #""+ (i+1)+"": ""; String strin = br.readLine(); String strout = """"; for (int k = 0 ;k < strin.length() ;k ++){ if (strin.charAt(k) == ' '){ strout+="" ""; } else{ strout+= map.get(strin.charAt(k)); } } op+=strout+""\n""; } fos.write(op.getBytes()); fos.close(); }; } " B11695,"import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; /** Main function is ""solve"" **/ public class CodeJamProblem3 { static HashMap mappings = null; public static void main(String args[]) { solve(); } private static void solve() { readFromInputAndWriteInOutput(); } private static void readFromInputAndWriteInOutput() { try { File f = new File(""C-small-attempt0.in""); FileReader fileReader = new FileReader(f); BufferedReader buff = new BufferedReader(fileReader); String totalTestCases = buff.readLine(); PrintWriter printWriter = new PrintWriter( ""C-small-attempt0.out""); int testCases = Integer.parseInt(totalTestCases); for (int i = 1; i <= testCases; i++) { String line = buff.readLine(); String outputLine = ""Case #"" + i + "": ""; String result = solveForThisLine(line); outputLine = outputLine.concat(result); printWriter.println(outputLine); //System.out.println(outputLine); } printWriter.close(); fileReader.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static String solveForThisLine(String line) { String lineSplit[] = line.split("" ""); int numA = Integer.parseInt(lineSplit[0]); int numB = Integer.parseInt(lineSplit[1]); int result = 0; int length = lineSplit[0].length(); int tensLength = 1; // System.out.println(); for(int i=0;i list2 = new ArrayList(); for (int j = 0; j <=length; j++) { int m = reverse(i, j,tensLength); if (numA <= n && n < m && m <= numB) { if(list2.contains(m)) { continue; } list2.add(m); result = result + 1; } } } return result + """"; } private static int reverse(int number, int shiftBy, int tensLength) { int temp = 0, reversedNumber = 0; for (int i = 0; i parts = Arrays.asList(line.split("" "")); lBound = Integer.parseInt(parts.get(0)); uBound = Integer.parseInt(parts.get(1)); Multimap out = ArrayListMultimap.create(); for (int l = lBound; l < uBound; l++) { String thing = String.valueOf(l); Set friends = Sets.newHashSet(); for (int offset = 1; offset < thing.length(); offset++) { String friend = thing.substring(offset).concat(thing.substring(0, offset)); if (friend.startsWith(""0"")) { continue; } int friendly = Integer.parseInt(friend); if (friendly <= l || friendly > uBound) { continue; } friends.add(friend); } out.putAll(thing, friends); } answer = out.values().size(); } public String output() { return ""Case #"" + index + "": "" + answer; } } public static void main(String[] args) throws Exception { in = new BufferedReader(new FileReader(inputFile)); out = new BufferedWriter(new FileWriter(outputFile)); try { String line = in.readLine(); int nbCases = Integer.parseInt(line); int index = 0; while ((line = in.readLine()) != null) { index++; Parser p = new Parser(line, index); out.write(p.output()); out.newLine(); } } finally { in.close(); } out.flush(); } } " B11285,"import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { new RecycledNumbers().fun(); } private void fun() { String file = ""D:/CodeJam/input.in""; int result = 0; try { scan = new Scanner(new File(file)); } catch (FileNotFoundException e) { e.printStackTrace(); } int cases = scan.nextInt(); for(int i = 1; i <= cases ; i++) { int lowLimit = scan.nextInt(); int highLimit = scan.nextInt(); result = findResult(lowLimit, highLimit); System.out.println(""Case #""+i+"": ""+result); } } private int findResult(int lowLimit, int highLimit) { if(highLimit < 10) return 0; int[] lowArr = null; int count = 0; int shift = 0; ArrayList list = new ArrayList(); for(int i = lowLimit; i <= highLimit; i++) { list.clear(); lowArr = toArray(i); for(int j = 0; j < lowArr.length-1; j++) { int[] shiftArr = shift(lowArr); if(lowArr.length == shiftArr.length) { shift = arrayToInt(shiftArr); if(i < shift && shift >= lowLimit && shift <= highLimit) { if(!list.contains(shift)) { list.add(shift); count++; } } } } } return count; } private int[] shift(int[] array) { int i = 0; int temp = array[array.length-1]; for(i = array.length-1 ; i > 0; i--) { array[i] = array[i-1]; } array[0] = temp; return array; } private int arrayToInt(int[] array) { int result = 0; for(int i =0; i < array.length ; i++) { result = array[i] + result * 10; } return result; } private int[] toArray(int value) { int array[] = new int[100]; int count = 0; while(value > 0) { int temp = value % 10; value = value / 10; array[count++] = temp; } int array2[] = new int[count]; int j = count - 1; for(int i = 0; i < count ; i++ , j--) { array2[j] = array[i]; } return array2; } Scanner scan = null; } " B10178,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.HashSet; public class RecycledNumbers { public static void main(String[] args) throws Exception { String sb = null; int ans = 0; BufferedReader is = new BufferedReader(new FileReader(new File(""D:\\C-small-attempt0.in""))); BufferedWriter os = new BufferedWriter(new FileWriter(""D:\\out.txt"")); os.flush(); HashSet hs = null; int loopIter = Integer.parseInt(is.readLine()); for(int i=0; i(); String x[] = sb.split("" ""); int start = Integer.parseInt(x[0]); int end = Integer.parseInt(x[1]); for(int j=start; j<=end; j++){ String h = j + """"; for(int k=0; k= start && xxx <= end){ //System.out.println(""start = "" + start + "", end = "" + end + "", j = "" + j + "", reverse = "" + h); hs.add(""("" + j + "","" + h + "")""); ans++; } } } if(ans %2 != 0){ System.out.println(""FUCKED! = "" + sb); } os.write(""Case #"" + (i+1) + "": "" + hs.size()/2 + ""\n""); os.flush(); } } } " B13012,"package gcj; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; public abstract class SolverBase { public static final String TOKEN_SEPARATOR = "" ""; public static final String IMPOSSIBLE = ""IMPOSSIBLE""; public String problemName; public boolean verbose = false; public SolverBase(String problemName) { this.problemName = problemName; } public void solve(InputStream in, PrintStream out) throws Exception { InputStreamReader isr = new InputStreamReader(in); BufferedReader reader = new BufferedReader(isr); long N = Long.parseLong(reader.readLine()); for (long i = 1; i <= N; i++) { out.print(""Case #"" + i + "": ""); solveSingle(reader, out); } } public abstract void solveSingle(BufferedReader reader, PrintStream out) throws Exception; public long[] readSingleLineLongArray(BufferedReader reader) throws Exception { String[] longsAsStrings = readSingleLineStringArray(reader); long[] longs = new long[longsAsStrings.length]; for (int i = 0; i < longsAsStrings.length; i++) { longs[i] = Long.parseLong(longsAsStrings[i]); } return longs; } public int[] readSingleLineIntArray(BufferedReader reader) throws Exception { String[] intsAsStrings = readSingleLineStringArray(reader); int[] ints = new int[intsAsStrings.length]; for (int i = 0; i < intsAsStrings.length; i++) { ints[i] = Integer.parseInt(intsAsStrings[i]); } return ints; } public String[] readSingleLineStringArray(BufferedReader reader) throws Exception { String line = reader.readLine(); if (verbose) { System.out.println(""Reading line "" + line); } return line.split(TOKEN_SEPARATOR); // return StringUtils.split(line, TOKEN_SEPARATOR); } public String[][] readStringArrays(BufferedReader reader, int lines) throws Exception { String[][] arrays = new String[lines][]; for (int i = 0; i < lines; i++) { arrays[i] = readSingleLineStringArray(reader); } return arrays; } public char[][] readCharArrays(BufferedReader reader, int lines) throws Exception { char[][] arrays = new char[lines][]; for (int i = 0; i < lines; i++) { String line = reader.readLine(); arrays[i] = line.toCharArray(); } return arrays; } public long[][] readLongArrays(BufferedReader reader, int lines) throws Exception { long[][] arrays = new long[lines][]; for (int i = 0; i < lines; i++) { arrays[i] = readSingleLineLongArray(reader); } return arrays; } protected void check(boolean b) { if (!b) { throw new IllegalStateException(""Check failed""); } } } " B12828,"package Default_2012; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; public class C { public static void main(String[] args) throws Exception { Scanner in = new Scanner(""IO_2012/inputs/C-small-attempt0.in""); PrintWriter out = new PrintWriter(""IO_2012/outputs/C-small-attempt0.out""); int n = in.nextInt(); for (int i = 1; i <= n; i++) { in.nextLine(); int a = in.nextInt(); int b = in.nextInt(); int count = 0; if (a < 10 && b < 10) { out.println(""Case #"" + i + "": 0""); continue; } int v[] = new int[b + 1]; for (int z = a; z <= b; z++) { String s = String.valueOf(z); for (int j = 0; j < s.length(); j++) { int num, total = 0; for (int ii = j + 1; ii < s.length(); ii++) { num = s.charAt(ii) - '0'; total *= 10; total += num; } for (int ii = 0; ii <= j; ii++) { num = s.charAt(ii) - '0'; total *= 10; total += num; } if (total != z && total >= a && total <= b && z < total && v[total] != z) { count++; v[total] = z; } } } out.println(""Case #"" + i + "": "" + count); } out.close(); } public static class Scanner { private final BufferedReader in; private String line = """"; private int pos; private int lineNo; public Scanner(String Arquive) throws Exception { in = new BufferedReader(new FileReader(Arquive)); nextLine(); } public boolean hasNext() throws IOException { return in.ready(); } public void close() { try { in.close(); } catch (IOException e) { throw new AssertionError(""Failed to close with "" + e); } } public void nextLine() { try { line = in.readLine(); } catch (IOException e) { throw new AssertionError(""Failed to read line with "" + e); } pos = 0; lineNo++; } public String next() { if (pos != 0) { pos++; } StringBuilder sb = new StringBuilder(); while (pos < line.length() && line.charAt(pos) > ' ') sb.append(line.charAt(pos++)); return sb.toString(); } public int nextInt() { int num, total = 0; boolean negativo = false; if (pos != 0) { pos++; } if (pos < line.length() && line.charAt(pos) == '-') { negativo = true; pos++; } while (pos < line.length() && line.charAt(pos) > ' ') { num = line.charAt(pos++) - '0'; total *= 10; total += num; } if (negativo) total *= -1; return total; } public long nextLong() { long num, total = 0; boolean negativo = false; if (pos != 0) { pos++; } if (pos < line.length() && line.charAt(pos) == '-') { negativo = true; pos++; } while (pos < line.length() && line.charAt(pos) > ' ') { num = line.charAt(pos++) - '0'; total *= 10; total += num; } if (negativo) total *= -1; return total; } } } " B13019,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package question3; import com.sun.org.apache.xpath.internal.FoundIndex; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; /** * * @author karim */ public class Question3 { static Map found = new HashMap(); /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { BufferedWriter out = new BufferedWriter(new FileWriter(""output.out"")); BufferedReader in = new BufferedReader(new FileReader(""C-small-attempt0.in"")); int numOfcases = Integer.parseInt(in.readLine()); for (int caseNum = 1; caseNum <= numOfcases; caseNum++) { found = new HashMap(); String input = in.readLine(); Scanner s = new Scanner(input); int a = s.nextInt(); int b = s.nextInt(); long output = 0; if (b >= 10) { for (int currentNum = b; currentNum >= a; currentNum--) { int temp = currentNum; int divisor = 10; while (temp / divisor != 0) { int div = temp / divisor; int reminder = temp % divisor; divisor *= 10; int newNumber = Integer.parseInt("""" + reminder + div); if (newNumber >= a && newNumber <= b && newNumber != currentNum) { Pair p = new Pair(newNumber, currentNum); if (!found.containsKey(p)) { System.out.println(currentNum + "" "" + newNumber); found.put(p, 1); output++; } } } } } out.write(""Case #"" + caseNum + "": "" + output); out.newLine(); } out.flush(); out.close(); in.close(); } } " B10181," import java.util.Comparator; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.util.Collection; import java.util.List; import java.io.IOException; import java.util.Arrays; import java.util.InputMismatchException; import java.util.ArrayList; import java.math.BigInteger; import java.util.Collections; import java.io.InputStream; import java.util.*; import java.io.*; class Main{ public static void main(String...s) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); int Test=in.readInt(); new Solver(Test,in,out); out.close(); } } class Solver { static int T; static InputReader in; static OutputWriter out; static IOUtils utils; Solver(int T,InputReader in,OutputWriter out) { this.T=T; this.in=in; this.out=out; solve(); } static int findDigit(int num) { int count=0,cnt=0; int tmp=num%10; while(num > 0) { count++; if(tmp == (num %10)) { cnt++;} num/=10; } return (cnt == count ? 0:count); } static void solve() { int itr=1; //preprocess(); for(int f = 0 ; f < T ; f++) { int A=in.readInt(); int B=in.readInt(); int sum=0; for(int i=A;i<=B;i++) { int tmp=i,newNum=tmp,x=0,ans=0; int howManyDigit=findDigit(tmp);if(howManyDigit == 0) { ans=0;continue;} if(howManyDigit == 2) x=10; if(howManyDigit == 3) x=100; if(howManyDigit == 4) x=1000; for(int f1 = 1 ; f1 < howManyDigit ; f1++) { int tmp1=newNum; newNum=( tmp1%10 ) * x ;int y=1;tmp1=tmp1/10; while(tmp1 > 0) { newNum+=(tmp1%10)*y; tmp1/=10; y*=10; } if(newNum >= A && newNum <= B ) { ans++;} } sum+=ans; } out.printLine(""Case #""+itr+"":""+"" ""+sum/2); itr++; } } } /*class MoreUtils { static char mark[]; static int prime[]=new int[1000000]; static int pcount=-1; static int Tree[]; static int Brr[]; static InputReader in; static OutputWriter out; MoreUtils(int Arr[],int UPPER_LIMIT,InputReader in,OutputWriter out) { Brr=new int[UPPER_LIMIT+1];Brr[0]=0; for(int i=1;i<=UPPER_LIMIT;i++) {Brr[i]=Arr[i];} Tree=new int[ UPPER_LIMIT * 3]; buildTree(1,1,UPPER_LIMIT); //for(int i=1;i<=2*UPPER_LIMIT;i++) out.print(Tree[i]+"" ""); } public static int[] prime(int UPPER_LIMIT) { mark=new char[UPPER_LIMIT/2/8+1]; for (int i = 3; i*i <=UPPER_LIMIT; i += 2) if ( (mark[i>>4] & (1<<((i>>1)&7))) == 0 ) for (int j = i*i; j <=UPPER_LIMIT; j += i<<1) mark[j>>4] |= (1<<((j>>1)&7)); prime[++pcount] = 2; for (int i = 3; i <=UPPER_LIMIT; i += 2) if ( (mark[i>>4]&(1<<((i>>1)&7))) == 0) {prime[++pcount] = i;} return prime; } static void buildTree(int N,int LOWER_LIMIT,int UPPER_LIMIT) { if(LOWER_LIMIT == UPPER_LIMIT) { Tree[N]=Brr[ LOWER_LIMIT]; return ; } int mid=( LOWER_LIMIT + UPPER_LIMIT) >> 1; buildTree(2*N , LOWER_LIMIT , mid); buildTree(2*N+1 , mid+1 , UPPER_LIMIT); Tree[N]=Math.max(Tree[2*N], Tree[2*N+1]); } static long query(int N, int l , int r , int x , int y) { if(y < l || x > r) {return 0;} if( l >=x && r <= y){return Tree[N];} int mid = (l + r) >> 1; long L=query( 2*N , l , mid , x , y); long R=query(2*N+1 ,mid+1 , r , x , y); return Math.max(L, R); } }*/ class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); long sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(outputStream); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } } class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.readInt(); return array; } public static long[] readLongArray(InputReader in, int size) { long[] array = new long[size]; for (int i = 0; i < size; i++) array[i] = in.readInt(); return array; } } class IntegerUtils { public static int compare(long a, long b) { if (a < b) return -1; if (a > b) return 1; return 0; } } " B10838,"import java.io.*; /** * * @author ankush */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args)throws IOException { //System.out.println(Math.floor(Math.log10(11))); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine()); int ans[]=new int[t]; for(int i=0;ij && s<=b && n==q) { count++; // System.out.println(j+"" ""+s+"" ""+count+"" ""+p+"" ""+q+"" ""+m); } m=s%10; p=s/10; } } ans[i]=count; } for(int i=0;i set = new HashSet(); for(int j = 1; j < s.length(); j++) { int k = Integer.parseInt(s1.substring(j, j + s.length())); set.add(k); } for(Integer k : set) { if(a <= k && k <= b && i < k) { result++; } } } return Integer.toString(result); } } " B10278,"package gcj_qr2012_a; import java.io.File; import java.io.FileNotFoundException; /** * * @author Fidel */ public class qr_problemB { public static void main(String args[]) throws FileNotFoundException{ File f = new File(""input.txt""); java.util.Scanner sc = new java.util.Scanner(f); int T = sc.nextInt(); for (int i = 0; i < T; i++) { int A = sc.nextInt(); int B = sc.nextInt(); int y = 0; for (int j = A; j <= B; j++) { for (int k = B; k > j; k--) { String a = String.valueOf(j); for (int l = 1; l < String.valueOf(k).length(); l++) { String b = String.valueOf(k); String tmp = b.substring(b.length()-l) + b.substring(0, b.length()-l); if(tmp.matches(a)){ y++; break; } } } } System.out.println(""Case #"" + (i+1) + "": "" + y); } } } " B12501,"import java.io.*; import java.util.*; class Recycled { public static void main(String[] args) throws IOException { Scanner s = new Scanner(new File(args[0])); int numTests = s.nextInt(); for (int i = 1; i <= numTests; i++) { // Clear the trailing newline on this line. s.nextLine(); int A = s.nextInt(); int B = s.nextInt(); int L = (""""+A).length()-1; int E = (int)Math.pow(10, L); int count = 0; List seen = new ArrayList(L); for (int j = A; j < B; j++) { int curr = j; for (int k = 0; k < L; k++) { curr = (curr / 10) + (curr % 10) * E; if (curr > j && curr <= B && !seen.contains(curr)) { count++; seen.add(curr); } } seen.clear(); } System.out.println(""Case #"" + i + "": "" + count); } } } " B10239,"package codejam2.recycled; import java.util.HashSet; import java.util.Scanner; import codejam2.CodejamCase; import codejam2.CodejamRunner; public class Recycled extends CodejamRunner implements CodejamCase { private int min; private int max; private String result; @Override public void compute() { int r = 0; for(int i = min; i <= max; i++) { HashSet ss = new HashSet(); String s = String.valueOf(i); for(int j = 1; j < s.length(); j++) { String n = s.substring(j) + s.substring(0, j); int in = Integer.valueOf(n); if (in > i && in <= max) { ss.add(n); } } r += ss.size(); } result = String.valueOf(r); } @Override public String getOutput() { return result; } @Override public CodejamCase parseCase(Scanner s) { Recycled r = new Recycled(); r.min = s.nextInt(); r.max = s.nextInt(); return r; } /** * @param args */ public static void main(String[] args) { new Recycled().run(args); } } " B10990,"import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Scanner; public class QC2012 { public static void main(String[] args) throws Exception { new QC2012(); } static final String filename = ""C-small-attempt0""; int testcases; public QC2012() throws Exception { FileReader ifile = new FileReader(filename+"".in""); Scanner scanner = new Scanner(ifile); testcases = Integer.parseInt(scanner.nextLine()); FileWriter ofile = new FileWriter(filename+"".out""); for (int i = 1; i <= testcases; i++) { ofile.write(""Case #""+i+"": ""+solve(scanner.nextInt(), scanner.nextInt())+(i != testcases ? ""\n"" : """")); } ofile.close(); System.out.println(""Finished""); } private int solve(int A, int B) throws Exception { int sum = 0; for (int n = A; n <= B-1; n++) { for (int m = n+1; m <= B; m++) { if (isRecycled(Integer.toString(n),Integer.toString(m))) sum++; } } return sum; } private boolean isRecycled(String n, String m) { String rotn = n; do { if (rotn.equals(m)) return true; rotn = rotR(rotn); } while(!n.equals(rotn)); return false; } private String rotR(String n) { return n.charAt(n.length()-1) + n.substring(0, n.length()-1); } } " B11241,"import java.util.List; import java.util.Vector; public class DataModel extends Thread { class Data { private int no; private List pairs; public Data(int no) { this.no = no; pairs = new Vector(); } public void addToList(int no) { pairs.add(no); } public int getPairs() { int p = 0; for (Integer i : pairs) { if (i != no) p++; } return p; } public boolean isInList(int i) { return pairs.contains(i); } } private int lowBound; private int highBound; private int caseNo; private Data[] range; private int output; private boolean stateCalc; public DataModel(String input, int caseNo) { this.caseNo = caseNo; String[] temp = input.split("" ""); stateCalc = false; try { lowBound = Integer.parseInt(temp[0]); highBound = Integer.parseInt(temp[1]); } catch (Exception e) { e.printStackTrace(); System.exit(1); } range = new Data[highBound - lowBound + 1]; for (int i = lowBound; i <= highBound; i++) { range[i - lowBound] = new Data(i); } } @Override public void run() { char[] split; int splitOn; for (int i = lowBound; i <= highBound; i++) { split = (i + """").toCharArray(); if (split.length == 1) { output = 0; break; } for (int j = 0; j < split.length; j++) { splitOn = splitOnPos(split, j); if (splitOn <= highBound && splitOn >= lowBound && splitOn != i) { if (!range[i - lowBound].isInList(splitOn)) { range[i - lowBound].addToList(splitOn); } } } } calcOut(); stateCalc = true; } private void calcOut() { for (int i = 0; i < range.length; i++) { for (int j = 0; j < range[i].getPairs(); j++) output++; } output /= 2; } private int splitOnPos(char[] arr, int splitpos) { StringBuilder sb = new StringBuilder(); for (int i = splitpos; i < arr.length; i++) { sb.append(arr[i]); } for (int i = 0; i < splitpos; i++) { sb.append(arr[i]); } return Integer.parseInt(sb.toString()); } public boolean isDone() { return stateCalc; } public void getOutput() { System.out.println(""Case #"" + caseNo + "": "" + output); } }" B12280,"import java.util.*; import java.io.*; import java.lang.Integer; public class QuestionC { public static void main(String[] args) throws IOException { Scanner inPut = new Scanner(new File(""C-small-attempt0.in"")); FileWriter fWriter = new FileWriter(""C-small-attempt0.out""); int caseTotal = inPut.nextInt(); inPut.nextLine(); for (int caseNum = 1; caseNum <= caseTotal; caseNum++) { // read the string length for this case int base = 1; int smallNum = inPut.nextInt(); int largeNum = inPut.nextInt(); int digit = 0; int temp = smallNum; while(temp != 0) { temp = temp/10; digit++; } int[] num = new int[digit]; int total = 0; for (int i = 1; i < digit; i++) { base = base * 10; } fWriter.write(""Case #"" + caseNum + "": ""); for(int i = largeNum; i >= smallNum; i--) { num[0] = i; for (int j = 1; j < digit; j++) { boolean norepeat = false; num[j] = num[j - 1] / base + (num[j - 1] % base) * 10; if (num[j] >= smallNum && num[j] <= largeNum) { norepeat = true; for (int k = j - 1; k >= 0; k--) { norepeat = norepeat && (num[j] != num[k]); } } if(norepeat) total++; } } total = total / 2; fWriter.write(total + ""\n""); } fWriter.flush(); fWriter.close(); } } " B12994,"package mgg.utils; public class Pair { public int first; public int second; public Pair(int first, int second){ this.first = first; this.second = second; } @Override public String toString() { return ""("" + first + "", "" + second + "") ""; } } " B11881,"import java.util.*; import java.io.*; import java.math.*; public class C { private static String INPUT_FILE = ""C-small-attempt0.in""; private static String OUTPUT_FILE = ""c.out""; private static Map listLengthToPairs = new HashMap(); public static void main(String args[]) { listLengthToPairs.put(1, 0); listLengthToPairs.put(2, 1); listLengthToPairs.put(3, 3); listLengthToPairs.put(4, 6); listLengthToPairs.put(5, 10); listLengthToPairs.put(6, 15); listLengthToPairs.put(7, 21); Scanner input = null; PrintStream output = null; try { input = new Scanner(new File(INPUT_FILE)); output = new PrintStream(OUTPUT_FILE); } catch (Exception e) { System.out.println(e); } int testCases = Integer.parseInt(input.nextLine()); int count = 1; String curArgs; int lowerBound; int upperBound; while(input.hasNextLine()) { output.print(""Case #"" + count + "": ""); String spl = input.nextLine(); lowerBound = Integer.parseInt(spl.split("" "")[0]); upperBound = Integer.parseInt(spl.split("" "")[1]); int totalViablePairs = 0; Set numbersSeen = new HashSet(); for (int i=lowerBound; i<=upperBound; i++) { if (!numbersSeen.contains(i)) { int viable = permuteNum(i, lowerBound, upperBound, numbersSeen); totalViablePairs += viable; } } if (count != testCases) { output.println(totalViablePairs); } else { output.print(totalViablePairs); } count++; } } private static int permuteNum(int num, int lower, int upper, Set seen) { String s = num + """"; int length = s.length(); int viablecount = 1; // add initial to seen set seen.add(num); for (int i=0; i= lower && newnum <= upper && !seen.contains(newnum)) { //System.out.println(newnum); viablecount++; // add found number to seen set seen.add(newnum); //System.out.println(""just added: "" + newnum); } num = newnum; } return listLengthToPairs.get(viablecount); } }" B12232,"package qualification; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class C { String solve(Scanner in) throws IOException { int A = in.nextInt(), B = in.nextInt(), pow = 1, pairs = 0; while(10*pow <= A) pow *= 10; boolean[] seen = new boolean[B+1]; for(int n = A; n <= B; n++) if(!seen[n]) { int count = 0; for(int m = n; m > B || !seen[m]; m = m/10 + m%10 * pow) if(A <= m && m <= B) { seen[m] = true; count++; } pairs += count * (count-1) / 2; } return """"+pairs; } /*************************************************************************************************/ public static void main(String[] args) throws IOException { for(File f : new File(""."").listFiles()) if(f.isFile() && f.getName().startsWith(C.class.getSimpleName() + ""-"") && f.getName().endsWith("".in"")) { Scanner in = new Scanner(new FileReader(f)); PrintWriter out = new PrintWriter(new FileWriter(f.getName() + "".out"")); int cases = in.nextInt(); in.nextLine(); for(int caseno = 1; caseno <= cases; caseno++) out.printf(""Case #%d: %s%n"", caseno, new C().solve(in)); out.close(); } } } " B12777,"import java.io.*; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Main { public static void main(String[] args) throws Exception { PrintWriter out = new PrintWriter(new FileOutputStream(new File(""output.txt"")), false); BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(new File(""input.txt"")))); // StringTokenizer st = new StringTokenizer(in.readLine()); // Scanner s = new Scanner(System.in); int n = Integer.parseInt(in.readLine()); for(int i = 0;i < n;i++) { StringTokenizer st = new StringTokenizer(in.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); int len = len(a); int ten = (int)Math.pow(10, len-1); int res = 0; for(int j = a;j <= b;j++) { int cur = j; int val = j; int per = period(j,len); for(int k = 0;k < per;k++) { int c = val%10; val = val/10+c*ten; if(val > cur && val <= b) { res++; } } } out.println(""Case #""+(i+1)+"": ""+res); out.flush(); } } public static int period(int n, int len) { if(len == 2 && n/10 == n%10) return 1; if(len == 4 && n%100 == n/100) return 2; if(len == 6 && n%100 == n/10000 && n%100 == n/100%100) return 2; if(len == 6 && n%1000 == n/1000) return 3; return len; } public static int len(int n) { int len = 0; while(n > 0) { n /= 10; len++; } return len; } }" B12852,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; public class Main { public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new FileReader(""C-small-attempt0.in"")); PrintWriter bw = new PrintWriter(new FileWriter(""C-small-attempt0.out"")); int num = Integer.parseInt(br.readLine()); for (int i = 0; i < num; i++) { String[] content=br.readLine().split(""[ ]""); int start=Integer.parseInt(content[0]); int end=Integer.parseInt(content[1]); int count=0; for (int j = start; j list = new LinkedList(); String pair; for(int i = A; i <= B; i++) { digit = Integer.toString(i); len = digit.length(); if(len > 1 && !digit.endsWith(""0"")) { for(int j = 1; j <= len - 1; j++) { sb = new StringBuffer(); sb.append(digit.substring(len - j, len)); sb.append(digit.substring(0, len - j)); r = sb.toString(); if(r.charAt(0) != '0' && !r.equals(digit)) { d = Integer.valueOf(r); if(d >= A && d <= B) { if(i < d) pair = i + ""|"" + d; else pair = d + ""|"" + i; if(!list.contains(pair)) { list.add(pair); cnt++; } } } } } } System.out.println(""Case #"" + idx + "": "" + cnt); } public static void main(String[] args) { RecycledNumbers r = new RecycledNumbers(); r.solve(); } } " B10248,"import java.io.*; import java.util.*; import java.text.*; public class Main implements Runnable{ /** * @param args */ private StringTokenizer stReader; private BufferedReader bufReader; private PrintWriter out; public static void main(String[] args) { // TODO Auto-generated method stub (new Main()).run(); } @Override public void run() { // TODO Auto-generated method stub bufReader = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); stReader = null; Solves(); out.flush(); } public String ReadLine() { String result = null; try { result = bufReader.readLine(); } catch (IOException e) { } return result; } public String NextString(){ if (stReader == null || !stReader.hasMoreTokens()){ stReader = new StringTokenizer(ReadLine(),""\n\r ""); } return stReader.nextToken(); } public int NextInt(){ return Integer.parseInt(NextString()); } public long NextLong(){ return Long.parseLong(NextString()); } public double NextDouble(){ return Double.parseDouble(NextString()); } void Solves(){ int n = NextInt(); for(int i =0; i < n; i++){ out.print(""Case #"" +(i + 1) + "": ""); Solve(); out.println(); } out.flush(); } void Solve(){ int A = NextInt(); int B = NextInt(); int result = 0; TreeSet treeSet = new TreeSet(); for(int i = A; i <=B; i++){ if (i <= 10) continue; StringBuilder parse = new StringBuilder(String.valueOf(i)); treeSet.clear(); for(int j =0;j < parse.length(); j++){ int val = Shift(parse); if (val > i && val <= B && !treeSet.contains(val)) { result++; treeSet.add(val); } } treeSet.clear(); } out.print(result); } int Shift(StringBuilder parse){ char last = parse.charAt(parse.length()-1); parse = parse.deleteCharAt(parse.length()-1); parse = parse.insert(0, last); return Integer.valueOf(parse.toString()); } } " B12544,"package contest.googlejam; import java.io.File; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import contest.ContestProblem; import contest.Input; // http://code.google.com/codejam/africa_arabia/contests.html public class Qualifier2012 { public static void main(String[] args) { ContestProblem problem = codeJam2012_Qualification_C; File folder = new File(""C:\\Users\\Admin\\Desktop\\GoogleJam Tests\\2012\\Qualification Round\\""); File test = new File(folder, ""test.txt""); File small = new File(folder, ""C-small-attempt0.in""); File large = new File(folder, ""C-large.in""); // ContestProblem.runProblem(problem.setInputFile(test).calcOutputFromInput()); ContestProblem.runProblem(problem.setInputFile(small).calcOutputFromInput()); // ContestProblem.runProblem(problem.setInputFile(large).calcOutputFromInput()); } // Problem C. Recycled Numbers static ContestProblem codeJam2012_Qualification_C = new ContestProblem() { @Override public void parseInput(Input in, PrintWriter out) { int cases = in.readInt(); for (int caseNum = 1; caseNum <= cases; caseNum++) { List input = in.readStrList(); String strA = input.get(0); String strB = input.get(1); int a = Integer.parseInt(strA); int b = Integer.parseInt(strB); Set> distinctPairs = new HashSet<>(); for (int i = a; i <= b; i++) { Set recycledNums = new HashSet<>(); recycledNums.addAll(recycle(i)); for (Integer n : recycledNums) { for (Integer m : recycledNums) { if (n.toString().length() != m.toString().length()) continue; if (!(a <= n && n < m && m <= b)) continue; List pair = new ArrayList(); pair.add(n); pair.add(m); distinctPairs.add(pair); } } } /* * System.out.format(""%d -> %d%n"", a, b); for (List pair : distinctPairs) { * System.out.println(Arrays.toString(pair.toArray(new Integer[0]))); } */ out.print(String.format(""Case #%d: %s%n"", caseNum, distinctPairs.size())); } } Set recycle(int num) { String str = Integer.toString(num); Set dump = new HashSet<>(); for (int i = 0; i < str.length(); i++) { int r = Integer.parseInt(str.substring(i) + str.substring(0, i)); dump.add(r); } return dump; } }; // Problem B. Dancing With the Googlers static ContestProblem codeJam2012_Qualification_B = new ContestProblem() { final int maxDiff = 2; @Override public void parseInput(Input in, PrintWriter out) { int cases = in.readInt(); for (int caseNum = 1; caseNum <= cases; caseNum++) { List input = in.readIntList(); int numGooglers = input.get(0); int numSurprises = input.get(1); int p = input.get(2); List totalPoints = input.subList(3, 3 + numGooglers); int goodScore = 0; int onlySurprises = 0; for (Integer total : totalPoints) { int avg = total / 3; int normal = 0; int surprises = 0; for (int a = avg - maxDiff; a <= avg + maxDiff; a++) { for (int b = avg - maxDiff; b <= avg + maxDiff; b++) { for (int c = avg - maxDiff; c <= avg + maxDiff; c++) { if (a + b + c != total) { // System.out.format(""%d + %d + %d != %d%n"", a, b, c, total); continue; } int min = Math.min(Math.min(a, b), c); int max = Math.max(Math.max(a, b), c); if (min < 0) continue; if (max >= p) { int diff = max - min; if (diff == 2) { surprises++; System.out.format(""%d + %d + %d = %d (Surprise)%n"", a, b, c, total); } else if (diff == 0 || diff == 1) { normal++; System.out.format(""%d + %d + %d = %d%n"", a, b, c, total); } else { // System.out.format(""diff (%d + %d + %d) > %d%n"", a, b, c, maxDiff); } } else { // System.out.format(""max (%d + %d + %d) < %d%n"", a, b, c, p); } } } } if (normal == 0 && surprises > 0) { onlySurprises++; System.out.format("" %d is onlySurprise%n"", total); } else if (normal > 0) { goodScore++; } else { System.out.format("" %d failed%n"", total); } } System.out.format(""goodScores = %d%n"", goodScore); System.out.format(""onlySurprises = %d%n"", onlySurprises); System.out.format(""numSurprises = %d%n"", numSurprises); int maxPossible = goodScore; if (numSurprises > onlySurprises) { maxPossible += onlySurprises; } else { maxPossible += Math.min(numSurprises, onlySurprises); } out.print(String.format(""Case #%d: %s%n"", caseNum, maxPossible)); } } }; // Problem A. Speaking in Tongues static ContestProblem codeJam2012_Qualification_A = new ContestProblem() { Map charMap = new HashMap<>(); @Override public void parseInput(Input in, PrintWriter out) { charMap.put(' ', ' '); charMap.put('a', 'y'); charMap.put('b', 'h'); charMap.put('c', 'e'); charMap.put('d', 's'); charMap.put('e', 'o'); charMap.put('f', 'c'); charMap.put('g', 'v'); charMap.put('h', 'x'); charMap.put('i', 'd'); charMap.put('j', 'u'); charMap.put('k', 'i'); charMap.put('l', 'g'); charMap.put('m', 'l'); charMap.put('n', 'b'); charMap.put('o', 'k'); charMap.put('p', 'r'); charMap.put('q', 'z'); charMap.put('r', 't'); charMap.put('s', 'n'); charMap.put('t', 'w'); charMap.put('u', 'j'); charMap.put('v', 'p'); charMap.put('w', 'f'); charMap.put('x', 'm'); charMap.put('y', 'a'); charMap.put('z', 'q'); int cases = in.readInt(); for (int caseNum = 1; caseNum <= cases; caseNum++) { String input = in.readStr(); String output = """"; for (int i = 0; i < input.length(); i++) { output += charMap.get(input.charAt(i)); } out.print(String.format(""Case #%d: %s%n"", caseNum, output)); } } }; } " B12780,"package gcj2012.Pre; import java.util.*; public class C { static Scanner sc = new Scanner(System.in); public static void main(String[] f){ long numCases = Long.parseLong(sc.nextLine()); for(long kase = 0 ; kase < numCases ; kase++){ String[] ss = sc.nextLine().split("" ""); int a = Integer.parseInt(ss[0]); int b = Integer.parseInt(ss[1]); HashSet hs = new HashSet(); for(int i = a ; i <= b ; i++){ int first = i; String fs = """"+first; int len = ("""" + a).length(); for(int j = 1 ; j < len ; j++){ int second = Integer.parseInt(fs.substring(j) + fs.substring(0, j)); if(a <= second && second <= b && (""""+second).length() == len && first != second){ hs.add(new Pair(first, second)); } } } System.out.println(""Case #"" + (kase+1) + "": "" + hs.size()); } } /** * 4 1 9 10 40 100 500 1111 2222 Case #1: 0 Case #2: 3 Case #3: 156 Case #4: 287 */ public static class Pair{ public int first, second; public Pair(int f, int s){ if(f < s){ this.first = f; this.second = s; }else{ this.first = s; this.second = f; } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + first; result = prime * result + second; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (first != other.first) return false; if (second != other.second) return false; return true; } } } " B10713,"import java.util.*; public class Main{ static int power(int d) { if(d== 0) return 1; else if(d%2 == 0) { int a = power(d/2); return a*a; } else { int a = power(d/2); return a*a*10; } } public static void main(String [] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for(int cc = 1; cc<= T; cc++) { int A = in.nextInt(); int B = in.nextInt(); int Digit = Integer.toString(A).length(); int tab[] = new int[3000]; for(int i = 0; i<3000; i++) { tab[i] = -1; } for(int i = A; i= A && next <=B) { if(tab[next] == -1) { tab[next] =0; tab[i] ++; } } current = next; } } } int res = 0; for(int i = A; i= 0){ int pa = 0; int x = pb; while (a.charAt(pa++) == b.charAt(pb++)){ if (pb >= b.length()) pb = 0; if (pa >= a.length()){ achou = true; break; } } if (achou){ total++; break; } pb = b.indexOf(a.charAt(0), x+1); } } } bw.write(""Case #"" + i + "": "" + total + ""\n""); } br.close(); bw.close(); } } " B10081,"import java.io.*; import java.lang.*; class RotateNumber { public static long RotateNumber(long number, long A, long B) { long start = number; long sum = 0; int numdigits = (int) Math.log10((double)number); // would return numdigits - 1 int multiplier = (int) Math.pow(10.0, (double)numdigits); while(true) { long q = number / 10; long r = number % 10; number = number / 10; number = number + multiplier * r; if(number == start) break; if (start < A) break; if (start >= A && start < number && number <= B) { sum++; } } return sum; } public static void main(String[] args) throws IOException { FileInputStream fstream = new FileInputStream(""/tmp/codejam/A-small-practice.in""); //DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); PrintWriter out = new PrintWriter(new File(""/home/peeyushk/tmp/output.ou"")); String strLine; strLine = br.readLine().trim(); int test = Integer.parseInt(strLine); for (int i=0;i possibles = new HashSet(); String base = String.valueOf(n); for (int i=1; in && check<=limit) ++retVal; } return retVal; } } " B11728,"/* * SpeakingAboutBox.java */ package speaking; import org.jdesktop.application.Action; public class SpeakingAboutBox extends javax.swing.JDialog { public SpeakingAboutBox(java.awt.Frame parent) { super(parent); initComponents(); getRootPane().setDefaultButton(closeButton); } @Action public void closeAboutBox() { dispose(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // //GEN-BEGIN:initComponents private void initComponents() { closeButton = new javax.swing.JButton(); javax.swing.JLabel appTitleLabel = new javax.swing.JLabel(); javax.swing.JLabel versionLabel = new javax.swing.JLabel(); javax.swing.JLabel appVersionLabel = new javax.swing.JLabel(); javax.swing.JLabel vendorLabel = new javax.swing.JLabel(); javax.swing.JLabel appVendorLabel = new javax.swing.JLabel(); javax.swing.JLabel homepageLabel = new javax.swing.JLabel(); javax.swing.JLabel appHomepageLabel = new javax.swing.JLabel(); javax.swing.JLabel appDescLabel = new javax.swing.JLabel(); javax.swing.JLabel imageLabel = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(speaking.SpeakingApp.class).getContext().getResourceMap(SpeakingAboutBox.class); setTitle(resourceMap.getString(""title"")); // NOI18N setModal(true); setName(""aboutBox""); // NOI18N setResizable(false); javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(speaking.SpeakingApp.class).getContext().getActionMap(SpeakingAboutBox.class, this); closeButton.setAction(actionMap.get(""closeAboutBox"")); // NOI18N closeButton.setName(""closeButton""); // NOI18N appTitleLabel.setFont(appTitleLabel.getFont().deriveFont(appTitleLabel.getFont().getStyle() | java.awt.Font.BOLD, appTitleLabel.getFont().getSize()+4)); appTitleLabel.setText(resourceMap.getString(""Application.title"")); // NOI18N appTitleLabel.setName(""appTitleLabel""); // NOI18N versionLabel.setFont(versionLabel.getFont().deriveFont(versionLabel.getFont().getStyle() | java.awt.Font.BOLD)); versionLabel.setText(resourceMap.getString(""versionLabel.text"")); // NOI18N versionLabel.setName(""versionLabel""); // NOI18N appVersionLabel.setText(resourceMap.getString(""Application.version"")); // NOI18N appVersionLabel.setName(""appVersionLabel""); // NOI18N vendorLabel.setFont(vendorLabel.getFont().deriveFont(vendorLabel.getFont().getStyle() | java.awt.Font.BOLD)); vendorLabel.setText(resourceMap.getString(""vendorLabel.text"")); // NOI18N vendorLabel.setName(""vendorLabel""); // NOI18N appVendorLabel.setText(resourceMap.getString(""Application.vendor"")); // NOI18N appVendorLabel.setName(""appVendorLabel""); // NOI18N homepageLabel.setFont(homepageLabel.getFont().deriveFont(homepageLabel.getFont().getStyle() | java.awt.Font.BOLD)); homepageLabel.setText(resourceMap.getString(""homepageLabel.text"")); // NOI18N homepageLabel.setName(""homepageLabel""); // NOI18N appHomepageLabel.setText(resourceMap.getString(""Application.homepage"")); // NOI18N appHomepageLabel.setName(""appHomepageLabel""); // NOI18N appDescLabel.setText(resourceMap.getString(""appDescLabel.text"")); // NOI18N appDescLabel.setName(""appDescLabel""); // NOI18N imageLabel.setIcon(resourceMap.getIcon(""imageLabel.icon"")); // NOI18N imageLabel.setName(""imageLabel""); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(imageLabel) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(versionLabel) .addComponent(vendorLabel) .addComponent(homepageLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(appVersionLabel) .addComponent(appVendorLabel) .addComponent(appHomepageLabel))) .addComponent(appTitleLabel, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(appDescLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 266, Short.MAX_VALUE) .addComponent(closeButton)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(imageLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(appTitleLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(appDescLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(versionLabel) .addComponent(appVersionLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(vendorLabel) .addComponent(appVendorLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(homepageLabel) .addComponent(appHomepageLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 19, Short.MAX_VALUE) .addComponent(closeButton) .addContainerGap()) ); pack(); }// //GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton closeButton; // End of variables declaration//GEN-END:variables } " B12457," import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.Scanner; import java.util.Set; import com.google.common.collect.Sets; public class C { public static void main(String [] args) throws IOException { String inputFile = ""src/C-small-attempt0.in""; Scanner in = new Scanner(new File(inputFile)); PrintStream out = new PrintStream(inputFile.substring(0, inputFile.length()-2)+""out""); int cases = in.nextInt(); for (int c = 1; c <= cases; c++) { int a = in.nextInt(); int b = in.nextInt(); int count = 0; for (int i = a; i < b; i++) { String is = String.valueOf(i); Set matches = Sets.newHashSet(); for (int j = 1; j < is.length(); j++) { is = is.substring(1) + is.charAt(0); int t = Integer.parseInt(is); if (t > i && t <= b && !matches.contains(t)) { count++; matches.add(t); } } } out.print(""Case #""+c+"": "" + count); out.println(); } out.close(); } } " B10678,"import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; public class recycled_numbers { public static class Test { int a; int b; String a_str; String b_str; } public static boolean contains(ArrayList a,Tuple tuple) { boolean contain=false; for(int i=0;i array=new ArrayList(); Tuple tuple=new Tuple(); for(int j=test.a;j<=test.b;j++) { for(int i=1;i=test.a && number<=test.b && number>j) { tuple.a=j; tuple.b=number; boolean bool=contains(array,tuple); if(!bool) { Tuple temp=new Tuple(); temp.a=j; temp.b=number; recycle++; array.add(temp); } } } } return recycle; } public static void main(String[] args) throws FileNotFoundException { Scanner input=new Scanner(new File(""C-small-attempt0.in"")); input.nextLine(); int i=1; while(input.hasNextLine()) { System.out.print(""Case #"" + i + "": ""); Test test=getTest(input); int number=recycled(test); System.out.print(number + ""\n""); i++; } } } " B10692,"import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class recycle { public static void main(String args[]) throws IOException { Scanner s = new Scanner(new File(""D:\\workspace\\GC12\\src\\input2.txt"")); FileWriter fo = new FileWriter(new File(""D:\\workspace\\GC12\\src\\output2.txt"")); int number = s.nextInt(); for(int i = 1; i<= number; i++) { fo.write(""Case #"" + i + "": ""); int a = s.nextInt(); int b = s.nextInt(); Set aCounted = new HashSet(); for (int j = a;j<=b;j++) { StringBuffer n = new StringBuffer(String.valueOf(j)); for (int p = 0; p < n.length(); p++) { n.append(n.charAt(0)); n.deleteCharAt(0); if (j < Integer.parseInt(n.toString()) && Integer.parseInt(n.toString()) <= b) { aCounted.add(String.valueOf(j) + n.toString()); } } } fo.write(aCounted.size() + ""\n""); } fo.close(); s.close(); } } " B13036,"package qualification.q2; /** * Created by IntelliJ IDEA. * User: ofer * Date: 14/04/12 * Time: 18:47 * To change this template use File | Settings | File Templates. */ public class Q2Solver { public int solve(int n,int s,int p, int[] sums){ int res = 0; int surprisesLeft = s; for (int sum : sums){ int div = sum / 3; int mod = sum % 3; if (div >= p){ res++; } else if( p - div == 1){ if (div > 0 && mod == 0 && surprisesLeft > 0){ res++; surprisesLeft--; } else if (mod > 0){ res++; } } else if (p -div ==2 && mod == 2 && surprisesLeft > 0){ res++; surprisesLeft--; } } return res; } } " B12700,"package commons; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.LinkedList; import java.util.List; public class FileUtilities { public static void writeFile(List strings, File file) throws IOException { file.createNewFile(); FileWriter writer = new FileWriter(file); for (int i = 1; i <= strings.size(); i++) { writer.write(""Case #""); writer.write(i + "": ""); writer.write(strings.get(i-1)); writer.write(""\n""); } writer.close(); } public static List readFile(File file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(file)); String input = reader.readLine(); List result = new LinkedList(); while (!(input == null)) { result.add(input); input = reader.readLine(); } reader.close(); return result; } } " B12950,"package google.problems; import google.loader.Challenge; public abstract class AbstractChallenge implements Challenge{ private final int problemNumber; private String result; public AbstractChallenge(int i) { this.problemNumber = i; } protected void setResult(String result){ this.result = result; } @Override public String getResult() { return ""Case #""+problemNumber+"": ""+result+""\n""; } protected int getInt(int pos, String[] tokens) { return Integer.parseInt(tokens[pos]); } } " B11597,"import java.util.*; public class C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int cases = sc.nextInt(); for(int ctr=0; ctr set = new HashSet(); for(int n=start; n<=end; n++){ String s = Integer.toString(n); for(int i=1; i= min && theorem < posit) { return false; } } return true; } public static int getNumberOfPairs(int posit, int min, int max, int length) { Set seen = new HashSet(); String doubledIn = posit + """" + posit; int counted = 0; for (int j = 0; j= min && theorem <= max && !seen.contains(subSequence)) { seen.add(subSequence); counted += 1; } } if (counted == 1) { return 0; } if (counted == 2) { return 1; } if (counted == 3) { return 3; } if (counted == 4) { return 6; } if (counted == 5) { return 10; } if (counted == 6) { return 15; } if (counted == 7) { return 21; } return counted*(counted-1)/2; } } " B12754,"package com.dagova.recycledNumbers; import java.util.TreeSet; public class RecycledNumbersSolver { private static int solution; private static int aNumber; private static int bNumber; public static int solve(String line) { solution = 0; String[] splittedLine = line.split("" ""); aNumber = Integer.parseInt(splittedLine[0]); bNumber = Integer.parseInt(splittedLine[1]); for(int number = aNumber; number < bNumber-1; number++) { solution += solveNumber(number); } return solution; } public static int solveNumber(int number) { // con el treeset evita que un n de varias veces el mismo m. Antes usaba el contador recycledNumbers y por eso fallaba. TreeSet ms = new TreeSet(); // int recycledNumbers = 0; String numberAsString = Integer.toString(number); int numberLength = numberAsString.length(); for(int charIterator = 1; charIterator < numberLength; charIterator++) { if(numberAsString.charAt(charIterator) >= numberAsString.charAt(0)) { int recycledNumber = generateRecycledNumber(numberAsString, charIterator); if(recycledNumber <= bNumber && recycledNumber > number) { ms.add(recycledNumber); // recycledNumbers++; } } } return ms.size(); // return recycledNumbers; } public static int generateRecycledNumber(String numberAsString, int charIterator) { String prefix = numberAsString.substring(0, charIterator); String sufix = numberAsString.substring(charIterator); return Integer.parseInt(sufix.concat(prefix)); } } " B12883,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.LinkedList; import java.util.Scanner; class MyPair { public int one = 0; public int two = 0; }; public class ProblemC { public static boolean has(int one, int two, LinkedList list) { for (int i = 0; i < list.size(); i += 1) { MyPair p = list.get(i); if (p.one == one && p.two == two) return true; } return false; } public static void add(int one, int two, LinkedList list) { MyPair p = new MyPair(); p.one = one; p.two = two; list.add(p); } public static LinkedList strswp(int b) { String str = b+""""; LinkedList q = new LinkedList(); LinkedList ch = new LinkedList(); for(int i = 0 ; i < str.length() ; i+=1) { ch.add(str.charAt(i)) ; } for(int i = 0 ; i < str.length()-1 ; i+=1) { String kp = """"; ch.addFirst(ch.pollLast()); for(int j = 0 ; j < ch.size() ; j++) { kp += ch.get(j); } if(kp.charAt(0) != '0' && !kp.equals(str)) { q.add(kp); } } return q; } public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(new File(""C:\\C-small-attempt1.in"")); //Scanner sc = new Scanner(new File(""C:\\toy.txt"")); PrintWriter pw = new PrintWriter(new File(""C:\\out"")); int nl = Integer.parseInt(sc.next()); for(int n = 0 ; n < nl ; n+=1) { int a = Integer.parseInt(sc.next()); int b = Integer.parseInt(sc.next()); int cnt = 0 ; LinkedList listcmp = new LinkedList(); LinkedList mem = new LinkedList(); for(int i = a ; i <= b ; i+=1) { listcmp = strswp(i); for(int j = 0 ; j < listcmp.size() ; j+=1) { int c = Integer.parseInt(listcmp.get(j)); boolean hasss = i < c ? has(i, c, mem) : has(c, i, mem); if(c >= a && c<=b && i >= a && i <= b && !hasss) { cnt ++; //System.out.println("" a = "" + i + "", b = "" + c); if(iA; j--) { for(int k=A; k set = new HashSet(); int result = 0; String num = (n + """"); for (int i = 1; i < num.length(); i++) { String part1 = """"; String part2 = """"; part1 = num.substring(0, i); part2 = num.substring(i, num.length()); int temp = Integer.parseInt(part2 + part1); if (n < temp && temp <= b && !set.contains(temp)) { set.add(temp); result++; } } return result; } } " B13223,"package qualification.c; import java.awt.Point; import java.io.File; import java.io.FileNotFoundException; import java.util.Comparator; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class Core { public static void main(String[] args) { int t, a, b; try { Scanner scan = new Scanner(new File(args[0])); t = scan.nextInt(); for (int i = 1; i <= t; i++) { a = scan.nextInt(); b = scan.nextInt(); System.out.println(solve(i, a, b)); } } catch (FileNotFoundException e) { e.printStackTrace(); } } public static String solve(int caseNumber, int a, int b) { a = Math.max(10, a); if ((b < 12) || (b <= a)) return ""Case #"" + caseNumber + "": 0""; int rev; String s; Set set = new TreeSet(new Comparator() { @Override public int compare(Point p1, Point p2) { if (p1.x != p2.x) return p1.x - p2.x; return p1.y - p2.y; } }); for (int i = a; i <= b; i++) { s = String.valueOf(i); for (int j = 0; j < s.length(); j++) { rev = Integer.valueOf(s.substring(j) + s.substring(0, j)); if ((rev > b) || (rev <= i) || (String.valueOf(rev).length() != s.length())) continue; set.add(new Point(i, rev)); } } return ""Case #"" + caseNumber + "": "" + set.size(); } /* * public static String solve(int caseNumber, int a, int b) { * if (b < 12) * return ""Case #"" + caseNumber + "": 0""; * * a = Math.max(10, a); * * int n = 0; * String s, bStr; * bStr = String.valueOf(b); * char f; * int check; * for (int i = a; i <= b; i++) { * s = String.valueOf(i); * System.out.println(""STR: "" + s); * f = s.charAt(0); * for (int j = 1; j < s.length(); j++) { * if ((s.charAt(j) < f) || (s.charAt(j) > bStr.charAt(0))) * continue; * * check = 0; * if (s.charAt(j) == f) { * while (((j + check) < s.length()) && (s.charAt(j + check) == f)) * check++; * if ((j + check) == s.length()) { * if (i == 449) * System.out.println(j + "" : "" + check + "" : "" + s.length()); * continue; * } * } * * check = 0; * if (Integer.valueOf("""" + s.charAt(j)) <= Integer.valueOf("""" * + bStr.charAt(0))) { * while (((j + check) < s.length()) * && (Integer.valueOf("""" + s.charAt(j + check)) <= Integer * .valueOf("""" + bStr.charAt(check)))) * check++; * * if ((j + check) != (s.length())) * continue; * } * * System.out.println(s + "" : "" + s.substring(j) + s.substring(0, j)); * n++; * } * } * * return ""Case #"" + caseNumber + "": "" + n; * } */ }" B11355,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { long totalCases = 0; /** * @param args */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub new RecycledNumbers().solve(); } public void solve() throws Exception { BufferedReader br = null; PrintWriter pw = null; try { br = new BufferedReader(new FileReader(""smallinput2.txt"")); pw = new PrintWriter(new FileWriter(""smalloutput2.txt"")); String str = """"; if ((str = br.readLine()) != null) { System.out.println(str); totalCases = Integer.parseInt(str); System.out.println(""Total cases:"" + totalCases); } for (int ctr=1;ctr<=totalCases;ctr++) { str = br.readLine(); System.out.println(""Input string:"" + str); String[] strArr = str.split("" ""); String str1 = strArr[0]; String str2 = strArr[1]; long num1 = Long.parseLong(str1); long num2 = Long.parseLong(str2); int len = str1.length(); int totalCount = 0; Set numSet = new HashSet(); for (long l1 = num1; l1 < num2; l1++) { String str3 = new Long(l1).toString(); for (long l2 = l1+1; l2 <= num2; l2++) { String str4 = new Long(l2).toString(); //System.out.println(""Matching "" + str3 + "","" + str4); if (len == 2) { String originalString = str3.substring(0,1)+str3.substring(1,2); String recycledString = str4.substring(1,2)+str4.substring(0,1); //System.out.println(""recycledString:"" + recycledString); if (recycledString.equals(originalString)) { //System.out.println(""OriginalString:"" + str3 + "",MatchingString:"" + str4); numSet.add(str3+str4); } } if (len == 3) { String originalString = str3.substring(0,1)+str3.substring(1,2)+str3.substring(2,3); String recycledString = str4.substring(2,3)+str4.substring(0,1)+str4.substring(1,2); //System.out.println(""recycledString:"" + recycledString); if (recycledString.equals(originalString)) { //System.out.println(""OriginalString:"" + str3 + "",MatchingString:"" + str4); numSet.add(str3+str4); } recycledString = str4.substring(1,2)+str4.substring(2,3)+str4.substring(0,1); if (recycledString.equals(originalString)) { //System.out.println(""OriginalString:"" + str3 + "",MatchingString:"" + str4); numSet.add(str3+str4); } } if (len == 4) { String originalString = str3.substring(0,1)+str3.substring(1,2)+str3.substring(2,3)+str3.substring(3,4); String recycledString = str4.substring(3,4)+str4.substring(0,1)+str4.substring(1,2)+str4.substring(2,3); //System.out.println(""recycledString:"" + recycledString); if (recycledString.equals(originalString)) { //System.out.println(""OriginalString:"" + str3 + "",MatchingString:"" + str4); numSet.add(str3+str4); } recycledString = str4.substring(2,3)+str4.substring(3,4)+str4.substring(0,1)+str4.substring(1,2); if (recycledString.equals(originalString)) { //System.out.println(""OriginalString:"" + str3 + "",MatchingString:"" + str4); numSet.add(str3+str4); } recycledString = str4.substring(1,2)+str4.substring(2,3)+str4.substring(3,4)+str4.substring(0,1); if (recycledString.equals(originalString)) { //System.out.println(""OriginalString:"" + str3 + "",MatchingString:"" + str4); numSet.add(str3+str4); } } if (len == 5) { String originalString = str3.substring(0,1)+str3.substring(1,2)+str3.substring(2,3)+str3.substring(3,4)+ str3.substring(4,5); String recycledString = str4.substring(4,5)+str4.substring(0,1)+str4.substring(1,2)+str4.substring(2,3)+ str4.substring(3,4); //System.out.println(""recycledString:"" + recycledString); if (recycledString.equals(originalString)) { //System.out.println(""OriginalString:"" + str3 + "",MatchingString:"" + str4); numSet.add(str3+str4); } recycledString = str4.substring(3,4)+str4.substring(4,5)+str4.substring(0,1)+str4.substring(1,2)+ str4.substring(2,3); if (recycledString.equals(originalString)) { //System.out.println(""OriginalString:"" + str3 + "",MatchingString:"" + str4); numSet.add(str3+str4); } recycledString = str4.substring(2,3)+str4.substring(3,4)+str4.substring(4,5)+str4.substring(0,1)+ str4.substring(1,2); if (recycledString.equals(originalString)) { //System.out.println(""OriginalString:"" + str3 + "",MatchingString:"" + str4); numSet.add(str3+str4); } recycledString = str4.substring(1,2)+str4.substring(2,3)+str4.substring(3,4)+str4.substring(4,5)+ str4.substring(0,1); if (recycledString.equals(originalString)) { //System.out.println(""OriginalString:"" + str3 + "",MatchingString:"" + str4); numSet.add(str3+str4); } } if (len == 6) { String originalString = str3.substring(0,1)+str3.substring(1,2)+str3.substring(2,3)+str3.substring(3,4)+ str3.substring(4,5)+str3.substring(5,6); String recycledString = str4.substring(5,6)+str4.substring(0,1)+str4.substring(1,2)+str4.substring(2,3)+ str4.substring(3,4)+str4.substring(4,5); //System.out.println(""recycledString:"" + recycledString); if (recycledString.equals(originalString)) { //System.out.println(""OriginalString:"" + str3 + "",MatchingString:"" + str4); numSet.add(str3+str4); } recycledString = str4.substring(4,5)+str4.substring(5,6)+str4.substring(0,1)+str4.substring(1,2)+ str4.substring(2,3)+str4.substring(3,4); if (recycledString.equals(originalString)) { //System.out.println(""OriginalString:"" + str3 + "",MatchingString:"" + str4); numSet.add(str3+str4); } recycledString = str4.substring(3,4)+str4.substring(4,5)+str4.substring(5,6)+str4.substring(0,1)+ str4.substring(1,2)+str4.substring(2,3); if (recycledString.equals(originalString)) { //System.out.println(""OriginalString:"" + str3 + "",MatchingString:"" + str4); numSet.add(str3+str4); } recycledString = str4.substring(2,3)+str4.substring(3,4)+str4.substring(4,5)+str4.substring(5,6)+ str4.substring(0,1)+str4.substring(1,2); if (recycledString.equals(originalString)) { //System.out.println(""OriginalString:"" + str3 + "",MatchingString:"" + str4); numSet.add(str3+str4); } recycledString = str4.substring(1,2)+str4.substring(2,3)+str4.substring(3,4)+str4.substring(4,5)+ str4.substring(5,6)+str4.substring(0,1); if (recycledString.equals(originalString)) { //System.out.println(""OriginalString:"" + str3 + "",MatchingString:"" + str4); numSet.add(str3+str4); } } if (len == 7) { String originalString = str3.substring(0,1)+str3.substring(1,2)+str3.substring(2,3)+str3.substring(3,4)+ str3.substring(4,5)+str3.substring(5,6)+str3.substring(6,7); String recycledString = str4.substring(6,7)+str4.substring(0,1)+str4.substring(1,2)+str4.substring(2,3)+ str4.substring(3,4)+str4.substring(4,5)+str4.substring(5,6); //System.out.println(""recycledString:"" + recycledString); if (recycledString.equals(originalString)) { //System.out.println(""OriginalString:"" + str3 + "",MatchingString:"" + str4); numSet.add(str3+str4); } recycledString = str4.substring(5,6)+str4.substring(6,7)+str4.substring(0,1)+str4.substring(1,2)+ str4.substring(2,3)+str4.substring(3,4)+str4.substring(4,5); if (recycledString.equals(originalString)) { //System.out.println(""OriginalString:"" + str3 + "",MatchingString:"" + str4); numSet.add(str3+str4); } recycledString = str4.substring(4,5)+str4.substring(5,6)+str4.substring(6,7)+str4.substring(0,1)+ str4.substring(1,2)+str4.substring(2,3)+str4.substring(3,4); if (recycledString.equals(originalString)) { //System.out.println(""OriginalString:"" + str3 + "",MatchingString:"" + str4); numSet.add(str3+str4); } recycledString = str4.substring(3,4)+str4.substring(4,5)+str4.substring(5,6)+str4.substring(6,7)+ str4.substring(0,1)+str4.substring(1,2)+str4.substring(2,3); if (recycledString.equals(originalString)) { //System.out.println(""OriginalString:"" + str3 + "",MatchingString:"" + str4); numSet.add(str3+str4); } recycledString = str4.substring(2,3)+str4.substring(3,4)+str4.substring(4,5)+str4.substring(5,6)+ str4.substring(6,7)+str4.substring(0,1)+str4.substring(1,2); if (recycledString.equals(originalString)) { //System.out.println(""OriginalString:"" + str3 + "",MatchingString:"" + str4); numSet.add(str3+str4); } recycledString = str4.substring(1,2)+str4.substring(2,3)+str4.substring(3,4)+str4.substring(4,5)+ str4.substring(5,6)+str4.substring(6,7)+str4.substring(0,1); if (recycledString.equals(originalString)) { //System.out.println(""OriginalString:"" + str3 + "",MatchingString:"" + str4); numSet.add(str3+str4); } } } } System.out.println(""TotalCount:"" + numSet.size()); pw.print(""Case #"" + (ctr) + "": "" + numSet.size() + ""\n""); } } catch (Exception e) { e.printStackTrace(); } finally { br.close(); pw.close(); } } } " B10333,"package codejam.qual2012; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.HashSet; import java.util.Set; public class C { public int count(int start, int end) { int count = 0; for (int i = start; i <= end; i++) { String a = Integer.toString(i); Set unique = new HashSet(); String b = a; for (int j = 0; j < a.length() - 1; j++) { b = b.substring(a.length() - 1, a.length()) + b.substring(0, a.length() - 1); if (unique.contains(b)) { continue; } else { unique.add(b); } // System.out.println(b); int bi = Integer.parseInt(b); if (bi > i && bi <= end) { // System.out.println(a + "": "" + b); count++; } } } return count; } public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintStream out = new PrintStream(new BufferedOutputStream(System.out)); String line = in.readLine(); int testCases = Integer.parseInt(line); C c = new C(); // Read in all test cases for (int testCase = 1; testCase <= testCases; testCase++) { line = in.readLine(); String[] data = line.split("" ""); int start = Integer.parseInt(data[0]); int end = Integer.parseInt(data[1]); out.println(""Case #"" + testCase + "": "" + c.count(start, end)); } out.flush(); } } " B11165,"import java.util.*; import java.lang.*; import java.io.*; class recycle { public static void main(String args[]) { try { PrintWriter pw=new PrintWriter(""out.txt""); //creating file reader instance and reading first line BufferedReader br=new BufferedReader(new FileReader(args[0])); String line=br.readLine(); int T=Integer.parseInt(line); //number of test cases T //------------------------- //processing each test case for(int i=0;in && m<=B) { result++; // System.out.println(""valid""); } ++ilen; } } // System.out.println(""Case #""+(i+1)+"": "" + result); pw.println(""Case #""+(i+1)+"": "" + result); /*------------------------**/ } br.close(); pw.close(); }//end of try catch(Exception e) { System.out.println(""Exception caught: ""+e); } } }" B11960,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class RecycledNumbers { private static int noOfDigits(int n){ if (n < 10) return 1; return 1 + noOfDigits(n/10); } private static int raisedTo(int n, int m){ if (n==0) return 0; else if (m==0) return 1; else if (m==1) return n; return n*raisedTo(n, m-1); } private static int rotateBy(int n, int s, int nod){ if (s == 0) return n; int N = noOfDigits(n); int pow = raisedTo(10, nod-1); int MSB = (N==nod)? n/pow: 0; return rotateBy((n%pow)*10+MSB, s-1, nod); } private static int[] giveDistinctNos(int n, int min, int max){ int s = 0, r = n, j=0; int N = noOfDigits(r); int A[] = new int[N]; for (int i=0; imax || N != noOfDigits(r)) r = rotateBy(r, 1, N); } return A; } private static int nC2(int n){ return n*(n-1)/2; } public static void main(String[] args) throws NumberFormatException, IOException { // for (int i=0; i< 2000000; i++); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int T = new Integer(in.readLine()).intValue(); int A = 0, B = 0, ans = 0; String str[]; int X[]; for (int i=0; i current && tempNo <= B) { ++count; } } return count; } } " B10364,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package example2; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class recycle{ public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int nocases = Integer.parseInt(br.readLine()); long ans[] = new long[nocases]; for (int i = 0; i < nocases; i++) { String token[] = br.readLine().split("" ""); long A = Integer.parseInt(token[0]); long B = Integer.parseInt(token[1]); ans[i] = method(A, B); } for (int i = 0; i < nocases; i++) { System.out.println(""Case #"" + (i + 1) + "": "" + ans[i]); } } private static int circularshift(char[] c, long n, long B) { int i = 0; long m = 0, m1 = 0; int ct = 0; int len = c.length; for (int k = 0; k < len; k++) { char temp = c[0]; for (i = 1; i < len; i++) { c[i - 1] = c[i]; } c[i - 1] = temp; String s = String.valueOf(c); m = Integer.parseInt(s); if (m <= B) { if (m1 != m) { if (n < m) { ct++; m1 = m; } } } } return ct; } private static long method(long A, long B) { long count = 0; for (long i = A; i <= B; i++) { long n = i; int ct = 0; String s = String.valueOf(n); char c1[] = s.toCharArray(); ct = circularshift(c1, n, B); count = count + (long) ct; } return count; } } " B10413,"package com.google.codjam.utils; import java.util.ArrayList; public class FileDataAndSettings { private Integer nCases; private ArrayList inputCase; private String tokenSep; public FileDataAndSettings() { inputCase = new ArrayList(0); } public void setNCases(Integer nCases) { this.nCases = nCases; } public Integer getNCases() { return nCases; } public void setInputCase(ArrayList inputCase) { this.inputCase = inputCase; } public ArrayList getInputCase() { return inputCase; } public void setTokenSep(String tokenSep) { this.tokenSep = tokenSep; } public String getTokenSep() { return tokenSep; } } " B11251,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; public class RecycledNumbers { private static int T; private static ArrayList lowerLimit, upperLimit; private static ArrayList numOfPairs; public static void main(String[] args) { readInputFile (); getNumberOfRecycledPairs (); writeOutputFile (); } private static void readInputFile () { numOfPairs = new ArrayList (); lowerLimit = new ArrayList (); upperLimit = new ArrayList (); String line = """"; try { BufferedReader bufferedReader = new BufferedReader (new InputStreamReader (new FileInputStream (""input/C-small-attempt0.in""))); line = bufferedReader.readLine (); T = Integer.parseInt (line); while ((line = bufferedReader.readLine ()) != null) { String [] dataSet = line.split ("" ""); lowerLimit.add (Integer.parseInt (dataSet [0])); upperLimit.add (Integer.parseInt (dataSet [1])); } System.out.println (lowerLimit + ""\n"" + upperLimit); bufferedReader.close (); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private static void getNumberOfRecycledPairs () { for (int i = 0; i < T; i++) { int numOfValidPairs = 0; for (int j = lowerLimit.get (i); j < upperLimit.get (i); j++) { int numOfDigits = String.valueOf (j).length (); //int num = j; for (int k = 1; k < numOfDigits; k++) { //num = ((num % (int)Math.pow (10, numOfDigits - 1)) * 10 + // (num / (int)Math.pow (10, numOfDigits - 1))); int num = ((j % (int)Math.pow (10, k)) * (int)Math.pow (10, numOfDigits - k)) + (j / (int)Math.pow (10, k)); //if (num / (int)Math.pow (10, numOfDigits - 1) > 0) { if (String.valueOf (num).length() == String.valueOf (j).length()) { if (j < num && num <= upperLimit.get (i)) { numOfValidPairs++; } } } } numOfPairs.add (numOfValidPairs); } } private static void writeOutputFile () { try { BufferedWriter bufferedWriter = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (""output/output.out""))); for (int i = 0; i < numOfPairs.size (); i++) { bufferedWriter.write (""Case #"" + (i + 1) + "": "" + numOfPairs.get (i) + ""\n""); } bufferedWriter.close (); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } " B11193,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package problem.c; import java.util.Scanner; import java.io.*; /** * * @author Jason */ public class ProblemC { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Scanner input = new Scanner(System.in); System.out.println(""Enter name of input file: ""); File inputFile = new File(input.next()); File outputFile = new File(""output.txt""); Scanner file = null; PrintWriter output = null; while(file == null) { try{ file = new Scanner(inputFile); output = new PrintWriter(outputFile); } catch(Exception E){ System.out.println(""invalid file""); } } int cases = file.nextInt(); file.nextLine(); for (int i = 0; i < cases;) { int pairs = 0; int A = file.nextInt(); int B = file.nextInt(); for(;A < B;A++) { int[] newA = null; if (A>999999) newA = new int[7]; else if (A>99999) newA = new int[6]; else if (A>9999) newA = new int[5]; else if (A>999) newA = new int[4]; else if (A>99) newA = new int[3]; else if (A>9) newA = new int[2]; else newA = new int[1]; int tempA = A; for(int j = newA.length-1; j >= 0;j--) { newA[j] = tempA % 10; tempA = tempA / 10; } int[] savedFound = {0, 0, 0, 0, 0, 0}; int foundIterator = 0; for(int j = 0; j < newA.length-1; j++) { int temp = newA[newA.length-1]; for(int k = 0; k < newA.length; k++) { int temp2 = newA[k]; newA[k] = temp; temp = temp2; } temp = 0; for(int k = newA.length-1, tens = 1; k >= 0;k--,tens*=10) { temp += newA[k]*tens; } if (temp > A && temp <= B && temp != savedFound[0] && temp != savedFound[1] && temp != savedFound[2] && temp != savedFound[3] && temp != savedFound[4] && temp != savedFound[5] ) { pairs++; savedFound[foundIterator++] = temp; } } } output.println(""Case #"" + ++i + "": "" + pairs); } output.close(); } }" B11420,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.HashSet; public class qualC { public static void main(String[] args) { String prblm=""C""; boolean fl=!true; String filein=prblm+""-""+((fl)?""large"":""small"")+"".in.txt""; String fileout=prblm+""-""+((fl)?""large"":""small"")+"".out.txt""; try { BufferedReader fr= new BufferedReader(new FileReader(filein)); BufferedWriter fw= new BufferedWriter(new FileWriter(fileout)); String s=fr.readLine(); int n=Integer.parseInt(s); HashSet hs=new HashSet(); for (int i = 1; i <= n; i++) { s=fr.readLine(); String[] tok=s.split("" ""); int A=Integer.parseInt(tok[0]); int B=Integer.parseInt(tok[1]); int nd=1; int msk=1; for (int t=A/10; t > 0; t/=10) { nd++; msk*=10; } int nrn=0; for (int j = A; j <= B; j++) { hs.clear(); int d=10; int res=msk; while (res>0) { int nj=(j%d)*res+j/d; if (nj>j && nj<=B && !hs.contains(nj)) { nrn++; hs.add(nj); } d*=10; res/=10; } } System.out.println(nrn); fw.write(""Case #""+i+"": ""+ nrn +""\n""); } fr.close(); fw.close(); } catch (Exception e) { e.printStackTrace(); } } } " B11142,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.util.ArrayList; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; /** * Google Code Jam 2012 * Qualifier Round * Problem C * * @author Brian Crockford */ public class GCJ20120C { public static final String inputFilename = ""C-small-attempt0.in""; static class LongPair { final long[] data = new long[2]; public LongPair(long x, long y) { set(x, y); } public long getX() { return data[0]; } public long getY() { return data[1]; } public void set(long x, long y) { data[0] = Math.min(x,y); data[1] = Math.max(x,y); } @Override public boolean equals(Object o) { LongPair p = (LongPair) o; if (null != p) { return (data[0] == p.getX() && data[1] == p.getY()) || (data[1] == p.getY() && data[0] == p.getX()); } return false; } @Override public int hashCode() { long hash = 1; hash = hash * 31 + data[0]; hash = hash * 31 + data[1]; return (int) hash; } } static class DataSet { private static HashSet pairs; static { pairs = new HashSet(500000); } public long begin, end; @Override public String toString() { return new StringBuilder(""<$DataSet: "").append(begin).append("", "").append(end).append("">"").toString(); } public long countRecycles() { int digits = countDigits(begin); for (long i=begin; i<=end; ++i) { for (int j=1; j= begin && result <= end) pairs.add(new LongPair(i, result)); } } long result = pairs.size(); pairs.clear(); return result; } public static DataSet parse(String s) { DataSet result = new DataSet(); result.begin = Long.parseLong(s.substring(0, s.indexOf(' '))); result.end = Long.parseLong(s.substring(1+s.indexOf(' '))); return result; } } public static Reader getFileReader(String filename) { BufferedReader result = null; try { result = new BufferedReader(new FileReader(filename)); } catch (FileNotFoundException e) { System.err.println(""Couldn't find the file \""""+filename+""\""""); e.printStackTrace(); } return result; } public static String readLine(BufferedReader reader) { try { return reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } public static void closeReader(Reader r) { try { r.close(); } catch (IOException e) { e.printStackTrace(); } } public static Writer getFileWriter(String filename) { BufferedWriter result = null; try { result = new BufferedWriter(new FileWriter(filename)); } catch (IOException e) { e.printStackTrace(); } return result; } public static void writeLine(BufferedWriter writer, String line) { try { writer.write(line); writer.newLine(); } catch (IOException e) { e.printStackTrace(); } } public static void closeWriter(Writer w) { try { w.close(); } catch (IOException e) { e.printStackTrace(); } } public static String formatCase(int caseNumber, long result) { return new StringBuilder(""Case #"").append(caseNumber).append("": "").append(result).toString(); } public static int countDigits(long n) { return (int) 1 + (int)Math.floor(Math.log10(n)); } public static int getDigit(long n, int digit) { return(int)(n/(long)Math.pow(10, digit-1)) % 10; } public static long shiftLong(long n, int digits) { long mask = (long) Math.pow(10, digits); long upshift = (long) Math.pow(10, (countDigits(n)-digits)); return (upshift*(n%mask)) + (n/mask); } public static void main(String[] args) { BufferedReader in = (BufferedReader) getFileReader(inputFilename); int lineCount = Integer.parseInt(readLine(in)); List dataSets = new ArrayList(); for (int i=0; i { public Problem3OutputFileWriter(File outputFile) { super(outputFile); } } " B12361,"package qualification; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.Map.Entry; public class RecycledNumbers { private static final String PATH = ""D:\\EclipseWorkspace\\GoogleCodeJam\\inout_file2012\\qualification""; private static final String IN_FILE = ""C-small-attempt0.in""; private static final String OUT_FILE = ""A-large.out""; private BufferedReader br = null; private BufferedWriter bw = null; private void init() throws Exception { br = new BufferedReader(new FileReader(PATH + ""\\"" + IN_FILE)); bw = new BufferedWriter(new FileWriter(PATH + ""\\"" + OUT_FILE)); } private void end() throws Exception { br.close(); bw.close(); } private void execute() throws Exception { int t = 0; int n = 0; String line = null; int first = 0; int last = 0; // Read line t = Integer.parseInt(br.readLine()); // t = 1; for (int i = 0; i < t; ++i){ // Read line line = br.readLine(); first = Integer.parseInt( line.split("" "")[0] ); last = Integer.parseInt( line.split("" "")[1] ); // test = ""4 O 2 B 1 B 2 O 4""; // test = ""3 O 5 O 8 B 100""; // test = ""2 B 2 B 1""; // Write to file // bw.write(""Case #""+(i+1)+"": "" + timeSpent); // bw.newLine(); System.out.println(""Case #""+(i+1)+"": "" + countRecycledNo(first, last) ); } } private int countRecycledNo(int first, int last) { String number = null; String newNumber = null; int count = 0; List list = new ArrayList(); for (int i = first; i <= last; ++i) { number = Integer.toString(i); for (int j = 1; j < number.length(); ++j){ newNumber = number.substring(j) + number.substring(0, j); int newNo = Integer.parseInt(newNumber); if ( newNo > i && newNo <= last && !list.contains(newNo)) { // System.out.println( ""("" + i + "", "" + newNo + "")""); list.add(newNo); count++; } } list.clear(); } return count; } public static void main(String[] args) { RecycledNumbers instance = new RecycledNumbers(); try { instance.init(); instance.execute(); instance.end(); } catch (Exception e) { e.printStackTrace(); } } } " B11085,"package fixjava; /** Adapted from http://www.johndcook.com/standard_deviation.html */ public class RunningStats { int n = 0; double oldM, newM, oldS, newS, min, max; public void clear() { n = 0; } public void add(double x) { n++; // See Knuth TAOCP vol 2, 3rd edition, page 232 if (n == 1) { oldM = newM = min = max = x; oldS = 0.0; } else { newM = oldM + (x - oldM) / n; newS = oldS + (x - oldM) * (x - newM); min = Math.min(min, x); max = Math.max(max, x); // set up for next iteration oldM = newM; oldS = newS; } } public int numValues() { return n; } public double mean() { return (n > 0) ? newM : 0.0; } public double variance() { return ((n > 1) ? newS / (n - 1) : 0.0); } public double stdDev() { return Math.sqrt(variance()); } public double min() { return (n > 0) ? min : 0.0; } public double max() { return (n > 0) ? max : 0.0; } } " B11885,"import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; public class QualCRecycledNumbers { static boolean debug = false; static int MIN = 1, MAX = 2500; //static int MIN = 1, MAX = 2000000; static void print(String str) { if (debug) System.out.print(str); } static void println(String str) { if (debug) System.out.println(str); } static void println(int str) { if (debug) System.out.println(str); } static void println() { if (debug) System.out.println(); } public static void main(String[] args) { Utils.openInFile(""C-small-attempt0.in""); Utils.openOutFile(""out.txt"", debug); String input = Utils.readFromFile(); int lineCount = Integer.parseInt(input); HashMap> recyclable = new HashMap>(); HashSet cleared = new HashSet(MAX); for (int i = MIN; i < MAX; i++) { if (i % 100000 == 0) System.out.println(i); if (cleared.contains(i)) continue; int newVal = i; String iStr = """"+i; ArrayList array = new ArrayList(); print(""i=""+i+"": ""); do { String numStr = """"+newVal; while (numStr.length() < iStr.length()) numStr = ""0""+numStr; numStr = numStr.charAt(numStr.length()-1) + numStr.substring(0, numStr.length()-1); newVal = Integer.parseInt(numStr); if ((""""+newVal).length() < iStr.length()) continue; cleared.add(newVal); print(newVal + "" ""); array.add(newVal); // adds itself at the end } while (newVal != i); println(); if (!array.isEmpty()) { Collections.sort(array); recyclable.put(i, array); } } for (int line = 1; line <= lineCount; line++) { println(); input = Utils.readFromFile(); String[] split = input.split("" ""); int AMin = Integer.parseInt(split[0]), BMax = Integer.parseInt(split[1]); ArrayList array; int count = 0; for (int i = 0; i <= BMax; i++) { if ((array = recyclable.get(i)) != null) { // min is implicitly enforced from structure int tempcount = 0; int stop = array.size(), start = array.size(); for (int k = 0; k < array.size(); k++) { if (start == array.size() && array.get(k) >= AMin) start = k; if(array.get(k) > BMax) { stop = k; break; } } if (stop == 1) continue; int diff = stop-start; //tempcount += stop*(stop-1)/2; tempcount += diff*(diff-1)/2; count += tempcount; print(""i=""+i+"" count=""+tempcount+"", diff=""+(stop-start)); for (int j = start; j < stop; j++) { print("" ""+array.get(j)); } println(); } } println(""input=""+input); String output = ""Case #"" + line + "": ""; output += count; Utils.writeToFile(output); //if (line == 3) break; } Utils.closeInFile(); Utils.closeOutFile(); } } " B12171,"import java.io.*; import java.util.*; public class Main { static private String formatPair(int toMove, String num1) { String back = num1.substring(num1.length() - toMove); String front = num1.substring(0,num1.length() - toMove); return (back + front); } static private int getDistinctPairs(int v1,int v2) { String num1 = Integer.toString(v1); String num2 = Integer.toString(v2); if (num1.length() != num2.length()) return 0; for (int i = 1; i < num1.length();i++) { String match = formatPair(i,num1); if (match.equals(num2)) return 1; } return 0; } static int getDistinctPairsBetween(int a, int b) { int count = 0; //generate all possible values for (int i=a; i <= b; i++) for (int j=i+1;j <= b; j++) { boolean valid = (i >= a && i < j && j > i && j <= b); if (valid) count += getDistinctPairs(i,j); } return count; } static public void main(String args[]) { try{ FileWriter fstream = new FileWriter(""output.out""); BufferedWriter out = new BufferedWriter(fstream); try { BufferedReader input = new BufferedReader(new FileReader(new File(args[0]))); try { String line = null; line = input.readLine(); int count = Integer.parseInt(line); for (int i =0; i { // PROBLEM SOLUTION STARTS HERE ----------------------------------------------------------- // ---------------------------------------------------------------------------------------- Solver(Scanner in, int testId) { this.testId = testId; // TODO: Read input A = in.nextInt(); B = in.nextInt(); } // TODO: Define input variables final int A, B; @Override public String call() throws Exception { long now = System.nanoTime(); // TODO: Solve problem here and return result as a string int digits = digitCount(A); int[] formers = new int[digits]; int count = 0; for (int n = A; n < B; n++) { int subcount = 0; inner: for (int rot=1; rot n && m <= B) { for (int i=0; i solvers = new ArrayList(); for (int i=0; i> solutions = executor.invokeAll(solvers); for (int i = 0; i < numTests; i++) { try { System.out.println(String.format(""Case #%d: %s"", solvers.get(i).testId, solutions.get(i).get())); } catch (Exception e) { System.out.println(String.format(""Case #%d: EXCEPTION !!!!!"", solvers.get(i).testId)); System.err.println(String.format(""Case #%d: EXCEPTION !!!!!"", solvers.get(i).testId)); e.printStackTrace(System.err); } } executor.shutdown(); System.err.println(String.format(""TOTAL: %d ms"" , (System.nanoTime() - now) / 1000000)); } }" B10524,"package dom.zar.jam.qualifications; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) { Scanner in = new Scanner(System.in); int inputLines = in.nextInt(); for (int i = 0; i < inputLines;) { int a = in.nextInt(); int b = in.nextInt(); System.out.println(""Case #"" + ++i + "": "" + result(a, b)); } } private static int result(int a, int b) { int size = b - a + 1; int[] nums = new int[size]; for (int i = 0; i < size; ++i) nums[i] = a + i; int counter = 0; for (int i = 0; i < size; ++i) { if (nums[i] > -1) { counter += rotate(nums[i], a, b, nums); nums[i] = -1; } } return counter; } private static int rotate(Integer n, int a, int b, int[] nums) { String valString = n.toString(); int length = valString.length(); valString = valString + valString; int counter = 0; for (int i = 1; i < length; ++i) { int rotated = Integer.parseInt( valString.substring(i, i + length)); if (rotated > n && rotated <= b && nums[rotated - a] != -1) { counter++; nums[rotated - a] = -1; } } return (counter * (counter + 1)) >> 1; } } " B11159,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Joel */ import java.io.*; public class RecycledNumbers { public static void main(String[] args) { try { FileWriter output = new FileWriter(""C:\\Users\\Joel\\Documents\\CSCI 221\\Netbeans Projects\\Google CodeJam\\src\\C-small-attempt2.out""); BufferedWriter out = new BufferedWriter(output); FileReader reader = new FileReader(""C:\\Users\\Joel\\Documents\\CSCI 221\\Netbeans Projects\\Google CodeJam\\src\\C-small-attempt2.in""); BufferedReader in = new BufferedReader(reader); int p = Integer.parseInt(in.readLine()); StringBuilder test; int count = 0; for (int i = 0; i < p; i++) { String nums = in.readLine(); int m = Integer.parseInt(nums.substring((nums.indexOf("" "")) + 1)); int n = Integer.parseInt(nums.substring(0, nums.indexOf("" ""))); for (int j = n; j < (m+1); j++) { test = new StringBuilder(Integer.toString(j)); int k; do { char move = test.charAt(test.length() - 1); test.insert(0, move); test.deleteCharAt(test.length() - 1); k = Integer.parseInt(test.toString()); if (k > j && k < (m + 1) && k != j) count++; } while(k != j); } out.write(""Case #"" + (i + 1) + "": "" + count + ""\n""); count = 0; } out.close(); } catch (IOException e) { } } } " B12859,"import java.util.*; import java.util.regex.*; import java.text.*; import java.math.*; import java.io.*; public class RecycledNumbers { private final static String FILE_IN = RecycledNumbers.class.getSimpleName() + "".in""; private final static String FILE_OUT = RecycledNumbers.class.getSimpleName() + "".out""; public static void main(String[] args) throws Exception { final Scanner in = new Scanner(new File(FILE_IN)); final PrintWriter out = new PrintWriter(FILE_OUT); final int testCnt = in.nextInt(); for (int caseNum = 1; caseNum <= testCnt; ++ caseNum){ final int a = in.nextInt(); final int b = in.nextInt(); final int last [] = new int [b + 1]; int result = 0; for (int i = a; i <= b; ++ i){ final String s = String.valueOf(i); for (int pos = 1; pos < s.length(); ++ pos){ final String newNum = s.substring(pos) + s.substring(0, pos); final int newInt = Integer.valueOf(newNum); if (newInt > i && newInt <= b){ if (last[newInt] != i){ ++ result; last[newInt] = i; } } } } out.println(String.format(""Case #%d: %d"", caseNum, result)); } in.close(); out.close(); } } " B10398,"package R0; import java.io.*; import java.util.*; public class C { private static final int res[] = new int[8]; private static long check(int A, int B, int m, int c) { long ret = 0; for (int i = A; i < B; i++) { int x = i; for (int k = 0; k < c; k++) { res[k] = x = x / 10 + m * (x % 10); if ( x <= i || x > B ) continue; boolean found = false; for (int j = 0; j < k && !found; j++) found = (res[j] == x); if ( !found ) ret++; } } return ret; } private static long solve() { int A = ni(); int B = ni(); if ( B < 10 ) return 0; if ( A == B ) return 0; int m = 10; for (int i = 1; i < 7; i++) { if ( B < m * 10 ) return check(A, B, m, i); m *= 10; } return 0; } private static final boolean STDIO = false; private static final String TASK = ""C""; private static final String ROUND = ""R0""; private static final String DATA = ""sm""; private static Scanner sc; private static PrintStream out; public static void main(String[] args) throws FileNotFoundException, IOException { Locale.setDefault(Locale.ENGLISH); String DATA_IN = String.format(""tst/%s/%s.%s.in"", ROUND, TASK, DATA); String DATA_OUT = String.format(""tst/%s/%s.%s.out"", ROUND, TASK, DATA); String str = null; if ( args.length > 0 ) str = args[0]; else if ( !STDIO ) str = DATA_IN; sc = new Scanner((str != null) ? new FileInputStream(str) : System.in); str = null; if ( args.length > 1 ) str = args[1]; else if ( !STDIO ) str = DATA_OUT; out = (str != null) ? new PrintStream(str) : System.out; int TC = ni(); for (int i = 1; i <= TC; i++) { long ret = solve(); out.println(String.format(""Case #%d: %d"", i, ret)); } } private static int ni() { return sc.nextInt(); } } " B12620,"import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; public class SpeakingTongues extends JamProblem { Map map = new HashMap<>(); public static void main(String[] args) throws IOException { SpeakingTongues p = new SpeakingTongues(); p.prepare(); p.go(); } void prepare() { map.put('y', 'a'); map.put('e', 'o'); map.put('q', 'z'); String[] from = new String[3]; String[] to = new String[3]; to[0] = ""ejp mysljylc kd kxveddknmc re jsicpdrysi""; to[1] = ""rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd""; to[2] = ""de kr kd eoya kw aej tysr re ujdr lkgc jv""; from[0] = ""our language is impossible to understand""; from[1] = ""there are twenty six factorial possibilities""; from[2] = ""so it is okay if you want to just give up""; for (int i = 0; i < to.length; i++) { char[] t = to[i].toCharArray(); char[] f = from[i].toCharArray(); for (int j = 0; j < f.length; j++) { char fc = f[j]; char tc = t[j]; map.put(tc, fc); } } for (char c = 'a'; c <= 'z'; c++) { if (map.containsKey(c)) { continue; } for (char c2 = 'a'; c2 <= 'z'; c2++) { if (map.containsValue(c2)) { continue; } map.put(c,c2); } } } @Override String solveCase(JamCase jamCase) { StringBuilder b = new StringBuilder(); STCase ca = (STCase) jamCase; char[] chars = ca.str.toCharArray(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; b.append(map.get(c)); } return b.toString(); } @Override JamCase parseCase(List file, int line) { STCase ca = new STCase(); ca.lineCount = 1; ca.str = file.get(line); return ca; } } class STCase extends JamCase { String str; }" B10677,"import static java.util.Arrays.deepToString; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Scanner; public class QC { public static void main(String[] args) throws Exception { new QC().run(); } int calculateDigit(int num) { int res = 0; while(num>0) { res++; num = num/10; } return res; } void run() throws Exception { //Scanner sc = new Scanner(System.in); //PrintWriter pw = new PrintWriter(System.out); Scanner sc = new Scanner(new FileReader(""C-small-attempt1.in"")); FileWriter fstream = new FileWriter(""out.in""); BufferedWriter out = new BufferedWriter(fstream); int ntest = Integer.valueOf(sc.nextLine()); for(int test=1;test<=ntest;++test) { int min = sc.nextInt(); int max = sc.nextInt(); int score = 0; for(int i=min; i<=max; i++) { int digit = calculateDigit(i); List list = new ArrayList(); for(int j=1; j i && calculateDigit(mix) == calculateDigit(i)) { //debug(i + "" "" +mix); list.add(mix); score++; } } } out.write(""Case #"" + test + "": ""); out.write(score+""""); debug(score); out.write(""\n""); } out.close(); sc.close(); } void debug(Object...os) { System.err.println(deepToString(os)); } void debugArray(Object[]...os) { System.err.println(deepToString(os)); } } " B10680,"/* GCJ2012-Q */ import java.io.*; import java.util.*; import java.math.*; public class GCJ2012QC { static BufferedReader fin; static PrintWriter fout; // change numefile static String file=""qcs2""; static String infile=file+"".in""; static String outfile=file+"".out""; // // write result to output file private static void writetestresult(int test, String ret){ fout.println(""Case #""+test+"": ""+ret); } // open files private static void openfiles() throws IOException{ fin = new BufferedReader(new FileReader(infile)); fout = new PrintWriter(new BufferedWriter(new FileWriter(outfile))); } // close files private static void closefiles() throws IOException{ fin.close(); fout.close(); } // solve test no. ""test"" private static String solvetest(int test) throws IOException{ System.out.println("">>>Solving test...""+test); // Parse input for test no. test int iret=0; String a=fin.readLine(); String[] as=a.split("" ""); int A=Integer.parseInt(as[0]); int B=Integer.parseInt(as[1]); for (int n=A; n lst=new ArrayList(); int len=(""""+n).length(); String sm=""""+n; for (int j=0; j<=len; j++) { String sk=sm; int lk=sk.length(); sm=sk.charAt(lk-1)+sk.substring(0, lk-1); int m=Integer.parseInt(sm); if (m>n && m<=B) if (!lst.contains(m)) { lst.add(m); // System.out.println(n+"" ""+m); } } iret+=lst.size(); } String ret=""""; ret=""""+iret; return ret; } // main here public static void main(String[] args) throws IOException{ // open files openfiles(); // read first line, no. of tests String line=fin.readLine(); int T=Integer.parseInt(line); // solve T tests for (int test=1; test<=T; test++) { //long stime=System.currentTimeMillis(); String ret=solvetest(test); writetestresult(test, ret); //long etime=System.currentTimeMillis(); //long dtime=(etime-stime); //System.out.println(""Test ""+test+"": ""+dtime+""ms""); } // close files closefiles(); } } " B12489,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class RecycledNumbers { public static void main(String[] args) { RecycledNumbers recycled = new RecycledNumbers(); recycled.read_input_file(); /*if(recycled.check_if_the_number_is_a_recycled_pair(""23451"", ""34512"", ""12345"")) { number_of_recycled_pairs ++; System.out.println(number_of_recycled_pairs); }*/ } public boolean check_if_the_number_is_a_recycled_pair(String first_number, String second_number, String original_number) { if (original_number.equals(first_number)) { return false; } else if(first_number.equals(second_number)) { return true; } else { return check_if_the_number_is_a_recycled_pair((first_number.substring(1) + first_number.charAt(0)), second_number, original_number); } } public void read_input_file() { try { BufferedReader rd = new BufferedReader(new FileReader(""C-small-attempt2.in"")); FileWriter fstream = new FileWriter(""output.txt""); BufferedWriter out = new BufferedWriter(fstream); T = Integer.parseInt(rd.readLine()); System.out.println(T); while (true) { String A_and_B = rd.readLine(); System.out.println(A_and_B); if (A_and_B == null) { break; } parse_line(A_and_B, out); number_of_recycled_pairs = 0; } out.close(); rd.close(); } catch (IOException ex) { System.out.println(""file not found""); } } public void parse_line(String A_and_B, BufferedWriter out) { String A = A_and_B.substring(0, A_and_B.indexOf("" "")); String B = A_and_B.substring(A_and_B.indexOf("" "") + 1); for (Integer i = Integer.parseInt(A); i < Integer.parseInt(B); i++) { for (Integer j = i + 1; j <= Integer.parseInt(B); j++) { String original_number = i.toString(); String first_number = original_number.substring(1) + original_number.charAt(0); String second_number = j.toString(); if (check_if_the_number_is_a_recycled_pair(first_number, second_number, original_number)) { number_of_recycled_pairs ++; } } } Save_line_to_output_file(out); } public void Save_line_to_output_file(BufferedWriter out) { try{ // Create file out.write(""Case #"" + (counter + 1) + "": "" + number_of_recycled_pairs); out.newLine(); counter ++; //Close the output stream } catch (Exception e) {//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } int counter = 0; int T= 0; static int number_of_recycled_pairs = 0; } " B10509,"import java.util.HashMap; import java.util.Scanner; public class Recycle { private static HashMap mCache = new HashMap(); public static boolean isRecycle(int a, int b) { if (a >= b) return false; Pair2 p = new Pair2(a, b); Boolean cacheValue = mCache.get(p); if (cacheValue != null) return cacheValue; //System.out.println(""isRecycle("" + a + "", "" + b + "")""); int len = (int)Math.floor(Math.log10(b)); for (int i = 0; i < len; i++) { b = b / 10 + (b % 10) * pow10(len); //System.out.println(b); if (a == b) { mCache.put(p, true); return true; } } mCache.put(p, false); return false; } public static int pow10(int pow) { int ret = 1; for (int i = 0; i < pow; i++) { ret *= 10; } return ret; } public static int countRecycle(int start, int end) { int count = 0; for (int i = start; i <= end; i++) { for (int j = i; j <= end; j++) { if (isRecycle(i, j)) { count++; } } } return count; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int num = in.nextInt(); for (int i = 0; i < num; i ++) { int a = in.nextInt(); int b = in.nextInt(); System.out.println(""Case #"" + (i + 1) + "": "" + countRecycle(a, b)); } } } " B12597,"package main; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.HashSet; public class ProblemB { public static void main(String args[]){ try{ FileInputStream fileInputStream = new FileInputStream(args[0] + "".in""); DataInputStream in = new DataInputStream(fileInputStream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter fstream = new FileWriter(args[0] + "".out""); BufferedWriter out = new BufferedWriter(fstream); String strLine; strLine = br.readLine(); int T = Integer.parseInt(strLine); for(int i = 1; i <= T; i++){ strLine = br.readLine(); String[] limits = strLine.split("" "", 2); int lowerLimit = Integer.parseInt(limits[0]); int upperLimit = Integer.parseInt(limits[1]); int count = 0; for(int j = lowerLimit; j < upperLimit; j++){ int n = j; String temp = Integer.toString(j); HashSet hashSet = new HashSet(); for(int k = 0; k < temp.length() - 1; k++){ temp = temp.substring(temp.length() - 1, temp.length()) + temp.substring(0, temp.length() - 1); int m = Integer.parseInt(temp); if(n < m && m <= upperLimit){ String temp1 = temp; hashSet.add(temp1); } } count = count + hashSet.size(); } System.out.println(""Case #"" + i + "": "" + count); out.write(""Case #"" + i + "": "" + count + ""\n""); } out.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } } " B13264,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class Recycled { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String inStr = null; int numCases = 0; try { inStr = br.readLine(); numCases = Integer.parseInt(inStr); for (int i = 0; i < numCases; i++) { inStr = br.readLine(); System.out.println(""Case #"" + (i+1) + "": "" + checkNums(inStr)); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static int checkNums(String s) { int [] n, m; int length, A, B; int result = 0; Scanner ints = new Scanner(s); A = ints.nextInt(); B = ints.nextInt(); length = (s.length()-1) / 2; n = new int[length]; m = new int[length]; for (int i = A; i < B; i++) { for (int j = i+1; j <= B; j++) { String nStr = """" + i; String mStr = """" + j; for (int x = 0; x < length; x++) { n[x] = nStr.charAt(x) - 48; m[x] = mStr.charAt(x) - 48; } for (int x = 0; x < length - 1; x++) { int tempInt = n[length - 1]; for (int y = length - 1; y > 0; y--) { n[y] = n[y-1]; } n[0] = tempInt; if (isEqual(n, m, length)) { result++; break; } } } } return result; } public static Boolean isEqual(int[] m, int [] n, int length) { for (int i = 0; i < length; i++) { if (n[i] != m[i]) return false; } return true; } } " B11198,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package test; import java.io.BufferedReader; import java.io.FileReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * * @author Jeric Bryle Sy Dy */ public class GJamC2 { private static class Ref { public int cnt; public Set set; public Ref() { cnt = 0; set = new HashSet(); } } private static void permuteMove(char[] arr, int len, String strN, String strB, Ref ref) { int arrLen = arr.length; char[] result = new char[arrLen]; int index = 0; for (int i = arrLen - len; i < arrLen; ++i) { result[index++] = arr[i]; } for (int i = 0; i < arrLen - len; ++i) { result[index++] = arr[i]; } String strCur = new String(result); if (strCur.compareTo(strN) > 0 && strCur.compareTo(strB) <= 0 && !ref.set.contains(strCur)) { ref.set.add(strCur); ++ref.cnt; } } public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new FileReader(""C:/Users/Jeric Bryle Sy Dy/Downloads/C-small-attempt0.in"")); PrintWriter out = new PrintWriter(""C:/Users/Jeric Bryle Sy Dy/Downloads/C-small-attempt0.out""); int t = Integer.parseInt(br.readLine()); for (int tIter = 0; tIter < t; ++tIter) { Scanner s = new Scanner(br.readLine()); int a = s.nextInt(); int b = s.nextInt(); Ref ref = new Ref(); for (int n = a; n < b; ++n) { ref.set.clear(); String strN = String.valueOf(n); // permute(strN.toCharArray(), 0, strN, String.valueOf(b), 1, ref); for (int len = 1; len < strN.length(); len++) { permuteMove(strN.toCharArray(), len, strN, String.valueOf(b), ref); } } s.close(); out.printf(""Case #%d: %d\n"", tIter + 1, ref.cnt); } br.close(); out.close(); } } " B10917,"import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { public static int[] POWER_OF_10 = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000}; public static int rotate(int n, int offset) { return (n % POWER_OF_10[offset]) * POWER_OF_10[(int) Math.log10(n) + 1 - offset] + (n / POWER_OF_10[offset]); } public static int count(int low, int high) { int count = 0; if (low < 10) { low = 10; } HashSet group = new HashSet(); for (int i = low; i < high; i++) { int numDigit = (int) Math.log10(i) + 1; while (numDigit > 0) { int num = rotate(i, numDigit--); if (num > i && num <= high && !group.contains(num)) { count++; group.add(num); } } group.clear(); } return count; } public static void main(String[] args) { final Scanner in = new Scanner(System.in); final int numCase = in.nextInt(); in.nextLine(); for (int i = 0; i < numCase; i++) { int low = in.nextInt(); int high = in.nextInt(); System.out.println(""Case #"" + (i+1) + "": "" + count(low, high)); in.nextLine(); } } } " B10235,"import java.net.*; import java.io.*; import java.lang.*; public class RecycledNumbers { public static void clear(int[] arr){ for(int i=0; i<30; i++) arr[i] = -1; } public static boolean checkEntry(int x, int[] arr){ for(int i=0; i<30; i++) { if(x == arr[i]) return true; } return false; } public static void main(String[] args) throws IOException { String[] spl; int counter = 1; int count = 0; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String input; int a,b,e = 0; String xform; int[] arr = new int[30]; int arrCounter = 0; clear(arr); while((input = in.readLine()) != null){ spl = input.split("" ""); a = Integer.parseInt(spl[0]); b = Integer.parseInt(spl[1]); int bLength = (Integer.toString(b)).length(); for(int i=a; i xform.charAt(k)) { if( (bLength > l) || (b >= (e = Integer.parseInt(xform.substring(j) + xform.substring(0 , j)))) ) { //System.out.println(""number:"" + xform + '\t' + Integer.parseInt(xform.substring(j) + xform.substring(0 , j))); if(!checkEntry(e , arr)){ count++; arr[arrCounter] = e; arrCounter++; } break; } else break; } else continue; } } } System.out.println(""Case #"" + counter + "": "" + count ); counter++; count = 0; } }} " B10290,"package com.gcj.parser; import java.util.ArrayList; import java.util.List; public class Number { private static List getRecylcedCombining(int value){ List toReturn = new ArrayList(); Integer intValue = new Integer(value); String strValue = intValue.toString(); for (int i = 1; i < strValue.length() ; i ++) { Integer newValue = new Integer(strValue.substring(i, strValue.length()) + strValue.substring(0, i)); if (newValue.intValue() > value && !toReturn.contains(newValue)){ toReturn.add(newValue); } } return toReturn; } public static int nbOfRecycledInteger(int min, int max){ int toReturn = 0; // boolean[] alreadyDone = new boolean[10000000]; for (int i = min ; i <= max ; i++){ List list = getRecylcedCombining(i); for (Integer number : list){ int intNumber = number.intValue(); if (intNumber >= min && intNumber <= max ){//&& !alreadyDone[intNumber]){ toReturn++; // alreadyDone[intNumber]=true; } } } return toReturn; } public static void main(String[] args) { System.out.println(nbOfRecycledInteger(1111, 2222)); } } " B11570,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package googlecodejam2012; import java.io.FileNotFoundException; import java.util.*; /** * * @author Pavlos */ public class ProblemC { public static void main(String[] args) throws FileNotFoundException { Read.OpenFile(""C-small-attempt0.in""); Write.OpenFile(""solC.txt""); int T = Read.readInt(); for (int zz = 1; zz <= T; zz++) { int A = Read.readInt(); int B = Read.readInt(); int size = String.valueOf(A).length(); ArrayList As = new ArrayList<>(); ArrayList Temps = new ArrayList<>(); for (int i = A; i <= B; i++) { int temp = i; for (int j = 0; j < size; j++) { int suf = temp%10; temp /= 10; temp += suf*(Math.pow(10, size-1)); if(temp <= B && temp >= A && i < temp && temp != i) { if(As.indexOf(i)== Temps.indexOf(temp) && As.indexOf(i) != -1 && Temps.indexOf(temp)!=-1) continue; As.add(i); Temps.add(temp); } } } Write.WriteToFile(String.format(""Case #%d: %d\n"",zz,As.size())); }//end zz Write.CloseFile(); } } " B13081,"import java.io.*; import java.util.*; public class My { public static void main(String[] args)throws IOException { new My().start(); } public void start()throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; int test=Integer.parseInt(br.readLine()); int ans=0; int ind=1; while(test-->0){ ans=0; st=new StringTokenizer(br.readLine()); int A=Integer.parseInt(st.nextToken()); int B=Integer.parseInt(st.nextToken()); HashSet hs; for(int num=A;num<=B;num++){ String n=num+""""; int len=n.length(); hs=new HashSet(); for(int i=1;i=A && m>num){ hs.add(m); } } ans+=hs.size(); } System.out.println(""Case #""+ind+"": ""+ans); ind++; } } }" B11337,"import java.util.Scanner; public class Main extends AbstractCodeJam { @Override protected Problem readProblem(Scanner scan) { ProblemSample pb = new ProblemSample(); // PARAMETRES A LIRE !!! pb.setA(scan.nextInt()); pb.setB(scan.nextInt()); scan.nextLine(); return pb; } /** * @param args */ public static void main(String[] args) { new Main().solveProblems(System.in, System.out); } } " B13227,"import java.awt.List; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.StringTokenizer; public class recycle { static int lower = 0; static int upper = 0; static int count = 0; static HashSet num_list = new HashSet(); public static void PerformShift(int number) { int start = number; int numdigits = (int) Math.log10((double) number); int multiplier = (int) Math.pow(10.0, (double) numdigits); while (true) { //int q = number / 10; int r = number % 10; number = number / 10; number = number + multiplier * r; boolean flg = true; int bits = 0; if(number != start && number >= lower && number <=upper) { num_list.add(number+"":""+start); num_list.add(start+"":""+number); } if (number == start) break; } } public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(""input.txt"")); BufferedWriter out = new BufferedWriter(new FileWriter(""output.txt"")); int no_cases = Integer.parseInt(in.readLine()); for (int index = 0; index < no_cases; ++index) { StringTokenizer limits = new StringTokenizer(in.readLine(),"" ""); lower = Integer.parseInt(limits.nextToken()); upper = Integer.parseInt(limits.nextToken()); int start = (int) System.currentTimeMillis(); for (int i = lower; i <= upper; ++i) { if(i<9) continue; PerformShift(i); } if(index==no_cases-1) out.write(""Case #"" + (index + 1) + "": "" + num_list.size()/2); else out.write(""Case #"" + (index + 1) + "": "" + num_list.size()/2 + ""\n""); num_list.clear(); } out.close(); } } " B10292,"package com.gcj.main; import java.util.ArrayList; import com.gcj.parser.Number; import com.gcj.parser.Parser; public class Main { public static void main(String[] args) { Parser parser = new Parser(""resource/InputData.txt""); ArrayList[] datas = parser.toArray(); int index = 1; for (ArrayList dataRow : datas){ int min = dataRow.get(0).intValue(); int max = dataRow.get(1).intValue(); StringBuffer stringBuf = new StringBuffer(""Case #"").append(index).append("": "").append(Number.nbOfRecycledInteger(min, max)); System.out.println(stringBuf.toString()); index ++; } } }" B12955,"package google.contest.A; import google.loader.Challenge; import google.problems.AbstractReader; public class AReader extends AbstractReader { @Override protected Challenge createChallenge(int number) { int theLine = getActualLine(); String[] lines = getLines(); AChallenge chal = new AChallenge(theLine,lines[theLine]); setActualLine(theLine+1); return chal; } } " B13077,"import java.io.*; import java.util.*; public class RecyledNumbers { public static void main(String args[]) throws IOException{ Scanner scan=new Scanner(new File(""C-small-attempt0.in"")); PrintWriter pw=new PrintWriter(new File(""result.txt"")); int caseNum=Integer.parseInt(scan.nextLine()); for(int i=1;i<=caseNum;i++){ String a=scan.nextLine(); //System.out.println(a); int result=0; String[] temp=new String[2]; temp=parseString(a); //System.out.println(temp); String A=temp[0]; String B=temp[1]; for(int j=Integer.parseInt(A);j movedNum=new ArrayList(); for(int i=1;iInteger.parseInt(toBeJudged) && temp<=Integer.parseInt(B)) { if(!movedNum.contains(temp)) movedNum.add(temp); System.out.println(toBeJudged+"" ""+temp); } } return movedNum.size(); } } " B11652," import java.io.*; public class Main { static final String FILE = ""C-small-attempt0""; static final String INPUT = FILE + "".in""; static final String OUTPUT = FILE + "".out""; // public static void main(String[] args) throws FileNotFoundException, IOException { int T, A, B, x, y; PrintWriter pw; try (BufferedReader br = new BufferedReader(new FileReader(INPUT))) { pw = new PrintWriter(OUTPUT); T = Integer.parseInt(br.readLine()); for (x = 1; x <= T; x++) { y = 0; // String[] temp = br.readLine().split("" ""); A = Integer.parseInt(temp[0]); B = Integer.parseInt(temp[1]); // for (int i = A; i <= B; i++) { String n = Integer.toString(i); String m = new String(n); for (int j = 0; j < n.length() - 1; j++) { m = m.charAt(m.length() - 1) + m; m = m.substring(0, n.length()); if (Integer.parseInt(n) < Integer.parseInt(m) && Integer.parseInt(m) <= B) { y++; } } } // System.out.println(""Case #"" + x + "": "" + y); pw.println(""Case #"" + x + "": "" + y); } } pw.close(); } } " B11946,"import java.io.*; import java.util.*; public class C { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; enum InputType { SAMPLE, SMALL, LARGE; } static final InputType currentInputType = InputType.SMALL; static final int attemptNumber = 0; // for small inputs only int pow10; void solve() throws IOException { int a = nextInt(); int b = nextInt(); pow10 = 1; int cnt = Integer.toString(a).length(); for (int i = 0; i < cnt - 1; i++) pow10 *= 10; long ans = 0; for (int i = a; i <= b; i++) { for (int j = (i % 10) * pow10 + (i / 10); j != i; j = (j % 10) * pow10 + j / 10) if (a <= j && j <= b && j > i) ans++; } out.println(ans); } void inp() throws IOException { switch (currentInputType) { case SAMPLE: br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); break; case SMALL: String fileName = ""C-small-attempt"" + attemptNumber; br = new BufferedReader(new FileReader(fileName + "".in"")); out = new PrintWriter(fileName + "".out""); break; case LARGE: fileName = ""C-large""; br = new BufferedReader(new FileReader(fileName + "".in"")); out = new PrintWriter(fileName + "".out""); break; } int test = nextInt(); for (int i = 1; i <= test; i++) { System.err.println(""Running test "" + i); out.print(""Case #"" + i + "": ""); solve(); } out.close(); } public static void main(String[] args) throws IOException { new C().inp(); } String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } String nextString() { try { return br.readLine(); } catch (Exception e) { eof = true; return null; } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } } " B10808,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package actual; import codejam.*; import java.io.*; import java.util.Scanner; /** * * @author atm */ public class PC { public static void main(String[] args) throws Exception { int Cases; int L,U; String words[]; FileInputStream fstreamIN = new FileInputStream(""F:\\codejam\\input\\C-small-attempt0.in""); FileOutputStream fstreamOUT = new FileOutputStream(""F:\\codejam\\output\\C-small-attempt0.out""); Scanner in=new Scanner(fstreamIN); PrintWriter out=new PrintWriter(fstreamOUT); Cases=in.nextInt(); for(int i=0;ij) ans++; } } } else { for(int j=L;j<=U;j++){ if(onedigcir(j)<=U){ if(onedigcir(j)>j) ans++; } if(twodigcir(j)<=U){ if(twodigcir(j)>j) if(onedigcir(j)!=twodigcir(j)) ans++; } } } out.printf(""Case #%d: %d\n"",i+1,ans); } out.close(); } static int revtwo(int num){ return (num%10)*10+(num/10); } static int onedigcir(int num) { int newnum; newnum=(num%10)*100+(num/10); return newnum; } static int twodigcir(int num) { int newnum; newnum=(num%100)*10+(num/100); return newnum; } } " B12897,"package exercise; public class Solver { private static int[][] MATCHES; public static Integer[] solve(Integer[][] input) { Integer[] result = new Integer[input.length]; for (int cnt = 0; cnt < input.length; ++cnt) result[cnt] = solve(input[cnt]); return result; } public static int solve(Integer[] input) { if (input == null || input.length < 2) return 0; Integer min = input[0]; Integer max = input[1]; int result = 0; MATCHES = new int[max][4]; for (int cnt = min; cnt < max; ++cnt) { result += countMatches(cnt, min, max); } for (int i = 0; i < MATCHES.length; ++i) for (int j = 0; j < MATCHES[i].length; ++j) if (MATCHES[i][j] != 0) ++result; else break; return result; } private static int countMatches(int value, int min, int max) { String string = String.valueOf(value); int result = 0; for (int idx = string.length() - 1; idx > 0; --idx) { String candidateString = string.substring(idx, string.length()) + string.substring(0, idx); Integer candidate = Integer.parseInt(candidateString); if (candidate.compareTo(value) > 0 && candidate.compareTo(min) >= 0 && candidate.compareTo(max) <= 0) { addToMatches(value, candidate); } } return result; } private static void addToMatches(int value, int match) { boolean inserted = false; for (int cnt = 0; cnt < MATCHES[value].length; ++cnt) { if (MATCHES[value][cnt] == 0) { MATCHES[value][cnt] = match; inserted = true; break; } else if (MATCHES[value][cnt] == match) return; } if (!inserted) { int[] save = MATCHES[value]; MATCHES[value] = new int[save.length * 2]; int cnt; for (cnt = 0; cnt < save.length; ++cnt) { MATCHES[value][cnt] = save[cnt]; } MATCHES[value][cnt] = match; } } } " B12211,"package hk.polyu.cslhu.codejam.solution; import java.util.List; import org.apache.log4j.Logger; public abstract class Solution implements Cloneable { public static Logger logger = Logger.getLogger(Solution.class); protected String result; /** * Set the problem to be solved * * @param problemDesc List The description of problem */ public abstract void setProblem(List problemDesc); /** * Solve the problem */ public abstract void solve(); /** * Return the result of problem * * @return String Result */ public String getResult() { return this.result; } public Solution clone() throws CloneNotSupportedException { return (Solution) super.clone(); } } " B12584,"package com.ignaciobona.codejam.practice.problema; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.HashMap; public class Solver { public static String PROBLEM_NUMBER=""C""; public static String PATH_TO_INPUT_FILE_SMALL=""inputs/""+PROBLEM_NUMBER+""-small-attempt0.in""; public static String PATH_TO_OUPUT_FILE_SMALL=""outputs/""+PROBLEM_NUMBER+""-small-attempt0.out""; public static String PATH_TO_INPUT_FILE_LARGE=""inputs/""+PROBLEM_NUMBER+""-large.in""; public static String PATH_TO_OUPUT_FILE_LARGE=""outputs/""+PROBLEM_NUMBER+""-large.out""; public static boolean SMALL=true; public static class Problem{ public int nCase; public int a; public int b; public StringBuffer outputString; public void solve(){ HashMapmap=new HashMap(); outputString=new StringBuffer(""Case #""+nCase+"": ""); int found=0; for(int n=a;n<=b;n++){ int nDigits=(n+"""").length(); int m=n; for(int j=1;j set = new HashSet(); for (int k = 1; k <= T; ++k){ int A = input.readInt(); int B = input.readInt(); long res = 0; for (int i = A; i <= B; ++i){ String char_array = String.valueOf(i); int length = char_array.length(); set.clear(); for (int j = 1; j < char_array.length(); ++j){ if (char_array.charAt(j) == '0'){ continue; } if (char_array.charAt(j) > char_array.charAt(0)){ continue; } int val = i % power[length - j] * power[j] + i / power[length - j]; if (val < i && val >= A){ set.add(val); } } res += set.size(); } output.println(""Case #"" + k + "": "" + res); } return; } } class In { private Scanner scanner; // assume Unicode UTF-8 encoding //private String charsetName = ""UTF-8""; private String charsetName = ""ISO-8859-1""; // assume language = English, country = US for consistency with System.out. private Locale usLocale = new Locale(""en"", ""US""); /** * Create an input stream for standard input. */ public In() { scanner = new Scanner(new BufferedInputStream(System.in), charsetName); scanner.useLocale(usLocale); } /** * Create an input stream from a socket. */ public In(Socket socket) { try { InputStream is = socket.getInputStream(); scanner = new Scanner(new BufferedInputStream(is), charsetName); scanner.useLocale(usLocale); } catch (IOException ioe) { System.err.println(""Could not open "" + socket); } } /** * Create an input stream from a URL. */ public In(URL url) { try { URLConnection site = url.openConnection(); InputStream is = site.getInputStream(); scanner = new Scanner(new BufferedInputStream(is), charsetName); scanner.useLocale(usLocale); } catch (IOException ioe) { System.err.println(""Could not open "" + url); } } /** * Create an input stream from a file. */ public In(File file) { try { scanner = new Scanner(file, charsetName); scanner.useLocale(usLocale); } catch (IOException ioe) { System.err.println(""Could not open "" + file); } } /** * Create an input stream from a filename or web page name. */ public In(String s) { try { // first try to read file from local file system File file = new File(s); if (file.exists()) { scanner = new Scanner(file, charsetName); scanner.useLocale(usLocale); return; } // next try for files included in jar URL url = getClass().getResource(s); // or URL from web if (url == null) { url = new URL(s); } URLConnection site = url.openConnection(); InputStream is = site.getInputStream(); scanner = new Scanner(new BufferedInputStream(is), charsetName); scanner.useLocale(usLocale); } catch (IOException ioe) { System.err.println(""Could not open "" + s); } } /** * Is the input stream empty? */ public boolean isEmpty() { return !scanner.hasNext(); } /** * Does the input stream have a next line? */ public boolean hasNextLine() { return scanner.hasNextLine(); } /** * Read and return the next line. */ public String readLine() { String line; try { line = scanner.nextLine(); } catch (Exception e) { line = null; } return line; } // return rest of input as string /** * Read and return the remainder of the input as a string. */ public String readAll() { if (!scanner.hasNextLine()) { return null; } // reference: http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html return scanner.useDelimiter(""\\A"").next(); } /** * Return the next string from the input stream. */ public String readString() { return scanner.next(); } /** * Return the next int from the input stream. */ public int readInt() { return scanner.nextInt(); } /** * Return the next double from the input stream. */ public double readDouble() { return scanner.nextDouble(); } /** * Read ints from file */ public static int[] readInts(String filename) { In in = new In(filename); String[] fields = in.readAll().trim().split(""\\s+""); int[] vals = new int[fields.length]; for (int i = 0; i < fields.length; i++) vals[i] = Integer.parseInt(fields[i]); return vals; } /** * Close the input stream. */ public void close() { scanner.close(); } } class Out { // force Unicode UTF-8 encoding; otherwise it's system dependent private static final String UTF8 = ""UTF-8""; private PrintWriter out; /** * Create an Out object using an OutputStream. */ public Out(OutputStream os) { try { OutputStreamWriter osw = new OutputStreamWriter(os, UTF8); out = new PrintWriter(osw, true); } catch (IOException e) { e.printStackTrace(); } } /** * Create an Out object using standard output. */ public Out() { this(System.out); } /** * Create an Out object using a Socket. */ public Out(Socket socket) { try { OutputStream os = socket.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os, UTF8); out = new PrintWriter(osw, true); } catch (IOException e) { e.printStackTrace(); } } /** * Create an Out object using a file specified by the given name. */ public Out(String s) { try { OutputStream os = new FileOutputStream(s); OutputStreamWriter osw = new OutputStreamWriter(os, UTF8); out = new PrintWriter(osw, true); } catch (IOException e) { e.printStackTrace(); } } /** * Close the output stream. */ public void close() { out.close(); } /** * Print an object and then terminate the line. */ public void println(Object x) { out.println(x); } } " B12011," import java.util.*; public class C { public static void main(String[] args) { new C(new Scanner(System.in)); } ArrayList makeNice(int v) { ArrayList vs = new ArrayList(); while (v > 0) { vs.add(v%10); v = v/10; } return vs; } int changeBack(ArrayList val) { int res = 0; int u=1; for (int v : val) { res += v*u; u = u*10; } return res; } public C(Scanner in) { int tc = 1; int T = in.nextInt(); while (T-->0) { int A = in.nextInt(); int B = in.nextInt(); int res = 0; for (int val=A; val<=B; val++) { TreeSet ts = new TreeSet(); //System.out.println(val); //System.out.print(val+"":""); ArrayList vs = makeNice(val); for (int u=0; u val && nv <= B) ts.add(nv); } Collections.rotate(vs,1); } //System.out.println(ts); res += ts.size(); // System.out.println(ts); } System.out.printf(""Case #%d: %d%n"", tc++, res); } } } " B11093,"package qualifiers.recyclednumbers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class RecycledNumbers { public static void main(String[] args) { try { FileReader fileReader = new FileReader(""input/C-small-attempt0.in""); BufferedReader bufferedReader = new BufferedReader(fileReader); String record = null; int numOfCases = -1; int lineCount = 0; List inputList = new ArrayList(); // Read input while ((record = bufferedReader.readLine()) != null) { // First row is number of cases if (lineCount == 0) { numOfCases = Integer.valueOf(record); } // Input else { inputList.add(record); } lineCount++; } fileReader.close(); // Perform algo List results = new ArrayList(); for (String input : inputList) { String[] boundStrArray = input.split("" ""); int lowerBound = Integer.valueOf(boundStrArray[0]); int upperBound = Integer.valueOf(boundStrArray[1]); int result = 0; // 1 - 9 if (upperBound <= 9) { results.add(result); continue; } else { int numOfDigits = String.valueOf(upperBound).length(); Map> exclusionMap = new HashMap>(); List resultValueList = new ArrayList(); for (int i = lowerBound; i <= upperBound; i++) { // Shift to front by j digits for (int j = 1; j < numOfDigits; j++) { String value = String.valueOf(i); String newValue = value.substring(value.length() - j) + value.substring(0, value.length() - j); // Leading 0 - continue if (newValue.charAt(0) == '0') { continue; } // More than upperBound - continue else if (Integer.valueOf(newValue) > upperBound) { continue; } // Less than lowerBound - continue else if (Integer.valueOf(newValue) < lowerBound) { continue; } // Same values else if (value.equals(newValue)) { continue; } else { // In exclusion list already - continue if (exclusionMap.containsKey(value)) { List exclusionList = exclusionMap.get(value); if (exclusionList.contains(newValue)) continue; } // In exclusion list already - continue if (exclusionMap.containsKey(newValue)) { List exclusionList = exclusionMap.get(newValue); if (exclusionList.contains(value)) continue; } // Match, add to exclusion list so we don't run again if (exclusionMap.containsKey(value)) { List exclusionList = exclusionMap.get(value); exclusionList.add(newValue); } else { List exclusionList = new ArrayList(); exclusionList.add(newValue); exclusionMap.put(value, exclusionList); } // Match, add to exclusion list so we don't run again if (exclusionMap.containsKey(newValue)) { List exclusionList = exclusionMap.get(newValue); exclusionList.add(value); } else { List exclusionList = new ArrayList(); exclusionList.add(value); exclusionMap.put(newValue, exclusionList); } result++; } } } results.add(result); } } // Write output FileWriter fileWriter = new FileWriter(""output/results.out""); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); for (int i = 0; i < results.size(); i++) { int result = results.get(i); bufferedWriter.write(""Case #"" + (i+1) + "": "" + result); if (i < results.size() - 1) bufferedWriter.write(""\n""); } //Close the output stream bufferedWriter.close(); } catch (IOException e) { System.out.println(""IOException error!""); e.printStackTrace(); } } } " B10188," /** * * @author Prasun */ import java.io.*; public class C2012 { public static void main(String prsn[]) throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int T,A,B, i,j, cnt=0,div, m, qsn, rem, CNo=1, n; T=Integer.parseInt(br.readLine()); String[] line=null; //System.out.println("" "" + Mul(T,1000)); while(T>0) { line=br.readLine().split("" ""); A=Integer.parseInt(line[0]); B=Integer.parseInt(line[1]); cnt=0; OUTER: for(i=A;i0) m=m* 10 * Mul(rem,div); if(m==j) { cnt++; //System.out.println( i + "" : "" + j + "" == "" + m); break; } n--; }while(n>0); } } System.out.println(""Case #"" + CNo + "": "" + cnt); CNo++; T--; } } public static int length(int x) { int l=0; while(x>0) { x=x/10; l++; } return l; } public static int Mul(int x, int div) { int cnt=-1; while(div!=0 && (x/div) <= 0) { cnt++; div=div/10; } return cnt; } } " B12108,"package com.renoux.gael.codejam.utils; public class TechnicalException extends RuntimeException { private static final long serialVersionUID = 1L; public TechnicalException() { super(); } public TechnicalException(String message, Throwable cause) { super(message, cause); } public TechnicalException(String message) { super(message); } public TechnicalException(Throwable cause) { super(cause); } } " B10158,"package taskc; import java.util.*; public class TaskC { public static void main(String[] args) { new TaskC().main(); } int numOfDigits(int x) { int res = 0; while (x > 0) { res++; x /= 10; } return res; } int getCycle(int n, int i) { String s = Integer.toString(n); int leftlen = s.length() - i; String res = s.substring(leftlen) + s.substring(0, leftlen); return Integer.parseInt(res); } Set generateCycleNumbers(int x) { Set res = new HashSet(); int n = numOfDigits(x); for (int i = 1; i < n; i++) { int z = getCycle(x, i); if (numOfDigits(z) == numOfDigits(x)) { res.add(z); } } return res; } int f(int x, int y) { int res = 0; for (int i = x; i <= y; i++) { Set cycles = generateCycleNumbers(i); for (int q: cycles) { if (q >= x && q <= y && q != i) { //System.out.println(i +"" -> "" + q); res++; } } } return res/2; } void main() { Scanner s = new Scanner(System.in); int T = s.nextInt(); for (int i = 1; i <= T; i++) { int a = s.nextInt(), b = s.nextInt(); int ans = f(a, b); System.out.println(""Case #"" + i + "": "" + ans); } } } " B10725,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.PrintWriter; import java.util.Scanner; public class Recycle { static int u,l,j,n,m=0,k; static int arr[]; public static void solve() throws Exception { PrintWriter out =new PrintWriter(new File(""Recycle.out"")); Scanner sc =new Scanner(new File(""R.in"")); int t=sc.nextInt(); for (int i = 1; i <= t; i++) { int p; arr=new int[1000]; l=sc.nextInt(); u=sc.nextInt(); int res=0,r=0; for(j=l;j<=u;j++) { String j1=Integer.toString(j); //out.println(""j ""+j1); for(int x=((j1.length())-1);x>=1;x--) { for(p=0;p<1000;p++){ String c=j1.substring(x,(j1.length())); //out.println(""c ""+c); String a=c+(j1.substring(0,x)); //out.println(""a ""+a); int n=Integer.parseInt(a); for(k=l;k<=u;k++) { if((k!=j) && (k==n) && (n!=arr[p])) { res=res+1; arr[p]=n; break; } } } }} out.println(""Case #""+ i +"": ""+(res/2000)); } out.close(); } public static void main(String[] args) throws Exception { solve(); } } " B11737," import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; class Pair { private final L left; private final R right; public Pair(L left, R right) { this.left = left; this.right = right; } public L getLeft() { return left; } public R getRight() { return right; } @Override public int hashCode() { return left.hashCode() ^ right.hashCode(); } @Override public boolean equals(Object o) { if (o == null) return false; if (!(o instanceof Pair)) return false; Pair pairo = (Pair) o; return this.left.equals(pairo.getLeft()) && this.right.equals(pairo.getRight()) || this.left.equals(pairo.getRight()) && this.right.equals(pairo.getLeft()); } } public class Dancing { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String str = in.readLine(); int numberOfCases = Integer.parseInt(str); ArrayList array = new ArrayList(); for (int j = 0; j < numberOfCases; j++) { String str1 = in.readLine(); String delimiter = "" ""; String[] temp; temp = str1.split(delimiter); String lowerlimit = temp[0]; String upperlimit = temp[1]; int count = recycledInteger(upperlimit, lowerlimit); array.add(count); } for (int i = 0; i < array.size(); i++) { System.out.println(""Case #""+(i+1)+"": ""+array.get(i)); } } public static int recycledInteger(String upperlimit, String lowerlimit) { int lower = Integer.parseInt(lowerlimit); int upper = Integer.parseInt(upperlimit); // String.valueOf(i); int counter = 0; int temp = lower; ArrayList> arraypairs = new ArrayList>(); while (temp <= upper) { String string = String.valueOf(temp); for (int i = 1; i < string.length(); i++) { String recycled = string.substring(i, string.length()) + string.substring(0, i); if (Integer.parseInt(recycled) >= lower && Integer.parseInt(recycled) <= upper) { Pair pair = new Pair( Integer.parseInt(recycled), temp); if (Integer.parseInt(recycled) != temp) { if(!arraypairs.contains(pair)){ //System.out.println(temp+"" ""+recycled); counter++; } arraypairs.add(pair); } } } temp++; } return counter; } } " B11485,"import java.lang.*; import java.io.*; import java.util.*; public class rotate{ public static void main(String args[])throws Exception{ int i,j,k,m; int n_test_case; FileInputStream fin = new FileInputStream(""C-small-attempt0.in""); DataInputStream in = new DataInputStream(fin); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String str,tempN,tempM; String ABstr[]=new String[2]; FileWriter fout = new FileWriter(""output.txt""); BufferedWriter out = new BufferedWriter(fout); str = br.readLine(); n_test_case=Integer.parseInt(str); for(i=0;i arl=new ArrayList(); for(k=j+1;k<=B;k++) { tempN= new Integer(j).toString();//n tempM= new Integer(k).toString();//m if(ABstr[0].length()>1) { for(m=0;m=10) { t/=10; ++digits; mult *= 10; } } long ans = 0; int[] buf = new int[digits]; for (int n=A; n n && rot <= B) { buf[cnt++] = rot; } } if (cnt>0) { Arrays.sort(buf, 0, cnt); ++ans; for (int i=1; i setRecycled = new HashSet(); if (len > 1) { for (int i = start; i <= end; i++) { String numStr = String.valueOf(i); char[] numChar = numStr.toCharArray(); HashSet set = new HashSet(); for (char ch : numChar) { set.add(ch); } if (set.size() == 1) { continue; } int origNum = Integer.parseInt(numStr); for (int j = 0; j < len - 1; j++) { // System.out.println(""numStr :: "" + numStr); numStr = rotateNumber(numStr, len); // System.out.println(""after rotating numStr :: "" // + numStr); int num = Integer.parseInt(numStr); if (num != origNum && num >= start && num <= end) { // System.out.println(""Pair :: ("" + origNum // + "" , "" + // numStr + "")""); // System.out.println(""recycled no found... adding "" // + // (origNum < num ? """" + origNum + num : """" // + num + // origNum) + "" to set""); setRecycled.add(origNum < num ? """" + origNum + "","" + num : """" + num + "","" + origNum); // System.out.println(""size :: "" + // setRecycled.size()); } } } } System.out.println(setRecycled.size()); bw.write(""Case #"" + (k + 1) + "": "" + setRecycled.size() + ""\n""); // TreeSet set = new TreeSet(setRecycled); // System.out.println(set); } } } catch (Exception e) { e.printStackTrace(); } try { if (br != null) { br.close(); } if (bw != null) { bw.flush(); bw.close(); } } catch (Exception e) { e.printStackTrace(); } } public static String rotateNumber(String num, int len) { return num.charAt(len - 1) + num.substring(0, len - 1); } } " B10085,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.Scanner; public class recycled { private static File f = new File(""C:/Users/Cybermask/Desktop/myfile.txt""); private static File outfile = new File(""C:/Users/Cybermask/Desktop/out.txt""); private static BufferedReader reader; private static String read() throws Exception{ return reader.readLine(); } private static int toint(String s){ return Integer.parseInt(s); } private static ArrayList reverse(ArrayListlist){ ArrayList result = new ArrayList(); for(int i=0;i hs = new HashSet(); for(int o=1;o=f && result<=l && result > first){ hs.add(result); } } count+=hs.size(); } pw.println(count); } pw.flush(); } }" B11390,"import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Recycled_Numbers { public static int recycled(int A, int B) { int n = 0, j = 0, m = 0, c = 0; String tmp = """", subB = """", subE = """", recycled = """"; for (n = A; n <= B; n++) { // System.out.println(""""); tmp = String.valueOf(n); for (j = 0; j < tmp.length(); j++) { subB = tmp.substring(0, j + 1); subE = tmp.substring(j + 1); recycled = subE + subB; m = Integer.parseInt(recycled); if ((m > n) && (m <= B)) { c++; //System.out.println(n+"",""+m); } // System.out.println(recycled); } } return c; } public static void main(String[] args) { String filename = ""/myown/developpement/Google_Code_Jam/recycled_numbers.in""; String ligne = """"; StringTokenizer st1; int i = 0, j = 0; int nbrLigne = 0; String tmp = """"; int A = 0, B = 0; try { FileInputStream fStream = new FileInputStream(filename); BufferedReader in = new BufferedReader(new InputStreamReader( fStream)); if (in.ready()) { ligne = in.readLine(); nbrLigne = Integer.parseInt(ligne); for (j = 0; j < nbrLigne; j++) { ligne = in.readLine(); st1 = new StringTokenizer(ligne, "" ""); A = Integer.parseInt(st1.nextToken()); // tmp = """"; B = Integer.parseInt(st1.nextToken()); //System.out.println(A + "","" + B); System.out.println(""Case #""+(j+1)+"": "" + recycled(A, B)); } } } catch (IOException e) { System.out.println(""File input error""); } } } " B12377,"import java.io.*; import java.util.*; public class RecycledNumbers { public static void main(String[] args) { try { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String s = in.readLine().trim(); int t = Integer.parseInt(s); for (int i = 0; i < t; i++) { String[] input = in.readLine().trim().split("" ""); int a = Integer.parseInt(input[0]); int b = Integer.parseInt(input[1]); int total = 0; int n; int m; while (a <= b) { n = a; m = n+1; while (m <= b) { //System.out.println(""PAIR (n,m) = ("" + n + "","" + m + "")""); StringBuffer strN = new StringBuffer(""""+n); //System.out.println(""strN: "" + strN); for (int j = 0; j < strN.length()-1; j++) { strN.append(strN.charAt(0)); strN.delete(0,1); //System.out.println(""shifted strN..."" + strN ); //System.out.println(""BUG"" + strN.toString().equals(""""+m)); if (Integer.parseInt(strN.toString()) == m) { //System.out.println(""^--------PAIR FOUND-------^""); total++; break; } /* if (a < Integer.parseInt(n.toString()) && Integer.parseInt(n.toString()) <= b) { System.out.println(""---------->found pair (n,m) = ("" + a + "","" + n + "")"" ); total++; } else if (Integer.parseInt(n.toString()) == a && Integer.parseInt(n.toString()) == b ) { total++; } else if (Integer.parseInt(n.toString()) == b) { System.out.println(""---------->found pair (n,m) = ("" + a + "","" + n + "")"" ); total++; } else { System.out.println(""*********>IS NOT a pair (n,m) = ("" + a + "","" + n + "")"" ); } */ /* if (Integer.parseInt(n.toString()) == a) { total++; break; } */ } m++; } a++; } /* while (a <= b) { if ( a < 10 ) { break; } StringBuffer n = new StringBuffer(""""+a); System.out.println(""n: "" + n); for (int j = 0; j < n.length()-1; j++) { n.append(n.charAt(0)); n.delete(0,1); System.out.println(""shifted n..."" + n ); /* if (a < Integer.parseInt(n.toString()) && Integer.parseInt(n.toString()) <= b) { System.out.println(""---------->found pair (n,m) = ("" + a + "","" + n + "")"" ); total++; } else if (Integer.parseInt(n.toString()) == a && Integer.parseInt(n.toString()) == b ) { total++; } else if (Integer.parseInt(n.toString()) == b) { System.out.println(""---------->found pair (n,m) = ("" + a + "","" + n + "")"" ); total++; } else { System.out.println(""*********>IS NOT a pair (n,m) = ("" + a + "","" + n + "")"" ); } */ /* if (Integer.parseInt(n.toString()) == a) { total++; break; } }*/ /* if (Integer.parseInt(n.toString()) < a || Integer.parseInt(n.toString()) > b) { } else if (n.charAt(0) == '0' || input[1].charAt(0) == '0' ) { } else if (Integer.parseInt(n.toString()) == a && Integer.parseInt(n.toString()) == b ) { total++; } else if (Integer.parseInt(n.toString()) > a && Integer.parseInt(n.toString()) <= b ) { total++; } } */ /* a++; } System.out.println(""Case #"" + (i+1) + "": "" + total); */ System.out.println(""Case #"" + (i+1) + "": "" + total); } } catch (IOException e) { e.printStackTrace(); } } } " B12515,"import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class C { public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(new File(""input.txt"")); int tt = sc.nextInt(); int cc = 0; for(int t = 0; t < tt; ++t) { int A = sc.nextInt(); int B = sc.nextInt(); int len =String.format(""%d"", B).length(); int ans = 0; for(int n = A; n < B; ++n) { for(int m = n+1; m <= B; ++m) { String x = String.format(""%d"", n); String y = String.format(""%d"", m); boolean found = false; for(int i = 1; i < len; ++i) { String z = x.substring(i) + x.substring(0, i); if(z.equals(y)) { found = true; break; } } if(found) ans++; } } System.out.format(""Case #%d: %s\n"", ++cc, ans); } } } " B10864,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; public class ProblemC { private String line = """"; private String fileContents = """"; private String delim = ""\r\n""; private String fileName = ""C-small-attempt0.in""; public void solve() { StringTokenizer st = new StringTokenizer(fileContents,delim); StringTokenizer lineToken = null; int count = 1; int testCases = 0; int lower = 0; int upper = 0; int y = 0; ArrayList numbersList = new ArrayList(); testCases = Integer.parseInt(st.nextToken()); while(st.hasMoreTokens()) { line = st.nextToken(); System.out.print(""Case #""); System.out.print(count++); System.out.print("": ""); lineToken = new StringTokenizer(line,"" ""); lower = Integer.parseInt(lineToken.nextToken()); upper = Integer.parseInt(lineToken.nextToken()); y = 0; int numberLen = 0; for(int i=lower; i i && ni <= n[1]) { boolean dup = false; for (int k = 0; k < j-1; k++) { if(sh[k] == ni) dup = true; } if(!dup) res++; } } } return res; } private int shift(int i, int j, int len) { int ex = i % ((int)Math.pow(10, j)); int div = i / (int)Math.pow(10, j); return ex * (int)Math.pow(10, len-j) + div; } private int getLen(int n) { int c = 0; while(n > 0){ n /= 10; c++; } return c; } } " B13205,"// Google Code Jam 2011 // lid package Real; import java.io.*; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.InputMismatchException; import org.apache.commons.lang.ArrayUtils; @SuppressWarnings(""unused"") class T3 implements Runnable { // params // static String filePrefix = ""/jam/C-example""; static String filePrefix = ""/jam/C-small-attempt0""; //static String filePrefix = ""/jam/A-large""; // I/O private InputReader in; //@SuppressWarnings(""unused"") private PrintWriter out; public static void main(String[] args) { new Thread(new T3()).start(); // init filestreams then start thread } // Init filestreams public T3() { try { System.setIn(new FileInputStream(filePrefix + "".in"")); System.setOut(new PrintStream(new FileOutputStream(filePrefix + "".out""))); } catch (FileNotFoundException e) { log(""Tried to open "" + filePrefix + "".in""); throw new RuntimeException(); } in = new InputReader(System.in); out = new PrintWriter(System.out); } // Start thread public void run() { // Keep track of time for efficiency (Zaphod) long startTime = System.currentTimeMillis(); logn(""Starting.""); int num_cases = in.readInt(); logn(""Num_cases: "" + num_cases); ArrayList list = new ArrayList(50); for (int case_num = 0; case_num < num_cases; case_num++) { // brute force that bitch int start = in.readInt(); int end = in.readInt(); int numOut = 0; for (Integer cur = start; cur <= end; cur++) { String curS = cur.toString(); for (int rotnum = 0; rotnum < curS.length(); rotnum++) { // String curSr = curS.substring(beginIndex) curS = curS.substring(curS.length()-1,curS.length()) + curS.substring(0,curS.length()-1); if (curS.charAt(0) == '0') continue; Integer rotInt = Integer.parseInt(curS); if (rotInt <= end && rotInt >= start && rotInt > cur) { list.add(rotInt); numOut++; logn("""" + cur + "","" + curS); // break; } } } fout(""Case #"" + (case_num + 1) + "": ""); fout("""" + numOut); fout (""\n""); } logn(""Done.""); long stopTime = System.currentTimeMillis(); logn(""Time: "" + (stopTime - startTime) / 1000.0); } private static void fout (String msg) { System.out.print(msg); } private static void log (String msg) { System.err.print(msg); } private static void logn (String msg) { System.err.println(msg); } // readCharacter, readString, readInt, readLong, readLine, readDouble //@SuppressWarnings(""unused"") // from Egor Kulikov private static class InputReader { private InputStream stream; private byte[] buf = new byte[1000]; private int curChar, numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuffer buf = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { buf.appendCodePoint(c); c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) s = readLine0(); return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) return readLine(); else return readLine0(); } public BigInteger readBigInteger() { try { return new BigInteger(readString()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } public double readDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } } //@SuppressWarnings(""unused"") private static int getBit (int input, int pos) { input >>= pos; return input & 0x0001; } } " B12389,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; import java.io.*; import java.util.*; /** * * @author jgao */ public class CodeJamC { /** * @param args the command line arguments */ public static void main(String[] args) { String file = ""C-small-attempt0.in""; List input; try { input = readFile(file); } catch(Exception e) { return; } boolean[][] mat = recycleMatrix(0,1000); for (int i=1; i readFile(String file) throws Exception { List content = new ArrayList(); BufferedReader in = new BufferedReader(new FileReader(file)); for (String line=in.readLine(); line!=null; line=in.readLine()) { content.add(line); } in.close(); return content; } public static boolean[][] recycleMatrix(int n, int m) { boolean[][] res = new boolean[m-n+1][m-n+1]; for (int i=n; i * Cette classe comporte des méthodes utilitaires de gestion des flux d'entrée/sortie. *

* * @author renouxg */ public class FluxUtils { /** *

* Constructeur privé : cette classe utilitaire n'est pas destinée à être instanciée. *

*/ private FluxUtils() { // classe non instanciable } /** *

* Cette méthode utilitaire ferme tous les objets Closeable qui lui sont passés en paramètre. * Les éléments nuls sont ignorés. Si la fermeture de l'un ou plusieurs d'entre eux renvoie une erreur, on * tâche néanmoins de fermer tous les flux ; la première erreur survenue est ensuite relancée. *

* * @param fluxArray les objets implémentant {@link Closeable} qu'il faut fermer. * @throws IOException toute exception qui peut se produire à la fermeture d'un {@link Closeable}. */ public static void closeCloseables(final Closeable... fluxArray) { IOException relaunch = null; for (Closeable flux : fluxArray) { if (flux == null) { continue; } try { flux.close(); } catch (IOException lEx) { if (relaunch == null) { relaunch = lEx; } else { // Nouvelle exception, ignorée } } } if (relaunch != null) { throw new TechnicalException(relaunch); } } } " B12827,"import java.util.Scanner; public class RecycledSmall { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int cases = scan.nextInt(); for (int trial = 1; trial <= cases; trial++) { System.out.print(""Case #"" + trial + "": ""); int a = scan.nextInt(); int b = scan.nextInt(); int rots = 0; for (int v = a; v < b; v++) { rots += countRotations(v, b); } System.out.println(rots); } } private static int countRotations(int v, int b) { String vString = Integer.toString(v); String nextString = vString; int count = 0; while (true) { nextString = rotate(nextString); if (nextString.equals(vString)) break; int newV = Integer.parseInt(nextString); if (newV > v && newV <= b) count++; } return count; } private static String rotate(String nextString) { return nextString.substring(1) + nextString.charAt(0); } } " B10654,"import java.io.*; import java.util.*; import java.io.*; import java.util.*; import static java.lang.System.*; import java.util.Map; import java.util.TreeMap; import java.util.Collection; import java.util.List; import java.util.Arrays; import java.util.Iterator; public class goog { public static void main(String[] args) throws IOException { Scanner file = new Scanner(new File(""C-small-attempt0.in."")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""prob1.out""))); int times = file.nextInt(); file.nextLine(); for(int i = 0;i answers = new ArrayList(); out.print(""Case #""+(i+1)+"": ""); int a =file.nextInt(); int b= file.nextInt(); int answer =0; int random =0; for(int d = a; d hs = new HashSet(); for (int test=1; test<=tests; test++) { out.print(""Case #""+test+"": ""); int a = nextInt(); int b = nextInt(); int t = Integer.valueOf(a).toString().length(); int dp = 1; for (int i=1; ii && x>=a && x<=b) { hs.add(x*100l*dp+i); res++; } // out.println(i+"" ""+x); } } res = hs.size(); out.println(hs.size()); hs.clear(); } } BufferedReader br; StringTokenizer st; PrintWriter out; public void run() { try { //br = new BufferedReader(new InputStreamReader(System.in)); //out = new PrintWriter(System.out); br = new BufferedReader(new FileReader(""input.txt"")); out = new PrintWriter(""output.txt""); solve(); br.close(); out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(123); } } String next() throws IOException { while (st == null || !st.hasMoreTokens()) { String s = br.readLine(); if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } double nextDouble() throws IOException { return Double.parseDouble(next()); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } public static void main(String[] args) { new Main().run(); } } " B12916,"import java.awt.datatransfer.StringSelection; import java.util.*; public class q3 { public static void main(String[] args) { new q3().run(); } Scanner input = new Scanner(System.in); void run(){ int c = input.nextInt(); for(int i=1;i<=c;i++){ System.out.print(""Case #""+i+"": ""); solve(); } } void solve(){ int a = input.nextInt(); int b = input.nextInt(); boolean [] used = new boolean [b+1]; int ans = 0; String x; int i,j,k,y; for(i=a;i<=b;i++){ x = Integer.toString(i);; for(j=1;j<=x.length()-1;j++){ y = recycled(x,j); //System.out.println(y); if(y >= a && y <= b && !used[y] && i!=y){ //System.out.println(i +"" ""+y); ans++; } } used[i] = true; } System.out.println(ans); } int recycled(String x,int n){ String f = x.substring(x.length()-n,x.length()); int i; for(i=0;i99?100:10)+a/10; } else return (a % 100)*10+a/100; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub File f = new File(""D://1.txt""); Scanner sc; try { sc = new Scanner(f); int n = sc.nextInt(); //System.out.println(n); for (int i = 0;ij && recycle(j,1)<=b){ //System.out.println(j); //System.out.println(recycle(j,1)); num++; } if (j>99 && recycle(j,2)>j && recycle(j,2)<=b) { //System.out.println(j); //System.out.println(recycle(j,2)); num++; } } } System.out.println(""Case #""+(i+1)+"": ""+num); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B11323,"import java.util.*; import java.io.*; import static java.lang.Math.*; public class A { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader in = new BufferedReader(new FileReader(""C-small-attempt0.in"")); FileWriter fw = new FileWriter(""output.out""); /*BufferedReader in = new BufferedReader(new FileReader(""A-large.in"")); FileWriter fw = new FileWriter(""A-large.out"");*/ int N = new Integer(in.readLine()); String[] output = new String[N]; int[] trueCount = new int[N]; for (int cases = 0; cases < N; cases++) { int CaseNo = cases+1; output[cases] = """"; StringTokenizer G = new StringTokenizer(in.readLine()); int W = G.countTokens(); int[] a = new int[2]; String[] b = new String[W]; for (int j = 0; j < a.length; j++) { a[j] = new Integer(G.nextToken()); } int counter = 1; int A =a[0]; int B =a[1]; int C = a[0]; System.out.println(A + "" x "" +B); int lengthA = Integer.toString(A).length(); if (lengthA == 1){ trueCount[cases] = 0; } else{ int range = B - A + 1; int[] rangeA = new int[range]; rangeA[0] = A; while (A currentN && currentM >= C){ trueCount[cases]+=1; } } } } fw.write(""Case #""+CaseNo+"": ""+ trueCount[cases]+ ""\n""); } fw.flush(); fw.close(); } } " B10380,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; public class RecycledNumbers { public static void main(String []args) throws IOException{ BufferedReader reader = new BufferedReader(new FileReader(new File(""C-small-attempt0.in""))); BufferedWriter writer = new BufferedWriter(new FileWriter(new File(""out""))); int T = Integer.parseInt(reader.readLine()); for(int i = 0;i set = new HashSet(); String[] limits = reader.readLine().split("" ""); int A = Integer.parseInt(limits[0]); int B = Integer.parseInt(limits[1]); for(int j = A;j list = new LinkedList(); String num = """"+j; for(int k = 0;kj&&result<=B){ set.add(new ValuePairs(j,result)); System.out.println(j+"" ""+result+""\n""); } } } writer.write(""Case #""+(i+1)+"": ""+set.size()+""\n""); writer.flush(); } } } " B10943," import java.io.BufferedReader; import java.io.FileReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Vector; public class Task3 { public static void main(String[] args) { try { readSolveAndWrite(""C-small-attempt1.in"", ""output_file.txt""); } catch(IOException ioException) { System.err.println(ioException); } } protected static void readSolveAndWrite(final String inputPath, final String outputFile) throws IOException { BufferedReader in = new BufferedReader(new FileReader(inputPath)); BufferedWriter out = new BufferedWriter(new FileWriter(outputFile)); int n = Integer.parseInt(in.readLine()); for(int i = 0; i < n; i++) { final String inputLine = in.readLine(); final String outputLine = ""Case #"" + (i + 1) + "": "" + solve(inputLine); out.write(outputLine); out.newLine(); } out.flush(); out.close(); in.close(); } protected static int convertToInt(Vector digits) { int result = 0; for(int i = digits.size() - 1; i >= 0; i--) result = result*10 + digits.elementAt(i).intValue(); return result; } protected static Vector> getPermutations(final int n) { Vector base = new Vector(); int m = n; while(true) { int digit = m % 10; base.add(new Integer(digit)); m = m / 10; if(m == 0) break; } Vector> permutations = new Vector>(); for(int i = 0; i < base.size(); i++) { Vector temp = new Vector(); for(int j = i; j < base.size(); j++) temp.add(base.elementAt(j)); for(int j = 0; j < i; j++) temp.add(base.elementAt(j)); permutations.add(temp); } return permutations; } protected static String solve(final String line) { HashMap map = new HashMap(); String[] elements = line.split("" ""); final int min = Integer.parseInt(elements[0]); final int max = Integer.parseInt(elements[1]); int result = 0; for(int i = min; i <= max; i++) { Vector> permutations = getPermutations(i); int current = convertToInt(permutations.elementAt(0)); for(int j = 1; j < permutations.size(); j++) { int temp = convertToInt(permutations.elementAt(j)); if(current < temp && min <= temp && temp <= max && null == map.get(new String(current + """" + temp))) { result++; map.put(new String(current + """" + temp), new Integer(1)); map.put(new String(temp + """" + current), new Integer(1)); } } } return """" + result; } }" B11273,"/** * */ package google.jam.code; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; /** * @author walir * */ public class RecycledNumbers { private BufferedReader bufferedReader; public RecycledNumbers() throws FileNotFoundException { File file = new File(""C:/test""); InputStreamReader in = new InputStreamReader(new FileInputStream(file)); bufferedReader = new BufferedReader(in); } public static void main(String[] args) throws NumberFormatException, IOException{ RecycledNumbers recycledNumbers = new RecycledNumbers(); recycledNumbers.bp(); } private void bp() throws NumberFormatException, IOException { int numberOfCases = Integer.valueOf(bufferedReader.readLine()); for (int i = 1; i <= numberOfCases; i++) { String s[] = bufferedReader.readLine().split("" ""); Integer lLim = Integer.valueOf(s[0]); Integer uLim = Integer.valueOf(s[1]); int res = calc(lLim, uLim); System.out.println(""Case #"" + i + "": "" + res); } } private int calc(Integer lLim, Integer uLim) { int total = 0; for(int l = lLim;l0){ temp /= 10; d++; } int a[]=new int[d]; for(int i=0;i file, int line) { StoreCreditCase cas = new StoreCreditCase(); String fist = file.get(line); String second = file.get(line+1); String third = file.get(line+2); cas.credit= Integer.parseInt(fist); cas.lineCount = 3; cas.itemCount = Integer.parseInt(second); cas.prices = JamUtil.parseIntList(third, cas.itemCount); return cas; } } class StoreCreditCase extends JamCase { int itemCount; int[] prices; public int credit; } " B10076,"package qualification; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.PrintStream; public class C { static byte[][] MAP = new byte[1000][1000]; private static final char[] CASE = ""Case #"".toCharArray(); public static void main(String[] args) throws Throwable { // in = System.in; // out = System.out; in = new FileInputStream(""in/C-small-attempt0.in""); // in = new FileInputStream(""in/C-large.in""); out = new PrintStream(new FileOutputStream(""out/C.out"")); int T = readInt(); for (int test = 1; test <= T; test++) { int A = readInt(); int B = readInt(); int result = 0; for (int n = A; n < B; n++) { int nLen = length(n); // find all possible recycled numbers for this one for (int i = 1; i < nLen; i++) { int tenpow = pow(10,i); int tenpowfront = pow(10, nLen-i); int m = (n/tenpow) + ((n%tenpow) * tenpowfront); if (m == n) break;// if we found n back, it is a circular number (ex: 123123), and if we keep going, we'll duplicate the results found // the recycled numbers have to be: n < m; m <= B if (n < m && m <= B) { result++; } } } writeOut(CASE); writeOutNumber(test); writeOut(':'); writeOut(' '); writeOutNumber(result); writeOutLn(); flush(); } flush(); } static int length(int num) { int len = 1; int powerTen = 10; while (num >= powerTen) { powerTen *= 10; len++; } return len; } static InputStream in; static PrintStream out; static byte[] buffer = new byte[8192]; static int pos; static int max; static final int maxOut = 8192; static byte[] output = new byte[maxOut]; static int posOut = 0; static char[] tmpcharr = new char[128]; static int pow2(int v) { return v * v; } static int pow(int v, int mag) { return (int) Math.pow(v, mag); } static boolean reachedEndOfLine() throws Throwable { while (true) { int data = read(); if (data == -1) return true; if (data == '\r' || data == '\n') { return true; } if (data == ' ') { continue; } pos--; return false; } } // COMPARISION FUNCTIONS static boolean isValidChar(int v) { // nao verifica o 'DELETE' (127) return (v & 0xE0) != 0; } static boolean isNum(int v) { return v >= '0' && v <= '9'; } static boolean isLowercase(int cur) { return cur >= 'a' && cur <= 'z'; } static boolean isUppercase(int cur) { return cur >= 'A' && cur <= 'Z'; } // is a letter (alphabetic) static boolean isAlpha(int cur) { return isLowercase(cur) || isUppercase(cur); } // is alphanumeric (letters and numbers) static boolean isAlphaNum(int cur) { return isAlpha(cur) || isNum(cur); } static boolean isMinus(int cur) { return cur == '-'; } static boolean isPlus(int cur) { return cur == '+'; } // INPUT FUNCTIONS static void goToBeginOfNextWord() throws Throwable { int cur; // se for -1 já sai do método while ((cur = read()) != -1) { // se for um char válido então deixa o ponteiro nele if (cur > 32) { pos--; return; } } } // return the length of the string read static String readWord() throws Throwable { int len = 0; int cur; // descarta os espacos em branco primeiro while ((cur = read()) < 33) { if (cur == -1) return """"; } tmpcharr[len++] = (char) cur; while ((cur = (char) read()) > 32) { tmpcharr[len++] = (char) cur; } return new String(tmpcharr, 0, len); } static void discardWord() throws Throwable { int cur; // descarta os espacos em branco primeiro while ((cur = read()) < 33) { if (cur == -1) return; } // descarta os valores 'validos' while ((cur = read()) > 32) ; } static int readInt() throws Throwable { int cur; while (!isNum(cur = read()) && !isMinus(cur)) if (cur == -1) return -1; int v = 0; boolean minus = false; if (isMinus(cur)) { minus = true; cur = read(); } while (isNum(cur)) { v *= 10; v += (cur - '0'); cur = read(); } return minus ? -v : v; } static char readChar() throws Throwable { int cur; for (;;) { cur = read(); if (cur == -1) return 0; if (cur == '\r' || cur == '\n' || cur == ' ') continue; return (char) cur; } } static long readLong() throws Throwable { int cur; while (!isNum(cur = read()) && !isMinus(cur)) if (cur == -1) return -1; long v = 0; boolean minus = false; if (isMinus(cur)) { minus = true; cur = read(); } while (isNum(cur)) { v *= 10; v += (cur - '0'); cur = read(); } return minus ? -v : v; } static boolean hasInput() throws Throwable { while (true) { int data = read(); if (data == -1) return false; if ((data & 0xE0) != 0) { pos--; return true; } } } static int read() throws Throwable { if (pos >= max) { max = in.read(buffer); if (max < 0) return -1; pos = 0; } return buffer[pos++] & 0xff; } // OUTPUT FUNCTIONS // escreve um char static void writeOut(char c) { if (posOut >= maxOut) { writeOutToStream(); } output[posOut++] = (byte) c; } // escreve a quebra de linha static void writeOutLn() { writeOut('\n'); } // escreve um char[] static void writeOut(char[] cs) { writeOut(cs, 0, cs.length); } // escreve uma cadeia de caracteres static void writeOut(char[] chars, int offset, int length) { final int end = offset + length; for (int i = offset; i < end; i++) { writeOut(chars[i]); } } static void writeOutNumber(int value) { int len = 0; int pos = tmpcharr.length; if (value == 0) { writeOut('0'); return; } boolean negative = value < 0; if (negative) value = -value; while (value > 0) { tmpcharr[--pos] = (char) ((value % 10) + '0'); len++; value /= 10; } if (negative) writeOut('-'); writeOut(tmpcharr, pos, len); } static void writeOutNumberAsBin(int num) { int len = 0; int pos = tmpcharr.length; if (num == 0) { writeOut('0'); return; } while (num > 0) { tmpcharr[--pos] = ((num & 1) == 1) ? '1' : '0'; len++; num >>>= 1; } writeOut(tmpcharr, pos, len); } static void flush() { writeOutToStream(); out.flush(); } // PRIVATE methods must be used only by the utility methods private static void writeOutToStream() { out.write(output, 0, posOut); posOut = 0; } }" B10222,"import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.PrintStream; import java.util.Scanner; //javac C.java && java C x.in x.out public class C { public static void main(String[] args) throws FileNotFoundException { InputStream in = System.in; if(args.length>0) in = new FileInputStream(args[0]); PrintStream out = System.out; if(args.length>1) out = new PrintStream(args[1]); Solver s = new Solver(new Scanner(in),out); //Multiple case input s.cases(); //Single case input //s.go(); } } class Solver { Scanner in; PrintStream out; public Solver(Scanner scanner, PrintStream printStream) { in = scanner; out = printStream; } public void cases() { int numCases = in.nextInt(); in.nextLine(); for(int i=0;i0) { a/=10; mod*=10; digs++; } for(int n = A; n <= B; n++) { for(int m = n+1; m <= B; m++) { int nn=n; for(int i = 0; i < digs; i++) { nn=(nn+mod*(nn%10))/10; if(nn==m) { ans++; break; } } } } out.println(ans); } }" B11211,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; public class Recycled { private static String FileNameFrom = """"; private static String FileNameTo = """"; /** * @param args */ private int calculate(int n, int m){ HashSet pairsTest = null; int totalPairs = 0; String n_Str = null; int n_Length = 0; for(int i_n = n; i_n < m; i_n++){ n_Str = String.valueOf(i_n); //System.out.println(n_Str); n_Length = n_Str.length(); int afterShift = 0; pairsTest = new HashSet(); for(int move_n = 1; move_ni_n)&&(afterShift <= m)){ if(!pairsTest.contains(i_n + "" "" + afterShift)){ pairsTest.add(i_n + "" "" + afterShift); totalPairs = totalPairs + 1; } else{ //System.out.println(i_n + "" "" + afterShift); } } } pairsTest = null; } return totalPairs; } private int getShifted(int n,int moveToLast){ StringBuffer n_SB = new StringBuffer(); char[] moveThisPart = new char[moveToLast]; n_SB.append(n); n_SB.getChars(0, moveToLast, moveThisPart, 0); n_SB.delete(0, moveToLast); n_SB.append(moveThisPart); return Integer.valueOf(n_SB.toString()); } public static void main(String[] args) { // TODO Auto-generated method stub Recycled rec = new Recycled(); rec.loadPropertiesFile(""recycle""); int testCaseNumber = 0; BufferedReader input = null; BufferedWriter bufferedWriter = null; String line = null; try { input = new BufferedReader(new FileReader(FileNameFrom)); bufferedWriter = new BufferedWriter(new FileWriter(FileNameTo)); line = input.readLine(); testCaseNumber = Integer.parseInt(line); for(int k =0;k set = new HashSet(); int digits = text.indexOf("" ""); ArrayList list1 = new ArrayList(); ArrayList list2 = new ArrayList(); for (int n=A; n<=B; n++){ if (!set.contains(n)) { String nString = Integer.toString(n); HashSet group = new HashSet(); group.add(n); for (int j=1; j=A && m<=B && m!=n) { group.add(m); } } for (int i : group) set.add(i); Object[] groupArray = group.toArray(); for (int i=0; i current_n && current_m >= a) { ++count; } } } } out.println(count); } in.close(); out.close(); } }" B12656,"import java.io.*; import java.util.*; public class RecycledNumbers { public static void main(String[] args)throws Exception { File f = new File(""recyclednumbers.txt""); File outp = new File(""recyclednumbers.out""); Scanner sc = new Scanner(new FileReader(f)); Writer wr = new BufferedWriter(new FileWriter(outp)); int t = sc.nextInt(); for(int casse=1; casse<=t; casse++) { String as = sc.next(), bs = sc.next(); int a = Integer.parseInt(as), b = Integer.parseInt(bs); boolean[][] check = new boolean[b-a+1][b-a+1]; int digits = (int) (Math.ceil(Math.log10(b))); for(int i=a; i<=b; i++) { String temp1 = new Integer(i).toString(); //StringBuffer temp1 = new StringBuffer(s); int start=0; for(int j=1; j<=digits; j++) { StringBuffer temp2 = new StringBuffer(temp1.length()); int count = 1; for(int k=start; count<=digits; count++, k=(k+1)%digits) temp2.append(temp1.charAt(k)); start++; if(temp2.charAt(0)=='0') continue; int n1 = Integer.parseInt(temp1.toString()); int n2 = Integer.parseInt(temp2.toString()); if(a<=n2 && n2<=b) check[n1-a][n2-a] = check[n2-a][n1-a] = true; } } int count = 0; for(int i=0; i100){ int f2 = flip2(i); if (( i results = new ArrayList<>(); int A, B; Scanner in = new Scanner(System.in); int t = Integer.parseInt(in.nextLine()); System.out.println(); for (int i = 0; i < t; i++) { String line = in.nextLine(); A = Integer.parseInt(line.split("" "")[0]); B = Integer.parseInt(line.split("" "")[1]); results.add(check(A, B)); } System.out.println(""Output""); for (int i = 0; i < results.size(); i++) { System.out.println(""Case #"" + (i + 1) + "": "" + results.get(i)); } } public static int check(int A, int B) { int count = 0; List M = new ArrayList<>(); List N = new ArrayList<>(); for (int i = A; i <= B; i++) { N.add(i); M.add(i); } for (int i = 0; i < N.size(); i++) { String nn = N.get(i) + """"; int n = Integer.parseInt(nn); for (int x = 1; x <= nn.length(); x++) { String sufix = nn.substring(0, x); String prefix = nn.substring(x); int newNum = Integer.parseInt(prefix + sufix); for (int j = 0; j < M.size(); j++) { int m = M.get(j); if (A <= n && n < m && newNum == m && m <= B) { count++; } } } } return count; } } " B12301,"package com.phonescreen; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; public class RecycledNumber { private static int count; public static void main(String[] args) { try { DataInputStream br = new DataInputStream(new BufferedInputStream(new FileInputStream(new File(""H:\\C-small-attempt1.in"")))); String s = br.readLine(); count = Integer.parseInt(s); if (count < 1 || count > 50) { return; } for (int i = 0; i < count; i++) { String[] testCase = br.readLine().split("" ""); if (testCase[0].length() != testCase[1].length()) { return; } int a = Integer.parseInt(testCase[0]); int b = Integer.parseInt(testCase[1]); if (a < 1 || b > 1000 || a > b) { return; } System.out.println(""Case #"" + ( i+1) + "": "" + getRecycledNumberCount(a, b)); } } catch (Exception e) { System.err.println(""Error:"" + e.getMessage()); } } private static int getRecycledNumberCount(int a, int b) { int count = 0; for (int i = a; i <= b; i++) { for (int j = i; j <= b; j++) { if (isRecycledNumbers(i + """", j + """")) { count++; } } } return count; } private static boolean isRecycledNumbers(String num1, String num2) { for (int i = 0; i < num1.length(); i++) { if (num2.indexOf(num1.charAt(i)) == -1 || num1.indexOf(num2.charAt(i)) == -1) { return false; } } for (int i = num1.length() - 1; i >= 0; i--) { String subStr = num1.substring(i); if (num2.indexOf(subStr) == -1) { subStr = num1.substring(i + 1); String s = subStr + num1.substring(0, (num1.length() - subStr.length())); if (s.equals(num2)) { return true; } } } return false; } } " B11364,"package com.jagsaund.codejam.qualifcation; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; public class RecycledNumbers { public RecycledNumbers() { } public String run(String line) { int m; int n; StringTokenizer tokenizer = new StringTokenizer(line); n = Integer.parseInt(tokenizer.nextToken()); m = Integer.parseInt(tokenizer.nextToken()); Map> map = new HashMap>(); for (int i=0; i<=(m-n); i++) { String value = Integer.toString((i+n)); // System.out.println(""current value: "" + value); if (!map.containsKey((i+n))) { map.put((i+n), new HashSet()); } for(int j=1; j= n && rotatedNumber <= m && rotatedNumber != (i+n)) { if (map.containsKey(rotatedNumber)) { } else { Set set = map.get((i+n)); set.add(rotatedNumber); map.put((i+n), set); // System.out.println(""Added: "" + rotatedNumber); // System.out.println(""Current pairs: "" + set.size()); } } } } int count = 0; Set keys = map.keySet(); for (Iterator it = keys.iterator(); it.hasNext();) { count += map.get(it.next()).size(); } return count + """"; } } " B10715,"import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Set; public class Main { public static void main(String[] args) { File inputFile = new File(""input.txt""); BufferedReader br = null; FileOutputStream out = null; try { br = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile))); String line; line = br.readLine(); if (line == null) { throw new IllegalStateException(""Empty input file!!!""); } StringBuilder result = new StringBuilder(); int length = Integer.parseInt(line), i = 1; while (i <= length) { result.append(""Case #"").append(i).append("": ""); /////////////////////////////////////////////////////////////////////////////////////////////////// Set match = new HashSet(); String[] numbers = br.readLine().split("" ""); int n = Integer.parseInt(numbers[0]); int m = Integer.parseInt(numbers[1]); for (int j = n;j < m; j++) { String num = j + """"; char[] charArray = num.toCharArray(); if (num.length() < 2 || isCharsEqual(charArray)) { continue; } addMatches(charArray, n, m, match); } result.append(match.size()); /////////////////////////////////////////////////////////////////////////////////////////////////// result.append(""\n""); i++; } File outputFile = new File(""output.txt""); outputFile.delete(); outputFile.createNewFile(); out = new FileOutputStream(outputFile); out.write(result.toString().getBytes()); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } private static boolean isCharsEqual(char[] num) { char c = num[0]; for (int i = 1; i < num.length; i++) { if (c != num[i]) { return false; } } return true; } private static void addMatches(char[] num, int lower, int upper, Set match) { String n = new String(num); char[] tmp = spin(num); for (int i = 1; i < num.length; i++) { if (tmp[0] != '0') { int m = Integer.parseInt(new String(tmp)); String key = genKey(n, """" + m); if (lower <= m && m <= upper && !n.equals(m + """") && !match.contains(key)) { match.add(key); } } tmp = spin(tmp); } } private static char[] spin(char[] source) { char[] target = new char[source.length]; for (int i = 1; i < source.length; i++) { target[i] = source[i - 1]; } target[0] = source[source.length - 1]; return target; } private static String genKey(String n, String m) { if (n.compareTo(m) < 0) { return n + ""|"" + m; } else return m + ""|"" + n; } } " B12917," import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.logging.Level; import java.util.logging.Logger; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author B4dT0bi */ public class RecycledNumbers { public static String [] input; public static String wholeOutput=""""; public static void readInput(String inputFile) { BufferedReader br = null; try { br = new BufferedReader(new FileReader(inputFile)); String serializedSettings = """"; String line = null; while ((line = br.readLine()) != null) serializedSettings += line + ""\n""; input=serializedSettings.split(""\n""); br.close(); } catch (Exception ex) { ex.printStackTrace(); } finally { try { br.close(); } catch (IOException ex) { ex.printStackTrace(); } } } public static void writeOutput(String inputFile) { try { BufferedWriter out = new BufferedWriter(new FileWriter(inputFile+"".out"")); out.write(wholeOutput); out.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { readInput(args[0]); wholeOutput=""""; for(int i=1;ialready=new HashSet(); for(int i=1;ix) { if(!already.contains(tmp)) { already.add(tmp); anz++; } } } return anz; } } " B11457,"import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class Recycled { private int A; private int B; private int pairs; /** * Constructor * * @param a * @param b */ public Recycled(int a, int b) { A = a; B = b; pairs = 0; } /** * @param args */ public static void main(String[] args) { try { // Input I/O handler File input = new File(args[0]); Scanner sc = new Scanner(input); int cases = Integer.parseInt(sc.nextLine()); // Output I/O handler FileWriter output = new FileWriter(args[1], true); PrintWriter pw = new PrintWriter(output); // Process all the cases for (int i = 1; i <= cases; i++) { String[] data = sc.nextLine().split("" ""); Recycled solver = new Recycled(Integer.parseInt(data[0]), Integer.parseInt(data[1])); solver.solve(); pw.println(""Case #"" + i + "": "" + solver.getPairs()); pw.flush(); } } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Returns the number of recycled number pairs. * @return */ private int getPairs() { return pairs; } /** * Solves the given test case. */ private void solve() { for (int n = A; n <= B; n++) { String written = """" + n; for (int k = 1; k < written.length(); k++) { String swap= written.substring(k) + written.substring(0,k); if (written.charAt(0)=='0'){ continue; } Integer m= Integer.parseInt(swap); if (n < m && m <= B) { System.out.println("""" + n + ""\t"" + m); pairs++; } } } } } " B11469,"package com.codejam.googlearse; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.HashSet; public class Problem3 { public static void main(String arg[]) { try{ FileInputStream fstream = new FileInputStream(""textfile.txt""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter foutstream = new FileWriter(""test1.out""); BufferedWriter out = new BufferedWriter(foutstream); String strLine, copyStrLine = """"; int caseCount = -1; strLine = br.readLine(); caseCount = Integer.parseInt(strLine); for(int j=0; j < caseCount; j++) //System.out.println (strLine); { strLine = br.readLine(); String[] splitStrings = strLine.split("" ""); int A = Integer.parseInt(splitStrings[0]); int B = Integer.parseInt(splitStrings[1]); int recycleCount = 0; for(int n = A; n < B; n++) { int count = 10 ; int counter = 0; int len = splitStrings[1].length()-1; int arrayNumbers[]; HashSet hashSet = new HashSet(); while(counter < len) { int tail = n % count; int front = n / count; count = count * 10 ; int val = (int) Math.pow(10,(len - counter)); int m = tail * val + front; //System.out.println(i+"":""+"":""+temp+"":""+val); if(m > A && m <= B && m > n) { hashSet.add(new Integer(m)); } counter++; } recycleCount = recycleCount + hashSet.size(); } System.out.println(recycleCount); out.write(""Case #"" + (j + 1) + "": "" + recycleCount + ""\n""); } out.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } } " B10927,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam.y12.round0; import utils.Jam; import utils.JamCase; /** * * @author fabien */ public class DancingGooglers extends Jam { public DancingGooglers(String filename) { super(filename); } @Override public JamCase getJamCase(int number) { return new Line(this, number, lines[number]); } private class Line extends JamCase { private String line; private int s; private int p; private int[] scores; public Line(Jam parent, int number, String line) { super(parent, number); this.line = line; } @Override public void parse() { String[] integers = line.split("" ""); scores = new int[Integer.parseInt(integers[0])]; s = Integer.parseInt(integers[1]); p = Integer.parseInt(integers[2]); int j = 0; for (int i = 3; i < integers.length; i++) { scores[j++] = Integer.parseInt(integers[i]); } } @Override public void solve() { int r = 0; if (p == 0) { r = scores.length; } else { float average = 0; float pnor = p - 1; float psus = p - 1.4f; for (int score : scores) { if (score > 0) { average = score / 3.0f; if (average > pnor) { r++; } else if (s > 0 && average >= psus) { r++; s--; } } } } result = Integer.toString(r); } } } " B11345,"package qualification; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class c { public static void main(String[] args){ if(args.length<1){ System.out.println(""Usage: ""); } String fn = args[0]; String fnOut = toFnOut(fn); try{ BufferedReader br = new BufferedReader(new FileReader(fn)); BufferedWriter bw = new BufferedWriter(new FileWriter(fnOut)); int NCase = Integer.valueOf(br.readLine().trim()); long stime = System.currentTimeMillis(); for(int icase=0;icase=x && k<=y ){ int klength = K.length(); if(klength ==1) k++; else{ for(int r = 1;r=x && newk>k && newk<=y ){ result++; } } k++; } K = Integer.toString(k); } return result; } static String toFnOut(String fn){ if(fn.lastIndexOf('.')!=-1){ return fn.substring(0,fn.lastIndexOf('.'))+"".out""; }else return fn + "".out""; } } " B12241,"package com.google.codejam; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; public class RecycledNumberSolver { public static int countRecycledNumber(int start, int end) { int count = 0; int numOfDigits = String.valueOf(start).length(); Set numberSet = new HashSet(end - start + 1); for (int i = start; i <= end; i++) { numberSet.add(String.valueOf(i)); } while(numberSet.isEmpty() == false) { Set rotateList = new HashSet(numOfDigits); String targetValue = numberSet.iterator().next(); rotateList.add(targetValue); char[] buf = new char[numOfDigits * 2]; for (int i = 0; i < numOfDigits; i++) { buf[i] = buf[i + numOfDigits] = targetValue.charAt(i); } for (int i = 1; i < numOfDigits; i++) { if (buf[i] != '0') { String rotateValue = String.valueOf(buf, i, numOfDigits); int value = Integer.parseInt(rotateValue); if (value >= start && value <= end) { rotateList.add(rotateValue); } } } numberSet.removeAll(rotateList); if (rotateList.size() > 1) { // System.err.printf(""rotate set: %s%n"", rotateList.toString()); count += rotateList.size() * (rotateList.size() - 1) / 2; } } return count; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub // System.out.println(""answer = "" + RecycledNumberSolver.countRecycledNumber(10, 40)); Scanner scanner = new Scanner(System.in); int totalCount = Integer.parseInt(scanner.nextLine()); for (int i = 0; i < totalCount; i++) { String[] inputs = scanner.nextLine().split("" ""); int answer = RecycledNumberSolver.countRecycledNumber(Integer.parseInt(inputs[0]), Integer.parseInt(inputs[1])); System.out.printf(""Case #%d: %d%n"", i+1, answer); } } } " B12841,"import java.io.File; import java.io.FileNotFoundException; import java.util.LinkedList; import java.util.Scanner; public class RecycledNumbers { public static int getlength(int number) { int size = 1; number = number/10; while (number!=0) { size++; number = number/10; } return size; } public static void main(String[] args) throws FileNotFoundException { Scanner s = new Scanner (new File(""C-small-attempt0.in"")); // (System.in); int i = s.nextInt(); int a,b,sa,c,cnt,r; LinkedList ll; for(int j = 0 ; j < i ; j++) { a = s.nextInt(); b = s.nextInt(); sa = getlength(a); cnt = 0; for( int k = a ; k <= b; k++) { r = k; ll = new LinkedList(); if(getlength(r)>1) for (int l = 0 ; l < sa-1 ; l++) { c = r/(int)Math.pow(10, sa-1); r = (r-c*(int)Math.pow(10, sa-1))*10+c; if(r<=b&&r>k&&!ll.contains(r)) { ll.add(r); cnt++; } } } System.out.println(""Case #""+(j+1)+"": ""+(cnt)); } } } " B12889,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.HashSet; import java.util.Set; /** * */ /** * @author Kamlesh Saran Dev * */ public class RecycledPair { int a; int b; /** * @param i * @param j */ public RecycledPair(int a, int b) { this.a = a; this.b = b; } /** * @return */ public int getNumberOfPairs() { int count = 0; for (int n = a; n < b; n++) { Set allCombinations = giveAllCombinations(n, b); count = count + allCombinations.size(); } return count; } /** * @param n * @return */ private Set giveAllCombinations(int n, int b) { Set result = new HashSet(); String nStr = Integer.toString(n); for (int i = 1; i < nStr.length(); i++) { String backPart = nStr.substring(i); String frontPart = nStr.substring(0, i); int newNumber = Integer.valueOf((backPart + frontPart)); if (n < newNumber && newNumber <= b) { result.add(newNumber); } } return result; } public static void main(String args[]) throws Exception { BufferedReader bufferedReader = new BufferedReader( new FileReader( new File( ""C:\\Documents and Settings\\Kamlesh\\Desktop\\codejam\\C-small-attempt0.in""))); int numberOfTest = Integer.valueOf(bufferedReader.readLine()); for (int i = 1; i <= numberOfTest; i++) { String line = bufferedReader.readLine(); String limits[] = line.split(""\\ ""); RecycledPair rp = new RecycledPair(Integer.valueOf(limits[0]), Integer.valueOf(limits[1])); System.out.println(""Case #"" + i + "": "" + rp.getNumberOfPairs()); } } } " B10414,"package com.google.codjam.utils; import com.google.codjam.problems.BotTrust; import com.google.codjam.problems.CandySplitting; import com.google.codjam.problems.RecycledNumbers; public class MainRun { public static void main(String[] args) { String prefixPath = ""D:\\pry\\googlejam\\2012\\pryCodJam\\src\\""; FileDataAndSettings fS = new FileDataAndSettings(); FileLoader.processFile( fS ,prefixPath+ ""input.in"", 1 ,new RecycledNumbers() ); } } " B10726,"//saurabh import java.io.*; import java.util.*; public class Recycle { public static void main(String args[]) throws IOException { Recycle ob=new Recycle(); int T,A,B; Scanner c= new Scanner(new File(""Recycle.txt"")); T=c.nextInt(); int ans[]=new int[T]; for(int i=0;i L=new LinkedList(); for(int i=0;ibase && x<=B) if(!L.contains(x)) { L.add(x); } } return L.size(); } } " B12927,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam2012; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.Scanner; /** * * @author Luis Sergio Curay */ public class c { public c() { Scanner in= new Scanner(System.in); int t= in.nextInt(); for (int i = 0; i < t; i++) { int a= in.nextInt(); int b= in.nextInt(); HashSet nums= new HashSet(); int res= 0; for (int j = a; j <= b; j++) { HashSet comb= combinaroty(j); for (Integer num : comb) { if(num >= a && num <= b && num != j) { if(!nums.contains(num)) { nums.add(j); res++; } } } } System.out.println(""Case #"" + (i + 1) + "": "" + res); } } public int reverse(int n) { String num= String.valueOf(n); for (int i = 0; i < num.length() - 1; i++) { num= num.substring(num.length() - 1) + num.substring(0, num.length() - 1); } return Integer.parseInt(num); } private HashSet combinaroty(int n) { HashSet res= new HashSet(); String num= String.valueOf(n); for (int i = 0; i < num.length() - 1; i++) { num= num.substring(num.length() - 1) + num.substring(0, num.length() - 1); res.add(Integer.parseInt(num)); } return res; } }" B12111,"package com.renoux.gael.codejam.utils; import java.util.Date; public class Timer { private static long timestamp; public static void start() { timestamp = new Date().getTime(); } public static String check() { long delay = (new Date().getTime() - timestamp); long seconds = delay / 1000; long millis = delay - 1000 * seconds; long minutes = seconds / 60; seconds = seconds % 60; return new StringBuilder().append(minutes).append("" min "") .append(seconds).append("" s "").append(millis).append("" ms "") .toString(); } } " B12860,"import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.util.HashMap; import java.util.Scanner; public class C { private Scanner in; private PrintWriter out; private final String file = ""C""; public C() throws IOException { try { System.setIn(new FileInputStream(""io/q/"" + file)); System.setOut(new PrintStream(new FileOutputStream(""io/q/"" + file + "".out""))); } catch (FileNotFoundException e) { System.err.println(e.getMessage()); } in = new Scanner(new BufferedInputStream(System.in)); out = new PrintWriter(System.out); // for case int T = in.nextInt(), t = 1; int A, B, l, sum, total, currentNumberChar, currentNumber; HashMap map; while (T-- > 0) { A = in.nextInt(); B = in.nextInt(); map = new HashMap(B - A + 1); total = 0; if (A > 9) { final int size = (A + """").length() - 1; final int exp = (int) Math.pow(10, size); for (int nextNumber = A; nextNumber <= B; nextNumber++) { // processed if (null != map.get(nextNumber)) continue; // process map.put(nextNumber, true); currentNumber = nextNumber; sum = 0; for (l = 0; l++ < size;) { currentNumberChar = currentNumber % 10; currentNumber = currentNumberChar*exp + (int)Math.floor(currentNumber/10); if ((currentNumber >= A) && (currentNumber <= B)) { if (null == map.get(currentNumber)) { map.put(currentNumber, true); sum++; } } } total += sum + sum*(sum-1)/2; } } out.printf(""Case #%d: %d%n"", t++, total); } in.close(); out.flush(); out.close(); } public static void main(String[] args) throws IOException { new C(); } }" B11167,"package code_jam_quali; import java.util.HashSet; import java.util.Scanner; /** * * @author sansarun */ public class Recycled { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int caseNumber = sc.nextInt(); for(int currentCase=1; currentCase<=caseNumber; currentCase++) { HashSet recycledPairSet = new HashSet(); int a = sc.nextInt(); int b = sc.nextInt(); int digit = (""""+a).length(); for(int n=a; n n && m <= b) { recycledPairSet.add(new NumberPair(n, m)); } } } System.out.println(String.format(""Case #%d: %d"", currentCase, recycledPairSet.size())); } } private static StringBuilder rotate(StringBuilder s) { if(s.length() == 0) return s; s.insert(0, s.charAt(s.length() - 1)); s.deleteCharAt(s.length() - 1); return s; } } class NumberPair { private int a; private int b; public NumberPair(int a, int b) { this.a = a; this.b = b; } @Override public boolean equals(Object obj) { if (!(obj instanceof NumberPair)) { return false; } NumberPair n = (NumberPair) obj; if (n.a == a && n.b == b) { return true; } else if (n.a == b && n.b == a) { return true; } else { return false; } } @Override public int hashCode() { return a+b; } } " B12425,"package hipotenusas; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); ArrayList aparecidos= new ArrayList(); StringBuffer aux1; StringBuffer aux2; String aux; int test= sc.nextInt(), min, max, longitud, suma; for (int i=1; i<=test; i++){ aparecidos.clear(); suma= 0; System.out.print(""Case #""+i+"": ""); min= sc.nextInt(); max= sc.nextInt(); for (int j=min; j<=max; j++){ aux1= new StringBuffer(Integer.toString(j)); longitud= aux1.length(); for (int k= 1; k= min) && (Integer.parseInt(aux) != j) && (!aparecidos.contains(aux+ "",""+ Integer.toString(j)))){ aparecidos.add(aux+ "",""+ Integer.toString(j)); aparecidos.add(Integer.toString(j)+ "",""+ aux); suma++; } } } System.out.println(suma); } } } " B11966,"package com.my; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.HashSet; import java.util.Set; public class Main { public static void main(String[] args) { try { RecycledNumbers r = new RecycledNumbers(); String fileLocation = ""C://Training//Google//RecycledNumbers//src//com//my//smallInput.txt""; BufferedReader reader = r.getInputFile(fileLocation); String line = reader.readLine(); int count =1; while ( ( line = reader.readLine()) != null ) { String inputs[] = line.split("" "" ); int numCount = r.recycle(Integer.parseInt(inputs[0]),Integer.parseInt(inputs[1])); System.out.println(""Case #"" + count + "": "" + numCount); ++count; } //System.out.println(r.recycle(100,999)); } catch (Exception e) { // TODO: handle exception } } } class RecycledNumbers { public BufferedReader getInputFile(String fileLocation) throws Exception{ BufferedReader reader = new BufferedReader(new FileReader(new File(fileLocation))); return reader; } int recycle(int first, int second) throws Exception{ int count = 0; for( int i=first; i<=second; ++i) { String str = Integer.toString(i); Set set = new HashSet(); int div = 1; for( int j =0 ; j j && tmp <= b ) {memo[tmp] = true; ret += dr; dr++; } } while( tmp != j ); } // System.out.println(""Case #"" + (i+1) + "": "" + ret); fout.println(""Case #"" + (i+1) + "": "" + ret); } fout.close(); sc.close(); } } " B12837,"import static java.util.Arrays.deepToString; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.PrintWriter; import java.util.ArrayList; public class C { public BufferedReader in; public PrintWriter out; void debug(Object...os) {System.err.println(deepToString(os));} static void pl(Object s) {System.out.println(s);} static void p(Object s) {System.out.print(s);} private int solve(int A, int B) { int count = 0; StringBuilder nn,mm; int n,m,c; for(n = A; n < B; ++n) { nn = new StringBuilder(); nn.append(n); for(m = n+1; m <= B; ++m) { mm = new StringBuilder(); mm.append(m); if (mm.length() > nn.length()) {m = B+1; break;} //number of digits dont match int l = mm.length(); for(c = 0; c < l-1; ++c) { mm.append(mm.charAt(0)).deleteCharAt(0); //rotate by 1 char if (mm.toString().equals(nn.toString())) { // pl(""\tMATCH ""+n+"" : ""+m); ++count; break; } } } } return count; } public void run() throws Exception { int T,A,B,v; String line;String[] tok; in = new BufferedReader(new FileReader(new File(""C-small-attempt0.in""))); out = new PrintWriter(new File(""C-small-attempt0.out"")); // in = new BufferedReader(new FileReader(new File(""C-large.in""))); // out = new PrintWriter(new File(""C-large.out"")); T = new Integer(in.readLine()); for(int t=1;t<=T;++t) { line = in.readLine(); tok = line.split("" ""); A = new Integer(tok[0]); B = new Integer(tok[1]); v = solve(A,B); System.out.println(""Case #"" + t + "": "" + v); out.println(""Case #"" + t + "": "" + v); } in.close();out.close(); } public static void main(String[] args) { try { java.util.Date t1 = new java.util.Date(); new C().run(); java.util.Date t2 = new java.util.Date(); long diff = (t2.getTime() - t1.getTime()); System.out.println(""Time: ""+(((float)diff)/1000)); } catch (Exception e) { e.printStackTrace(); } } } " B12422,"package blacky.codejam.qualifications; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { private static class Pair { final public int m; final public int n; public Pair(int m, int n) { this.m = m; this.n = n; } public boolean equals(Object other) { return ((Pair)other).m == this.m && ((Pair)other).n == this.n; } public String toString() { return String.format(""(%d,%d)"", this.m, this.n); } public int hashCode() { return this.m * 31 + n; } } public static void main(String args[]) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(new File(args[0]))); int numberOfTestCases = Integer.parseInt(reader.readLine()); for(int i = 0; i < numberOfTestCases; i++) { String numbers[] = reader.readLine().split("" ""); Set pairs = new HashSet(); int a = Integer.parseInt(numbers[0]); int b = Integer.parseInt(numbers[1]); for(int j = a; j < b; j++) { String jAsString = Integer.toString(j); int recycledNumbers[] = new int[jAsString.length()]; recycledNumbers[0] = j; for(int k = 1; k < jAsString.length(); k++) { int offset = jAsString.length() - k; String currentRecNum = jAsString.substring(offset).concat(jAsString.substring(0, offset)); recycledNumbers[k] = Integer.parseInt(currentRecNum); } Arrays.sort(recycledNumbers); for(int k = 0; k < recycledNumbers.length - 1; k++) { if(!(a <= recycledNumbers[k] && recycledNumbers[k] <= b)) continue; for(int l = k + 1; l < recycledNumbers.length; l++) { if(!(a <= recycledNumbers[l] && recycledNumbers[l] <= b)) continue; if(recycledNumbers[l] == recycledNumbers[k]) continue; pairs.add(new Pair(recycledNumbers[k], recycledNumbers[l])); } } } System.out.println(String.format(""Case #%d: %d"", i + 1, pairs.size())); } } } " B11786,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Ex3 { public static void main(String[] args) throws IOException{ String dir = System.getProperty(""user.dir""); String lineOfText; int T = 0; BufferedReader input = new BufferedReader(new FileReader(dir + ""\\C-small-attempt0.in"")); BufferedWriter output = new BufferedWriter(new FileWriter(dir + ""\\C-small-attempt0.out"")); try { lineOfText = input.readLine(); T = Integer.parseInt(lineOfText); int N=0; lineOfText = input.readLine(); while (lineOfText!=null) { N++; StringBuilder newString = new StringBuilder(); int result = 0; Pattern p = Pattern.compile(""-?\\d+""); Matcher m = p.matcher(lineOfText); m.find(); int A = Integer.parseInt(m.group()); m.find(); int B = Integer.parseInt(m.group()); ArrayList set = new ArrayList(); for(int i=A;i<=B;i++){ String num = new String(Integer.toString(i)); int length = num.length(); for(int y=1;y< length;y++){ String part1 = num.substring(0,y); String part2 = num.substring(y); String newNum = part2+part1; int newNumber = Integer.parseInt(newNum); String pair = Integer.toString(i)+Integer.toString(newNumber); if(newNumber>=A && newNumber <=B && newNumber>i){ if(!set.contains(pair)){ result +=1; set.add(pair); } } } } lineOfText = input.readLine(); newString.append(""Case #""+N+"": ""+result); output.write(newString.toString()); output.newLine(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { input.close(); output.close(); } } } " B12335,"import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { List lstLinesOutput = new ArrayList(); int iNbAnswers; List lstLinesInput = FileReaderHandler.openFile(""/home/guillaume/Bureau/input""); for(int n=1;n< Integer.parseInt(lstLinesInput.get(0)) + 1;n++){ String sOutput = ""Case #"" + n + "": ""; List box = new ArrayList(); iNbAnswers = 0; String sInput = lstLinesInput.get(n); String[] hInput = sInput.split("" ""); //to int array int[] iInput = new int[hInput.length]; for(int i=0;i < hInput.length;i++){ iInput[i] = Integer.parseInt(hInput[i]); } int iMin = iInput[0]; int iMax = iInput[1]; for(int i=iMin;i i && !box.contains(i + ""-"" + iToTest)){ box.add(i + ""-"" + iToTest); iNbAnswers++; } } } sOutput += iNbAnswers; lstLinesOutput.add(sOutput); } if(Integer.parseInt(lstLinesInput.get(0)) != lstLinesOutput.size()){ System.out.println(""ERROR!!!""); } FileWriterHandler.writeToFile(lstLinesOutput); } }" B10954,"package codejam.qualification; import java.io.IOException; import java.util.HashSet; import java.util.Set; import codejam.Task; public class C extends Task { private int t; private String[][] testCases; private String[] resultset; public C(String[] args) { super(args); } public static void main(String[] args) throws IOException { Task taskC = new C(args); taskC.execute(); } protected void catchInputData() throws IOException { t = Integer.parseInt(readLine()); testCases = new String[t][]; // iterates over cases for (int c = 0; c < t; c++) { testCases[c] = readLine().split("" ""); } } protected void processInputData() { resultset = new String[t]; // iterates over cases for (int c = 0; c < t; c++) { String[] testCase = testCases[c]; int a = Integer.parseInt(testCase[0]); int b = Integer.parseInt(testCase[1]); int y = 0; for (int n = a; n < b; n++) { Set mset = new HashSet(); String sn = String.valueOf(n); for (int i = 1; i < sn.length(); i++) { if (sn.charAt(i) != '0') { String sm = sn.substring(i) + sn.substring(0, i); int m = Integer.parseInt(sm); if (m > n && m <= b && !mset.contains(m)) { y++; mset.add(m); } } } } resultset[c] = """"+y; } } protected void generateOutputFile() throws IOException { // iterates over cases for (int c = 0; c < t; c++) { writeLine(""Case #"" + (c + 1) + "": "" + resultset[c]); } } } " B10753,"import java.io.FileNotFoundException; import java.io.FileReader; import java.io.PrintWriter; import java.util.Scanner; import java.util.Vector; public class recycle { public static void main(String arg[]) throws FileNotFoundException { Scanner in=new Scanner(new FileReader(""rec.in"")); PrintWriter pw=new PrintWriter(""ansRec.txt""); int cases=in.nextInt(); in.nextLine(); for(int counter=1;counter<=cases;counter++) { int small=in.nextInt(); int large=in.nextInt(); int ans=0; for(int i=small;i vec=new Vector(); for(int j=1;ji&&newI<=large&&!vec.contains(newI)) { ans++; // System.out.print(""(""+i+"", ""+newI+"") -- ""); vec.add(newI); f2=true; } // System.out.println(""for ""+i+"" checking with ""+newI); } // if(f2) System.out.println(); } pw.println(""Case #""+counter+"": ""+ans); } pw.close(); } } " B12281,"import java.util.*; import static java.lang.Math.*; import java.io.*; public class C { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(""C:/Users/Disha/Desktop/codejam/C-small.in"")); FileWriter fw = new FileWriter(""C:/Users/Disha/Desktop/codejam/C-small.out""); /*BufferedReader in = new BufferedReader(new FileReader(""C:/Users/Disha/Desktop/codejam/C-large.in"")); FileWriter fw = new FileWriter(""C:/Users/Disha/Desktop/codejam/C-large.out"");*/ int N = new Integer (in.readLine()); int count = 0; for (int cases = 1; cases <= N; cases++) { count = 0; String[] ss = in.readLine().split("" ""); int a = Integer.parseInt(ss[0]); int b = Integer.parseInt(ss[1]); for (int here = a; here <= b; here++) { int len = Integer.toString(here).length(); int len2 = (int) (Math.pow(10, (len-1))); int num2 = 0; int num1 = here; for(int i=0; i<= (len - 1) ; i++){ num2 = (10 * (num1 % len2)) + (num1 / len2); while(Integer.toString(num2).length() < len){ num2 = num2*10; i++; } if (num2 == here){ break; } if ((num2 <= b) && (num2 > here)){ count ++; } num1 = num2; } } fw.write (""Case #"" + cases + "": "" + count + ""\n"" ); } fw.flush(); fw.close(); }} " B10037,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class GoogleReplaced { static BufferedWriter bw = null; public static void main(String[] args) throws Exception { try { Scanner sc = new Scanner(new File(""C-small-attempt.in"")); bw = new BufferedWriter(new FileWriter(""output.txt"")); long totalCases = sc.nextLong(); for (int i = 1; i <= totalCases; i++) { int finalCount = 0; int i1 = sc.nextInt(); int i2 = sc.nextInt(); int tempNum1 = i1; for (; tempNum1 <= i2; tempNum1++) { String string = String.valueOf(tempNum1); List usedList = new ArrayList(); for (int j = 1; j < string.length(); j++) { String string1 = string.substring(string.length() - j, string .length()); String string2 = string.substring(0, string.length() - j); String newString = string1 + string2; int newIntValue = Integer.parseInt(newString); if ((i1 <= newIntValue) && ((i2 >= newIntValue))) { if (newIntValue > tempNum1) { if (!usedList.contains(newIntValue)) { usedList.add(newIntValue); finalCount = finalCount + 1; } } } } } bw.append(""Case #"" + i + "": ""); bw.append(String.valueOf(finalCount)); bw.append(""\n""); } } catch (Exception e) { e.printStackTrace(); } finally { bw.flush(); bw.close(); } } } " B11735,"package y2012.Qualification; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class RecycledNumbers extends IOStream { public RecycledNumbers(String fileName) { super(fileName); } private int runThisTestCase() throws IOException { Set recycledPairs = new HashSet(); String[] limits = bufferedReader.readLine().split("" ""); long a = Long.valueOf(limits[0]); long b = Long.valueOf(limits[1]); long num = a; while (num <= b) { String numString = String.valueOf(num); int numDigits = numString.length(); for (int idx = 0; idx < numDigits; idx++) { String recycledString = numString.substring(idx) + numString.substring(0, idx); long recycled = Long.valueOf(recycledString); if (recycled >= a && recycled <= b && num != recycled) { RecycledSet rs = new RecycledSet(num, recycled); recycledPairs.add(rs); } } num++; } return recycledPairs.size(); } public static void main(String[] args) throws Exception { RecycledNumbers obj = new RecycledNumbers(""/net/10.0.0.60/Users/454083/Desktop/Moshin/CodeJam/RecycledNumbers""); try { obj.getReader(); obj.getWriter(); int testcases = Integer.parseInt(bufferedReader.readLine().trim()); for (int testcase = 1; testcase <= testcases; testcase++) { int value = obj.runThisTestCase(); bufferedWriter.write(""Case #"" + testcase + "": "" + value + ""\n""); System.out.println(""Case #"" + testcase + "": "" + value); } obj.close(); } catch (IOException e) { e.printStackTrace(); } } } class RecycledSet { long num1; long num2; public RecycledSet(long num1, long num2) { if (num1 < num2) { this.num1 = num1; this.num2 = num2; } else { this.num1 = num2; this.num2 = num1; } } public int hashCode() { return (int) (num1 & num2); } public boolean equals(Object o) { if (o instanceof RecycledSet) { RecycledSet rs = (RecycledSet) o; if (this.num1 == rs.num1 && this.num2 == rs.num2) { return true; } } return false; } } class IOStream { static public BufferedReader bufferedReader = null; static public BufferedWriter bufferedWriter = null; String fileName = """"; public IOStream(String fileName) { this.fileName = fileName; } protected void getReader() throws IOException { bufferedReader = new BufferedReader(new FileReader(new File(fileName + "".in""))); } protected void getWriter() throws IOException { bufferedWriter = new BufferedWriter(new FileWriter(new File(fileName + "".out""))); } protected void close() throws IOException { if (bufferedReader != null) bufferedReader.close(); if (bufferedWriter != null) { bufferedWriter.flush(); bufferedWriter.close(); } } protected int[] splitString2Int(String[] words) { int[] ints = new int[words.length]; int i = 0; for (String str : words) { ints[i] = Integer.parseInt(str); i++; } return ints; } } " B10631,"package base; public interface Assignment { String solve(); } " B12521,"import java.util.*; import java.io.*; public class ProblemC { public static void main(String arg[])throws IOException { FileReader fin=new FileReader(arg[0]); FileWriter fout=new FileWriter(""Output.txt""); Scanner src=new Scanner(fin); Scanner t1=new Scanner(src.nextLine()); int cases=(t1.nextInt()); int no=0; int ans=0; while(src.hasNext()) { Scanner temp=new Scanner(src.nextLine()); no++; ans=0; long A=temp.nextInt(); long B=temp.nextInt(); long t=A; while(t<=B) { int count=0; long n=t; do { n=n/10; count++; }while(n!=0); for(int i=1;it) ans++; } t++; } fout.write(""Case #""+no+"": ""+ans+""\n""); } fout.close(); } }" B12090,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; import java.util.StringTokenizer; public class G2 { private Scanner reader; private FileWriter fstream; private BufferedWriter out; String nextline; int noLines; int intA; int intB; int lineIndex=1; int value=0; public boolean isValid(int n,int m) { return (!(n==m)&&(intA<=n)&&(n numList = new ArrayList(); while(runningNum=firstNum && newNum <=secNum && newNum!=runningNum){ String strFComb = runningNum set = new HashSet(); String str = i+""""; for (int p=str.length()-1;p>=1;p--) { String test = str.substring(p) + str.substring(0,p); int j = Integer.parseInt(test); String test2 = j+""""; if (i < j && j <= b && str.length()==test2.length() && !set.contains(j)) { set.add(j); number++; } } } return number; } } " B11567,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recyclednumbers; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.StringTokenizer; /** * * @author arjun */ public class RecycledNumbers { /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException { PrintStream out = new PrintStream(new FileOutputStream(""output.txt"")); System.setOut(out); parseAndTranslate(); } private static void parseAndTranslate() { try { // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(""C-small-attempt2.in""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine = br.readLine(); if (null != strLine) { int count = new Integer(strLine); //Read File Line By Line int lineNo = 0; while ((strLine = br.readLine()) != null) { lineNo++; doOp(strLine, lineNo); } //Close the input stream } in.close(); } catch (Exception e) {//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } private static void doOp(String strLine, int lineNo) { StringTokenizer st = new StringTokenizer(strLine); System.out.print(""Case #"" + lineNo + "": ""); String no = st.nextElement().toString(); Integer numberA = new Integer(no); no = st.nextElement().toString(); Integer numberB = new Integer(no); Integer count = 0; for (Integer i = numberA; i < numberB - 1; i++) { for (Integer j = i + 1; j <= numberB; j++) { boolean isRecycled = isNumberRecycleable(i, j); if (isRecycled) { count++; //System.out.println(""A: ""+ i + "" B:"" + j); } } } System.out.println(count); } private static boolean isNumberRecycleable(Integer noA, Integer noB) { String tmp = noA.toString(); char[] no1 = tmp.toCharArray(); String tmp2 = noB.toString(); char[] no2 = tmp2.toCharArray(); //System.out.println(""\n\nNo 1: "" + tmp + "" No 2: "" + tmp2); if (no1.length != no2.length) { return false; } else { for (int i = 1; i < no1.length; i++) { //System.out.println(""Diff: "" + i); boolean isRecy = isRecycleable(no1, no2, i); if(isRecy){ return isRecy; } } } return false; } private static boolean isRecycleable(char[] no1, char[] no2, int add) { for (int j = 0; j < no2.length; j++) { int k = (j + add) % no2.length; //System.out.println(""Cmp: no1["" + j +""] = "" + no1[j] + "" & no2[""+ k + ""] = "" + no2[k]); if(no1[j] != no2[k]){ return false; } } return true; } } " B11939,"package com.google.codejam.util; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class CodeJamOutputFile extends File { /** * */ private static final long serialVersionUID = -6971460798309687528L; private FileWriter writer; private Boolean caseZero = false; public CodeJamOutputFile(String pathname) { super(pathname); try { this.setWriter(); } catch (IOException e) { } } private void setWriter() throws IOException { this.writer = new FileWriter(this); } public FileWriter getWriter() { return writer; } public void writeCase(int caseId, String result){ if(caseId == 0){ caseZero = true; } caseId = caseZero ? caseId + 1 : caseId; try { writer.write(""Case #""+(caseId) +"": "" + result + ""\n""); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void close(){ try { writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B10008,"import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; public class C { Map> map = new HashMap>(); public C() { for (int i=1; i<=2000000; i++) { char ch[] = (""""+i).toCharArray(); Arrays.sort(ch); String key = new String (ch); Set val = map.containsKey(key)?map.get(key): new HashSet(); val.add(i); map.put(key, val); } System.out.println(""Done..\n""); } boolean rot (int a, int b) { String A = """"+a; String B = """"+b; for (int i=1; i stopList = new HashSet(); for (int i=A; i<=B; i++) { char ch[] = (""""+i).toCharArray(); Arrays.sort(ch); String key = new String (ch); if (stopList.contains(key)) continue; Object values[] = map.get(key).toArray(); for (int j=0; j=A && valJ<=B) { for (int k=j+1; k=A && valK<=B) { if (rot(valJ, valK)) { total++; //System.out.println(valJ+"", ""+valK); } } } } } stopList.add(key); } return total; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); C c = new C(); //System.out.println(c.rot(12345, 45123)); int T = sc.nextInt(); for (int i=0; i 0) { mul *= 10; ii /= 10; dig ++; } mul /= 10; int right = i; int left = 0; for (int d=0; d i && k <= B) { if (v[k] != i) { cnt ++; v[k] = i; } } } } return cnt + ""\n""; } //////////////////////////////////////// // read input //////////////////////////////////////// public String runInput(BufferedReader br) throws IOException { String[] items = br.readLine().trim().split(""\\s+""); int A = Integer.parseInt(items[0]); int B = Integer.parseInt(items[1]); return solve(A, B); } //////////////////////////////////////// // main //////////////////////////////////////// public static void main(String[] args) { C c = new C(); try { c.parseFile(""C-sample""); c.parseFile(""C-small-attempt0""); //c.parseFile(""C-large""); } catch (IOException e) { e.printStackTrace(); } } //////////////////////////////////////// // library //////////////////////////////////////// public void parseFile(String filePrefix) throws IOException { String fileIn = filePrefix + "".in""; String fileOut = filePrefix + "".out""; BufferedReader br = new BufferedReader(new FileReader(fileIn)); BufferedWriter bw = new BufferedWriter(new FileWriter(fileOut)); int n = Integer.parseInt(br.readLine()); for (int i=1; i<=n; i++) { String ret = ""Case #"" + i + "": ""; ret += runInput(br); System.out.print(ret); bw.write(ret); } br.close(); bw.close(); } } " B11035,"import java.io.File; import java.io.FileWriter; import java.util.HashMap; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) throws Exception { RecycledNumbers recycledNumbers = new RecycledNumbers(); // file name String fileName = ""recycled_numbers""; // file variable File inputFile = new File(fileName + "".in""); File outputFile = new File(fileName + "".out""); Scanner scanner = new Scanner(inputFile); FileWriter writer = new FileWriter(outputFile); // problem variable int totalCase; // get total case totalCase = Integer.parseInt(scanner.nextLine()); System.out.println(""Total case:""+totalCase); for (int caseIndex = 1; caseIndex <= totalCase; caseIndex++) { String lineDetail = scanner.nextLine(); String[] inputArray = lineDetail.split("" ""); String min = inputArray[0]; String max = inputArray[1]; int possibleCases = 0; possibleCases = recycledNumbers.findPossibleCases(min, max); String output = ""Case #"" + caseIndex + "": "" + possibleCases; System.out.println(output); writer.write(output + ""\n""); } scanner.close(); writer.close(); } private int findPossibleCases(String min, String max){ int possibleCases = 0; int startVal = Integer.parseInt(min); int endVal = Integer.parseInt(max); int n,m = 0; HashMap usedPattern = new HashMap(); for(int i=startVal; i(); //startAt for(int j= 0; j n) && (m <=endVal)){ if(!usedPattern.containsKey(shiftStr) ){ possibleCases++; } } // keep the temp of shifting data usedPattern.put(shiftStr, shiftStr); } m = 0; } return possibleCases; } } " B10847,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package q3; import java.io.*; /** * * @author ken */ public class Q3 { /** * @param args the command line arguments */ public static void main(String[] args) { try { FileInputStream fstream = new FileInputStream(""C-small-attempt0.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; int inputSize = Integer.parseInt(br.readLine()); int currentCase = 1; //while ((strLine = br.readLine()) != null) { while (inputSize > 0) { strLine = br.readLine(); int min = Integer.parseInt(strLine.split("" "")[0]); int max = Integer.parseInt(strLine.split("" "")[1]); int counter = 0; for (int i = min; i <= max; i++) { for (int j = i; j <= max; j++) { if (isRecycled(Integer.toString(i), Integer.toString(j))) { counter ++; } } } System.out.println(""Case #"" + currentCase + "": "" + counter); inputSize --; currentCase++; } in.close(); //System.out.println(""hello"".substring(0, 1)); //System.out.println(""hello"".substring(1)); //System.out.println(isRecycled(""12345"",""34512"")); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } public static boolean isRecycled(String x, String y) { if (x.length() != y.length()) { return false; } for (int i = 1; i < x.length() + 1; i++) { String newString = x.substring(i)+x.substring(0, i); //System.out.println(newString); if (newString.equalsIgnoreCase(y) && !newString.equalsIgnoreCase(x)) return true; } return false; } } " B12130,"import java.util.Scanner; public class ProblemC { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int testCases = Integer.parseInt(scanner.nextLine()); for (int i = 1; i <= testCases; i++) { String[] inputs = scanner.nextLine().split(""\\s""); int A = Integer.parseInt(inputs[0]); int B = Integer.parseInt(inputs[1]); int result = solve(A, B); System.out.println(""Case #"" + i + "": "" + result); } } private static int solve(int A, int B) { int recycledPairs = 0; for (int n = A; n < B; n++) { for (int m = n + 1; m <= B; m++) { // System.out.println(""Checking pair "" + n + "" "" + m); if (isRecycledPairs(n, m)) { recycledPairs++; } } } return recycledPairs; } private static boolean isRecycledPairs(int n, int m) { boolean result = false; String nString = String.valueOf(n); String mString = String.valueOf(m); String recycledString = null; for (int i = 0; i < nString.length(); i++) { recycledString = nString.substring(i, nString.length()) + nString.substring(0, i); // System.out.println(recycledString); if (mString.equals(recycledString)) { result = true; } } return result; } } " B10856,"package be.mokarea.gcj.common; import java.io.FileWriter; import java.io.PrintWriter; import java.io.Writer; public abstract class GoogleCodeJamBase { protected abstract Transformation createTransformation(TestCaseReader testCaseReader, PrintWriter outputWriter) throws Exception; protected abstract String getOutputFileName() throws Exception; protected abstract TestCaseReader getTestCaseReader() throws Exception; public void execute() { try { PrintWriter outputWriter = null; try { outputWriter = new PrintWriter(new FileWriter(getOutputFileName())); Transformation transformation = createTransformation(getTestCaseReader(),outputWriter); transformation.transformAll(); outputWriter.flush(); } finally { closeQuietly(outputWriter); } } catch (Throwable t) { t.printStackTrace(); } } private void closeQuietly(Writer outputWriter) { if (outputWriter != null) { try { outputWriter.close(); } catch (Throwable t) { t.printStackTrace(); } } } } " B12794,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package googlecodejam; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.StringTokenizer; /** * * @author massimo */ public class ProblemC { public static void main(String[] args) throws FileNotFoundException, IOException { BufferedReader in = new BufferedReader(new FileReader(""in.in"")); PrintWriter out = new PrintWriter(""out.out""); int t = Integer.parseInt(in.readLine()); for (int i = 1; i <= t; i++) { StringTokenizer st = new StringTokenizer(in.readLine(), "" ""); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); HashSet res=new HashSet(); for (int j=a; j<=b; j++) { String s=Integer.toString(j); for (int k=0; k=a && j!=j2) { if (j0){C/=10; M*=10;} M2 = (B0){ C=C*10%M + C*10/M; if((C < M1)||(C>M2)) continue; //or -9*exp if(C < c) {t=false; break;} if(C == c) {break;} n++; } if(t) return n+1; else return 0; } @Override public void run() { try { in = new Scanner(new File(taskname + "".in"")); out = new PrintWriter(taskname+"".out""); //out = new PrintWriter(System.out, true); // in = new BufferedReader( new InputStreamReader(System.in)); // out = new BufferedWriter( new OutputStreamWriter(System.out)); solve(); out.flush(); } catch (Exception e) { e.printStackTrace(); } } } " B12382,"import java.util.*; import java.io.*; class Caso{ int a; int b; public void leer(Scanner s){ a=s.nextInt(); b=s.nextInt(); } public Caso(){ } public String obtenerRespuesta(){ long resultado=0; for(int i=a;i<=b;i++){ int j=1; int nd=(int)Math.log10(i)+1; HashMaph=new HashMap(); while(j1){ for(int j=0;ji)) { //System.out.println(n+"" for ""+num); noOfPerm++; } } } } ans=ans+noOfPerm; if(currentCase<(noOfCases+1)) ans=ans+""\n""; //System.out.println(noOfPerm); } } fstream.close(); //System.out.println(ans); writeToFile(ans); } catch (IOException ex) { ; } } public static void writeToFile(String line) { try{ // Create file FileWriter fstream = new FileWriter(""out.txt""); BufferedWriter out = new BufferedWriter(fstream); out.write(line); //Close the output stream out.close(); }catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } public static void perm(String s) { int len=s.length(); String pattern=""""; for(int n=(len-1),k=len;n>=0;n--) { pattern=s.substring(n, k)+s.substring(0, n); set.add(pattern); //System.out.println(pattern); } } } " B11357,"import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class ProblemC { /** * @param args */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); int T = Integer.valueOf(str); int[] A = new int[T]; int[] B = new int[T]; int[] res = new int[T]; for (int i = 0; i < T; i++) { A[i] = sc.nextInt(); B[i] = sc.nextInt(); } for (int i = 0; i < T; i++) { for (int n = A[i]; n < B[i]; n++) { Set pairs = new HashSet(); String jstr = String.valueOf(n); for (int j = 0; j < jstr.length() - 1; j++) { jstr = jstr.charAt(jstr.length() - 1) + jstr.substring(0, jstr.length() - 1); int m = Integer.valueOf(jstr); if (n < m && m <= B[i]) { if (!pairs.contains(n + "","" + m)) { pairs.add(n + "","" + m); res[i]++; } } } } System.out.println(""Case #"" + (i + 1) + "": "" + res[i]); } } } " B11716,"public class Result { public String output; public int i; public Result(int i) { this.i = i; } @Override public String toString() { return ""Case #""+i+"": "" + output; } } " B10406,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; public class Recycled { private static BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(System.in)); public static void main(String[] args) throws IOException { String line = bufferedReader.readLine(); int cases = Integer.parseInt(line); for (int i = 1; i <= cases; i++) { line = bufferedReader.readLine(); String[] split = line.split("" ""); int A = Integer.parseInt(split[0]); int B = Integer.parseInt(split[1]); HashSet usedPairs = new HashSet(); int answer = 0; int duplicates = 0; if (B > 10) { for (int j = A; j < B; j++) { String number = """" + j; // System.err.println(""Current number: "" + number); for (int k = 0; k < number.length(); k++) { String rotated = number.substring(k) + number.substring(0, k); // System.err.println(""Rotated number: "" + rotated); int a = Integer.parseInt(number); int b = Integer.parseInt(rotated); if (Math.min(a, b) >= A && a != b && Math.max(a, b) <= B) { String hashKey; if (a < b) { hashKey = number + rotated; } else { hashKey = rotated + number; } if (!usedPairs.contains(hashKey)) { answer++; usedPairs.add(hashKey); // System.err.println(""Found a new pair!""); } else { /* * System.err * .println(""Found a duplicate: Number - "" + * number + "", Rotated: "" + rotated); */ duplicates++; } } } } } // System.err.println(""Found "" + duplicates + "" duplicated pairs""); System.out.println(""Case #"" + i + "": "" + answer); } } } " B12343,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package gcodejam2012; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.PrintStream; import java.math.BigInteger; import java.util.LinkedList; import java.util.Scanner; /** * * @author alei */ public class C { public static void main(String[] Args) throws FileNotFoundException{ Scanner sn = new Scanner(new FileInputStream(""c.in"")); System.setOut(new PrintStream(""c.out"")); int nCases = sn.nextInt(); for(int i=0;ipairs = new LinkedList<>(); for(int j=0;jn){ if(mint>=A && mint <=B){ if(!pairs.contains(m)){ nRecycleds++; pairs.add(m); } } } } else{ curFt =curChar + curFt; } } } return nRecycleds; } } " B12477,"import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.HashSet; public class RecycledNumbers { /** * Google Code Jam 2012: Problem C. Recycled Numbers * @author hullarb * @param args * @throws IOException * @throws NumberFormatException */ public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader input = new BufferedReader(new FileReader(args[0])); OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(args[0].contains(""in"")?args[0].replace(""in"", ""out""):args[0] + "".out"")); int testCases = Integer.parseInt(input.readLine()); for(int i = 0; i < testCases; i++) { String[] parts = input.readLine().split("" ""); int A = Integer.parseInt(parts[0]); int B = Integer.parseInt(parts[1]); int pairs = 0; for(int j = A; j found = new HashSet(); for(int i = 0; i < digits.length() - 1; i++) { int n = Integer.parseInt(digits.substring(digits.length() - 1 - i) + digits.substring(0,digits.length() - 1 - i)); if(n > j && n <= b && !found.contains(n)) { found.add(n); pairs++; } } return pairs; } } " B10368,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam2012; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; /** * * @author acer */ public class C { /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException, IOException { // TODO code application logic here FileInputStream input = new FileInputStream(""input.txt""); DataInputStream in = new DataInputStream(input); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileOutputStream output = new FileOutputStream(""output.txt""); int T = Integer.parseInt(br.readLine()); int A, B; for (int i = 0; i < T; i++) { String[] temp = br.readLine().split("" ""); A = Integer.parseInt(temp[0]); if (A < 12) { A = 12; } B = Integer.parseInt(temp[1]); if (B < A) { output.write((""Case #"" + (i + 1) + "": "" + ""0"" + ""\n"").getBytes()); continue; } int j = A, count = 0; while (j <= B) { String thisNo = new Integer(j).toString(); Set intSet = new HashSet(); for (int k = 1; k < thisNo.length(); k++) { int newNo = Integer.parseInt(thisNo.substring(thisNo.length() - k) + thisNo.substring(0, thisNo.length() - k)); if (newNo <= B && Integer.parseInt(thisNo) < newNo && !intSet.contains(newNo)) { count++; intSet.add(newNo); } } j++; } output.write((""Case #"" + (i + 1) + "": "" + count + ""\n"").getBytes()); } } } " B12222,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class RecycledNumbers { public static void main(String[] args) { List lines = getline(""C:\\Users\\Ami\\Downloads\\C-small-attempt1.in""); System.out.println(""number of TestCases-->>"" + lines.remove(0)); Process(lines); } private static void Process(List lines) { int i = 1; for (String line : lines) { int k = 0; String[] nums = line.split("" ""); int A = Integer.valueOf(nums[0]); int B = Integer.valueOf(nums[1]); for (int j = A; j < B; j++) { String j2 = """" + j; for (int x = 1; x <=j2.length(); x++) { int num = Integer.parseInt(j2.substring(x) + j2.substring(0, x)); if (num > j && num <= B){ k++; //System.out.println(j2+"" : ""+num); } } } System.out.println(""Case #"" + i + "": "" + k); i++; } } private static List getline(String path) { List ls = new ArrayList(); try { FileInputStream fstream = new FileInputStream(path); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { ls.add(strLine); } in.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } return ls; } } " B12957,"package google.contest.B; import google.loader.Challenge; import google.problems.AbstractChallenge; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class BChallenge extends AbstractChallenge implements Challenge { private int numberOfGooglers; private int numberOfSurprise; private int desiredScore; List scores; private String resultNumber; private static HashMap map; public BChallenge(int number, String line) { super(number); String[] tokens = line.split("" ""); numberOfGooglers = Integer.parseInt(tokens[0]); numberOfSurprise = Integer.parseInt(tokens[1]); desiredScore = Integer.parseInt(tokens[2]); scores = new ArrayList(); for(int i=0;i bigger = new ArrayList(); List biggerAndSurprising = new ArrayList(); List smaller = new ArrayList(); List smallerAndSuprising = new ArrayList(); for(Integer score : scores ){ ScoreInfo info = getScoreInfo(score); if(info.canBeBigger(desiredScore)){ if(info.mustBeSuprisingBeingBigger(desiredScore)){ biggerAndSurprising.add(score); }else{ bigger.add(score); } }else{ if(info.canBeSuprising()){ smallerAndSuprising.add(score); }else{ smaller.add(score); } } } int biggerSize = bigger.size(); int biggerAndSuprSize = biggerAndSurprising.size(); int smallerSize = smaller.size(); int smallerAndSupSize = smallerAndSuprising.size(); if(biggerAndSuprSize>=numberOfSurprise){ resultNumber = """"+ ( biggerSize + numberOfSurprise); return; } resultNumber = """"+ (biggerSize + biggerAndSuprSize); } private ScoreInfo getScoreInfo(Integer score) { return map.get(score); } private void init() { map = new HashMap(); for(int i=0;i<11;i++){ for(int j=0;j<11;j++){ for(int k=0;k<11;k++){ addTripple(i,j,k); } } } } private void addTripple(int i, int j, int k) { int sum = i+j+k; if(! map.containsKey(sum)){ map.put(sum, new ScoreInfo(sum)); } map.get(sum).addTripple(i,j,k); } private static class ScoreInfo{ private List tripples; public ScoreInfo(int sum) { tripples = new ArrayList(); } public boolean mustBeSuprisingBeingBigger(int desiredScore) { for(Tripple tripple : tripples){ if(tripple.isBigger(desiredScore)){ if(!tripple.isSuprising()){ return false; } } } return true; } public boolean canBeBiggerAndSuprising(int desiredScore) { for(Tripple tripple : tripples){ if(tripple.isBigger(desiredScore)){ if(tripple.isSuprising()){ return true; } } } return false; } public boolean canBeBigger(int desiredScore) { for(Tripple tripple : tripples){ if(tripple.isBigger(desiredScore)){ return true; } } return false; } public boolean canBeSuprising() { for(Tripple tripple : tripples){ if(tripple.isSuprising()){ return true; } } return false; } public void addTripple(int i, int j, int k) { Tripple tripple = new Tripple(i,j,k); if(tripple.isValid()){ tripples.add(tripple); } } } private static class Tripple{ private final int i; private final int j; private final int k; public Tripple(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } public boolean isBigger(int desiredScore) { return i>=desiredScore || j>=desiredScore || k>=desiredScore; } public boolean isSuprising() { return 2==getMaxDifference(); } private boolean isValid() { int max = getMaxDifference(); return max<3; } private int getMaxDifference() { int a1 = Math.abs(i-j); int a2 = Math.abs(i-k); int a3 = Math.abs(k-j); int max = Math.max(Math.max(a1,a2), a3); return max; } } } " B11400,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; public class Recycle { public Recycle() { String line; Integer maxInputs,output; Integer a, b; try { BufferedReader read = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(""input""))); BufferedWriter write = new BufferedWriter(new FileWriter(""output"")); maxInputs = new Integer(read.readLine()); for(int i = 1 ; i <= maxInputs ; i++) { int success = 0; line = read.readLine(); String[] numbers = line.split("" ""); a = new Integer(numbers[0]); b = new Integer(numbers[1]); success = getCount(a,b); output = new Integer(success); write.write(""Case #""+i+"": ""); write.write(output.toString()); write.write(""\n""); } write.close(); }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * @param args */ public static void main(String[] args) { long startTime = System.nanoTime(); new Recycle(); long endTime = System.nanoTime();; System.out.println(""Took ""+(endTime - startTime) + "" ns""); } int getCount(int start, int end) { int count = 0 ; String numStart = new Integer(start).toString(); int digits = numStart.length(); String num ; char[] perm = new char[digits]; if(digits == 1) return 0; for( Integer i = start; i <= end; i++) { num = i.toString(); for( int j = 1; j < digits; j++) { for(int k = 0 ; k < digits; k++) { perm[k] = num.charAt((j+k)%digits); } Integer permNum = Integer.parseInt(new String(perm)); if(i < permNum && permNum >= start && permNum <= end) { count++; System.out.println(i+"" ""+permNum); } } } return count; } } /* * if(digits == 2) { perm[0] = num.charAt(1); perm[1] = num.charAt(0); Integer j = Integer.parseInt(new String(perm)); if( j == i ) continue; if(j >= start && j <= end) { if( i < j ) count++; } } if(digits == 3) { perm[0] = num.charAt(2); perm[1] = num.charAt(0); perm[2] = num.charAt(1); Integer j = Integer.parseInt(new String(perm)); if( j == i ) continue; if(j >= start && j <= end) { if( i < j ) count++; } perm[0] = num.charAt(1); perm[1] = num.charAt(2); perm[2] = num.charAt(0); j = Integer.parseInt(new String(perm)); if( j == i ) continue; if(j >= start && j <= end) { if( i < j ) count++; } } */ " B11758,"package kjetil.codejam.qualification.recycled; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { private static final String INPUT_FILENAME = ""input_recycled/C-small-attempt0.in""; private static final String OUTPUT_FILENAME = ""output_files/recycled.out""; static class Pair { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + m; result = prime * result + n; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (m != other.m) return false; if (n != other.n) return false; return true; } private int n, m; Pair(int n, int m) { this.n = n; this.m = m; } public int getN() { return n; } public int getM() { return m; } } public static void main(String[] args) { try { FileWriter fstream = new FileWriter(OUTPUT_FILENAME); BufferedWriter out = new BufferedWriter(fstream); File file = new File(INPUT_FILENAME); BufferedReader reader = new BufferedReader(new FileReader(file)); int numberOfTestCases = Integer.parseInt(reader.readLine()); for (int i = 0; i < numberOfTestCases; i++) { String[] numberStrings = reader.readLine().split("" ""); int a = Integer.parseInt(numberStrings[0]); int b = Integer.parseInt(numberStrings[1]); int numberOfRecycledPairs = getNumberOfRecycledPairs(a, b); out.write(""Case #"" + (i+1) + "": "" + Integer.toString(numberOfRecycledPairs) +""\n""); } out.close(); reader.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } private static int getNumberOfRecycledPairs(int a, int b) { Set pairs = new HashSet(); for (int n = a; n < b; n++) { String current = Integer.toString(n); for (int j = 1; j < current.length(); j++) { String sub = current.substring(j); if (sub.charAt(0) != '0') { int m = Integer.parseInt(sub+current.substring(0, j)); if (n < m && m <= b ) { pairs.add(new Pair(n, m)); } } } } return pairs.size(); } } " B13211," import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.StringTokenizer; public class C { String PATH = ""C:\\Users\\XiaoweiChen\\Desktop\\Jam\\""; String inPath = PATH + ""C-small-attempt0.in""; String outPath = PATH + ""C-small-attempt0.out""; BufferedReader reader = null; BufferedWriter writer = null; StringTokenizer tokenizer = null; int ni() throws IOException { return Integer.parseInt(ns()); } long nl() throws IOException { return Long.parseLong(ns()); } double nd() throws IOException { return Double.parseDouble(ns()); } String ns() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } String nline() throws IOException { tokenizer = null; return reader.readLine(); } public static void main(String[] args) throws FileNotFoundException, IOException { new C().solve(); } public C() throws FileNotFoundException, IOException { reader = new BufferedReader(new FileReader(inPath)); writer = new BufferedWriter(new FileWriter(outPath)); } public void solve() throws IOException { int round = ni(); for (int ccase = 1; ccase <= round; ccase++) { long A = nl(); long B = nl(); long count = 0; HashSet pair = new HashSet(); for (long m = A; m <= B; m++) { String rep = Long.toString(m); int length = rep.length(); for (int i = 1; i < length; i++) { long n = Long.parseLong(rep.substring(length - i) + rep.substring(0, length - i)); if (n < m && n <= B && n >= A) { if (!pair.contains(n + "" < "" + m)) { pair.add(n + "" < "" + m); count++; } } } } String print = ""Case #"" + ccase + "": "" + count + ""\n""; System.out.print(print); writer.write(print, 0, print.length()); } writer.close(); } } " B10871,"package GoogleCodeJam.ed2012; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; public class QualificationC2012 { private String inputFile; private String outputFile; private BufferedReader reader = null; private BufferedWriter writer = null; private int[] foundValues = new int[6]; /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { QualificationC2012 qualificationC2012 = new QualificationC2012(""QualificationC2012.in"", ""QualificationC2012.out""); qualificationC2012.run(); } private void run() throws Exception { openFiles(); solve(); closeFiles(); } private void solve() throws Exception { long startTime = System.currentTimeMillis(); int n = Integer.valueOf(reader.readLine()); for (int i = 1; i<=n; i++) { writer.write(""Case #""+i+"": ""); String[] line = reader.readLine().split("" ""); int a = Integer.valueOf(line[0]); int b = Integer.valueOf(line[1]); int sum = 0; for (int j=a; j9); return validPairs; } private boolean found(int n, int total) { for (int i=0; i(); int longitud = String.valueOf( b ).length(); for( int index = b; index >= a; index-- ){ countIntoRange( index, longitud, a, b ); } return validationSet.size(); } private static void countIntoRange( int number, int longitud, int a, int b ){ String numero = String.valueOf( number ); while( numero.length() < longitud ){ numero = ""0""+numero; } for( int i = 0; i < longitud; i++ ){ int newNumber = Integer.parseInt( numero.substring( numero.length()-(i+1) ) + numero.substring( 0, numero.length()-(i+1) ) ); if( number < newNumber && newNumber >= a && newNumber <= b ){ validationSet.add(number+""->""+newNumber); //System.out.println(number+""->""+newNumber); } } } private static Set validationSet; private static void solveProblem( File inputFile ) throws IOException{ BufferedReader bufferedReader = new BufferedReader( new FileReader( inputFile ) ); BufferedWriter bufferedWriter = new BufferedWriter( new FileWriter( new File( inputFile.getParent(), inputFile.getName().substring( 0, inputFile.getName().length()-3 )+"".out"" ) ) ); Long t = Long.parseLong( bufferedReader.readLine() ); String problem = null; StringBuilder solution = null; for( long problemIndex = 0l; problemIndex < t; problemIndex++ ){ problem = bufferedReader.readLine(); solution = new StringBuilder(""Case #""+(problemIndex+1)+"": ""); String[] splitProblem = problem.split("" ""); int a = Integer.parseInt( splitProblem[ 0 ] ); int b = Integer.parseInt( splitProblem[ 1 ] ); solution.append( findRecycledNumbers( a, b ) ); bufferedWriter.write( solution.toString() ); bufferedWriter.write( ""\n"" ); } bufferedWriter.flush(); bufferedWriter.close(); bufferedReader.close(); } /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { Calendar calIni = Calendar.getInstance(); Calendar calFin = null; File folder = new File("".""); System.out.println(""Searching files in ""+folder.getAbsolutePath()); String[] inputFileList = folder.list( new FilenameFilter() { @Override public boolean accept(java.io.File dir, String name) { return name != null && name.endsWith("".in""); } }); for( String fileName : inputFileList ){ System.out.println( fileName ); Main.solveProblem( new File( folder.getAbsolutePath(), fileName ) ); } calFin = Calendar.getInstance(); System.out.println(""Tiempo:""+(calFin.getTimeInMillis()-calIni.getTimeInMillis())/1000); } } " B12513,"package codejam.qual_2012; import java.io.File; import java.io.PrintStream; import java.util.Scanner; public class MainC { static boolean[] seen; public static void main(String[] args) throws Exception { String f = ""/home/floris/dev/java/Test/src/codejam/qual_2012/C-small-attempt0.in""; Scanner sc = new Scanner(new File(f)); System.setOut(new PrintStream(new File(f+"".out""))); int T = sc.nextInt(); for (int i=1; T-- > 0; i++) { System.out.printf(""Case #%d: %d%n"", i, solve(sc.nextInt(), sc.nextInt())); } } private static long solve(int A, int B) { long result = 0; int pos = 1; int t = A/10; while (t != 0) {t/=10; pos++;} int cutoff = 1; for (int i = 1; i < pos; i++) cutoff *=10; seen = new boolean[cutoff*10]; fillSeen(); for (int i = A; i<=B; i++) { if (seen[i]) continue; result += roll(A, B, i, pos, cutoff); } return result; } private static long roll(int A, int B, int v, int pos, int cutoff) { pos--; pos--; int result = 0; if (A<=v && v <= B) result++; seen[v] = true; int n = (v%cutoff)* 10 + v/cutoff; switch (pos) { case 6: if (!seen[n ]&& A<=n && n <= B) result++; seen[n] = true; n = (n%cutoff)* 10 + n/cutoff; case 5: if (!seen[n ]&& A<=n && n <= B) result++; seen[n] = true; n = (n%cutoff)* 10 + n/cutoff; case 4: if (!seen[n ]&& A<=n && n <= B) result++; seen[n] = true; n = (n%cutoff)* 10 + n/cutoff; case 3: if (!seen[n ]&& A<=n && n <= B) result++; seen[n] = true; n = (n%cutoff)* 10 + n/cutoff; case 2: if (!seen[n ]&& A<=n && n <= B) result++; seen[n] = true; n = (n%cutoff)* 10 + n/cutoff; case 1: if (!seen[n ]&& A<=n && n <= B) result++; seen[n] = true; n = (n%cutoff)* 10 + n/cutoff; case 0: if (!seen[n ]&& A<=n && n <= B) result++; seen[n] = true; } return ((long)result)*(result-1)/2; } private static boolean allDigitsSame(int c) { int d = c%10; c /= 10; while (c != 0) { if (c%10 != d) return false; c /= 10; } return true; } private static void fillSeen() { seen[0] = true; for (int i = 1; i < 10; i++) { int j = i; while (j < seen.length) { seen[j]=true; j = j * 10 + i; } } } } " B11092,"package probc; import codejam.CodeJam; public class Main extends CodeJam { public static void main(String[] args) { new Main() { // Override the input file with the following: e.g. if the value is ""large"", then read ""A-large.in"" instead of the default // @SuppressWarnings(""unused"") // public static final String OVERRIDE_INPUT_FILE = ""small-attempt0""; // ""large""; }; } // -------------------------------------------------------------------------------------------------------------- @Override public void solve() { int T = readInt(); for (int t = 0; t < T; t++) { int A = readInt(); int B = readInt(); int totRecycPairs = 0; int[] recycNums = new int[10]; for (int n1 = A; n1 < B; n1++) { int numRecyc = 0; String s1 = n1 + """"; for (int j = 1, l = s1.length(); j < l; j++) { String s2 = s1.substring(j) + s1.substring(0, j); int n2 = Integer.parseInt(s2); if (n2 > n1 && n2 <= B) { // Uniquify -- necessary? boolean found = false; for (int i = 0; i < numRecyc && !found; i++) if (recycNums[i] == n2) found = true; if (!found) recycNums[numRecyc++] = n2; } } totRecycPairs += numRecyc; // System.out.println(""> "" + n1); } writeCaseNumThenLine("""" + totRecycPairs); } } } " B11220,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.*; public class jam3 { /** * @param args */ static int chuli(String s) { int count = 0; String[] ab = s.split("" ""); int a = Integer.parseInt(ab[0]); int b = Integer.parseInt(ab[1]); HashSet over = new HashSet(); HashSet cur = new HashSet(); for(int i=a;i<=b;i++) { String is = String.valueOf(i); if(!over.contains(is)) { cur.clear(); String is2 = is+is; for(int i2=0;i2=a&&ins<=b) cur.add(ns); } count+=(cur.size()*(cur.size()-1))/2; over.addAll(cur); } } return count; } public static void main(String[] args) { // TODO Auto-generated method stub try{ /* System.out.println(chuli(""1 9"")); System.out.println(chuli(""10 40"")); System.out.println(chuli(""100 500"")); System.out.println(chuli(""1111 2222"")); */ File fin1 = new File(""d:\\C-small-attempt0.in""); FileInputStream fs1 = new FileInputStream(fin1); BufferedReader br1 = new BufferedReader(new InputStreamReader(fs1)); File fout6 = new File(""d:\\cjamout1""); FileOutputStream fos6 = new FileOutputStream(fout6); BufferedWriter wr6 = new BufferedWriter(new OutputStreamWriter(fos6)); String line = br1.readLine(); int n = 1; line = br1.readLine(); while(line!=null) { if(!line.trim().equals("""")) { wr6.write(""Case #""+String.valueOf(n++)+"": ""+String.valueOf(chuli(line))); wr6.newLine(); } line = br1.readLine(); } br1.close(); fs1.close(); wr6.close(); fos6.close(); } catch(Exception e) { e.printStackTrace(); } } } " B13099,"import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.LinkedList; import java.util.Scanner; public class Recycled { public static void main(String[] args) throws IOException { Scanner s = new Scanner(new File(""io/recycled-biga.in"")); FileWriter fw = new FileWriter(new File(""io/recycled.out"")); int cases = s.nextInt(); s.nextLine(); for(int i = 0; i < cases; i++) { int a = s.nextInt(); int b = s.nextInt(); String out = ""Case #"" + (i+1) + "": "" + solve(a, b); System.out.println(out); fw.write(out + ""\n""); } s.close(); fw.close(); } private static int solve(int n, int m) { int rotations = Integer.toString(n).length(); int count = 0; String nStr; // For each n to m for(int i = n; i < m; i++) { LinkedList l = new LinkedList(); nStr = """" + i; // Rotate through all possible configurations of n for(int r = 0; r < rotations -1; r++) { nStr = nStr.substring(rotations - 1) + nStr.substring(0, rotations-1); if(nStr.charAt(0) != '0') { int newN = Integer.parseInt(nStr); if(newN > i && newN <= m) { if(l.contains(newN) == false) { l.add(newN); count++; } } } } } return count; } } " B10504,"import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { try { Scanner in = new Scanner(new FileReader(""in.txt"")); PrintWriter out = new PrintWriter(new FileWriter(""out.txt""), true); int N = in.nextInt(); for (int I = 1; I <= N; I++) { int a = in.nextInt(); int b = in.nextInt(); int count = 0; for (int i = a; i < b; i++) { char m[] = (i + """").toCharArray(); //out.println(""m: ""+ Arrays.toString(m)); char[] mm = m.clone(); Arrays.sort(mm); for (int j = i + 1; j <= b; j++) { char n[] = (j + """").toCharArray(); char[] nn = n.clone(); Arrays.sort(nn); if (Arrays.equals(nn, mm)) { for(int k = 1; k < n.length; k++){ String s = new String(Arrays.copyOfRange(n.clone(), k, n.length)); s += new String(Arrays.copyOf(n.clone(), k)); if(s.equals(new String(m))){ count++; break; } } } //out.println(""n: ""+ Arrays.toString(n)); /*int index = 0; for (int k = n.length - 1; k >= index; k--) { if (m[index] == n[k]) { char c = n[k]; for(int kk = k; kk > index; kk--){ n[kk] = n[kk - 1]; } n[index] = c; index++; } } if (index == n.length - 1) { count++; out.println(""m: ""+ Arrays.toString(m)); out.println(""n: ""+ Arrays.toString(n)); } */ } } out.println(""Case #"" + I + "": "" + count); } } catch (Exception e) { e.printStackTrace(); } } }" B12628,"import com.sun.org.apache.bcel.internal.generic.AALOAD; import java.io.IOException; import java.util.HashSet; import java.util.List; import java.util.Set; public class RecycledNum extends JamProblem { public static void main(String[] args) throws IOException { RecycledNum p = new RecycledNum(); p.go(); } @Override String solveCase(JamCase jamCase) { RecNCase ca = (RecNCase) jamCase; int res = 0; for (int n = ca.A; n < ca.B; n++) { String m = """"; //print(""n ""+n); Set bag = new HashSet<>(); int length = intLength(n); for (int t = 1; t < length; t++) { int pow = (int) Math.pow(10, t); int pow2 = (int) Math.pow(10,length-t); int f = (n / pow); int s = n - (pow * f); int cand = f + (pow2 * s); //print(""m "" + cand); if (cand < ca.A || cand > ca.B || cand <= n) { continue; } if (bag.contains(cand)) { continue; } if (intLength(cand) != intLength(n)) { continue; } res++; bag.add(cand); //print(""""+ n+ "" "" + cand); } } return """" + res; } private void print(String m) { System.out.println(m); } private int intLength(int n) { return Integer.toString(n).length(); } @Override JamCase parseCase(List file, int line) { RecNCase ca = new RecNCase(); ca.lineCount = 1; String s = file.get(line); int[] ints = JamUtil.parseIntList(s, 2); ca.A = ints[0]; ca.B = ints[1]; return ca; } } class RecNCase extends JamCase { int A, B; } " B11166,"package jam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; public class Recycled { public static void main(String[] x)throws IOException{ File file=new File(""A.in""); Writer output = null; File out=new File(""A.out""); output = new BufferedWriter(new FileWriter(out)); BufferedReader fileIn = new BufferedReader(new FileReader(file)); String fileLine,delims,outs; String[] tokens; int cases,lower,higher,surprise,goal,ans,indA,indB,i; int [] items; int [] dat = new int[2000001]; for(i=0;i<2000001;++i) { dat[i]=-1; } fileLine=fileIn.readLine(); cases = Integer.parseInt(fileLine); delims = ""[ ]+""; System.out.println(""Cases = ""+cases); for (i=0;i=lower&&temp!=i&¬in(gar,temp)) { arr[temp-lower]=1; ++count; gar[j]=temp; } } // System.out.println(""i is ""+i); // System.out.println(""count is ""+count); maincount = maincount+comb(count,2); // System.out.println(""maincount is ""+maincount); } } return maincount; } private static int comb(int count, int i) { if(count ts=new TreeSet(); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int c=Integer.parseInt(br.readLine().trim()); FileWriter fichero = new FileWriter(""largoa.txt""); PrintWriter pw = new PrintWriter(fichero); for(int kc=0;kc=l){ ts.add(a+"" ""+n); ts.add(n+"" ""+a); } } } } System.out.println(""Case #""+(kc+1)+"": ""+ts.size()/2); //pw.println(""Case #""+(kc+1)+"": ""+ts.size()/2); ts.clear(); } fichero.close(); } }" B12722,"package codejam.Y2012; import java.io.File; import java.io.FileNotFoundException; import java.util.Collections; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { /** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(new File( ""C:\\Documents and Settings\\vikmalik\\Desktop\\input1.txt"")); int numCases = sc.nextInt(); // System.out.println(""\nCount = "" + getCount(100, 500)); for (int i = 1; i <= numCases; i++) { int a = sc.nextInt(); int b = sc.nextInt(); int count; if(a < b){ count = getCount(a, b); }else{ count = getCount(b, a); } System.out.println(""Case #"" + i + "": "" + count); } } private static int getCount(int a, int b) { int lim = 0; int count = 0; if (b > 10 && b < 100) { lim = 1; } else if (b >= 100) { lim = 2; } Set numList = new HashSet(); for (int j = 1; j <= lim; j++) { double divFactor = Math.pow(10, j); double mulFactor = 10; for (int i = a; i <= b; i++) { int diviser = (int) (i / divFactor); int remider = (int) (i % divFactor); if(remider == 0 || (divFactor == 100 && remider < 10)){ continue; } if(i>=100){ mulFactor =100; }else{ mulFactor =10; } int num = (int) (remider * mulFactor + diviser); // System.out.println(""diviser = ""+ diviser); // System.out.println(""remider = ""+ remider); // System.out.println(""num = ""+ num); if (num >= a && num <= b && i != num && i>10 ) { String pair; if(i pairs = new HashSet(); for (int n = A; n < B; ++n) { for (int i = 1; i < numDigits; ++i) { int m = recycle(n, i); if (n < m && m <= B) pairs.add(n + "","" + m); } } System.out.println(""Case #"" + t + "": "" + pairs.size()); } } // Recycles n by moving the first i digits to the back private static int recycle(int n, int i) { String iStr = Integer.toString(n); String newStr = iStr.substring(i) + iStr.substring(0,i); return Integer.parseInt(newStr); } }" B12534,"package com.google.codejam; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; public class RecycledNumbers { public static void main(String argsp[]) throws NumberFormatException, IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(""/Users/ashwinjain/Desktop/SmsLogger/InterviewStreet/src/com/google/codejam/in3.txt""))); int cases = Integer.parseInt(br.readLine()); for(int x=0;x added = new HashMap(); for(int i=1;i=a && d<=b && !added.containsKey(d)){ added.put(d, true); count++; } } c++; } System.out.println(""Case #""+(x+1)+"": ""+count/2); } } } " B11971,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; public class Small_C { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub File inf; File outf; try{ inf= new File(""C-small-attempt0.in""); FileReader inputFil = new FileReader(inf); BufferedReader in = new BufferedReader(inputFil); // System.out.println(""hiiiiiiii""); FileWriter fstream = new FileWriter(""output3.txt""); BufferedWriter out = new BufferedWriter(fstream); int T= Integer.parseInt(in.readLine()); for (int i=0;i=1) { ans=0; } else if(A<100 && A>=10) { for(int j=A;j<=B;j++) { n=j; n1=(n%10)*10+(n/10); for(int k=j;k<=B;k++) { if(k!=j && k==n1) ans++; } } } else if(A<1000 && A>=100) { for(int j=A;j<=B;j++) { n=j; n1=(n%10)*100+(n/10); n2=(n%100)*10+(n/100); for(int k=j;k<=B;k++) { if(k!=j && k==n1) ans++; if(k!=j && k==n2) ans++; } } } else if(A==1000) { ans=0; } out.write(ans+""""); out.newLine(); } out.close(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } } " B11668,"import java.io.*; import java.util.*; import java.math.*; class C { private static final boolean DEBUG_ON = true; private static final boolean ECHO_ON = true; private static BufferedReader input; private static BufferedWriter output; private static final int INF = Integer.MAX_VALUE / 2; private static final int MOD = 10007; public static void main(String[] args) { try { input = new BufferedReader(new FileReader(args[0] + "".in"")); output = new BufferedWriter(new FileWriter(args[0] + "".out"")); String line = input.readLine(); int testcases = getInt(line, 0); for (int testcase = 1; testcase <= testcases; testcase++) { line = input.readLine(); int A = getInt(line, 0); int B = getInt(line, 1); HashSet set = new HashSet(); for (int N = A; N < B; N++) { String s = String.valueOf(N); for (int i = 1; i < s.length(); i++) { String s1 = s.substring(0, i); String s2 = s.substring(i, s.length()); int M = Integer.parseInt(s2+s1); if ((N < M) && (M <= B)) { long key = N; key <<= 32; key += M; set.add(key); } } } String result = ""Case #"" + testcase + "": "" + set.size(); output(result); } input.close(); output.close(); } catch (Exception e) { e.printStackTrace(); } } public static int getInt(String line, int index) {return Integer.parseInt(getString(line, index));} public static long getLong(String line, int index) {return Long.parseLong(getString(line, index));} public static double getDouble(String line, int index) {return Double.parseDouble(getString(line, index));} public static String getString(String line, int index) { line = line.trim(); while (index > 0) {line = line.substring(line.indexOf(' ') + 1); index--;} if ((-1) == line.indexOf(' ')) {return line;} else {return line.substring(0, line.indexOf(' '));} } public static int[] getIntArray(String line) { String[] strings = getStringArray(line); int[] numbers = new int[strings.length]; for (int i = 0; i < strings.length; i++) {numbers[i] = Integer.parseInt(strings[i]);} return numbers; } public static long[] getLongArray(String line) { String[] strings = getStringArray(line); long[] numbers = new long[strings.length]; for (int i = 0; i < strings.length; i++) {numbers[i] = Long.parseLong(strings[i]);} return numbers; } public static double[] getDoubleArray(String line) { String[] strings = getStringArray(line); double[] numbers = new double[strings.length]; for (int i = 0; i < strings.length; i++) {numbers[i] = Double.parseDouble(strings[i]);} return numbers; } public static String[] getStringArray(String line) {return line.trim().split(""(\\s)+"", 0);} public static int[] getIntArray(String line, int begin, int end) { String[] strings = getStringArray(line, begin, end); int[] numbers = new int[end - begin]; for (int i = begin; i < end; i++) {numbers[i - begin] = Integer.parseInt(strings[i - begin]);} return numbers; } public static long[] getLongArray(String line, int begin, int end) { String[] strings = getStringArray(line, begin, end); long[] numbers = new long[end - begin]; for (int i = begin; i < end; i++) {numbers[i - begin] = Long.parseLong(strings[i - begin]);} return numbers; } public static double[] getDoubleArray(String line, int begin, int end) { String[] strings = getStringArray(line, begin, end); double[] numbers = new double[end - begin]; for (int i = begin; i < end; i++) {numbers[i - begin] = Double.parseDouble(strings[i - begin]);} return numbers; } public static String[] getStringArray(String line, int begin, int end) { String[] lines = line.trim().split(""(\\s)+"", 0); String[] results = new String[end - begin]; for (int i = begin; i < end; i++) {results[i - begin] = lines[i];} return results; } public static char[][] getCharMatrix(BufferedReader input) throws Exception { String line = input.readLine(); int R = getInt(line, 0); int C = getInt(line, 1); char[][] matrix = new char[R][C]; for (int i = 0; i < R; i++) { line = input.readLine(); for (int j = 0; j < C; j++) {matrix[i][j] = line.charAt(j);} } return matrix; } public static int[][] getIntMatrix(BufferedReader input) throws Exception { String line = input.readLine(); int R = getInt(line, 0); int C = getInt(line, 1); int[][] matrix = new int[R][C]; for (int i = 0; i < R; i++) { line = input.readLine(); for (int j = 0; j < C; j++) {matrix[i][j] = getInt(line, j);} } return matrix; } public static boolean[][] newBooleanMatrix(int R, int C, boolean value) { boolean[][] matrix = new boolean[R][C]; for (int i = 0; i < R; i++) for(int j = 0; j < C; j++) {matrix[i][j] = value;} return matrix; } public static char[][] newCharMatrix(int R, int C, char value) { char[][] matrix = new char[R][C]; for (int i = 0; i < R; i++) for(int j = 0; j < C; j++) {matrix[i][j] = value;} return matrix; } public static int[][] newIntMatrix(int R, int C, int value) { int[][] matrix = new int[R][C]; for (int i = 0; i < R; i++) for(int j = 0; j < C; j++) {matrix[i][j] = value;} return matrix; } public static long[][] newLongMatrix(int R, int C, long value) { long[][] matrix = new long[R][C]; for (int i = 0; i < R; i++) for(int j = 0; j < C; j++) {matrix[i][j] = value;} return matrix; } public static double[][] newDoubleMatrix(int R, int C, double value) { double[][] matrix = new double[R][C]; for (int i = 0; i < R; i++) for(int j = 0; j < C; j++) {matrix[i][j] = value;} return matrix; } public static void output(String s) throws Exception { if (ECHO_ON) {System.out.println(s);} output.write(s); output.newLine(); } public static String toKey(boolean[] array) { StringBuffer buffer = new StringBuffer(array.length + "",""); for (int i = 0; i < array.length / 16; i++) { char c = 0; for (int j = 0; j < 16; j++) { c <<= 1; if (array[i * 16 + j]) {c += 1;} } buffer.append(c + """"); } char c = 0; for (int j = 0; j < (array.length % 16); j++) { c <<= 1; if (array[(array.length / 16) * 16 + j]) {c += 1;} } buffer.append(c + """"); return buffer.toString(); } public static String toKey(int[] array, int bit) { StringBuffer buffer = new StringBuffer(array.length + "",""); if (bit > 16) { for (int i = 0; i < array.length; i++) { char c1 = (char)(array[i] >> 16); char c2 = (char)(array[i] & 0xFFFF); buffer.append("""" + c1 + c2); } } else { int n = 16 / bit; for (int i = 0; i < array.length / n; i++) { char c = 0; for (int j = 0; j < n; j++) { c <<= bit; c += array[i * n + j]; } buffer.append(c + """"); } char c = 0; for (int j = 0; j < (array.length % n); j++) { c <<= bit; c += array[(array.length / n) * n + j]; } buffer.append(c + """"); } return buffer.toString(); } public static void debug(String s) {if (DEBUG_ON) {System.out.println(s);}} public static void debug(String s0, double l0) {if (DEBUG_ON) {System.out.println(s0+"" = ""+l0);}} public static void debug(String s0, double l0, String s1, double l1) {if (DEBUG_ON) {System.out.println(s0+"" = ""+l0+""; ""+s1+"" = ""+l1);}} public static void debug(String s0, double l0, String s1, double l1, String s2, double l2) {if (DEBUG_ON) { System.out.println(s0+"" = ""+l0+""; ""+s1+"" = ""+l1+""; ""+s2+"" = ""+l2);}} public static void debug(String s0, double l0, String s1, double l1, String s2, double l2, String s3, double l3) {if (DEBUG_ON) {System.out.println(s0+"" = ""+l0+""; ""+s1+"" = ""+l1+""; ""+s2+"" = ""+l2+""; ""+s3+"" = ""+l3);}} public static void debug(String s0, double l0, String s1, double l1, String s2, double l2, String s3, double l3, String s4, double l4) {if (DEBUG_ON) {System.out.println(s0+"" = ""+l0+""; ""+s1+"" = ""+l1+""; ""+s2+"" = ""+l2+""; ""+s3+"" = ""+l3+""; ""+s4+"" = ""+l4);}} public static void debug(boolean[] array) {if (DEBUG_ON) {debug(array, "" "");}} public static void debug(boolean[] array, String separator) { if (DEBUG_ON) { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < array.length - 1; i++) {buffer.append((array[i] == true ? ""1"" : ""0"") + separator);} buffer.append((array[array.length - 1] == true) ? ""1"" : ""0""); System.out.println(buffer.toString()); } } public static void debug(boolean[][] array) {if (DEBUG_ON) {debug(array, "" "");}} public static void debug(boolean[][] array, String separator) {if (DEBUG_ON) {for (int i = 0; i < array.length; i++) {debug(array[i], separator);}}} public static void debug(char[] array) {if (DEBUG_ON) {debug(array, "" "");}} public static void debug(char[] array, String separator) { if (DEBUG_ON) { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < array.length - 1; i++) {buffer.append(array[i] + separator);} buffer.append(array[array.length - 1]); System.out.println(buffer.toString()); } } public static void debug(char[][] array) {if (DEBUG_ON) {debug(array, "" "");}} public static void debug(char[][] array, String separator) {if (DEBUG_ON) {for (int i = 0; i < array.length; i++) {debug(array[i], separator);}}} public static void debug(int[] array) {if (DEBUG_ON) {debug(array, "" "");}} public static void debug(int[] array, String separator) { if (DEBUG_ON) { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < array.length - 1; i++) {buffer.append(array[i] + separator);} buffer.append(array[array.length - 1]); System.out.println(buffer.toString()); } } public static void debug(int[][] array) {if (DEBUG_ON) {debug(array, "" "");}} public static void debug(int[][] array, String separator) {if (DEBUG_ON) {for (int i = 0; i < array.length; i++) {debug(array[i], separator);}}} } " B10059,"import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; public class RecycledNumbers { private final String inputFile = ""D:\\input.in""; private final String outputFile = ""D:\\output.out""; private static class TestCase{ int a; int b; public int calculateRecycleds(){ int result = 0; for (int i = a; i <= b; i++){ int numDigits = getNumDigits(i); int lastResycled = -1; for (int j = 0, divisor = 10; j < numDigits - 1; j++, divisor *= 10){ int recycled = i % divisor; for (int k = 0; k < numDigits - j - 1; k++){ recycled *= 10; } recycled += (i / divisor); if (isInRange(recycled) && recycled > i && lastResycled != recycled){ result ++; lastResycled = recycled; } } } return result; } private int getNumDigits(int i){ int numDigits = 0; while (i > 0){ numDigits++; i /= 10; } return numDigits; } private boolean isInRange(int i){ return (i >= a) && (i <= b); } } List input = new ArrayList(); public void parseInput(){ try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile))); int numTestCases = Integer.parseInt(br.readLine()); for (int i = 0; i < numTestCases; i++){ String [] lineTokens = br.readLine().split("" ""); TestCase tc = new TestCase(); tc.a = Integer.parseInt(lineTokens[0]); tc.b = Integer.parseInt(lineTokens[1]); input.add(tc); } br.close(); } catch (Exception e) { e.printStackTrace(); } } public void doOutput(){ try { PrintWriter pw = new PrintWriter(new FileOutputStream(outputFile)); for (int i = 0; i < input.size(); i++){ TestCase tc = input.get(i); pw.println(""Case #"" + (i + 1) + "": "" + tc.calculateRecycleds()); } pw.flush(); pw.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } public static void main(String [] args){ RecycledNumbers rn = new RecycledNumbers(); rn.parseInput(); rn.doOutput(); } } " B12312,"package google.gcj.recyclednumbers; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Scanner; import java.util.Set; public class RecycledNumbers4 { public static void main(String[] args) throws FileNotFoundException { RecycledNumbers4 recycledNumbers = new RecycledNumbers4(); recycledNumbers.doMain(); } private void doMain() throws FileNotFoundException { Scanner in = new Scanner(System.in); int T = in.nextInt(); int A, B, m, n, sum; for (int zz = 0; zz < T; zz++) { A = in.nextInt(); B = in.nextInt(); Queue queue = new LinkedList(); Set nm = new HashSet(); sum = 0; for (m = A; m <= B; m++) { if (!nm.contains(m)) { List ml = integerToList(m); // new n queue.clear(); for (int i = 0; i < ml.size(); i++) { queue.add(ml.get(i)); } for (int j = 0; j < queue.size(); j++) { n = integerListToInteger(queue); if (A <= n && n < m && m <= B) { sum++; // System.out.format(""Get %d\n"", n); nm.add(m); } queue.add(queue.remove()); } } } System.out.format(""Case #%d: %s\n"", zz + 1, sum); } } private List integerToList(int B) { List list = new ArrayList(); for (char c : String.valueOf(B).toCharArray()) { String s = String.valueOf(c); list.add(Integer.valueOf(s)); } return list; } private int integerListToInteger(Queue queue) { String s = """"; for (int l : queue) { s += String.valueOf(l); } return Integer.valueOf(s); } } " B11958,"package com.silverduner.codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; public class RecycledNumbers { public static boolean isRecycledPair(int n, int m) { int digits = 1 + (int)Math.floor(Math.log10(n)); int t = n; for(int i=1;i<=digits;i++) { t = ((t%10)*(int)Math.pow(10,digits-1) + (t/10)); if(t==m) return true; } return false; } public static void main(String[] args) throws Exception { File input = new File(""C-small-attempt0.in""); BufferedReader in = new BufferedReader(new FileReader(input)); File output = new File(""1.out""); BufferedWriter out = new BufferedWriter(new FileWriter(output)); // parse input int N = Integer.parseInt(in.readLine()); for(int i=0;i map = new HashMap(); Integer[] digits; for ( int i = A; i <= B; i++ ) { digits = getDigits(i); addToMap(digits, map); } int result = 0; for ( Long l : map.values() ) { result += (l * (l-1)) / 2; } return result; } public static void addToMap(Integer[] n, Map map) { Vector rots = getRotationSymmetricValues(n); // Remember to handle leading 0! All must have same length for ( Integer num : rots) { if ( map.containsKey(num) ) { map.put(num, map.get(num)+1); return; } } map.put(digitsToNum(n), 1L); } public static Vector getRotationSymmetricValues(Integer[] n) { Vector result = new Vector(); int origNum = digitsToNum(n); Queue v = new LinkedList(); for ( int i = 0; i < n.length; i++ ) { v.add(n[i]); } while (true) { Integer first = v.poll(); v.add(first); if ( v.peek() == 0 ) continue; int num = 0; for ( Integer i : v) { num *= 10; num += i; } if ( num == origNum ) break; result.add(num); } return result; } public static int digitsToNum(Integer[] digits) { int num = 0; for ( int i = 0; i < digits.length; i++ ) { num *= 10; num += digits[i]; } return num; } static Comparator comp = new Comparator() { @Override public int compare(Integer arg0, Integer arg1) { if ( arg0 == 0 ) return 1; else if ( arg1 == 0) return -1; else return arg0.compareTo(arg1); } }; public static Integer[] getDigits(int n) { int numDigits = (int)Math.log10(n) + 1; Integer[] digits = new Integer[numDigits]; for ( int i = 0; i < numDigits; i++ ) { digits[numDigits-1-i] = n % 10; n /= 10; } return digits; } } " B10894,"package jam2012.qround; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.List; public class RPair { int n; int m; public RPair(int n,int m){ this.n = n; this.m = m; } public static void main(String args[]) { int line = 0; try{ BufferedReader br = new BufferedReader(new FileReader(""C-small-attempt0.in"")); BufferedWriter bw = new BufferedWriter(new FileWriter(""C-small-attempt0.out"")); // BufferedReader br = new BufferedReader(new FileReader(""input.in"")); String str; String[] strIn; Integer.parseInt(br.readLine()); while ((str = br.readLine()) != null) { strIn = str.split("" ""); int min = Integer.parseInt(strIn[0]); int max = Integer.parseInt(strIn[1]); int count = 0; List used = new ArrayList(); for(int i=min;i<=max;i++){ int[] mutList = play(i,min,max); for(int j=0;jmutList = new ArrayList(); for (int i=1;i= min && mut <= max) mutList.add(mut); } if (mutList.size() != 0){ int[] intArray = new int[mutList.size()]; for (int i = 0; i < mutList.size(); i++) { intArray[i] = mutList.get(i); } return intArray; } else return new int[0]; } } " B12326,"import java.util.* ; public class RecycledNumbers { public static void main(String args[]) throws Exception { String inFileName = ""C:\\Documents and Settings\\kumarxnx.BKNG\\Desktop\\CodeJam\\3\\in""; String outFileName = ""C:\\Documents and Settings\\kumarxnx.BKNG\\Desktop\\CodeJam\\3\\out""; FileReaderWriter fri = new FileReaderWriter(inFileName,FileReaderWriter.READ_MODE) ; FileReaderWriter fro = new FileReaderWriter(outFileName,FileReaderWriter.WRITE_MODE) ; int inputs = fri.readInt() ; ArrayList nums ; HashMap map ; long low ; long high ; for(long i=0 ; i=low && newNum<=high) { if ( ! ( map.containsKey(""""+num+"",""+newNum) || map.containsKey(""""+newNum+"",""+num) ) ) { map.put(""""+num+"",""+newNum,null) ; } } } } } public static char[] shiftByOne(char[] arr) { char c = arr[arr.length - 1] ; char cnew [] = new char[arr.length] ; for(int i=1;i set = new HashSet(); private static void countRecycle(String numStr, int min, int max) { int num = Integer.valueOf(numStr); for (int i = 1; i < numStr.length(); ++i) { String frontStr = numStr.substring(0, i); String backStr = numStr.substring(i, numStr.length()); if (backStr.charAt(0) == '0') { continue; } String newNumStr = backStr + frontStr; int newNum = Integer.valueOf(newNumStr); if (newNum >= min && newNum <= max && newNum > num) { // System.out.println( numStr + "", "" + newNumStr); set.add(numStr + "":"" + newNumStr); } } return; } private static void solve(String minStr, String maxStr) { set.clear(); int min = Integer.valueOf(minStr); int max = Integer.valueOf(maxStr); int length = minStr.length(); for (int i = min; i <= max; ++i) { String numStr = Integer.toString(i); countRecycle(numStr, min, max); } // System.out.println(""result = "" + set.size()); } public static void main(String[] args) throws IOException { if (args.length != 1) { System.err.println(""Usage: inputFilename""); return; } BufferedReader reader = new BufferedReader(new FileReader(args[0])); String line = reader.readLine(); int times = Integer.parseInt(line); for (int i = 0; i < times; ++i) { line = reader.readLine(); String[] tokens = line.split("" ""); solve(tokens[0], tokens[1]); System.out.println(""Case #"" + (i+1) + "": "" + set.size()); } } } " B11818,"/** * Google CodeJam 2012 * General framework that takes care of the similar and repetitive tasks for all the problems. * E.g. managing case input and output. * * By Üllar Soon */ package eu.positivew.codejam.framework; /** * CodeJam input case (string). * * @author Üllar Soon */ public class CodeJamStringCase implements CodeJamInputCase { private String value = """"; public CodeJamStringCase(String value) { this.value = value; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } @Override public String getType() { return ""String""; } } " B12365,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Scanner; /** * * @author linlin */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException, IOException { // TODO code application logic here File file=new File(""C-small-attempt0.in""); FileOutputStream o=new FileOutputStream(""a.txt""); Scanner s=new Scanner(file); int t=Integer.valueOf(s.nextLine()); for(int i=1;i<=t;i++){ String line=s.nextLine(); String[] num=line.split("" ""); int a=Integer.valueOf(num[0]); int b=Integer.valueOf(num[1]); int d=1; int tens=10; for(;tens<=a;tens=tens*10) d++; tens=tens/10; int[] total=new int[d]; for(int q=a;q<=b;q++){ int correct=0; int q1=q; boolean shift=true; for(int k=0;k=a)&&(q1<=b)){ correct++; //System.out.println(q1); } shift=false; } if(correct>1){ total[correct-1]=total[correct-1]+1; } } int result=0; for(int n=1;n i && new_num <= upperBound && !check[new_num-lowerBound] && !check2[new_num-lowerBound]) { check2[new_num-lowerBound] = true; count++; } } } } return count; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int numCase, lowerBound, upperBound; numCase = sc.nextInt(); for(int i = 0; i < numCase; i++) { lowerBound = sc.nextInt(); upperBound = sc.nextInt(); System.out.println(""Case #""+(i+1)+"": ""+compute(lowerBound,upperBound)); } } }" B12593,"package google; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintStream; import java.util.HashSet; import java.util.ArrayList; public class Interview { public static void main(String[] args) throws IOException, FileNotFoundException { BufferedReader file = new BufferedReader(new FileReader(args[0])); String line = file.readLine(); PrintStream z = new PrintStream(""output.txt""); while (line != null && !line.equals(""0"")) { line = file.readLine(); if (line == null) { break; } String[] input = line.split("" ""); System.out.println(""Case: "" + caseNum); int numUniquePairs = processInput(input); z.println(""Case #"" + caseNum + "": "" + numUniquePairs); System.out.println(""Case #"" + caseNum + "": "" + numUniquePairs); caseNum++; uniqueTable.clear(); } System.out.println(""finished""); } private static int caseNum = 1; private static HashSet uniqueTable = new HashSet(); private static int processInput(String[] input) throws FileNotFoundException { int A = Integer.parseInt(input[0]); int B = Integer.parseInt(input[1]); int numUniquePairs = 0; for (int i=A; i < B; ++i) { for (int j=i+1; j <= B; ++j) { if (uniqueTable.add(""""+i +"",""+j)) { if (isRecyclePair(i, j)) { numUniquePairs++; } } } } return numUniquePairs; } private static boolean isRecyclePair(Integer x, Integer y) { if (x.equals(y)) { return false; } String xStr = x.toString(); String yStr = y.toString(); for (int i=0; i input = new ArrayList(); ArrayList output = new ArrayList(); Scanner scanner = null; try { //scanner = new Scanner(new File(""\\\\filesrv/stufiles$/matt.tough/Google.txt"")); scanner = new Scanner(new File(""E:/GoogleIn.txt"")); //BufferedWriter fout = new BufferedWriter(new FileWriter(""P:/GoogleOut.txt"")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } while(scanner.hasNext()){ input.add(scanner.nextLine()); } scanner.close(); /* * 4 1 9 10 40 100 500 1111 2222 */ String temp = """"; String modified = """"; String line = """"; int left = 0; int right = 0; int min = 0; int max = 0; String[] split; int count = 0; int previous = 0; int current = 0; for(int i = 1; i < input.size(); i++){ line = input.get(i); split = line.split("" ""); min = Integer.parseInt(split[0]); max = Integer.parseInt(split[1]); for(int x = min; x < max; x++){ temp = x + """"; //current = x; for(int z = temp.length()-1; z >= 0; z--){ modified = temp.substring(z) + temp.substring(0, z); if(Integer.parseInt(temp) != Integer.parseInt(modified)){ //if(Integer.parseInt(temp) <= ((max + min) / 2) if(Integer.parseInt(modified) <= max && Integer.parseInt(modified) >= min){ if(Integer.parseInt(modified) > x){ System.out.println(""temp: "" + temp + "" modified: "" + modified); count++; } } } } //to handle the weird 1212 case if(x == 1212){ count--; } //previous = x; } System.out.println(count); output.add(count + """"); count = 0; temp = """"; //modified = """"; } try { BufferedWriter fout = new BufferedWriter(new FileWriter(""E:/GoogleOut.txt"")); for(int i = 0; i < output.size(); i++){ fout.write(""Case #"" + (i+1) + "": "" + output.get(i)); fout.newLine(); } fout.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B10230,"package com.google.code; import java.io.FileReader; import java.io.FileWriter; import java.io.Reader; /** * @author Wellington Tadeu dos Santos [wellsantos@wellsantos.com] */ public class ProblemC { boolean endOfLine; Reader reader; Appendable writer; public ProblemC(Reader in, Appendable out) throws Exception { this.reader = in; this.writer = out; } public static void main(String[] args) throws Exception { long time = System.nanoTime(); String in = ""./src/com/google/code/C-small-attempt0.in""; String out = in.substring(0, in.length() - 3) + "".out""; FileReader reader = new FileReader(in); FileWriter writer = new FileWriter(out); new ProblemC(reader, writer).run(); writer.flush(); writer.close(); reader.close(); System.out.println((System.nanoTime() - time) / 1000000.0); } private int readInt() throws Exception { int val = 0; int chr; while ((chr = this.reader.read()) >= '0' && chr <= '9') { val = val * 10 + (chr - '0'); } switch (chr) { case '\r': chr = this.reader.read(); case '\n': case -1: this.endOfLine = true; break; default: this.endOfLine = false; } return val; } private void run() throws Exception { int testCases = this.readInt(); for (int caseIndex = 1; caseIndex <= testCases; caseIndex++) { int a = this.readInt(); int b = this.readInt(); int count = 0; for (int n = a; n <= b; n++) { for (int m = n + 1; m <= b; m++) { String nx = String.valueOf(n); String mx = String.valueOf(m); int f = nx.length(); if (f == mx.length()) { for (int i = 0; i < f; i++) { if (mx.charAt(i) == nx.charAt(f - 1)) { if (mx.substring(0, i + 1).equals(nx.substring(f - i - 1, f)) && mx.substring(i + 1, f).equals(nx.substring(0, f - i - 1))) { count++; break; } } } } } } this.writer.append(""Case #"" + caseIndex + "": "" + count + ""\n""); } } }" B10951,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { public static void readFile() throws FileNotFoundException { File f = new File(""C-small.in""); Scanner in = new Scanner(f); PrintWriter out = new PrintWriter(new File(""C-small"")); Set setOfFound = new HashSet(); // List setOfFound = new ArrayList(); // Set setOfNotFound; C c = new C(); // System.out.println(c.new Pair(1, 2).compareTo(c.new Pair(2, 1))); // setOfFound.add(c.new Pair(1, 2)); // setOfFound.add(c.new Pair(2, 1)); // setOfFound.add(c.new Pair(1, 2)); // for (Pair p : setOfFound) // System.out.println(p); int T = in.nextInt(); // System.out.println(""T: "" + T); int A, B, strLength, newNbInt; String nbStr, newNbStr; for (int i = 0; i < T; i++) { setOfFound = new HashSet(); // setOfFound = new ArrayList(); // setOfNotFound = new HashSet(); A = in.nextInt(); B = in.nextInt(); // System.out.println(""A: "" + A + ""--B: "" + B); if (B > 9) { for (int j = A; j <= B; j++) { // if (i == 3) // System.out.println(""j: "" + j); nbStr = newNbStr = """" + j; strLength = nbStr.length(); for (int k = 0; k < strLength - 1; k++) { // if (i == 3) // System.out.println(""newNbStr1: "" + newNbStr); newNbStr = newNbStr.charAt(strLength - 1) + newNbStr.substring(0, strLength - 1); if (newNbStr.indexOf(""0"") == 0) { continue; } // if (i == 3) // System.out.println(""newNbStr: "" + newNbStr); if (!nbStr.equals(newNbStr)) { newNbInt = Integer.parseInt(newNbStr); if (newNbInt >= A && newNbInt <= B) { setOfFound.add(c.new Pair(j, newNbInt)); // if (i == 3) // System.out.println(""added: "" + newNbInt); } // else { // setOfNotFound.add(c.new Pair(j, newNbInt)); // } } } } } else { // System.out.println(""1 digit => finish: 0""); } // System.out.println(""Founnnnnnnnnnnnnnnnd / 2: "" + // setOfFound.size() / 2); if (i < T - 1) out.println(""Case #"" + (i + 1) + "": "" + setOfFound.size() / 2); else out.print(""Case #"" + (i + 1) + "": "" + setOfFound.size() / 2); // if (i == 3) { // for (Pair p : setOfFound) // System.out.println(p); // } } out.close(); } public static void main(String[] args) throws FileNotFoundException { readFile(); } public class Pair implements Comparable { int A; int B; public Pair(int A, int B) { this.A = A; this.B = B; } public Pair() { // TODO Auto-generated constructor stub } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Pair other = (Pair) obj; if (this.A == other.A && this.B == other.B || this.A == other.B && this.B == other.A) { return true; } return false; } @Override public int hashCode() { int hash = 7; hash = 79 * hash + this.A; hash = 79 * hash + this.B; return hash; } @Override public String toString() { return ""A = "" + A + "" || B = "" + B; } @Override public int compareTo(Pair other) { if (this.A == other.A && this.B == other.B || this.A == other.B && this.B == other.A) { return 0; } return 1; } } } " B11787,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.ArrayList; /** * */ /** * @author Bryan * */ public class problemC { /** * @param args */ public static void main(String[] args) { String filePath = ""/Users/Bryan/Documents/CodeJam/ProblemC/C-small-attempt0.in""; boolean isFirstLine = true; int counter = 1; StringBuffer resultString = new StringBuffer(); try { // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(filePath); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; // Read File Line By Line while ((strLine = br.readLine()) != null) { if (isFirstLine){ isFirstLine = false; continue; } resultString.append(""Case #"" + counter + "": ""); String[] numberList = strLine.split("" ""); int result = 0; int min = Integer.parseInt(numberList[0]); int max = Integer.parseInt(numberList[1]); for ( int a = min; a <= max; a++){ result = result + noOfPairs(Integer.toString(a),min, max); // System.out.println(""final result = "" + result); } System.out.println(""result = "" + result/2); resultString.append(result/2); resultString.append(""\n""); counter++; } // Close the input stream in.close(); } catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } writeStringToFile(resultString.toString()); } private static int noOfPairs(String num,int min, int max){ int noOfPairs = 1; String oldString = num; String newString = """"; String tempString = oldString; ArrayList addedList = new ArrayList(); for ( int counter = 0; counter < oldString.length(); counter++){ newString= tempString.substring(tempString.length()-1)+tempString.substring(0,tempString.length()-1); tempString=newString; // System.out.println(newString); if( !newString.startsWith(""0"") && Integer.parseInt(newString) <= max && Integer.parseInt(newString) >= min && !newString.equalsIgnoreCase(num) && !addedList.contains(newString)){ addedList.add(newString); noOfPairs++; } } if ( noOfPairs == 1 ){ return 0; } return noOfPairs - 1; // return nCr(noOfPairs,2); } private static void writeStringToFile(String outputString) { try { // Create file FileWriter fstream = new FileWriter(""/Users/Bryan/Documents/CodeJam/ProblemC/output.txt""); BufferedWriter out = new BufferedWriter(fstream); out.write(outputString); // Close the output stream out.close(); } catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } } " B13191,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Queue; import java.util.Stack; import java.util.concurrent.LinkedBlockingQueue; public class RecyclePair { public static void main(String[] args) { runTestCase(); } public static void runTestCase() { String fileName = ""C-small-attempt0.in"";// input file String outFileName = ""outputFile.txt"";// output file try { FileInputStream fStream = new FileInputStream(fileName); FileOutputStream fOutStream = new FileOutputStream(outFileName); BufferedReader bf = new BufferedReader(new InputStreamReader( fStream)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter( fOutStream)); int i = 0; int testSize = Integer.parseInt(bf.readLine()); while (i < testSize) { String in = bf.readLine(); bw.write(checkForMatchingPairs(in, ++i)); bw.newLine(); } // close the two files. bf.close(); bw.close(); } catch (Exception e) { e.printStackTrace(); } } public static String checkForMatchingPairs (String inputData , int testCase) { StringBuffer temp = new StringBuffer(); temp.append(""Case #"" + testCase + "": ""); String[] split = inputData.split("" ""); int lowerLimit = Integer.parseInt(split[0]); int upperLimit = Integer.parseInt(split[1]); int noOfMatches =0; for(int count=lowerLimit;count queue = new LinkedBlockingQueue(); Stack stack = new Stack(); int divisor = number; int noOfMatches = 0; while(divisor>0) { int remainder = divisor%10; divisor = divisor/10; stack.push(remainder); } while(!stack.isEmpty()) { queue.add(stack.pop()); } Integer count = 0; while(count number && matchingPair >= lowerLimit && matchingPair <=upperLimit) { noOfMatches++; System.out.println(number +"":""+ matchingPair ); } count++; Integer head = queue.poll(); queue.add(head); } return noOfMatches; } } " B13055,"import java.util.*; public class RecycledNumbers { void run(){ Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for(int c=1 ; c<=T ; c++){ Integer res = 0; int A = sc.nextInt(); int B = sc.nextInt(); for(int i=A ; i<=B ; i++){ String s = String.valueOf(i); HashSet used = new HashSet(); for(int j=0 ; j9) { for(int j=a;j<=b;j++){ current=j+""""; for(int k=1; kInteger.parseInt(current) && Integer.parseInt(current)>=a && previous.compareTo(current+"",""+pair)!=0){ result++; previous=current+"",""+pair; } } } } number=i+1; fout.println(""Case #""+number+"": ""+result); } fin.close(); fout.close(); }catch(Exception e){ System.out.println(e.toString()); } } } " B12446,"import java.util.*; import java.io.*; public class recycle { public static String cycle(String n){ String[] t = new String[n.length()]; for(int i = 0; i < n.length(); i++){ t[i] = n.substring(i, i+1); } String q = t[n.length() - 1]; for(int i = n.length() - 2; i >= 0; i--){ t[i+1] = t[i]; } t[0] = q; String res = """"; for(int i = 0; i < n.length(); i++){ res += t[i]; } return res; } public static boolean cycletest(String n, String m){ boolean con = false; for(int i = 0; i < m.length(); i++){ m = cycle(m); if(n.equals(m)){ con = true; } } return con; } public static void main(String[] args) throws IOException{ Scanner reader = new Scanner(new File(""recycle.in"")); PrintWriter out = new PrintWriter(new File(""recycle.out"")); int n = reader.nextInt(); int[][] set = new int[n][2]; for(int i = 0; i < n; i++){ set[i][0] = reader.nextInt(); set[i][1] = reader.nextInt(); } int counter = 0; int[] res = new int[n]; for(int i = 0; i < n; i++){ for(int j = set[i][0]; j <= set[i][1]; j++){ for(int q = j+1; q <= set[i][1]; q++){ if(cycletest(Integer.toString(q), Integer.toString(j))){ counter++; } } } res[i] = counter; counter = 0; } for(int i = 0; i < n; i++){ out.println(""Case #"" + (i+1) + "": "" + res[i]); } out.close(); System.exit(0); } } " B12158,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package googlecodejam_recyclingnumbers; import java.io.*; /** * * @author Ulyss */ public class GoogleCodeJam_RecyclingNumbers { /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException, IOException { // TODO code application logic here BufferedReader br = new BufferedReader(new FileReader(""C-small.in"")); PrintWriter pw = new PrintWriter(""C-small.out""); int T = Integer.parseInt(br.readLine()); for(int i = 0; i < T; i++){ int total = 0; String line = br.readLine(); String[] numbers = line.split("" ""); int A = Integer.parseInt(numbers[0]); int B = Integer.parseInt(numbers[1]); System.out.println(A + "" : "" + B); for(int lowIndex = A; lowIndex < B; lowIndex++){ for(int highIndex = lowIndex+1; highIndex <= B; highIndex++){ if( isRecycled(lowIndex, highIndex) ){ System.out.println("" Yes!!! "" + lowIndex + "" - "" + highIndex); total++; } } } pw.print(""Case #"" + (i+1) + "": "" + total); if( i < T-1 ){ pw.println(); } } br.close(); pw.close(); } public static boolean isRecycled(int n, int m){ if( n < 10 ){ return false; } if( n < 100 ){ if( n % 10 == m / 10 && n / 10 == m % 10 ){ return true; } else{ return false; } } if( n < 1000 ){ String nLine = String.valueOf(n); String mLine = String.valueOf(m); if( ( nLine.charAt(2) == mLine.charAt(0) && nLine.charAt(0) == mLine.charAt(1) && nLine.charAt(1) == mLine.charAt(2) ) || ( nLine.charAt(0) == mLine.charAt(2) && nLine.charAt(1) == mLine.charAt(0) && nLine.charAt(2) == mLine.charAt(1) ) ){ return true; } } return false; } } " B12834,"import java.io.File; import java.io.FileOutputStream; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Solver { private final static String DIR_PATH = ""e:\\jam\\""; private final static String IN_FILE_NAME = ""C-small-attempt0.in""; private final static String OUT_FILE_NAME = IN_FILE_NAME.replaceAll(""\\..*$"", "".out""); private final static File sInFile = new File(DIR_PATH, IN_FILE_NAME); private final static File sOutFile = new File(DIR_PATH, OUT_FILE_NAME); private final PrintStream mOut; private final Scanner mScanner; private static class ProxyOutputStream extends FilterOutputStream { public ProxyOutputStream(OutputStream out) { super(out); } @Override public void write(byte[] b, int off, int len) throws IOException { System.out.write(b, off, len); super.write(b, off, len); } } public static void main(String[] args) { try { Solver solver = new Solver(sInFile, sOutFile); solver.solve(); } catch(IOException ex) { ex.printStackTrace(); } } public Solver(File inFile, File outFile) throws IOException { mScanner = new Scanner(inFile); mOut = new PrintStream(new ProxyOutputStream(new FileOutputStream(outFile))); } private void printSolution(int no, String solution) { if(no == 0) { throw new IllegalArgumentException(""Solution number is 0! Should start with 1!""); } mOut.println(String.format(""Case #%d: %s"", no, solution)); } private void solve() throws IOException { int problemsCount = mScanner.nextInt(); mScanner.nextLine(); for(int i = 0; i < problemsCount; i++) { long min = mScanner.nextLong(); long max = mScanner.nextLong(); String solution = Long.toString(solve(min, max)); printSolution(i + 1, solution); } } int convert(int [] digits, int d0, long number) { while(number > 0) { digits[d0] = (int)(number % 10); d0--; number /= 10; } return d0 + 1; } long convertToInt(int [] digits, int d0, int dlen) { long number = 0; for(int i = 0; i < dlen; i++) { number = number * 10 + digits[d0 + i]; } return number; } //true if r > d boolean isGreater(int [] r, int r0, int [] d, int d0, int len) { for(int i = 0; i < len; i++) { int delta = r[r0 + i] - d[d0 + i]; if(delta > 0) { return true; } else if(delta < 0) { return false; } } return false; } private long solve(long min, long max) { if(max < 10) { return 0; } long counter = 0; int [] max_digits = new int[8]; int max_d0 = convert(max_digits, max_digits.length - 1, max); int [] digits = new int [7 + 1 + 7]; int d0 = 7;//points to least significant digit in array Set unique = new HashSet(); for(long number = min; number <= max; number++) { unique.clear(); /* convert number to array */ int n0 = convert(digits, d0, number); int dlen = d0 - n0 + 1; /* duplicate digits */ for(int i = 0; i < dlen - 1; i++) { digits[d0 + i + 1] = digits[n0 + i]; } /* count recycled numbers */ boolean printed = false; for(int i = 0; i < dlen - 1; i++) { int r0 = n0 + i + 1;//r0 for current recycled number //print(digits, r0, dlen); if(digits[r0] == 0) { //System.out.println("" - nope, leading zero.""); continue;//invalid case } /* is recycled number greater than original one? */ boolean greater = isGreater(digits, r0, digits, n0, dlen); /* is recycled number grater than max? */ boolean valid = !isGreater(digits, r0, max_digits, max_d0, dlen); if(greater && valid) { //System.out.println("" - yes.""); if(!printed) { //print(digits, n0, dlen); //System.out.println("" => ""); printed = true; } //System.out.print("" ""); //print(digits, r0, dlen); unique.add(convertToInt(digits, r0, dlen)); } else { if(!greater) { //System.out.println("" - nope, not greater than original.""); } else { //System.out.println("" - nope, greater than max.""); } } } if(printed) { //System.out.println(); } counter+=unique.size(); //System.out.println(""----""); } return counter; } void print(int [] digits, int d0, int dlen) { for(int i = d0; i < d0 + dlen; i++) { System.out.print(digits[i]); } } void println(int [] digits, int d0, int dlen) { print(digits, d0, dlen); System.out.println(); } } " B13094,"package RecycledNumbers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.ArrayList; public class RecycledNumbers { public static void main(String[] args) { try { // lets get the data in FileInputStream fstream = new FileInputStream(""E:/workspace_java/CodeJam12/src/RecycledNumbers/input.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; // open file for writing FileWriter fwstream = new FileWriter(""E:/workspace_java/CodeJam12/src/RecycledNumbers/output.out""); BufferedWriter out = new BufferedWriter(fwstream); // declare variables int i,j,k; int numCases; String[] strArr; // get number of cases strLine = br.readLine(); numCases = Integer.parseInt(strLine); // declare specific vars int low, high, n; int cur, len; int count; String ts, ns, a, b; ArrayList found = new ArrayList(); // loop through cases for(i=0;i ""); for(k = len - 1; k >= 0; k--){ a = ts.substring(k); b = ts.substring(0, k); n = Integer.parseInt(a + b); ns = new Integer(n).toString(); if(n >= low && n <= high && n > cur && !(in_array(ns+ts, found))){ count++; //System.out.print(ns + "" ""); } } //System.out.println(); } /* final tests if((one >= 0 && one <= 10) && (two >= 0 && two <= 10) && (three >= 0 && three <= 10)) { } else { System.out.println(""Out of bounds on number""); } if(total != tempScore) { System.out.println(""Score does not add up""); } if(surprisesTaken > numSurprises) { System.out.println(""Too many surprises""); } */ //System.out.println(one + "" "" + two + "" "" + three); System.out.print(""Case #""+(i+1)+"": ""); out.write(""Case #""+(i+1)+"": ""); System.out.println(count); out.write(Integer.toString(count)); out.newLine(); } //System.out.print(""Case #""+(i+1)+"": ""); //out.write(""Case #""+(i+1)+"": ""); //System.out.println(seanP2sum); //out.write(Integer.toString(seanP2sum)); //out.newLine(); out.close(); in.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } public static boolean in_array(String needle, ArrayList haystack){ boolean found = false; int i = 0; int len = haystack.size(); for(i=0; i list = readFile(""C:/Users/Wurschti/workspace2/2012_3_recycled/src/input.txt""); int counter = 1; int result = 0; LinkedList resultList = new LinkedList(); for (String s : list) { resultList = new LinkedList(); String[] pair = s.split("" ""); if (pair.length < 2) { result = 0; } else { int min = Integer.parseInt(pair[0]); int max = Integer.parseInt(pair[1]); int counter2 = min; while (counter2 < max) { String intToUse = counter2 + """"; for (int i = 0; i < intToUse.length(); i++) { char[] intAsCharArray = intToUse.toCharArray(); for (int j = 0; j < intAsCharArray.length - 1; j++) { intAsCharArray[j] = intAsCharArray[j + 1]; } intAsCharArray[intAsCharArray.length - 1] = intToUse.charAt(0); intToUse = """"; for (char c : intAsCharArray) { intToUse += c; } //evtl contains umschreiben int resultNumber = Integer.parseInt(intToUse); Pair p = new Pair(counter2, resultNumber); if (!isIn(p, resultList) && resultNumber <= max && resultNumber > counter2) { resultList.add(p); } } counter2++; } } System.out.format(""Case #%d: %s\n"", counter, resultList.size()); counter++; } } private static boolean isIn(Pair p, LinkedList list) { for (Pair p2 : list) { if (p.first == p2.first && p.second == p2.second) { return true; } } return false; } public static LinkedList readFile(String filename) throws IOException { LinkedList list = new LinkedList(); File file = new File(filename); if (!file.exists()) { System.out.println(""file not found""); return null; } BufferedReader in = new BufferedReader(new FileReader(file)); // read vocables String input = in.readLine(); input = in.readLine(); while (input != null) { list.add(input); input = in.readLine(); } in.close(); return list; } } " B12871,"package jpt.codejam; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Codejam2012 { static void solve_Qual_B() throws Exception { Scanner in = new Scanner(System.in); PrintStream out = System.out; int cases = in.nextInt(); for (int nCase = 1; nCase <= cases; ++nCase) { int N = in.nextInt(); int S = in.nextInt(); int p = in.nextInt(); int res = 0; for (int i=0; i=29) max2 = -1; if (max1 >= p) ++res; else if (max2 >= p && S > 0) { ++res; --S; } } out.printf(""Case #%d: %d\n"", nCase, res); } } static void solve_Qual_C() throws Exception { Scanner in = new Scanner(System.in); PrintStream out = System.out; int[] ten = new int[8]; ten[0] = 1; for (int i=1; i ms = new HashSet(); for (int n=A; n<=B; ++n) { int d = 1; for (int aux=10; aux<=n; aux*=10) ++d; ms.clear(); for (int k=1; k=m && n!=m && !ms.contains(m)) ++res; ms.add(m); } } out.printf(""Case #%d: %d\n"", nCase, res/2); } } public static void main(String[] args) throws Exception { //solve_Qual_B(); solve_Qual_C(); //solve_1A_A(); //solve_1A_B(); //solve_1A_C(); } } " B10762,"import java.util.*; class xyz { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int p=sc.nextInt(); int t=1; while(p!=0) { int a= sc.nextInt(); int b=sc.nextInt(); int cnt=0; for(int i=a;i<=b;i++) { String s=""""+i; int n=Integer.parseInt(s); char c[]=s.toCharArray(); for(int j=1;j<(c.length);j++) { char temp; temp=c[0]; for(int k=0;k<(c.length-1);k++) { c[k]=c[k+1]; } c[c.length-1]=temp; String s1=new String(c); int w=Integer.parseInt(s1); if((w>n)&&(w>=a)&&(w<=b)) cnt++; } } System.out.println(""Case #""+t+"": ""+cnt); t++; p--; } } }" B11684,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package uk.co.epii.codejam.recyclednumbers; /** * * @author jim */ public class DataRow { public final int A; public final int B; public DataRow(String in) { String[] parts = in.split("" ""); A = Integer.parseInt(parts[0]); B = Integer.parseInt(parts[1]); } } " B11215,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; public class RecycledNumbers { public static File inputFile, outputFile; public static List inputLines = new ArrayList(); public static List outputLines = new ArrayList(); public static Map mapGtE = new HashMap(); private static void initFiles() { inputFile = new File(""C:\\Users\\Enrique\\Desktop\\codejam\\RecycledNumbers\\C-small-attempt0.in""); outputFile = new File(""C:\\Users\\Enrique\\Desktop\\codejam\\RecycledNumbers\\RecycledNumbers.out""); } private static void readInput() { BufferedReader reader; try { reader = new BufferedReader(new FileReader(inputFile)); String line = """"; int numberOfCases = Integer.parseInt(reader.readLine()); for(int i=0; i recycledPairs = new HashSet(); int result=0; for(int i=downBounds; i<=upBounds; i++) { String numstr_rotate = String.valueOf(i); String numstr_original = String.valueOf(i); for(int j=1; j<=numstr_rotate.length()-1; j++) { numstr_rotate = numstr_rotate.charAt(numstr_rotate.length()-1)+numstr_rotate.substring(0,numstr_rotate.length()-1); if(!numstr_rotate.equals(numstr_original)) { if(Integer.parseInt(numstr_rotate) <= upBounds && Integer.parseInt(numstr_rotate) >= downBounds) { if(!recycledPairs.contains(numstr_original+"":""+numstr_rotate) && !recycledPairs.contains(numstr_rotate+"":""+numstr_original)) { recycledPairs.add(numstr_original+"":""+numstr_rotate); result++; } } } } } return result; } /** * @param args */ public static void main(String[] args) { initFiles(); readInput(); doAlgorithm(); writeOutput(); } } " B12509,"import java.io.File; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.Scanner; public class CodeJam2012Ex3 { public static void main(String arg[]) throws FileNotFoundException { File file = new File(""C-small-attempt1.in""); String output; Scanner scanner = new Scanner(file); int numTestCases = scanner.nextInt(); for (int i = 0; i < numTestCases; i++) { StringBuffer buffer = new StringBuffer(""Case #"" + (i + 1) + "": ""); int A = scanner.nextInt(); int B = scanner.nextInt(); buffer.append(CodeJam2012Ex3.countPairs(A, B)); if (i != numTestCases - 1) { buffer.append(""\n""); } output = buffer.toString(); System.out.print(output); } } public static int countPairs(int A, int B) { int pairs = 0; HashMap map = new HashMap(); for (int i = A; i <= B; i++) { String n = i + """"; int len = n.length(); for (int j = 1; j < len; j++) { String m = n.substring(len - j) + n.substring(0, len - j); int nNum = Integer.parseInt(n); int mNum = Integer.parseInt(m); if (nNum < mNum && n.length() == (mNum + """").length() && mNum <= B && !map.containsKey((n + m))) { map.put(n + m, (Boolean) true); pairs++; } } } return pairs; } } " B12849," public class RecycledPair { public int num1; public int num2; public RecycledPair(int n1, int n2) { this.num1 = n1; this.num2 = n2; } @Override public String toString() { return ""("" + num1 + "", "" + num2 + "")""; } @Override public boolean equals(Object obj) { if(obj instanceof RecycledPair) { RecycledPair other = (RecycledPair) obj; if((other.num1 == this.num1 && other.num2 == this.num2) || (other.num2 == this.num1 && other.num1 == this.num2)) { return true; } } return false; } @Override public int hashCode() { int prime = 31; return (num1 * prime) + (num2 * prime); } } " B12403,"import java.util.*; public class RecycledNumbers { static class Number implements Comparable { int[] digits; public Number(String str) { digits = new int[str.length()]; for(int i=0;i 0) { noDig++; t /= 10; } int cnt = 0; for(int n = A; n <= B; n++) { String s = """" + n; HashSet used = new HashSet(); for (int i = 0; i < noDig - 1; i++) { s = s.substring(1) + s.charAt(0); if (used.contains(s)) continue; used.add(s); int q = Integer.parseInt(s); if (q > n && q <= B) { cnt++; } } } io.println(cnt); } } " B11089,"package codejam; public class DirConsts { public static final String // INPUT_DIR = ""/home/luke/Downloads"", // OUTPUT_DIR = ""/home/luke/Downloads/CodeJam""; } " B10054,"import java.io.*; import java.util.*; public class CodeJamC { private static int noOfDigits(int number) { int noOfDigits = 0; while (number > 0) { number /= 10; noOfDigits++; } return noOfDigits; } private static int pow(int exponent) { int power = 1; for (int mulitply = 1; mulitply <= exponent; mulitply++) power *= 10; return power; } private static int countPairs(int A, int B) { int noOfDigits = noOfDigits(A); int noOfPairs = 0; int places = pow(noOfDigits); for (int next = A; next < B; next++) { HashSet used = new HashSet(); // System.out.println(""Next ""+ next); for (int back = 10; back < places; back *= 10) { int recycled = shift(next, back, places / back); // System.out.println(""Back: "" + back + ""RC "" + recycled); if (recycled > next && recycled <= B) { // System.out.println(next +"", "" + recycled); if (!used.contains(recycled)) { used.add(recycled); noOfPairs++; } } } } return noOfPairs; } private static int shift(int number, int back, int front) { return (number % back) * front + number / back; } /** * @param args */ public static void main(String[] args) throws IOException { String fileName = ""C-small0""; Scanner in = new Scanner(new File(fileName + "".in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter( fileName + "".out""))); // Keep track of time for efficiency long startTime = System.currentTimeMillis(); // Process each of the test cases int noOfCases = in.nextInt(); for (int caseNo = 1; caseNo <= noOfCases; caseNo++) { int A = in.nextInt(); int B = in.nextInt(); int noOfPairs = countPairs(A, B); System.out.println(""Case #"" + caseNo + "": "" + noOfPairs); out.println(""Case #"" + caseNo + "": "" + noOfPairs); } System.out.println(""Done""); long stopTime = System.currentTimeMillis(); System.out.println(""Time: "" + (stopTime - startTime) / 1000.0); // Close the files in.close(); out.close(); } } " B11154,"package org.nos.gcj; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.StringTokenizer; public class GCJ_Q_03 { static final String path = ""F:/GCJ/GCJ_Qalification_03/Small_1""; // static final String path = ""F:/GCJ/GCJ_Qalification_03/Large""; class TestCase { int A,B; } public TestCase readTestCase(BufferedReader br) throws Exception { TestCase tc = new TestCase(); String line = br.readLine(); StringTokenizer st = new StringTokenizer(line); tc.A = Integer.valueOf(st.nextToken()); tc.B = Integer.valueOf(st.nextToken()); return tc; } public void writeTestResult(BufferedWriter bw, TestCase tc) throws Exception { int rpCount = 0; for (int i = tc.A; i < tc.B; i++) { int digits = Long.valueOf(Math.round(Math.floor(Math.log10(i)))).intValue()+1; List local = new ArrayList(); for (int d = 1; d <= digits - 1; d++) { int recycled = Integer.valueOf((""""+i).substring(d, digits) +(""""+i).substring(0, d)); int rdigits = Long.valueOf(Math.round(Math.floor(Math.log10(recycled)))).intValue()+1; if (rdigits != digits) continue; if (recycled < i) continue; if (recycled > tc.B) continue; if (recycled == i) continue; if (local.contains(recycled)) continue; else local.add(recycled); rpCount++; } } bw.write(""""+rpCount); } public void solve() throws Exception { BufferedReader br = new BufferedReader(new FileReader(path+""/input.in"")); BufferedWriter bw = new BufferedWriter(new FileWriter(path+""/output.out"")); int testCases = new Integer(br.readLine()); for (int i=0; i used = new HashSet(); int A = in.nextInt(); int B = in.nextInt(); int count = 0; for (int i = A; i <= B; i++) { String s = Integer.toString(i); for (int k = 1; k < s.length(); k++) { String front = s.substring(0, k); String sub = s.substring(k); String reconstr = sub + front; if (reconstr.startsWith(""0"") || reconstr.equals(s)) continue; int reconstructed = Integer.parseInt(reconstr); if (reconstructed >= i) continue; if (used.contains(new Point(i, reconstructed))) continue; if (A <= reconstructed && reconstructed <= B) { used.add(new Point(i, reconstructed)); count++; } } } return count; } }" B11834,"import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; public class Solution { public static void main(String[] args){ Scanner scan = new Scanner(System.in); int T = scan.nextInt(); int[] counts = new int[T]; int max =2000001; boolean[] used = new boolean[max]; for(int i=0;i0){ temp=temp/10; num++; total*=10; } HashSet set = new HashSet(); int rotato=0; int size =0; for(int i=A;i<=B;i++){ if(!used[i]){ set.clear(); set.add(i); temp=i; int exp =1; for(int j=1;j=A && rotato<=B){ set.add(rotato); used[rotato]=true; } } //System.out.println(size); size = set.size(); if(size>1){ result+=size*(size-1)/2; } } } Arrays.fill(used, A,B,false); return result; } } " B10571,"package CodeJam; import java.io.*; import java.util.Scanner; public class C_2012 { public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""test.out""))); int c = in.nextInt(); for(int cases=0;casesInteger.parseInt(num)){ if(Integer.parseInt(inic+from)>=Integer.parseInt(n1)&&Integer.parseInt(inic+from)<=Integer.parseInt(n2)&&Integer.parseInt(from+inic)>=Integer.parseInt(n1)&&Integer.parseInt(from+inic)<=Integer.parseInt(n2)){ valor++; }else{ continue; } } } } public static void readFile(String filename){ BufferedReader entrada; BufferedWriter salida; try { entrada = new BufferedReader(new FileReader(filename)); entrada.readLine(); while(entrada.ready()){ String[] numbers; numbers=entrada.readLine().split("" ""); analizar(numbers); } }catch (Exception e){ e.printStackTrace(); } System.out.println(output); try { salida= new BufferedWriter(new FileWriter(filesalida)); salida.write(output); try { if (salida != null) { salida.flush(); salida.close(); } } catch (IOException ex) { ex.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } public static void main (String args[]){ System.out.print(""file path: ""); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { String userinput; userinput = br.readLine(); readFile(userinput); } catch (IOException ioe) { System.out.println(""IO error""); System.exit(1); } } } " B10831,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.HashMap; public class RecycledNumber { public static void main(String[] args) { try { FileInputStream fstream = new FileInputStream(args[0]); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; int count = 0; int noCases = 0; while ((strLine = br.readLine()) != null) { if (count > noCases) break; if (count == 0) { noCases = Integer.valueOf(strLine); } else { compute(count, strLine); } count++; } in.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } private static void compute(int caseNo, String str) { String[] AB = str.split("" ""); int A = Integer.valueOf(AB[0]); int B = Integer.valueOf(AB[1]); int meetsCriteria = 0; HashMap hm = new HashMap(); while (A < B) { hm = new HashMap(); int n = A; String nStr = String.valueOf(n); int nLen = nStr.length(); for (int j = 0; j < nLen - 1; j++) { nStr = nStr.charAt(nLen - 1) + nStr.substring(0, nLen - 1); int m = Integer.valueOf(nStr); if (Integer.valueOf(AB[0]) <= n && n < m && m <= B) { if (!hm.containsKey(m)) { hm.put(m, m); meetsCriteria++; } } } A++; } System.out .println(String.format(""Case #%s: %s"", caseNo, meetsCriteria)); } } " B11034,"package ch.socaciu.andrei.codejam; import java.io.*; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @author Andrei Socaciu */ public class Recycled { public static void main(String[] args) throws Exception { String in = ""data/Recycled-small-attempt0.in.txt""; String out = ""data/Recycled-small-attempt0.out.txt""; String line = null; BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(in))); List lines = new ArrayList(); while ((line = reader.readLine()) != null) { lines.add(line); } reader.close(); int tests = Integer.parseInt(lines.get(0)); List res = new ArrayList(); int k = 1; for (int i = 1; i <= tests; i++) { line = lines.get(k++); String[] parts = line.split("" ""); int a = Integer.parseInt(parts[0]); int b = Integer.parseInt(parts[1]); int result = solve(a,b); res.add(""Case #"" + i + "": "" + result); } BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(out))); for (String re : res) { writer.write(re); writer.write(""\n""); } writer.close(); } private static int solve(int a, int b) { int count = 0; Set unique = new HashSet(); for (int i = a; i < b; i++) { StringBuilder sb = new StringBuilder(Integer.toString(i)); for (int j = 0; j < sb.length() - 1; j++) { char last = sb.charAt(sb.length() - 1); sb.deleteCharAt(sb.length() - 1); sb.insert(0, last); if (sb.charAt(0) != '0') { int permutation = Integer.parseInt(sb.toString()); if (permutation >= a && permutation <= b && permutation > i) { String stringForm = i + "", "" + sb; if (unique.add(stringForm)) { count++; } } } } } return count; } } " B11502,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class problem { public static void main(String[] args) throws IOException{ final String filein = ""C:\\Users\\BYTE\\Downloads\\C-small-attempt0.in""; //final String filein = ""C:\\Users\\byte\\Downloads\\NewFolder\\C-small-attempt6.txt""; BufferedReader in = new BufferedReader(new FileReader(filein)); int tests=Integer.parseInt(in.readLine()); int a=0,b=0,num=0; for(int i=0;i0;k--) { if(arr[k]== '0') continue; else { String s = new String(arr); int z= Integer.parseInt(s.substring(k,arr.length)+s.substring(0,k)); if(z >= a && z<=b && z!=j && !(z solSofar = new ArrayList(); for (int i=1; i pairs = new HashSet(); final int order = (int) Math.floor(Math.log10(A)) + 1; for (int n = A; n <= B; n++) { int m = n; for (int o = 0; o < order - 1; o++) { // rotate m one digit int tail = m % 10; m /= 10; m += tail * Math.pow(10, order - 1); if (m > n && m >= A && m <= B) pairs.add(new Pair(n, m)); } } System.out.println(""Case #"" + t + "": "" + pairs.size()); out.println(""Case #"" + t + "": "" + pairs.size()); } out.close(); } } " B13029,"package qualification.q3; import qualification.common.InputReader; import qualification.common.OutputWriter; import qualification.q1.Q1Solver; /** * Created by IntelliJ IDEA. * User: ofer * Date: 14/04/12 * Time: 20:45 * To change this template use File | Settings | File Templates. */ public class Q3Sim { public static void main(String[] args){ String inputFile = ""input.txt""; String outPutFile = ""output.txt""; String[] lines = InputReader.getInputLines(inputFile); Q3Solver solver = new Q3Solver(); int numOfTests = Integer.parseInt(lines[0]); String[] output = new String[numOfTests]; for (int i = 0 ; i < numOfTests ; i++){ String[] nums = lines[i+1].split("" ""); int a = Integer.parseInt(nums[0]); int b = Integer.parseInt(nums[1]); int res = solver.solve(a,b); output[i] = ""Case #"" + (i+1) + "": "" + res; } OutputWriter.writeOutput(outPutFile, output); } } " B11740,"import java.util.*; import java.io.*; public class recycle { public static int[] pow10 = {1,10,100,1000,10000,100000,1000000,10000000}; public static void main(String[] args) throws Throwable { Scanner input=new Scanner(new File(""recycle.in"")); PrintWriter out=new PrintWriter(new File(""recycle.out"")); int cases=input.nextInt(); for(int test=1;test<=cases;test++) { boolean[] visited=new boolean[2000001]; int a=input.nextInt(); int b=input.nextInt(); int rank=0, num=1; int ans=0; for(;num<=a;num*=10,rank++); // rank = #digits for(int i=a;i<=b;i++) { if(visited[i]) continue; visited[i]=true; int temp=i; int count=1; for(int j=0;jb || visited[temp]) continue; visited[temp]=true; count++; } ans+=count*(count-1)/2; //count choose 2 } out.println(""Case #""+test+"": ""+ans); } out.close(); } }" B11118,"package recycle; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashSet; public class Recycle { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int count = Integer.parseInt(br.readLine()); for(int z = 0;z < count;z++) { int n = 0; int dbgCnt = 0; HashSet used = new HashSet(); HashSet dbgUsed = new HashSet(); String[] info = br.readLine().split("" ""); int a = Integer.parseInt(info[0]); int b = Integer.parseInt(info[1]); char[] max = String.valueOf(b).toCharArray(); for(int i = a;i < b;i++) { char[] digits = String.valueOf(i).toCharArray(); for(int j = 1;j < digits.length;j++) { boolean valid = true; boolean low = false; boolean high = false; boolean same = true; for(int k = 0;k < digits.length;k++) { char comp = digits[(k + j) % digits.length]; //System.out.println(comp + "" >="" + digits[k] + "" <="" + max[k]); if((high || comp > digits[k]) && (low || comp < max[k] || (k == digits.length - 1 && comp == max[k]))) { same = false; break; } else if((!high && comp < digits[k]) || (!low && comp > max[k])) { valid = false; break; } if(digits[k] != max[k]) { if(comp == digits[k]) { low = true; } else if(comp == max[k]) { high = true; } } } if(valid && !same) { //System.out.println(""Adding""); char[] recon = new char[digits.length]; for(int k = 0;k < digits.length;k++) { recon[k] = digits[(j + k) % digits.length]; } int num = Integer.parseInt(String.valueOf(recon)); //System.out.println(a + "" <= "" + i + "" < "" + num + "" <= "" + b); // if(!(a <= i && i < num && num <= b)) // { // System.out.println(""ERROR: "" + num); // } // if(used.contains((num) | ((long) i << 32))) { // System.out.println(""Reused""); } else { used.add((num) | ((long) i << 32)); n++; } // char[] num1 = String.valueOf(i).toCharArray(); // char[] num2 = String.valueOf(num).toCharArray(); // for(int k = 0;k < digits.length;k++) // { // if(num1[(j + k) % digits.length] != num2[k]) // System.out.println(""ERROR!""); // } } /*char[] recon = new char[digits.length]; for(int k = 0;k < digits.length;k++) { recon[k] = digits[(j + k) % digits.length]; } int num = Integer.parseInt(String.valueOf(recon)); if(i < num && num <= b && !dbgUsed.contains((num) | ((long) i << 32))) { dbgUsed.add((num) | ((long) i << 32)); dbgCnt++; }*/ } } /*for(long p : dbgUsed) { if(!used.contains(p)) { System.out.println((int) (p >> 32) + "" "" + (int) (p & 0xFFFFFFFF)); } }*/ System.out.println(""Case #"" + (z + 1) + "": "" + n/* + "" "" + dbgCnt + ((dbgCnt != n)?"" !!!"":"""")*/); } } } " B11370,"import java.io.*; public class C { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int T; T = Integer.parseInt(reader.readLine()); for (int i = 1; i <= T; i++) { String[] input = reader.readLine().split("" ""); int result = 0; int A=Integer.parseInt(input[0]); int B=Integer.parseInt(input[1]); if(A<10){ result=0; } else if(A<100){ for(int j=A;j<=B;j++){ String temp1 = j+""""; int temp = ( (Integer.parseInt(temp1.charAt(0)+"""") + Integer.parseInt(temp1.charAt(1)+"""")) * 11 ) - j; if(temp > j && temp <=B ){ ++result; } } } else if(A<1000){ for(int j=A;j<=B;j++){ String temp = j+""""; String temp1 = Character.toString(temp.charAt(2))+Character.toString(temp.charAt(0))+Character.toString(temp.charAt(1)); String temp2 = Character.toString(temp.charAt(1))+Character.toString(temp.charAt(2))+Character.toString(temp.charAt(0)); int temp3 = Integer.parseInt(temp1); int temp4 = Integer.parseInt(temp2); if(j0) { sum+=x%10; x /=10; } return sum ; } String n ; String m ; String temp1_1 ; public boolean Recycled(int x,int y,int begin) // y > x { if (x == y) return false ; if (sumOfDigit(x) != sumOfDigit(y)) return false ; n = x+"""" ; temp1_1 = x+"""" ; m = y+"""" ; while (begin< n.length() && n.charAt(begin) != m.charAt(0)) begin++; // System.out.println(""i = "" + begin); if (begin == n.length()) return false ; n = n.substring(begin); n += temp1_1.substring(0,begin); // System.out.println(""1 = "" + n); // System.out.println(""2 = "" +m); if (n.equals(m)) return true ; if (begin removeDuplicates; @Override public String solve(String[] dataset) { String strReturnValue =""""; String strRecycledNos = dataset[0]; String strRecycledNosArr[] = strRecycledNos.split("" ""); iLowerLimit = Integer.parseInt(strRecycledNosArr[0]); iUpperLimit = Integer.parseInt(strRecycledNosArr[1]); iVisited = new int[iUpperLimit+1]; removeDuplicates = new HashSet(); for(int i=iLowerLimit;i<=iUpperLimit;i++) { if(iVisited[i] == 0 && i > 9) { findMatchingNumbers(i); } } System.out.println(""Output : "" +removeDuplicates.size()); return strReturnValue + removeDuplicates.size(); } private void findMatchingNumbers(int iVar) { String strVar = """"+iVar; for(int i=1; i < (strVar.length());i++) { String strSuffix = strVar.substring(0,strVar.length() -i); String strPrefix = strVar.substring(strVar.length() -i,strVar.length()); int iNewNo = Integer.parseInt(strPrefix + strSuffix); if (iNewNo >= iLowerLimit && iNewNo <= iUpperLimit && iVar != iNewNo && iVisited[iNewNo] ==0 ) { removeDuplicates.add(iVar + "" : "" + iNewNo); iVisited[iVar] = 1; } } } } " B11232,"import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; public class C { public static void main(String[] args) throws NumberFormatException, IOException { // Use scanner! Good for reading in bigints too. // Arrays.fill for initialising arrays // Look up cumulative frequency tables (only for dynamic querying with new numbers coming in) BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(""in.in""))); PrintStream writer = new PrintStream(new FileOutputStream(""out.out"")); int cases = Integer.parseInt(reader.readLine()); for (int i = 1; i <= cases; i++) { String[] tokens = reader.readLine().split("" ""); int A = Integer.parseInt(tokens[0]); int B = Integer.parseInt(tokens[1]); HashSet> numbers = new HashSet>(); int maxPow = (int) Math.log10(A); for (int j = A; j <= B; j++) { for (int k = 0; k < maxPow; k++) { int cycled = j / (int) Math.pow(10, k + 1) + j % (int) Math.pow(10, k + 1) * (int) Math.pow(10, maxPow - k); if (cycled >= A && cycled <= B && maxPow == (int) Math.log10(cycled) && cycled != j) { ArrayList pair = new ArrayList(); pair.add(cycled); pair.add(j); Collections.sort(pair); numbers.add(pair); } } } writer.printf(""Case #%d: %d\n"", i, numbers.size()); } } } " B11236,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.Hashtable; public class RecycleNumber_1 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub try { BufferedReader br = new BufferedReader(new FileReader(""/Users/kushal/Downloads/C-small-attempt1.in"")); PrintWriter pr = new PrintWriter(""/Users/kushal/Desktop/recycle.out""); String line = """"; br.readLine(); int start; int end; int count; int number = -1; int temp , p1, p2; String str; int z = 1; HashSet hash = new HashSet(); ArrayList digits; while((line = br.readLine()) != null) { start = Integer.parseInt(line.split("" "")[0]); end = Integer.parseInt(line.split("" "")[1]); digits = new ArrayList(); count = 0; hash.clear(); for(int i=start; i<=end; i++) { number = i; //hash.add(i); if(i == 121) { //System.out.println(i+""kk""); } digits = new ArrayList(); while(number > 0) { digits.add(number%10); number /= 10; } number = digits.get(digits.size() - 1); for(int j = digits.size() - 2 ;j >= 0; j--) { str = """" + digits.get(j); if(j == 0 ) { p1 = digits.size() -1; } else { p1 = j - 1; } str += """" + digits.get(p1); while(true) { if(p1 == 0) { p1 = digits.size() -1; } else { p1 = p1 - 1; } if(p1 == j) { break; } str += """" + digits.get(p1); } //System.out.print(str + ""\t""); if(!str.startsWith(""0"")) { temp = Integer.parseInt(str); if((temp < i) && (temp >= start) && (temp <= end)) { if(!hash.contains(i+""_""+temp)) { hash.add(i+""_""+temp); //System.out.println(i + "" ""+ count); //continue; count++; } } } } //System.out.println(); } System.out.println(""Case #""+z+"": ""+count); z++; } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B11522,"import java.io.*; import java.math.*; import java.util.*; import java.text.*; import java.util.regex.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; import static java.lang.Integer.*; import static java.lang.Double.*; import static java.lang.Character.*; public class C { static class Pair { int a, b; public Pair(int a, int b) { super(); this.a = a; this.b = b; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + a; result = prime * result + b; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (a != other.a) return false; if (b != other.b) return false; return true; } } Object solve() { String As = sc.next(); int l = As.length(); int A = parseInt(As); int B = sc.nextInt(); int ml = (int)pow(10,l-1); HashSet used = new HashSet(); for (int n = A; n < B; n++) { int m = n; for (int i = 0; i < l; i++) { m = m/10 + (m%10)*ml; if (n < m && m <= B) used.add(new Pair(n,m)); } } return used.size(); } private static Scanner sc; private static PrintWriter fw; public static void main(String[] args) throws Exception { String inFile; // inFile = ""input.txt""; inFile = ""C-small-attempt0.in""; // inFile = ""A-large.in""; // sc = new Scanner(System.in); sc = new Scanner(new FileInputStream(inFile)); fw = new PrintWriter(new FileWriter(""output.txt"", false)); int N = sc.nextInt(); sc.nextLine(); for (int cas = 1; cas <= N; cas++) { fw.print(""Case #"" + cas + "": ""); // fw.println(""Case #"" + cas + "": ""); Object res = new C().solve(); if (res instanceof Double) fw.printf(""%.10f\n"", res); else fw.printf(""%s\n"", res); fw.flush(); } fw.close(); sc.close(); } } " B12206,"package hk.polyu.cslhu.codejam.solution.impl; public class AlienLanguage { } " B12193,"import java.util.*; /** * * @author Jhon */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner cin = new Scanner(System.in); List integers = new ArrayList<>(); int a = Integer.parseInt(cin.nextLine()); int[] begin = new int[a]; int[] end = new int[a]; int value, value2, count; boolean aux; String number; for (int i = 0; i < a; i++) { integers.clear(); count = 0; begin[i] = cin.nextInt(); end[i] = cin.nextInt(); for (int j = begin[i]; j <= end[i]; j++) { if (j >= 10) { if (j < 100) { number = j + """"; value = Integer.parseInt(number.charAt(1) + """" + number.charAt(0)); aux = true; for (Integer ii : integers) { if (ii.intValue() == value) { aux = false; break; } } if (aux && value != j && number.charAt(1) != '0' && begin[i] <= value && value <= end[i]) { integers.add(j); count++; } } else if (j <= 1000) { number = j + """"; value = Integer.parseInt(number.charAt(2) + """" + number.charAt(0) + """" + number.charAt(1)); value2 = Integer.parseInt(number.charAt(1) + """" + number.charAt(2) + """" + number.charAt(0)); aux = true; for (Integer ii : integers) { if (ii.intValue() == value) { aux = false; break; } } if (aux && value != j && 100 <= value && begin[i] <= value && value <= end[i]) { integers.add(j); count++; } aux = true; for (Integer ii : integers) { if (ii.intValue() == value2) { aux = false; break; } } if (aux && value2 != j && 100 <= value2 && begin[i] <= value2 && value2 <= end[i]) { integers.add(j); count++; } } } } System.out.println(""Case #""+(i+1)+"":""+count); } } }" B11104,"import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Formatter; import java.util.Scanner; public class RecycledNumbers { private Scanner fileReader; private File input; private Formatter fileWriter; private File output; public RecycledNumbers() throws FileNotFoundException { input = new File(""C-small-attempt0.in""); fileReader = new Scanner(input); output = new File(""output.txt""); fileWriter = new Formatter(output); } public int pairsByLine(String inLn) { int outLn = 0; String[] bounds = inLn.split("" ""); int A = Integer.parseInt(bounds[0]); int B = Integer.parseInt(bounds[1]); ArrayList done = new ArrayList(); for (int t = A; t <= B; t++) { String s = t + """"; for (int i = s.length() - 1; i > 0; i--) { String s1 = s.substring(i, s.length()); String s2 = s.substring(0, i); String res = s1 + s2; int reversed = Integer.parseInt(res); if (reversed <= B && reversed <= B &&t"" + reversed); outLn++; } } } return outLn; } private boolean repeated(String s) { boolean repeated = false; for (int i = 0; i < s.length(); i++) { for (int j = i + 1; j < s.length(); j++) { if (s.charAt(i) == s.charAt(j)) { repeated = true; } } } return repeated; } public void getPairs() { int i = 0; int testcases = Integer.parseInt(fileReader.nextLine()); while (fileReader.hasNextLine()) { i++; String line = fileReader.nextLine(); fileWriter.format(""%s%s%s"", ""Case #"" + i + "": "", pairsByLine(line) + """", ""\n""); } fileWriter.close(); } public static void main(String[] args) throws FileNotFoundException { RecycledNumbers rec = new RecycledNumbers(); rec.getPairs(); } } " B10354,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; import java.io.File; import java.math.BigInteger; import java.util.ArrayList; import java.util.Scanner; import java.util.TreeMap; /** * * @author Ben */ public class Main { public static Scanner freader; public static int caseCount, _height, _width; /** * @param args the command line arguments */ public static void main(String[] args) { //solveFreeCell(); //solveKiller(); //sovleDWG(); solveRC(); } public static void solveRC() { try{ freader = new Scanner( new File(""C:/Users/Ben/Documents/NetBeansProjects/CodeJam/src/1a2011/C-small-attempt0.in"")); caseCount = freader.nextInt(); freader.nextLine(); int caseIdx; for(caseIdx = 0; caseIdx < caseCount; caseIdx++) { System.out.print(""Case #"" + (caseIdx+1) + "": ""); int A = freader.nextInt(); int B = freader.nextInt(); int result = RC(A,B); System.out.println(result); freader.nextLine(); } } catch(Exception e) { e.printStackTrace(); } } public static int RC(int A, int B) { int count = 0; ArrayList iL; ArrayList jL; for(int i = A; i <= B-1; i++) { for(int j = i + 1; j <= B; j++) { iL = convertNumToArray(i); jL = convertNumToArray(j); if(iL.size() != jL.size()) continue; if(recycled(iL, jL)) { count++; } } } return count; } public static boolean recycled(ArrayList iL, ArrayList jL) { boolean equal; int size = iL.size(); for(int i = 0; i < size; i++) { equal = true; //compare iL and jL for(int j = 0; j < size; j++) { if(iL.get(j).intValue() != jL.get(j).intValue()) { equal = false; break; } } if(equal) return true; //shift iL Integer temp = iL.get(size-1); for(int j = size-1; j > 0; j--) { iL.set(j, iL.get(j-1)); } iL.set(0, temp); } return false; } public static ArrayList convertNumToArray(int x) { ArrayList L = new ArrayList(); while(x > 0) { int r = x % 10; L.add(0, new Integer(r)); x = x / 10; } return L; } public static void sovleDWG() { try{ freader = new Scanner( new File(""C:/Users/Ben/Documents/NetBeansProjects/CodeJam/src/1a2011/B-small-attempt0.in"")); caseCount = freader.nextInt(); freader.nextLine(); int caseIdx; for(caseIdx = 0; caseIdx < caseCount; caseIdx++) { System.out.print(""Case #"" + (caseIdx+1) + "": ""); int n = freader.nextInt(); int s = freader.nextInt(); int p = freader.nextInt(); int T [] = new int [n]; for(int i = 0; i < n; i++){ T[i] = freader.nextInt(); } int count = DWG(T, n, s, p); System.out.println(count); freader.nextLine(); } } catch(Exception e) { e.printStackTrace(); } } public static int DWG(int [] T, int n, int s, int p) { int minSuprisingScore = p + 2*max(p-2,0); int minNonSuprisingScore = p + 2*max(p-1,0); int count = 0; int maybe = 0; for(int i = 0; i < n; i++) { int curr = T[i]; if(curr >= minNonSuprisingScore) { count++; } else if(curr < minNonSuprisingScore && curr >= minSuprisingScore) { maybe++; } } count += min(maybe, s); return count; } public static int min(int x, int y) { if (x < y){ return x; } return y; } public static int max(int x, int y) { if (x > y){ return x; } return y; } public static void solveKiller() { try{ freader = new Scanner( new File(""C:/Users/Ben/Documents/NetBeansProjects/CodeJam/src/1a2011/B-large-practice.in"")); caseCount = freader.nextInt(); freader.nextLine(); int caseIdx; for(caseIdx = 0; caseIdx < caseCount; caseIdx++) { System.out.print(""Case #"" + (caseIdx+1) + "": ""); int n = freader.nextInt(); int m = freader.nextInt(); ArrayList L = new ArrayList(n); for(int i = 0; i < n; i++){ L.add(freader.next()); } String kword = null; int score, worst; for(int j = 0; j < m; j++) { String todo = freader.next(); worst = 1; for(int i = 0; i < n; i++) { score = killer(L.get(i), todo, (ArrayList)L.clone()); if(score < worst) { worst = score; kword = L.get(i); } } if(j == m-1) System.out.print(kword); else System.out.print(kword + "" ""); freader.nextLine(); } System.out.println(); } } catch(Exception e) { e.printStackTrace(); } } public static int killer(String word, String todo, ArrayList dict) { int score = 0; int index [] = new int [26]; updateTodo(todo, dict, index); char guess [] = new char [word.length()]; for(int i = 0; i < word.length(); i++) { guess[i] = '*'; } dict = updateDict(dict, guess); int j = 0; while(j < 26) { while(index[j] == 0) { ++j; if(j >= 26) return score; } if(!updateGuess(guess, word, todo.charAt(j))){ score--; dict = filter(dict, todo.charAt(j)); } dict = updateDict(dict, guess); updateTodo(todo, dict, index); ++j; } return score; } public static ArrayList filter(ArrayList dict, char c) { ArrayList result = new ArrayList(); for(String str : dict) { if(str.indexOf(c) < 0) { result.add(str); } } return result; } public static ArrayList updateDict(ArrayList dict, char [] guess) { ArrayList result = new ArrayList(); for(String str : dict){ if(matches(str,guess)){ result.add(str); } } return result; } public static boolean matches(String str, char [] guess) { if(str.length() != guess.length) return false; for(int i = 0; i < guess.length; i++) { if(guess[i] == '*') { continue; } else if(guess[i] != str.charAt(i)) { return false; } } return true; } public static void updateTodo(String todo, ArrayList dict, int [] index) { for(int i = 0; i < index.length; i++) index[i] = 0; for(String str : dict) { for(int i = 0; i < str.length(); i++) { index[todo.indexOf(str.charAt(i))] = 1; } } } public static boolean updateGuess(char [] guess, String word, char c) { boolean found = false; for(int i = 0; i < word.length(); i++){ if(word.charAt(i) == c){ guess[i] = c; found = true; } } return found; } public static void solveFreeCell() { try{ freader = new Scanner( new File(""C:/Users/Ben/Documents/NetBeansProjects/CodeJam/src/1a2011/A-large-practice.in"")); caseCount = freader.nextInt(); freader.nextLine(); int caseIdx; for(caseIdx = 0; caseIdx < caseCount; caseIdx++) { System.out.print(""Case #"" + (caseIdx+1) + "": ""); BigInteger n = new BigInteger(freader.next()); long pd = freader.nextInt(); long pg = freader.nextInt(); if(pd > 0 && pg == 0) { System.out.println(""Broken""); continue; } if(pd == 0 && pg == 100) { System.out.println(""Broken""); continue; } if(pd == 0 && pg != 100) { System.out.println(""Possible""); continue; } if(pd < 100 && pg == 100) { System.out.println(""Broken""); continue; } if(n.compareTo(new BigInteger(""100"")) >= 0){ System.out.println(""Possible""); continue; } double den; long div; div = gcd(pd, 100); den = (double)100/div; if(den > n.intValue()) { System.out.println(""Broken""); continue; } System.out.println(""Possible""); freader.nextLine(); } } catch(Exception e) { e.printStackTrace(); } } public static long gcd(long x, long y) { while(x != y) { //System.out.println(x + "" "" + y); if(x > y) { x = x - y; } else{ y = y - x; } } return x; } public static void solveMagika() { try{ freader = new Scanner( new File(""C:/Users/Ben/Documents/NetBeansProjects/CodeJam/src/codejam/B-large-practice.in"")); caseCount = freader.nextInt(); freader.nextLine(); int caseIdx; for(caseIdx = 0; caseIdx < caseCount; caseIdx++) { TreeMap oppMap = new TreeMap(); TreeMap comMap = new TreeMap(); ArrayList list = new ArrayList(); int c = freader.nextInt(); for(int i = 0; i < c; i++) { String str = freader.next(); String rev = new StringBuffer(str.substring(0,2)).reverse().toString(); comMap.put(str.substring(0, 2), str.substring(2)); comMap.put(rev.substring(0, 2), str.substring(2)); } int d = freader.nextInt(); for(int i = 0; i < d; i++) { String str = freader.next(); String rev = new StringBuffer(str).reverse().toString(); oppMap.put(str, str); oppMap.put(rev, rev); } int n = freader.nextInt(); String todo = freader.next(); //System.out.println(todo); Magika(caseIdx+1, n, todo, comMap, oppMap, list); freader.nextLine(); } } catch(Exception e) { e.printStackTrace(); } } public static void Magika(int caseIdx, int n, String todo, TreeMap comMap, TreeMap oppMap, ArrayList list) { list.add(todo.substring(0,1)); for(int i = 1; i < n; i++) { list.add(todo.substring(i,i+1)); int size = list.size(); if(size >= 2){ String newElement = comMap.get( list.get(size-2).concat(list.get(size-1)) ); if(newElement != null) { list.remove(list.size()-1); list.remove(list.size()-1); list.add(newElement); } } check(oppMap, list); } System.out.print(""Case #"" + caseIdx + "": [""); if(list.isEmpty()) { System.out.println(""]""); } else { for(int i = 0; i < list.size()-1; i++) { System.out.print(list.get(i) + "", ""); } System.out.println(list.get(list.size()-1) + ""]""); } } public static void check(TreeMap oppMap, ArrayList list) { int size = list.size(); for(int j = 0; j < size-1; j++) { for(int k = 0; k < size; k++) { if(oppMap.containsKey(list.get(j).concat(list.get(k)))) { list.clear(); return; } } } } public static void solveBotTrust() { try{ freader = new Scanner( new File(""C:/Users/Ben/Documents/NetBeansProjects/CodeJam/src/codejam/A-large-practice.in"")); caseCount = freader.nextInt(); freader.nextLine(); int caseIdx; for(caseIdx = 0; caseIdx < caseCount; caseIdx++) { int n = freader.nextInt(); int buttons [] = new int [n]; String robots [] = new String [n]; int i; for(i = 0; i < n; i++) { robots[i] = freader.next(); buttons[i] = freader.nextInt(); } BotTrust(caseIdx+1, robots, buttons, n); freader.nextLine(); } } catch(Exception e) { e.printStackTrace(); } } public static void BotTrust(int caseIdx, String [] robots, int [] buttons, int n) { int turn, seconds; boolean buttonPressed; Robot B, O, active, passive; turn = 0; seconds = 0; B = new Robot(""B""); O = new Robot(""O""); for(int i = 0; i < n; i++) if(robots[i].equals(""B"")){ B.nextPosition = buttons[i]; break; } for(int i = 0; i < n; i++) if(robots[i].equals(""O"")){ O.nextPosition = buttons[i]; break; } // System.out.println(""orange pos : "" + O.nextPosition); // System.out.println(""blue pos : "" + B.nextPosition); while(turn < n) { seconds++; buttonPressed = false; if(robots[turn].equals(""O"")){ active = O; passive = B; } else{ active = B; passive = O; } int moveIncr; if(active.currPosition == active.nextPosition){ moveIncr = 0; }else if(active.currPosition < active.nextPosition){ moveIncr = 1; }else{ moveIncr = -1; } if(moveIncr == 0) { buttonPressed = true; } else{ active.currPosition = active.currPosition + moveIncr; } if(passive.currPosition == passive.nextPosition){ moveIncr = 0; }else if(passive.currPosition < passive.nextPosition){ moveIncr = 1; }else{ moveIncr = -1; } passive.currPosition = passive.currPosition + moveIncr; if(buttonPressed){ turn++; for(int i = turn; i < n; i++){ if(robots[i].equals(active.name)) { active.nextPosition = buttons[i]; break; } } } } System.out.println(""Case #"" + caseIdx + "": "" + seconds); } private static class Robot { int currPosition, nextPosition; String name; public Robot(String _name) { currPosition = 1; nextPosition = 0; name = _name; } } } " B12441,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Recycled; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * * @author Pablo Quiñones */ public class Recycled { public static int min; public static int max; public static int times = 0; public static Map> mapa = new HashMap>(); //public static public static void VerificarMap() { List repetidos = new ArrayList(); //List reps = new ArrayList(); for (int i = min; i <= max; i++) { for (String s : mapa.get((i + """"))) { System.out.println((i + """") + ""..num: "" + s); String copia = Integer.parseInt(s) + """"; if (Integer.parseInt(s) >= min && Integer.parseInt(s) <= max && !repetidos.contains(s) && copia.length() == (i + """").length() ) { System.out.println(""S.."" + s); times++; repetidos.add(i + """"); } } } } public static void Reciclados(String x, List numeros) { String copia = x; int tam = x.length(); String mod = """"; for(int i=0; i 2) { for (int i = 1; i < x.length(); i++) { //System.out.println(copia+""..pedazo1: ""+copia.substring(copia.length()-i)); //System.out.println(copia+""..pedazo2: ""+copia.replace(copia.substring(copia.length()-i), """")); String cadena = x.substring(tam - i) + x.substring(0,tam-(i)); //System.out.println(x+""..char_ "" + cadena); if(Integer.parseInt(cadena) % Integer.parseInt(mod) != 0 && !cadena.equals(x)) numeros.add(cadena); } } else { if (x.length() == 2) { String st = (x.charAt(1) + """") + (x.charAt(0) + """"); //System.out.println(""char_ "" + st); if (Integer.parseInt(st) % 11 != 0) { numeros.add(st); } } } } public static void CalcularNumerosReciclados() { times = 0; List numeros = new ArrayList(); for (int i = min; i <= max; i++) { //permuteNumber("""", i + """",i+"""",numeros); Reciclados(i + """", numeros); mapa.put(i + """", new ArrayList(numeros)); numeros.clear(); } } public static void main(String[] args) { try { String file1 = ""C:\\Users\\Pablo\\Desktop\\CodeJamFiles\\C-small-attempt0.in""; FileInputStream fstream = new FileInputStream(file1); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine = br.readLine(); File file = new File(""C:\\Users\\Pablo\\Desktop\\CodeJamFiles\\write2C.in""); Writer output = new BufferedWriter(new FileWriter(file)); int cases = Integer.parseInt(strLine); int total = cases + 1; boolean tiene; while (cases > 0) { String[] linea = br.readLine().split("" ""); min = Integer.parseInt(linea[0]); System.out.println(""min: "" + min); max = Integer.parseInt(linea[1]); CalcularNumerosReciclados(); VerificarMap(); System.out.println(""Times: "" + times); output.write(""Case #""+(total-cases)+"": ""+times+""\n""); cases--; mapa.clear(); times = 0; } output.close(); } catch (Exception e) { } } } " B12723,"package com.theblind.problem; import java.util.HashSet; import java.util.Scanner; import com.theblind.utility.FileUtility; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); String inputFileName = in.next(); String inputData = FileUtility.readFromFile(inputFileName); RecycledNumbers problem = new RecycledNumbers(); String content = problem.solve(inputData); FileUtility.writeToFile(""output.txt"", content); } private String solve(String inputData) { // TODO Auto-generated method stub Scanner in = new Scanner(inputData); StringBuilder sb = new StringBuilder(); int testCases = in.nextInt(); for (int i = 1; i <= testCases; ++i) { sb.append(""Case #"" + i + "": ""); int A = in.nextInt(); int B = in.nextInt(); sb.append(calculate(A, B)); sb.append(""\n""); } return sb.toString(); } private int calculate(int A, int B) { // TODO Auto-generated method stub int result = 0; String b = Integer.toString(B); for (int i = A; i < B; ++i) { String n = Integer.toString(i); HashSet numbers = new HashSet(); for (int k = 1; k < n.length(); ++k) { String m = n.substring(k) + n.substring(0, k); if (numbers.contains(m)) { continue; } else { numbers.add(m); } if (m.compareTo(n) > 0 && m.compareTo(b) <= 0) { ++result; } } } return result; } } " B11726,"package google.codejam.commons; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class Utils { public static String[] readFromFile(String fileName) throws IOException { System.out.println(""Reading file "" + fileName); String[] lines = null; FileInputStream fstream = new FileInputStream(fileName); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine = br.readLine(); lines = new String[Integer.valueOf(strLine)]; int i = 0; while ((strLine = br.readLine()) != null) { lines[i++] = strLine; } in.close(); return lines; } public static void writeToFile(String[] lines, String fileName) throws IOException { System.out.println(""Writing file "" + fileName); FileWriter outFile = new FileWriter(fileName); PrintWriter out = new PrintWriter(outFile); for (String line : lines) { out.println(line); } out.close(); } } " B10337," import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; /* * To change this template, choose Tools | Templates and open the template in * the editor. */ /** * * @author megaterik */ public class C { public static void main(String[] args) throws FileNotFoundException { new C().solve(); } int[] lastAchivement; int calculate(int x, int a, int b) { String s = Integer.toString(x); int res = 0; for (int i = 0; i < s.length(); i++) { int val = Integer.parseInt(s.substring(i).concat(s.substring(0, i))); if (val >= a && val <= b && !s.substring(i).concat(s.substring(0, i)).startsWith(""0"") && val > x && lastAchivement[val] != x) { res++; lastAchivement[val] = x; // out.println(x + "" and "" + val); } } return res; } PrintWriter out; void solve() throws FileNotFoundException { Scanner in = new Scanner(new FileReader(""src/input.txt"")); out = new PrintWriter(new FileOutputStream(""src/output.txt""));; int testCases = in.nextInt(); for (int t = 1; t <= testCases; t++) { int a = in.nextInt(); int b = in.nextInt(); lastAchivement = new int[b + 1]; int res = 0; for (int i = a; i <= b; i++) res += calculate(i, a, b); out.println(""Case #"" + t + "": "" + res); } in.close(); out.close(); } } " B11727,"/* * Problem C. Recycled Numbers * * Do you ever become frustrated with television because you keep seeing the * same things, recycled over and over again? Well I personally don't care about * television, but I do sometimes feel that way about numbers. * * Let's say a pair of distinct positive integers (n, m) is recycled if you can * obtain m by moving some digits from the back of n to the front without * changing their order. For example, (12345, 34512) is a recycled pair since * you can obtain 34512 by moving 345 from the end of 12345 to the front. Note * that n and m must have the same number of digits in order to be a recycled * pair. Neither n nor m can have leading zeros. * * Given integers A and B with the same number of digits and no leading zeros, * how many distinct recycled pairs (n, m) are there with A ≤ n < m ≤ B? * * Input * * The first line of the input gives the number of test cases, T. T test cases * follow. Each test case consists of a single line containing the integers A * and B. * * Output * * For each test case, output one line containing ""Case #x: y"", where x is the * case number (starting from 1), and y is the number of recycled pairs (n, m) * with A ≤ n < m ≤ B. * * Limits * * 1 ≤ T ≤ 50. * * A and B have the same number of digits. Small dataset 1 ≤ A ≤ B ≤ 1000. Large dataset 1 ≤ A ≤ B ≤ 2000000. Sample Input Output 4 1 9 10 40 100 500 1111 2222 Case #1: 0 Case #2: 3 Case #3: 156 Case #4: 287 */ package google.codejam.y2012.qualifications; import google.codejam.commons.Utils; import java.io.IOException; import java.util.StringTokenizer; /** * @author Marco Lackovic * @version 1.0, Apr 14, 2012 */ public class RecycledNumbers { private static final String INPUT_FILE_NAME = ""C-small-attempt0.in""; private static final String OUTPUT_FILE_NAME = ""C-small-attempt0.out""; /* * Per c è una ricerca pseudocubica in un range finito Per ogni m, per ogni * n entrambi compresi tra a e b con m= 0; i--) { chars[i + 1] = chars[i]; } chars[0] = last; return chars; } } " B10627,"package Controller; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class IO { private String fileName; private BufferedReader reader; public IO(String fileName) { this.fileName = fileName; createReader(); } public String readLine() { try { return reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } public int readInt() { try { return Integer.parseInt(reader.readLine()); } catch (IOException e) { e.printStackTrace(); } return -1; } private void createReader() { FileReader file = null; try { file = new FileReader(fileName); } catch (FileNotFoundException e) { e.printStackTrace(); } reader = new BufferedReader(file); } } " B12527,"package com.blah; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class MainProblem2 { static String english = ""our language is impossible to understandthere are twenty six factorial possibilitiesso it is okay if you want to just give up"", grese = ""ejp mysljylc kd kxveddknmc re jsicpdrysirbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcdde kr kd eoya kw aej tysr re ujdr lkgc jv""; static TreeMap gToE = new TreeMap(); static String shiftToFront(String digits,int by){ String toReturn = digits.substring(digits.length()-by).concat(digits.substring(0,digits.length()-by)); return toReturn; } public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new FileReader(args[0])); int numCases = Integer.parseInt(br.readLine()); int cases[][] = new int[numCases][2]; int response[] = new int[numCases]; StringTokenizer st; for (int i = 0; i < numCases; i++) { st = new StringTokenizer(br.readLine()); cases[i][0] = Integer.parseInt(st.nextToken()); cases[i][1] = Integer.parseInt(st.nextToken()); } String daCase; int shifted; TreeSet recycled; for (int i = 0; i < numCases; i++) { recycled = new TreeSet(); for (int caseNumber = cases[i][0]; caseNumber <= cases[i][1]; caseNumber++) { daCase = """"+caseNumber; //System.out.println(""Testing integer ""+daCase); for (int k = 1; k < daCase.length(); k++) { shifted = Integer.parseInt(shiftToFront(daCase, daCase.length()-k)); if(shifted<=cases[i][1] && shifted>caseNumber){ recycled.add(""""+caseNumber+""""+shifted); } } } System.out.println(""Case #""+(i+1)+"": ""+recycled.size()); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }" B10098,"package se.round1.util; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; public class JamUtil { public static BufferedReader getReader(String path) { File file = new File(path); FileInputStream fis = null; try { fis = new FileInputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); } BufferedReader bf = new BufferedReader(new InputStreamReader(fis)); return bf; } public static BufferedWriter getWriter(String path) { try { return new BufferedWriter(new FileWriter(path)); } catch (IOException e) { e.printStackTrace(); } return null; } } " B11749,"public class InvalidInputException extends Exception { /** * */ private static final long serialVersionUID = -3613289305328322102L; public InvalidInputException() { super(); // TODO Auto-generated constructor stub } public InvalidInputException(String arg0, Throwable arg1, boolean arg2, boolean arg3) { super(arg0, arg1, arg2, arg3); // TODO Auto-generated constructor stub } public InvalidInputException(String arg0, Throwable arg1) { super(arg0, arg1); // TODO Auto-generated constructor stub } public InvalidInputException(String arg0) { super(arg0); // TODO Auto-generated constructor stub } public InvalidInputException(Throwable arg0) { super(arg0); // TODO Auto-generated constructor stub } } " B11697," public class kickClass { public static void main(String[] args){ //testGraph.run(); //testCollection.run(); solutionRunner t1 = new solutionRunner(); } } " B12691,"import java.util.Scanner; import jp.ne.sakura.yuki2006.CodeJam.CodeJam; import jp.ne.sakura.yuki2006.CodeJam.ITestCase; /** * */ /** * @author yuki * */ public class RecycledNumbers implements ITestCase { /** * @param args */ public static void main(String[] args) { new CodeJam(new RecycledNumbers(), ""Cout.txt""); } /* * (非 Javadoc) * * @see jp.ne.sakura.yuki2006.CodeJam.ITestCase#testCase(java.util.Scanner) */ @Override public String testCase(Scanner stdIn) { int A = stdIn.nextInt(); int B = stdIn.nextInt(); int totalCount = 0; for (int i = A; i <= B; i++) { int length = String.valueOf(i).length(); for (int j = 0; j < length; j++) { int radix = (int) (Math.pow(10, j)); int top = i / radix; int other = i % radix; Integer rn = Integer.parseInt(String.valueOf(other) + String.valueOf(top)); if (rn<=B && i < rn) { System.err.println(i); System.err.println(rn); System.err.println(); totalCount++; } } } return totalCount + """"; } } " B10879,"package de.at.codejam.util; public class TaskStatus implements CodeJamConstants { public static final int STATUS_WAITING = 0; public static final int STATUS_RUNNING = 1; public static final int STATUS_DONE = 2; public static final int STATUS_ERROR = 3; private int currentTaskStatus = STATUS_WAITING; private int numberCases = UNDEFINED; private int numberCurrentCase = UNDEFINED; public int getCurrentTaskStatus() { return currentTaskStatus; } public void setCurrentTaskStatus(int currentTaskStatus) { this.currentTaskStatus = currentTaskStatus; } public int getNumberCases() { return numberCases; } public void setNumberCases(int numberCases) { this.numberCases = numberCases; } public int getNumberCurrentCase() { return numberCurrentCase; } public void setNumberCurrentCase(int numberCurrentCase) { this.numberCurrentCase = numberCurrentCase; } @Override public String toString() { return ""TaskStatus [currentTaskStatus="" + currentTaskStatus + "", numberCases="" + numberCases + "", numberCurrentCase="" + numberCurrentCase + ""]""; } } " B12355,"package com.wonyoung.codejam.qualificationround; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class RecycledNumbers { private Integer testCasesT; private RecycledNumbersData [] data; class RecycledNumbersData { Integer A; Integer B; int count; public RecycledNumbersData() { } @Override public String toString() { return A + "" "" + B; } } public RecycledNumbers(String filename) throws IOException { BufferedReader br = new BufferedReader(new FileReader(filename)); String line; testCasesT = Integer.valueOf(br.readLine()); data = new RecycledNumbersData[testCasesT]; int count = 0; while ( count < testCasesT) { line= br.readLine(); String [] words = line.split("" ""); data[count] = new RecycledNumbersData(); data[count].A = Integer.valueOf(words[0]); data[count].B = Integer.valueOf(words[1]); // System.out.println(data[count].toString()); count++; } br.close(); } public String result(int i) { return ""Case #""+ (i+1) +"": ""+ numberOfPairs(i); } private int numberOfPairs(int i) { int start = data[i].A; int end = data[i].B; int found = 0; for(int num = start; num<=end; num++) { String n = String.valueOf(num); int nInt = Integer.valueOf(n); StringBuilder m = new StringBuilder(n); int sizeOfN = n.length(); List mList = new ArrayList(); while(--sizeOfN > 0) { rotate(m); int mInt = Integer.valueOf(m.toString()); if (m.charAt(0) == '0') continue; if (mInt <= nInt) continue; if (mInt <= end) { if (mList.contains(mInt)) continue; mList.add(mInt); found++; // System.out.println(nInt+ "" "" + mInt); } } } return found; } private void rotate(StringBuilder n) { n.append(n.charAt(0)); n.deleteCharAt(0); } public void print(String filename) throws IOException { BufferedWriter bw = new BufferedWriter(new FileWriter(filename)); int count = 0; while (count < testCasesT) { bw.write(result(count)); bw.newLine(); count++; } bw.close(); } public static void main(String args[]) throws IOException { RecycledNumbers rn = new RecycledNumbers(""C-small-attempt0.in""); rn.print(""C-small-attempt0.out""); } } " B12491,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.Arrays; public class Csmall { private static String move(String n) { return n.substring(1) + n.charAt(0); } private static boolean recycled(int n, int m) { // Parte 1 char[] cn = (n + """").toCharArray(); char[] cm = (m + """").toCharArray(); Arrays.sort(cn); Arrays.sort(cm); if (!Arrays.equals(cn, cm)) return false; // Parte 2 String cpy = n + """"; while (!(cpy = move(cpy)).equals(n + """")) if (Integer.parseInt(cpy) == m) return true; return false; } public static void main(String[] args) { BufferedReader br = null; try { br = new BufferedReader(new FileReader(args[0])); int s = Integer.parseInt(br.readLine()); for (int i = 0; i != s; ++i) { String x = br.readLine(); String[] tokens = x.split("" ""); int A = Integer.parseInt(tokens[0]); int B = Integer.parseInt(tokens[1]); int count = 0; System.out.print(""Case #"" + (i+1) + "": ""); for (int n = A; n <= B; ++n) for (int m = n + 1; m <= B; ++m) if (recycled(n,m)) ++count; System.out.println(count); } } catch (IOException e) { System.out.println(""Error :(""); } finally { try { if (br != null) br.close(); } catch (IOException ex) { System.out.println(""Error :(""); } } } }" B10410,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package gcj2012.qual; import java.io.File; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; /** * * @author scbit */ public class P3 { /** * @param args the command line arguments */ public static void main(String[] args) throws Exception { new P3().run(); } PrintWriter pw; void run() throws Exception { File infile = new File(""C-small-attempt0.in""); String outfile = ""result""; pw = new PrintWriter(outfile); int N = 0; //BufferedReader br=new BufferedReader(new FileReader(infile)); //N=Integer.parseInt(br.readLine()); Scanner sc = new Scanner(infile); N = sc.nextInt(); for (int case_i = 1; case_i <= N; case_i++) { int result = 0; int A=sc.nextInt(); int B=sc.nextInt(); for(int n=A;n<=B;n++){ int d=calcnum(n); int m=n; for(int i=1;in && m <=B) result++; } } pw.printf(""Case #%d: %s\n"", case_i, result); System.out.printf(""Case #%d: %s\n"", case_i, result); } pw.close(); } int calcnum(int num){ int t=num; int c=0; while(t>0){ t=t/10; c++; } return c; } } " B10885,"package de.at.codejam.util; import java.awt.Color; import java.awt.Dimension; import java.io.File; public interface CodeJamConstants { // CODES public static final int UNDEFINED = -1; // SIZES public static final Dimension DEFAULT_WINDOW_SIZE = new Dimension(1024, 720); public static final Dimension DEFAULT_STATUSPANEL_SIZE = new Dimension( 1024, 320); // FILES AND DIRECTORIES public static final File DEFAULT_CODE_JAM_DIRECTORY = new File( Settings.get(""default.dir"")); // COLORS public static final Color COLOR_WAITING = Color.WHITE; public static final Color COLOR_RUNNING = new Color(0.5f, 0.5f, 0.3f); public static final Color COLOR_DONE = new Color(0.2f, 0.5f, 0.3f); public static final Color COLOR_ERROR = new Color(0.5f, 0.2f, 0.3f); } " B12803,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package google.code.jam.qualification.round; import java.io.*; import java.util.*; /** * * @author ahmad */ public class GoogleCodeJamQualificationRound { /** * @param args the command line arguments */ public static String[] input=new String[0]; public static String[] output=new String[0]; static String a=""""; static String b=""""; static int counter=0; public static String[] addarray(String[] a,String val) { String[] b=new String[a.length+1]; for(int i=0;i3) { counter--; } output=addarray(output,""Case #""+i+"": ""+counter+""""); } } public static void solve(int n1,int n2) { // System.out.println(n1+"" ""+n2); // int i=Integer.parseInt(a); for(int i=Integer.parseInt(a);i lines = Files.readLines(new File(path), Charsets.UTF_8); OutputSupplier outputSupplier = Files .newWriterSupplier(new File(path + "".out""), Charsets.UTF_8); StringBuilder results = new StringBuilder(); for (int i = 1; i < lines.size(); i++) { List tokens = Lists.newArrayList(Splitter.on(' ').split( lines.get(i))); long lowerBound = Long.parseLong(tokens.get(0)); long upperBound = Long.parseLong(tokens.get(1)); long count = 0; if (lowerBound >= 10) { for (long n = lowerBound; n < upperBound; n++) { for (long m = n + 1; m <= upperBound; m++) { if (RecycledNumbers.isValidPair(n, m)) count++; } } } String result = String.format(""Case #%d: %d\n"", i, count); System.out.print(result); results.append(result); } CharStreams.write(results, outputSupplier); } } " B11887,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; public class CRecycledNumbers { public static HashSet hs = new HashSet(); public static int m; public static void solve() throws NumberFormatException, IOException { File f = new File(""E:\\downloads\\C-small-attempt0.in""); BufferedReader reader = new BufferedReader(new FileReader(f)); File f2 = new File(""C:\\Users\\kimo\\Desktop\\out.txt""); BufferedWriter writer = new BufferedWriter(new FileWriter(f2)); int x = Integer.parseInt(reader.readLine()); String st[] = null; for (int k = 0; k < x; k++) { st = reader.readLine().split("" ""); int n = Integer.parseInt(st[0]); m = Integer.parseInt(st[1]); int count = 0; for (int i = n; i < m + 1; i++) { if (i < m) { count += numOfways(i + """"); } } writer.write(""Case #"" + (k + 1) + "": "" + count); writer.newLine(); } writer.close(); reader.close(); } // public static boolean check(String n, String m) { // boolean found = false; // int i = 0; // for (; i < n.length() && !found; i++) { // if (n.charAt(i) == m.charAt(0)) { // found = true; // } // } // // int j = 0; // i = i - 1; // while (j < m.length() && found) { // // if (n.charAt(i) != m.charAt(j)) // found = false; // j++; // i = (i + 1) % m.length(); // } // return found; // } public static int numOfways(String n) { String tail = """"; String head = """"; String ss = """"; int counter = 0; hs.clear(); for (int i = 1; i < n.length(); i++) { tail = n.substring(i, n.length()); head = n.substring(0, i); ss = tail + head; int ssi = Integer.parseInt(ss); if ((ssi + """").length() == n.length()&&ssi>Integer.parseInt(n)) { if ( ssi <= m&&!hs.contains(ssi)) { hs.add(ssi); counter++; } } } return counter; } public static void main(String[] args) throws NumberFormatException, IOException { solve(); //m=500; //System.out.println(numOfways(""301"")); } } " B11535,"package com.google.jam.eaque.stub; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import com.google.jam.eaque.qualif.c.StubImpl; public class Main { /** * @param args */ public static void main(String[] args) { if (args.length != 2) { System.out.println(""args length : "" + args.length); System.exit(0); } Stub body = new StubImpl(); body.setOutputFileName(args[1]); try { InputFileManager ifm = new InputFileManager(args[0]); BufferedWriter bw = new BufferedWriter(new FileWriter( body.getOutputFileName())); long nbTestCases = ifm.readLong(); for (long i = 0; i < nbTestCases; i++) { bw.write(""Case #"" + (i + 1) + "":"" + body.runTestCase(ifm)); bw.newLine(); } ifm.close(); bw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B13234," import java.io.*; import java.util.*; public class QualC{ private BufferedReader in; private StringTokenizer st; private PrintWriter out; void solve() throws IOException{ int kases = nextInt(); int kase = 0; while(kases-->0){ kase++; out.print(""Case #""+kase+"": ""); int a = nextInt(); int b = nextInt(); int ans = 0; for (int n = a; n <= b; n++) { for (int m = n+1; m <= b; m++) { String x = n+""""; String y = m+""""; if(x.length() != y.length()) continue; String z = x+x; if(z.contains(y)) ans++; } } out.println(ans); } } QualC() throws IOException { in = new BufferedReader(new FileReader(""input.txt"")); out = new PrintWriter(new FileWriter(""output.txt"")); eat(""""); solve(); out.close(); } private void eat(String str) { st = new StringTokenizer(str); } String next() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } eat(line); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } public static void main(String[] args) throws IOException { new QualC(); } int gcd(int a,int b){ if(b>a) return gcd(b,a); if(b==0) return a; return gcd(b,a%b); } } " B11095,"import java.util.*; public class CodeJamC { /** * @param args */ public static void main(String[] args) { int A,B,tc; Scanner sc= new Scanner(System.in); tc=sc.nextInt(); for(int TC=1; TC<=tc; TC++){ A=sc.nextInt(); B=sc.nextInt(); int suma=0; Integer Ai= new Integer(A); String sA=Ai.toString(); String rigth; String aux; Integer n; for(int i=A; i<=B; i++){ Integer si= new Integer(i); String Ssi=si.toString(); for(int j=1; j=A && si findAddingCombination(int total, List listOfNumbers) { ArrayList solution = new ArrayList(); for (int i = 0; i < listOfNumbers.size(); i++){ for (int j = 0; j < listOfNumbers.size(); j++){ if( (i != j) && (listOfNumbers.get(i) + listOfNumbers.get(j) == total) ){ solution.add(listOfNumbers.get(i)); solution.add(listOfNumbers.get(j)); return solution; } } } return null; } public static List findAddingCombinationIndices(int total, List listOfNumbers) { ArrayList solution = new ArrayList(); for (int i = 0; i < listOfNumbers.size(); i++){ for (int j = 0; j < listOfNumbers.size(); j++){ if( (i != j) && (listOfNumbers.get(i) + listOfNumbers.get(j) == total) ){ solution.add(i); solution.add(j); return solution; } } } return null; } public static List findAddingCombinationIndicesBase1(int total, List listOfNumbers) { ArrayList solution = new ArrayList(); for (int i = 0; i < listOfNumbers.size(); i++){ for (int j = 0; j < listOfNumbers.size(); j++){ if( (i != j) && (listOfNumbers.get(i) + listOfNumbers.get(j) == total) ){ solution.add(i+1); solution.add(j+1); return solution; } } } return null; } public static List possibleTriplets(int score) { List listOfTriplets = new ArrayList(); for(Triplet t : allPossibleTriplets){ if(t.sum() == score){ listOfTriplets.add(t); } } return listOfTriplets; } private final static List allPossibleTriplets = allPossibleTriplets(); private static List allPossibleTriplets() { HashSet set = new HashSet(); // int cont = 0; for (int i = 0; i <= 10; i++) { for (int j = 0; j <= 10; j++) { if(Math.abs(i-j) <= 2){ for (int k = 0; k <= 10; k++) { if((Math.abs(i-k) <= 2) && (Math.abs(j-k) <= 2)){ // cont++; // System.out.println(""("" + i + "", "" + j + "", "" + k + "")\t\tcont = "" + cont);7 set.add(new Triplet(i, j, k)); } } } } } return new ArrayList(set); } } " B13118,"package phase1.problemC; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { RecycledNumbers s = new RecycledNumbers(); try { s.doIt(); } catch (Exception e) { e.printStackTrace(); } } private void doIt() throws Exception { Scanner s = new Scanner(new File(""C:\\Andre\\GCJInputs\\fase1\\p3\\C-small-attempt0.in"")); int T = Integer.valueOf(s.nextLine()); int cont=1; Writer out = new OutputStreamWriter(new FileOutputStream(""C:\\Andre\\GCJInputs\\fase1\\p3\\C-small-attempt0.out"")); while (cont<=T) { out.write(""Case #""+cont+"": ""); String[] values = s.nextLine().split("" ""); out.write(String.valueOf(calculate(values[0], values[1]))); out.write(""\n""); cont++; } out.flush(); out.close(); } private int calculate(String A, String B) { int r = 0; String c = A; if (c.length()==1) { return r; } int cont = Integer.parseInt(c)-1; int fim = Integer.parseInt(B); while (cont++ linhas = new HashSet(); while (qd++ Integer.parseInt(B)) continue; if (Integer.parseInt(n) < Integer.parseInt(m)) { linhas.add(linha); } linha=""""; } resp=linhas.size(); return resp; } private boolean numerosIguais(String s) { int cont=10; cont = cont + s.indexOf('0') + s.indexOf('1') + s.indexOf('2') + s.indexOf('3') + s.indexOf('4') + s.indexOf('5') + s.indexOf('6') + s.indexOf('7') + s.indexOf('8') + s.indexOf('9'); if (cont>2) return false; return true; } } " B11456,"import java.util.Scanner; public class CodeJamQC { static Scanner keyboard=new Scanner(System.in); public static void main(String[] args) { int num=keyboard.nextInt(); for(int x=0; xy&&numero<=b&&!usados[numero-y]){ output++; usados[numero-y]=true; } } } System.out.println(""Case #""+(x+1)+"": ""+output); } } }" B10135,"import java.io.*; import java.util.*; import java.math.*; public class Main { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tokenizer=null; public static void main(String[] args) throws IOException { new Main().execute(); } void debug(Object...os) { System.out.println(Arrays.deepToString(os)); } int ni() throws IOException { return Integer.parseInt(ns()); } long nl() throws IOException { return Long.parseLong(ns()); } double nd() throws IOException { return Double.parseDouble(ns()); } String ns() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(br.readLine()); return tokenizer.nextToken(); } String nline() throws IOException { tokenizer=null; return br.readLine(); } //Main Code starts Here int totalCases, testNum; int A,B; void execute() throws IOException { totalCases = ni(); for(testNum = 1; testNum <= totalCases; testNum++) { if(!input()) break; solve(); } } void solve() throws IOException { int count = 0; for(int i = A;i<=B;i++) { HashSet hs = new HashSet(); String s = String.valueOf(i); int k = s.length(); for(int j = 0;ji && no<=B) hs.add(no); } count+= hs.size(); } System.out.printf(""Case #%d: %d\n"",testNum,count); System.err.printf(""Case #%d: %d\n"",testNum,count); } boolean input() throws IOException { A = ni(); B = ni(); return true; } } " B11094,"import java.io.*; import java.util.*; public class C { BufferedReader ins; PrintStream outs; static String INPUT = ""C-small-attempt0.in""; static String OUTPUT; static { OUTPUT = ""C.out""; } Map> map = new HashMap>(); public C(BufferedReader ins, PrintStream outs) { this.ins = ins; this.outs = outs; } public void preprocess() { for(int j = 1; j<=2000000; j++) { String k = new Integer(j).toString(); Set set = new HashSet(); int sz = k.length(); for(int i = 1; i set = new HashSet(); for(int i = 0; i k && newk <=b) { if(!set.contains(x+""-""+sb)) { set.add(x+""-""+sb); } ret++; } } return set.size(); } public int permuteL(int k, int b) { String m = new Integer(k).toString(); int count = 0; for(String r : map.get(m)) { int newk = Integer.parseInt(r); if(newk>k && newk<=b) count++; } return count; } public int go(int a, int b) { int count = 0; for(int k = a; k < b; k++) { count += permuteK(k, b); } return count; } public void process() throws Exception { // preprocess(); // System.out.println(""Hi""); //Read input int t = Integer.parseInt(ins.readLine()); for(int T=1; T<=t;T++) { String x = ins.readLine().trim().replaceAll("" +"", "" ""); String[] tokens = x.split("" ""); int a = Integer.parseInt(tokens[0]); int b = Integer.parseInt(tokens[1]); outs.println(""Case #"" + T + "": "" + go(a,b)); } } public static void main(String args[]) throws Exception { //Input InputStreamReader fis = new FileReader(INPUT); BufferedReader bis = new BufferedReader(fis); //Output PrintStream ps = OUTPUT!=null ? new PrintStream(OUTPUT) : System.out; C c = new C(bis, ps); c.process(); return; } } " B12903,"package com.brianghig.gcj.recyclednumbers; public class Pair { private long n; private long m; public Pair() { //default, empty constructor } public Pair(long n, long m) { // A <= n < m <= B assert( m > n ); this.n = n; this.m = m; } public long getN() { return n; } public void setN(long n) { this.n = n; } public long getM() { return m; } public void setM(long m) { this.m = m; } } " B10529,"package recyclednumbers; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashSet; /** * @author Emmanuel JS Hoarau - Google Code Jam 2012 */ public class RecycledNumbers { String executeLine(final String line) { String words[] = line.split("" ""); String sa = words[0], sb = words[1]; int a = Integer.parseInt(sa); int b = Integer.parseInt(sb); int result = 0; for (int n = a; n <= b; ++n) { HashSet matches = new HashSet(); String s = Integer.toString(n); String ss = s + s.substring(0, s.length()-1); int l = s.length(); for (int j = 1; j < l; ++j) { if (ss.charAt(j) != '0') { String r = ss.substring(j, j+l); if ((r.compareTo(s) > 0) && (r.compareTo(sa) >= 0) && (r.compareTo(sb) <= 0) && !matches.contains(r)) { matches.add(r); ++result; } } } } return Integer.toString(result); } void execute() { try { InputStreamReader stream = new InputStreamReader(System.in); BufferedReader reader = new BufferedReader(stream); String line = reader.readLine(); int lines = Integer.parseInt(line); for (int i = 1; i <= lines; ++i) { line = reader.readLine(); StringBuilder out = new StringBuilder(); out.append(""Case #""); out.append(i); out.append("": ""); out.append(executeLine(line)); System.out.println(out.toString()); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { new RecycledNumbers().execute(); } } " B12787,"import java.io.FileNotFoundException; public class main { /** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { // TODO Auto-generated method stub Parser parser = new Parser(args[0]); Recycled recycled = new Recycled(parser.parse(1)); recycled.solve(); } } " B10122,"import com.sun.xml.internal.messaging.saaj.packaging.mime.util.LineInputStream; import sun.tools.tree.ReturnStatement; import javax.swing.*; import java.io.*; import java.util.ArrayList; /** * Date: 14/4/12 * Time: 9:19 AM */ public class GoogleFileStream { public static ArrayList getInput() throws IOException { JFileChooser fc = new JFileChooser(); fc.showOpenDialog(null); File f = fc.getSelectedFile(); ArrayList ret = new ArrayList(); LineInputStream lis = new LineInputStream(new FileInputStream(f)); String line; while( (line = lis.readLine()) != null ) { ret.add(line); } // number of lines: ret.remove(0); return ret; } public static void setOutput(ArrayList ret) throws IOException { JFileChooser fc = new JFileChooser(); fc.showSaveDialog(null); File f = fc.getSelectedFile(); StringBuilder sb = new StringBuilder(); FileWriter fw = new FileWriter(f); for( int i = 0; i < ret.size(); i++ ) { sb.delete(0, sb.length()); sb.append(String.format( ""Case #%d: "", i + 1)); sb.append( ret.get(i) ); sb.append( ""\n"" ); String o = sb.toString(); fw.write( o ); System.out.print(o); } fw.close(); } } " B10655," import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; import java.util.TreeSet; /* * To change this template, choose Tools | Templates and open the template in * the editor. */ /** * * @author Charles */ public class RecycledNumbers { static final String FILE_NAME = ""C""; /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException { ArrayList values = readFile(FILE_NAME + "".in""); int count = 1; PrintWriter outFile = new PrintWriter(new File(FILE_NAME + "".out"")); for (String line : values) { String output = processAlgorithm(line, count++); System.out.println(output); outFile.println(output); } outFile.close(); } /** * Reads the CodeJam files and returns the input as a List of String. * * @param fileName The name of the file to be read * @return the list containing the contents of the file. */ public static ArrayList readFile(String fileName) { ArrayList results = new ArrayList(); try { Scanner inFile = new Scanner(new File(fileName)); int numberOfLines = Integer.parseInt(inFile.nextLine()); while (inFile.hasNextLine()) { results.add(inFile.nextLine()); } if (numberOfLines != results.size()) { System.err.println(""File size does not match...""); System.exit(0); } } catch (FileNotFoundException ex) { System.err.println(""File not found...""); System.exit(0); } return results; } private static String processAlgorithm(String line, int caseNumber) { StringBuilder result = new StringBuilder(""Case #"" + caseNumber + "": ""); Scanner scan = new Scanner(line); int low = scan.nextInt(); int high = scan.nextInt(); int count = 0; for (int current = low; current < high; current++) { String temp = String.valueOf(current); TreeSet temps = new TreeSet(); for (int index = 0; index < temp.length(); index++) { temps.add(temp.substring(temp.length() - index) + temp.substring(0, temp.length() - index)); } for (int test = current + 1; test <= high; test++) { String testString = String.valueOf(test); if(temps.contains(testString)) { count++; } } } result.append(count); return result.toString(); } } " B10972,"import java.util.ArrayList; import java.util.HashMap; public class ProblemC { static ArrayList allTheNumbers = new ArrayList(); static HashMap binomCoeff = new HashMap(); public static int solveC(int A, int B) { allTheNumbers = new ArrayList(); int count = 0; String seeds[] = new String[B-A+1]; // System.out.println(""SIZE OF ARRAY:"" + seeds.length); for(int i = A, n = 0; n < seeds.length; i++, n++) { seeds[n] = Integer.toString(i); //System.out.println(seeds[n]); } for(int i = 0; i < seeds.length; i++) { count += binom(CircularStringShift(seeds[i], A, B),2); } return count; } public static int CircularStringShift(String s, int lowerLimit, int upperLimit) { String tmp = s; char placeHolder = ' '; int count = 0; int tmp2; for(int i = 0; i < s.length(); i++) { placeHolder = tmp.charAt(0); tmp = tmp.substring(1, tmp.length()) + placeHolder ; tmp2 = Integer.parseInt(tmp); if(!allTheNumbers.contains(tmp2) && tmp2 >= lowerLimit && tmp2 <= upperLimit && tmp != s) { count++; allTheNumbers.add(tmp2); } } return count; } static long binom(int n, int k) { if(binomCoeff.containsKey(n)) { return binomCoeff.get(n); } long coeff = 1; for (int i = n - k + 1; i <= n; i++) { coeff *= i; } for (int i = 1; i <= k; i++) { coeff /= i; } binomCoeff.put((long)n, coeff); return coeff; } } " B12976,"import java.io.* ; import java.text.DecimalFormat; import java.util.*; import static java.lang.Math.* ; import static java.util.Arrays.* ; public class C { public static void main(String[] args) throws FileNotFoundException { in = new Scanner(new InputStreamReader(new FileInputStream(""c_in.txt""))); out = new PrintStream(new BufferedOutputStream(new FileOutputStream(""c_out.txt""))); int n = in.nextInt() ; in.nextLine() ; int t = 1 ; while( n-- > 0) new C().solveProblem(t++); out.close(); } static Scanner in = new Scanner(new InputStreamReader(System.in)); static PrintStream out = new PrintStream(new BufferedOutputStream(System.out)); //static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); public void solveProblem(int nr) { out.print(""Case #"" + nr + "": "" ) ; int A = in.nextInt() ; int B = in.nextInt() ; int l = ( A + """").length() ; int som = 0 ; for( int i = A ; i <= B ; i++ ){ HashSet set = new HashSet() ; for( int j = 1 ; j < l ; j++ ){ int n = i ; n /= (int) pow(10,j) ; n += (i % pow(10,j) )*(int) pow(10,l-j) ; //System.out.println(n + "" "" + i); if( n > i && n <= B ) set.add(n) ; } som += set.size(); } out.println(som) ; System.err.println(""Case #"" + nr + "" solved"") ; } }" B10407,"import java.util.*; public class RecycledNumbers { public static void main(String []args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for(int i = 1; i <= T; i++) { System.out.print(""Case #"" + i + "": ""); int A = in.nextInt(); int B = in.nextInt(); int count = 0; int n = 0; int t = A; while(t > 0) { t /= 10; n++; } boolean []b = new boolean[B + 1]; for(int j = A; j <= B; j++) { int cycle = 0; for(int k = 0; k < n; k++) { t = rotate(j, n, k); if(A > t || t > B) continue; if(!b[t]) { b[t] = true; cycle++; } } count += cycle * (cycle - 1) / 2; } System.out.print(count); if(i < T) System.out.println(); } } public static int rotate(int n, int size, int r) { int p = 1; for(int i = 0; i < r; i++) p *= 10; int cp = 1; for(int i = 0; i < size - r; i++) cp *= 10; return n % p * cp + n / p; } }" B10883,"package de.at.codejam.util; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class AbstractOutputFileWriter { private File outputFile; public AbstractOutputFileWriter(File outputFile) { this.outputFile = outputFile; } public void setOutputFile(File outputFile) { this.outputFile = outputFile; } public void appendResult(String result) { FileWriter fileWriter; BufferedWriter bufferedWriter; try { fileWriter = new FileWriter(outputFile, true); bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.append(result); bufferedWriter.append(""\n""); bufferedWriter.close(); fileWriter.close(); } catch (IOException e) { // FIXME Error logging } finally { } } } " B11660,"/* * 3rd task of this years google Code Jam, lets see what I can do */ //Import of java classes and packages import java.util.Locale; import java.util.Scanner; //Body class public class RecycledNumbers { //main class start public static void main(String[] args){ Scanner sc = new Scanner(System.in); sc.useLocale(Locale.US); int recycledCount = 0; int testCount = sc.nextInt(); //This cycle will run for every test (why so obvious?) for(int i = 0; i < testCount; i++){ int first = sc.nextInt(); int second = sc.nextInt(); recycledCount = 0; for(int j = first; j <= second; j++){ if(j < 10) continue; String numberString = new String("""" + j); for(int k = 1; k < numberString.length(); k++){ String newNumber = new String(numberString.substring(k, numberString.length()) + numberString.substring(0,k)); //System.out.println(newNumber); int number = Integer.parseInt(newNumber); if((number > j) && (number <= second)) recycledCount++; } } System.out.println(""Case #"" + (i+1) + "": "" + recycledCount); } } //main class end } " B12742,"import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; import java.util.TreeSet; public class CJ_2012_Q_C { public static void main(String[] args) throws IOException { Scanner in = new Scanner(new File(""cj_files/in"")); FileWriter w = new FileWriter(new File(""cj_files/out"")); int cases = in.nextInt(); int a, b, numDigits, count, newNum; String oStr, nStr; TreeSet numbers = new TreeSet(); for(int i = 1; i <= cases; i++) { a = in.nextInt(); b = in.nextInt(); numDigits = (a + """").length(); count = 0; for(int j = a; j < b; j++) { oStr = j + """"; numbers.clear(); for(int k = 1; k < numDigits; k++) { nStr = oStr.substring(numDigits - k) + oStr.substring(0, numDigits - k); newNum = Integer.parseInt(nStr); if(newNum > j && newNum <= b) { numbers.add(newNum); } } count += numbers.size(); } w.write(String.format(""Case #%d: %d\n"", i, count)); } w.close(); } } " B12266,"import java.io.*; public class RecycledNumbers { public RecycledNumbers() {} public Integer count(String num, int A, int B) { int count = 0; Integer numS = new Integer(num); for (int i = 1; i < num.length(); i++) { Integer newNum = new Integer(num.substring(i) + num.substring(0, i)); if (newNum <= B && newNum > A && newNum > numS) { count++; //System.out.println(""("" + numS + "", "" + newNum + "")""); } } return count; } public static void main(String[] args) { RecycledNumbers rn = new RecycledNumbers(); try { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line; Integer T; int cn = 0; while ((line = in.readLine()) != null) { if (cn == 0) { T = new Integer(line); cn++; } else { int count = 0; String[] AB = line.split("" ""); int A = new Integer(AB[0]); int B = new Integer(AB[1]); for (int n = A; n < B; n++) { count += rn.count(Integer.toString(n), A, B); } System.out.println(""Case #"" + cn + "": "" + count); cn++; } } } catch (Exception e) {} } } " B12826,"import java.io.*; import java.util.*; public class Cre { public static void main(String args[])throws FileNotFoundException,IOException { RandomAccessFile in=new RandomAccessFile(""C-small-attempt0.in"",""r""); FileOutputStream out= new FileOutputStream(""out.txt""); int o=Integer.parseInt(in.readLine()); int j=0; String str[]=new String[o+1]; int res[]=new int[o]; while((str[j]=in.readLine())!=null) { String []nos=str[j].split("" ""); int a=Integer.parseInt(nos[0]); int b=Integer.parseInt(nos[1]); int []t=new int[b-a+1]; int m; for(int i=a,k=0;i<=b;i++,k++)t[k]=i; for(int i=0;i0;i--) { ch[i]=ch[i-1]; } ch[0]=temp; String st=new String(ch); return Integer.parseInt(st); } }" B12316,"package cj.qulification; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; public class P3 { public static boolean isRecycled(int n, int m){ String first=Integer.toString(n); for (int i=1;i mapp = new HashMap(); public static void main(String[] args) throws Exception { PrintWriter writer = new PrintWriter(new FileWriter(""output.txt"")); BufferedReader input = new BufferedReader(new FileReader(""C-small-attempt0.in"")); int size=Integer.parseInt(input.readLine()); for(int i=0; i Sett = new HashSet(); String tokens[] = input.readLine().split("" ""); int Llimit = Integer.parseInt(tokens[0]); int Hlimit = Integer.parseInt(tokens[1]); for(int j=Llimit; jj && Integer.parseInt(temp)<=Hlimit) { Sett.add(str1+temp); } } } writer.println(""Case #""+(i+1)+"": ""+Sett.size()); } writer.close(); input.close(); } }" B11066,"package fixjava; import java.util.concurrent.Callable; import java.util.concurrent.Future; import fixjava.ParallelWorkQueue.CallableFactory; public class ArrayStats { public final double[][] data; public final int n, k; private double[][] centered; private double[] mean; private double[][] cov; private double[] stddev = null; private double[][] corr = null; /** Calculate covariance matrix */ public ArrayStats(double[][] data) { if (data == null || data.length < 2 || data[0].length < 2) throw new IllegalArgumentException(""Invalid data""); this.data = data; this.n = data.length; this.k = data[0].length; } /** Compute mean for each dimension */ public double[] mean() { if (mean == null) { mean = new double[k]; for (int dim = 0; dim < k; dim++) { double tot = 0; for (int pt = 0; pt < n; pt++) tot += data[pt][dim]; mean[dim] = tot / n; } } return mean; } /** Compute stddev for each dimension */ public double[] stddev() { if (stddev == null) { // Make sure means are computed mean(); stddev = new double[k]; for (int dim = 0; dim < k; dim++) { for (int pt = 0; pt < n; pt++) { double diff = data[pt][dim] - mean[dim]; stddev[dim] += diff * diff; } stddev[dim] = Math.sqrt(stddev[dim] / n); } } return stddev; } /** Re-center data by subtracting mean from each dimension */ public double[][] centered() { if (centered == null) { // Make sure means are computed mean(); centered = new double[n][k]; for (int pt = 0; pt < n; pt++) for (int dim = 0; dim < k; dim++) centered[pt][dim] = data[pt][dim] - mean[dim]; } return centered; } /** Compute covariance matrix */ public double[][] cov() { if (cov == null) { // Make sure centered version of data is computed centered(); // Work on transposed array for cache coherence final double[][] centeredT = ArrayUtils.transpose(centered); cov = new double[k][k]; try { //final DecimalFormat formatPercent1dp = new DecimalFormat(""0.0%""); for (Future res : new ParallelWorkQueue(/* numThreads = */25, ParallelWorkQueue.makeIntRangeIterable(k), new CallableFactory() { //IntegerMutable counter = new IntegerMutable(); @Override public Callable newInstance(final Integer ii) { return new Callable() { int dim1 = ii.intValue(); double[][] centeredTLocal = centeredT; double[][] covLocal = cov; @Override public Void call() { for (int dim2 = dim1; dim2 < k; dim2++) { double numer = 0.0; for (int pt = 0; pt < n; pt++) numer += centeredTLocal[dim1][pt] * centeredTLocal[dim2][pt]; int denom = n - 1; covLocal[dim1][dim2] = covLocal[dim2][dim1] = denom == 0 ? 0 : numer / denom; } // int count = counter.increment(); // if (count % 10 == 0) // System.out.println(formatPercent1dp.format((count / (float) (k - 1)))); return null; } }; } })) // Barricade res.get(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } return cov; } /** Compute correlation matrix */ public double[][] corr() { if (corr == null) { // Make sure per-dim stddevs and covariance matrix are computed stddev(); cov(); corr = new double[k][k]; for (int dim1 = 0; dim1 < k; dim1++) { for (int dim2 = dim1; dim2 < k; dim2++) { double prod = stddev[dim1] * stddev[dim2]; corr[dim1][dim2] = corr[dim2][dim1] = prod == 0.0 ? 0.0 : cov[dim1][dim2] / prod; } } } return corr; } } " B10849,"package knucle.y2012.C; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.HashSet; import java.util.Set; public class C { public static void main(String[] args) throws Exception { FileReader fr = new FileReader(""C-small.in""); BufferedReader br = new BufferedReader(fr); BufferedWriter bw = new BufferedWriter(new FileWriter(""output.txt"")); int currentCase = 1; int caseNum = Integer.parseInt(br.readLine()); for(currentCase=1; currentCase<=caseNum; currentCase++){ String line = br.readLine(); bw.write(""Case #""); bw.write(Integer.toString(currentCase)); bw.write("": ""); String[] inputs = line.split("" ""); String minStr = inputs[0]; int min = Integer.parseInt(minStr); int max = Integer.parseInt(inputs[1]); int count = 0; for(int i=min+1; i<=max; i++){ String target = Integer.toString(i); int len = target.length(); Set possibles = new HashSet(); for(int splitPos=1; splitPos st = new HashSet(); for (int i=1;i s.charAt(i)) continue; String ssub = s.substring(i) + s.substring(0, i); int pn = Integer.parseInt(ssub); if (pn > n && pn <= B) { t++; if (!st.add(s+ssub)) { t--; } //System.out.println(n + "", "" + ssub + "" ++""); } else { //System.out.println(n + "", "" + ssub); } } return t; } } " B11924,"package net.jbirch.gcj12qual; import java.io.FileNotFoundException; import java.util.Scanner; import net.jbirch.gcj12qual.util.FileLoader; /** * * @author Birch */ public class C implements Runnable { protected FileLoader inFile; protected Scanner in; /** * @param args the command line arguments */ public static void main(String[] args) { (new C()).run(); } public C() { inFile = new FileLoader(""src\\main\\resources\\C.txt""); } public void run() { try { in = inFile.getScanner(); solve(); } catch (FileNotFoundException fnfe) { System.out.println(""File not found. Exiting.""); System.out.println(fnfe); } } //Commence overall magic protected void solve() { int cases = Integer.valueOf(in.nextLine()); for (int i = 0; i < cases; i++) { System.out.print(""Case #"" + (i + 1) + "": ""); solve(in.nextInt(), in.nextInt()); } } protected void solve(int low, int high) { int digits = (int) Math.log10(low); int count=0; for (int i = low; i <= high; i++) { int[] rotatedThisRound = new int[digits]; // for cases like 1212 - 2121 being counted twice. Sly. for (int j = 1; j <= digits; j++) { int rotated = this.rotateInt(i, j); if (rotated < low || rotated > high || i >= rotated || this.contains(rotatedThisRound, rotated)) continue; rotatedThisRound[j - 1] = rotated; count++; } } System.out.println(count); } protected int rotateInt(int i, int turns) { String theGuy = String.valueOf(i); String guyThe = theGuy.substring(turns) + theGuy.substring(0, turns); if (guyThe.startsWith(""0"")) return 0; // Force a fail case - rotated number has leading 0 and thus is of different length return Integer.valueOf(guyThe); } protected boolean contains(int[] a, int i) { for (int j : a) { if (j == i) return true; } return false; } } " B11542,"import java.util.HashMap; import java.util.Scanner; import java.util.concurrent.ArrayBlockingQueue; public class GCJ_3 { public static HashMap pairs = new HashMap(); //private static final String EMPTY_STR = """"; public static int combinations(long n1, Long B) { int combinations = 0; StringBuffer Nstr = new StringBuffer(String.valueOf(n1)); int nInt = Integer.valueOf(Nstr.toString()); ArrayBlockingQueue queue = new ArrayBlockingQueue(15); for (int i = 0; i < Nstr.length(); i++) { queue.add(Nstr.charAt(i)); } for (int i = 0; i < Nstr.length(); i++) { queue.add(queue.poll()); Object[] numbers = (Object[]) queue.toArray(); StringBuffer comb = new StringBuffer(); for (int j = 0; j < numbers.length; j++) comb.append(numbers[j]); if (comb.charAt(0) == '0') continue; int p1 = Integer.valueOf(comb.toString()); if ((p1 > nInt) && (p1 <= B)) { combinations++; pairs.put(Nstr.toString() + comb.toString(), new Object()); } } /*StringBuffer Nstr = new StringBuffer(String.valueOf(n1)); for (int i = 1; i < Nstr.length(); i++) { StringBuffer sb = new StringBuffer(Nstr.subSequence(i, Nstr.length())); sb.append(Nstr.subSequence(0, i)); if (Long.valueOf(Nstr.charAt(i) + EMPTY_STR) == 0) { continue; } if (Long.valueOf(Nstr.toString()) >= Long.valueOf(sb.toString())) { continue; } if ((Long.valueOf(sb.toString()) >= B)) { continue; } else { combinations++; } }*/ return combinations; } /** * @param args */ public static void main(String[] args) { Scanner scan = new Scanner(System.in); int T = scan.nextInt(); scan.nextLine(); int nCase = 1; while (T-- > 0) { StringBuffer Astr = new StringBuffer(scan.next()); StringBuffer Bstr = new StringBuffer(scan.next()); Long A = new Long(Astr.toString()); Long B = new Long(Bstr.toString()); pairs.clear(); for (long n = A; n < B; n++) { int c = GCJ_3.combinations(n, B); } scan.nextLine(); System.out.println(""Case #"" + (nCase++) + "": "" + pairs.size()); } } } " B11981,"package recycledNumbers; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; public class OutputFile { public void writeFile(ArrayList data) throws Exception { File file = new File(""C:\\Users\\Nikhil\\Desktop\\googleCodeJam\\output.txt""); BufferedWriter bufferedwriter = new BufferedWriter(new FileWriter(file)); for(int i=0;i= p) { // //System.out.println(""\t("" + x + "","" + y + "","" + z + "") "" + p); // s_match = true; // } // } // { // int z = x + 1; // int y = t[i] - x - z; // // if(x <= y && y <= z && z >= p) { // //System.out.println(""\t("" + x + "","" + y + "","" + z + "") "" + p); // n_match = true; // } // } // { // int z = x; // int y = t[i] - x - z; // // if(x <= y && y <= z && z >= p) { // //System.out.println(""\t("" + x + "","" + y + "","" + z + "") "" + p); // n_match = true; // } // } // } // match[i][0] = s_match; // match[i][1] = n_match; // // /*System.out.print(t[i]); // if(s_match) System.out.print("" *""); // if(n_match) System.out.print("" +""); // System.out.println();*/ // // if(n_match) // count++; // else if(s > 0 && s_match) { // s--; // count++; // } // } // return Integer.toString(count); // } // }; Base ProblemC = new Base(new int[] {0, 1}) { @Override protected String implementation(String[][] params) { int count = 0; try { int len = params[0][0].length(); Integer[] p = ArrayUtil.convert(params[0], Integer.class); for (int n = p[0]; n <= p[1]; n++) { int m = n; while(true) { m = (int) ((m%10)*Math.pow(10, len - 1)) + m/10; if(n < m && m <= p[1]) count++; if(n == m) break; } } }catch (Exception e) { e.printStackTrace(); System.exit(0); } return Integer.toString(count); } }; // Base ProblemD = new Base(new int[] {1, 0}) { // @Override // protected String implementation(String[][] params) { // int r = new Integer(params[0][0]).intValue(); // int c = new Integer(params[0][1]).intValue(); // int d = new Integer(params[0][2]).intValue(); // // // // // return """"; // } // }; ProblemC.run(); } } class Template { public static String _oFILE; public static String _iFILE; public static abstract class Base { static { System.out.println(""--- GOOGLE CODE JAM 2012 ---------------------------------------""); } private int[] inputType; private String columnSeperator = "" ""; private Template.Base.iCollection input; abstract protected String implementation(String[][] params) throws Exception; public Base(int[] inputType) throws Exception { this.inputType = inputType; if (new File(_iFILE).exists()) { input = new Template.Base.iCollection(); String strLine; BufferedReader buffReader = new BufferedReader(new FileReader(_iFILE)); while ((strLine = buffReader.readLine()) != null) input.add(strLine.split(columnSeperator)); buffReader.close(); input.index(); }else { throw new Exception(""Input File Missing""); } } public void run() throws Exception { int inputSize = new Integer(input.get(0)[0]).intValue(); BufferedWriter buffWriter = new BufferedWriter(new FileWriter(new File(_oFILE))); for (int i = 1; i <= inputSize; i++) { String result = implementation(Template.ArrayUtil.convert(input.item(i))); printResult(input.item(i), result); buffWriter.write(""Case #"" + i + "": "" + result + ""\n""); buffWriter.flush(); } buffWriter.close(); System.out.println(""----------------------------------------- GOOGLE INPUT TYPES ---""); System.out.println(""{0,n} : EACH CASE WITH n (n > 0) ROWS""); System.out.println(""{1,0} : EACH CASE WITH DYNAMIC (DEFINED @ FIRST ROW) SET OF ROWS""); System.out.println(""--------------------------------------------- Subodh Gairola ---""); } private void printResult(ArrayList params, String result) { for (int i = 0; i < params.size(); i++) { for (int j = 0; j < params.get(i).length; j++) { System.out.print(params.get(i)[j] + "" ""); } System.out.println(); } System.out.println(""\t\t|"" + result + ""|""); } class iCollection extends ArrayList { private static final long serialVersionUID = 1L; int[][] _index; public void index() { _index = new int[new Integer(this.get(0)[0]).intValue() + 1][2]; _index[0][0] = inputType[0]; _index[0][1] = inputType[1]; for (int i = 1; i < _index.length; i++) { if (_index[0][0] == 0) { int len = inputType[1]; _index[i][0] = 1 + (i - 1) * len; _index[i][1] = len; } else if (_index[0][0] == 1) { int lastPos = _index[i - 1][0]; int lastLen = _index[i - 1][1]; _index[i][0] = lastPos + lastLen; _index[i][1] = new Integer(this.get(_index[i][0])[0]).intValue() + 1; } } } public Template.Base.iCollection item(int index) { int pos = _index[index][0]; int len = _index[index][1]; Template.Base.iCollection params = new Template.Base.iCollection(); for (int i = pos; i < pos + len; i++) { params.add(this.get(i)); } return params; } } } public static class Generator { public int[] a; public BigInteger numLeft; public BigInteger total; public void reset() { for (int i = 0; i < a.length; i++) { a[i] = i; } numLeft = new BigInteger(total.toString()); } public BigInteger getNumLeft() { return numLeft; } public BigInteger getTotal() { return total; } public boolean hasMore() { return numLeft.compareTo(BigInteger.ZERO) == 1; } public static BigInteger getFactorial(int n) { BigInteger fact = BigInteger.ONE; for (int i = n; i > 1; i--) { fact = fact.multiply(new BigInteger(Integer.toString(i))); } return fact; } public static class Permutation extends Template.Generator { public Permutation(int n) { if (n < 1) { throw new IllegalArgumentException(""Minimum 1""); } a = new int[n]; total = Template.Generator.getFactorial(n); reset(); } public int[] getNext() { if (numLeft.equals(total)) { numLeft = numLeft.subtract(BigInteger.ONE); return a; } int temp; int j = a.length - 2; while (a[j] > a[j + 1]) { j--; } int k = a.length - 1; while (a[j] > a[k]) { k--; } temp = a[k]; a[k] = a[j]; a[j] = temp; int r = a.length - 1; int s = j + 1; while (r > s) { temp = a[s]; a[s] = a[r]; a[r] = temp; r--; s++; } numLeft = numLeft.subtract(BigInteger.ONE); return a; } } public static class Combination extends Template.Generator { private int n; private int r; public Combination(int n, int r) { if (r > n) { throw new IllegalArgumentException(); } if (n < 1) { throw new IllegalArgumentException(); } this.n = n; this.r = r; a = new int[r]; BigInteger nFact = Template.Generator.getFactorial(n); BigInteger rFact = Template.Generator.getFactorial(r); BigInteger nminusrFact = Template.Generator.getFactorial(n - r); total = nFact.divide(rFact.multiply(nminusrFact)); reset(); } public int[] getNext() { if (numLeft.equals(total)) { numLeft = numLeft.subtract(BigInteger.ONE); return a; } int i = r - 1; while (a[i] == n - r + i) { i--; } a[i] = a[i] + 1; for (int j = i + 1; j < r; j++) { a[j] = a[i] + j - i; } numLeft = numLeft.subtract(BigInteger.ONE); return a; } } } public static class ArrayUtil { @SuppressWarnings(""unchecked"") public static T[][] permutations(T[] array) { Template.Generator.Permutation x = new Template.Generator.Permutation(array.length); ArrayList permutations = new ArrayList(); while (x.hasMore()) { int[] indices = x.getNext(); T[] permutation = (T[]) Array.newInstance(array[0].getClass(), indices.length); for (int i = 0; i < indices.length; i++) { permutation[i] = array[indices[i]]; } permutations.add(permutation); } return convert(permutations); } @SuppressWarnings(""unchecked"") public static T[][] combinations(T[] array, int n) { Template.Generator.Combination x = new Template.Generator.Combination(array.length, n); ArrayList combinations = new ArrayList(); while (x.hasMore()) { int[] indices = x.getNext(); T[] combination = (T[]) Array.newInstance(array[0].getClass(), indices.length); for (int i = 0; i < indices.length; i++) { combination[i] = array[indices[i]]; } combinations.add(combination); } return convert(combinations); } @SuppressWarnings(""unchecked"") public static T[] convert(String[] array, Class cl) throws Exception { T[] n = (T[]) Array.newInstance(cl, array.length); for (int i = 0; i < array.length; i++) { n[i] = cl.getConstructor(String.class).newInstance(array[i]); }; return n; } public static String[] convert(T[] array) throws Exception { String[] n = new String[array.length]; for (int i = 0; i < array.length; i++) { n[i] = array[i].toString(); } return n; } @SuppressWarnings(""unchecked"") public static T[] convert(ArrayList arrayList) { if (arrayList.size() == 0) { return null; } T[] array = (T[]) Array.newInstance(arrayList.get(0).getClass(), arrayList.size()); for (int i = 0; i < array.length; i++) { array[i] = arrayList.get(i); } return array; } public static String join(T[] array, String seperator) { String string = """"; for (int i = 0; i < array.length; i++) { string += array[i].toString(); if (i < array.length - 1) { string += seperator; } } return string; } public static T[] remove(T[] array, int index) { ArrayList arrayList = new ArrayList(); for (int i = 0; i < array.length; i++) { if (i != index) { arrayList.add(array[i]); } } return convert(arrayList); } public static T[] unique(T[] array) { ArrayList arrayList = new ArrayList(); for (int i = 0; i < array.length; i++) { if (!arrayList.contains(array[i])) { arrayList.add(array[i]); } } return convert(arrayList); } } } " B13053," import java.util.*; import java.io.*; public class rcycn { public static void main(String[] args) throws Exception { BufferedReader inputer = new BufferedReader(new FileReader(""rcycn.in"")); PrintWriter outputer = new PrintWriter(new BufferedWriter(new FileWriter(""rcycn.out""))); int T = Integer.parseInt(inputer.readLine()); for(int i = 0; i < T; i++) { StringTokenizer st = new StringTokenizer(inputer.readLine()); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); int answer = 0; if(B >= 10) for(int n = A; n <= B; n++) for(String m = rotate(String.valueOf(n)); Integer.parseInt(m) != n; m = rotate(String.valueOf(m))) if(Integer.parseInt(m) <= B && Integer.parseInt(m) > n) answer++; outputer.println(""Case #"" + (i + 1) + "": "" + answer); } outputer.close(); inputer.close(); } public static String rotate(String n) { return n.substring(n.length() - 1) + n.substring(0, n.length() - 1); } }" B11857," import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author utp */ public class C { public static void main(String Args[]) throws IOException{ Scanner sc = new Scanner (new File(""input.in"")); FileWriter fw = new FileWriter(""output.out""); int T = sc.nextInt(); for (int k=0;k=0){ String sub2 = num2.substring(0, c); String sub1 = num2.substring(c); if (num1.equals(sub1.concat(sub2))){ // System.out.println(""Case #""+(k+1)+"": ""+sub1+"" ""+sub2+"" ""+num1+"" ""+num2); count++; } } } } fw.write(""Case #""+(k+1)+"": ""+count+""\n""); } fw.close(); } public static int calcular(char cad1[], char cad2[]){ for (int j=0;j<=cad1.length;j++){ String temp1 = String.copyValueOf(cad1, j,cad1.length-j); String tmp2 = String.copyValueOf(cad2); if (tmp2.contains(temp1)){ return temp1.length(); } } return -1; } } " B11688,"package codejam; import java.io.File; import java.util.Scanner; import java.io.FileWriter; import java.util.Arrays; /** * * @author Abiosoft */ public class Recycler { public static void main(String[] a) throws Exception { process(""Recycler.in""); } public static void process(String filename) throws Exception { File file = new File(filename); Scanner in = new Scanner(file); numberOfCase = Integer.parseInt(in.nextLine()); String[] results = new String[numberOfCase]; for (int i = 0; i < numberOfCase; i++) { String[] row = in.nextLine().split("" ""); results[i] = """" + solve(row); } in.close(); output(results); } public static void output(String[] results) throws Exception { File file = new File(""Recycler.out""); FileWriter out = new FileWriter(file); for (int i = 0; i < results.length; i++) { out.write(""Case #"" + (i + 1) + "": "" + results[i]); out.write(i < results.length - 1 ? ""\n"" : """"); } out.close(); } public static int solve(String[] row) { int n1 = Integer.parseInt(row[0]); int n2 = Integer.parseInt(row[1]); char[] r1; char[] r2; String s1; String s2; int count = 0; for (int i = n1; i < n2; i++) { for (int j = i + 1; j <= n2; j++) { r1 = (i + """").toCharArray(); r2 = (j + """").toCharArray(); s1 = new String(r1); s2 = new String(r2); Arrays.sort(r1); Arrays.sort(r2); if (Arrays.equals(r1, r2)) { count += testRecycle(s1, s2); } } } return count; } public static int testRecycle(String n, String m) { int count = 0; for (int i = 1; i < n.length(); i++) { String nn = n.substring(i); int index = m.indexOf(nn); if (index < 0) { continue; } String s = nn + n.substring(0, i); if (s.equals(m)) { return 1; } } return count; } public static int numberOfCase = 0; } " B12053,"import java.util.*; public class Recycled { public static void main(String args[]) { Scanner in=new Scanner(System.in); int cases=in.nextInt(); for(int i=1; i<=cases; i++) { int a=in.nextInt(), b=in.nextInt(); long ans=0; for(int x=a; x<=b; x++) { for(int y=x+1; y<=b; y++) { String one=Integer.toString(x), two=Integer.toString(y); if(one.length()!=two.length()) break; for(int s=1; s rotatedNumbers; for(int num = A;num<=B;num++) { rotatedNumbers = new Vector(); String rotatedNum = String.valueOf(num); for(int j = 0;j j && pair <= max ){ count++; counter++; if(i==3 && count > 1) System.out.println(counter+"" ""+j+"" ""+pair); continue; } } } pwStream.println (""Case #"" + (i+1) + "": "" +counter); } // close all I/O files brStream.close(); pwStream.close(); } catch(IOException e){} } }" B10682,"import java.io.*; import java.util.*; class Problems { public static void main (String [] args) throws Exception { BufferedReader f = new BufferedReader(new FileReader(""input.java"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""output.java""))); StringTokenizer st = new StringTokenizer(f.readLine()); int T=Integer.parseInt(st.nextToken()); for(int t=0;t set = new HashSet(); int total = 0; int mask = 1; if(A >= one) { if(A < two) { mask = one; } else if(A < three) { mask = two; } else if(A < four) { mask = three; } else if(A < five) { mask = four; } else if(A < six) { mask = five; } else { mask = six; } for(int j = A; j <= B; j++) { if(set.contains(j)) { continue; } set.add(j); int div = j / mask; int res = j - (mask * div); int target = res * 10 + div; while(j != target) { if(target >= A && target <= B && !set.contains(target)) { total++; } div = target / mask; res = target - (mask * div); target = res * 10 + div; } } } result.append(CASE).append(i).append("": "").append(total); if(i != T) { result.append(N_L); } writer.write(result.toString()); result.setLength(0); } writer.flush(); } catch(IOException e) { e.printStackTrace(); } finally { sc.close(); try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } } " B11501,"package problem.c; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class ProblemC { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); OutputBuilder out = new OutputBuilder(); Set pairs; int numCases; String A; String B; String[] linha; numCases = scanner.nextInt(); scanner.nextLine(); for (int k = 1; k <= numCases; k++) { linha = scanner.nextLine().split("" ""); A = linha[0]; B = linha[1]; pairs = resolve(A, B); out.addLine(k, pairs.size()); } System.out.println(out.toString()); } private static Set resolve(String A, String B) { Set pairs = new HashSet(); int inicio = Integer.valueOf(A); int fim = Integer.valueOf(B); int k; for (int i = inicio; i <= fim; i++) { String N = String.valueOf(i); for (k = 1; k <= N.length() - 1; k++) { if ((Character.getNumericValue(N.charAt(k)) <= Character.getNumericValue(B.charAt(0))) && Character.getNumericValue(N.charAt(k)) != 0) { String M = (N.substring(k) + N.substring(0, k)); if (!N.equals(M)) { if (Integer.valueOf(M) > inicio && Integer.valueOf(M) < fim) { pairs.add(new Pair(N, M)); } } } } } return pairs; } private static class Pair { String n, m; public Pair(String n, String m) { this.n = n; this.m = m; } @Override public int hashCode() { final int prime = 31; return prime * ((this.m == null) ? 0 : this.m.hashCode()) + prime * ((this.n == null) ? 0 : this.n.hashCode()); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } Pair other = (Pair) obj; if (this.m.equals(other.n) && (this.n.equals(other.m))) { return true; } if (this.m == null) { if (other.m != null) { return false; } } else if (!this.m.equals(other.m)) { return false; } if (this.n == null) { if (other.n != null) { return false; } } else if (!this.n.equals(other.n)) { return false; } return true; } } private static class OutputBuilder { private StringBuilder sb = new StringBuilder(); public void addLine(int i, int result) { this.sb.append(""Case #""); this.sb.append(i); this.sb.append("": ""); this.sb.append(result); this.sb.append('\n'); } @Override public String toString() { return this.sb.toString(); } } } " B10249,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; public class RNumber extends Basic2 { public static void main(String[] args) throws Exception { RNumber p3 = new RNumber(); p3.initialize(); p3.printOutput(); p3.bos.close(); } @Override public void printOutput() throws Exception { int noTC = Integer.parseInt(bis.readLine()); int runningTC = 1; while(runningTC<=noTC) { String[] a_b_str =bis.readLine().split("" ""); long[] a_b = new long[]{Long.parseLong(a_b_str[0]),Long.parseLong(a_b_str[1])}; if(a_b[0]>a_b[1]) { long temp = a_b[0]; a_b[0] = a_b[1]; a_b[1] = temp; } Set found = new HashSet(); int leading =0; for(long i=a_b[0];i<=a_b[1];i++) { long numberToCheck = i; for(long k = numberToCheck+1;k<=a_b[1];k++) { if(((""""+k).length()==(""""+numberToCheck).length()) && (""""+k+""""+k).contains(""""+numberToCheck)) { leading++; } /*int t= k; String n=""""+numberToCheck; int ld = 0; while(t>10 && t%10==0 && t>a_b[0]) { t=t/10; ld++; } String ldSt=""""; for(int hh=0;hh 0) { int resp = 0; int m = s.nextInt(); int n = s.nextInt(); //boolean[][] criv = new boolean[n-m+1][n-m+1]; boolean[] criv = new boolean[n-m+1]; for (int i = 0; i < criv.length; i++) { int current = m + i; String currentString = String.valueOf(current); if (currentString.charAt(0) == '0') continue; if (criv[current - m]) continue; criv[current - m] = true; int nInterv = 0; for (int j = 1; j < currentString.length(); j++) { String invString = currentString.substring(j).concat(currentString.substring(0, j)); Integer inv = Integer.valueOf(invString); if (invString.charAt(0) == '0') continue; if (invString.equals(currentString)) continue; if (inv > n || inv < m) continue; if (criv[inv - m]) continue; criv [inv-m] = true; nInterv ++; //System.out.println(currentString + "" --- "" + invString); } if (nInterv > 0) { int bbb = nInterv + 1; resp+= factorial(bbb) / (2 * factorial(bbb-2)); } } System.out.println(""Case #"" + iTests + "": "" + resp); iTests++; } } public static long factorial( int n ) { if( n <= 1 ) // base case return 1; else return n * factorial( n - 1 ); } } " B11313,"/** * Copyright 2012 Christopher Schmitz. All Rights Reserved. */ package com.isotopeent.codejam.lib; public interface InputConverter { boolean readLine(String data); T generateObject(); } " B12291,"import java.io.*; public class Palindrome { public static void main(String args[]) throws IOException { int N; int a,b,i; String s[]; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); N=Integer.parseInt(br.readLine()); for(i=1;i<=N;i++) { s=br.readLine().split("" ""); a=Integer.parseInt(s[0]); b=Integer.parseInt(s[1]); System.out.println(""Case #""+i+"": ""+calc(a,b)); } } public static int calc(int a,int b) { int i,j,k,p1,p2,cnt=0; int tmp[]; p1=-1; p2=-1; for(i=a;i=0;i--) { vals[cnt++]=Integer.parseInt(s.substring(i,digits)+s.substring(0,i)); } return vals; } } " B12481,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ //package codejam2012; import java.io.*; import java.util.ArrayList; /** * * @author BUDDHIMA */ public class Codejam2012 { /** * @param args the command line arguments */ public static void main(String[] args) throws Exception { // TODO code application logic here BufferedReader br = new BufferedReader(new FileReader(""C-small-attempt0.in"")); BufferedWriter out = new BufferedWriter(new FileWriter(new File(""outputC-small.txt""))); int tests = Integer.parseInt(br.readLine()); for (int testIndex = 1; testIndex <= tests; testIndex++) { int count = 0; String[] lineParts = br.readLine().split("" ""); // A B if (lineParts[0].length() < 2) { out.write(""Case #"" + testIndex + "": "" + 0 + ""\n""); continue; } else { int A = Integer.parseInt(lineParts[0]); int B = Integer.parseInt(lineParts[1]); for (int x = A; x < B; x++) { ArrayList preAdded=new ArrayList(); //memory for (int i = 1; i < lineParts[0].length(); i++) { String numpart1 = String.valueOf(x).substring(0, i); String numpart2 = String.valueOf(x).substring(i); int newnum = Integer.parseInt(numpart2 + numpart1); if (newnum <= B && x < newnum) { boolean isIn=false; for(int y=0;y"" + newnum); count++; preAdded.add(newnum); isIn=false; } } } } } //print results out.write(""Case #"" + testIndex + "": "" + count + ""\n""); } out.close(); } } " B10069,"import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; /** * */ /** * @author Abhimanyu * */ public class C { /** * @param args */ public static void main(String[] args) { try { Scanner sc = new Scanner(System.in); int caseNo = sc.nextInt(); FileWriter fstream = new FileWriter(""C:/Users/Anvesh/Desktop/out.txt""); BufferedWriter out = new BufferedWriter(fstream); for(int i = 1; i <= caseNo; i++) { int a = sc.nextInt(); int b = sc.nextInt(); int recyclableNo = 0; int start; int end; if(a > b) { end = a; start = b; } else { end = b; start = a; } for(int j = start; j <= end; j++) { for(int k = end; k > j; k--) { if(isPermutation(j, k)) { if(isEquivalent(j, k)) { recyclableNo++; } } } } System.out.println(""Case #"" + i + "": "" + recyclableNo); out.write(""Case #"" + i + "": "" + recyclableNo); out.newLine(); } //Close the output stream out.close(); } catch (IOException e) { e.printStackTrace(); } } private static int getNoOfDigits(long num) { int digitCount = 0; while(num > 0) { num /= 10; digitCount++; } return digitCount; } private static boolean isPermutation(int num1, int num2) { boolean result = false; int[] arr = new int[10]; int temp = num2; while (temp > 0) { arr[temp % 10]++; temp /= 10; } temp = num1; while (temp > 0) { arr[temp % 10]--; temp /= 10; } for (int i = 0; i < 10; i++) { if (arr[i] != 0) { result = true; } } return !result; } private static boolean isEquivalent(int num1, int num2) { boolean result = false; int rem; int digitNo = getNoOfDigits(num1); for(int i = 0; i < digitNo; i++) { if(num1 == num2) { result = true; break; } rem = num1 % 10; num1 /= 10; num1 += rem * Math.pow(10, digitNo - 1); } return result; } } " B12814," import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Hashtable; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author sanket */ public class RecycledNumbers { public static void main(String[] args) { // TODO code application logic here try { FillHash(); FileInputStream fstream = new FileInputStream(""C-small-attempt0.in""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); //System.out.print("" Enter N :""); BufferedReader br; br = new BufferedReader(new InputStreamReader(in)); ReadFile(br); } catch (Exception ex) { ex.printStackTrace(); } } public static void FillHash() { } public static String GetNumbersOfPair(long A, long B) { ArrayList a = new ArrayList(); int cnt = 0; for (long i = A; i <= B; i++) { for (long j = i; j <= B; j++) { String word = String.valueOf(j); for (int k = 0; k < word.length(); k++) { StringBuilder w = new StringBuilder(); w.append(word.substring(word.length() - (k + 1), word.length())); w.append(word.substring(0, word.length() - (k + 1))); //System.out.println(w + "" word :"" + word); if (i == Long.parseLong(w.toString()) && i != j) { // for distinct pair if (!a.contains(i + """" + j)) { a.add(i + """" + j); cnt++; } } } } } return cnt + """"; } public static void ReadFile(BufferedReader br) { try { String output = """"; StringBuilder sb = new StringBuilder(); int N = Integer.parseInt(br.readLine()); int items[] = new int[N]; for (int i = 0; i < N; i++) { StringBuilder sbTemp = new StringBuilder(br.readLine()); sb.append(""Case #""); sb.append((i + 1)); sb.append("": ""); String A = String.valueOf(sbTemp.substring(0, sbTemp.indexOf("" ""))); String B = String.valueOf(sbTemp.substring(sbTemp.indexOf("" "") + 1, sbTemp.length())); sb.append(GetNumbersOfPair(Long.parseLong(A), Long.parseLong(B))); output = output + sb + ""\n""; sb.delete(0, sb.length()); } // output starts System.out.print(output); } catch (Exception ex) { } } } " B11059,"package fixjava; import java.util.ArrayList; /** * An ArrayList that allows values to be set at positions greater than or equal to size(), which causes the end of the list to be padded with an * identity element before the value is set */ public class ArrayListAutoPadded extends ArrayList { private T identity; public ArrayListAutoPadded(T identity) { super(); this.identity = identity; } public ArrayListAutoPadded(T identity, int initialCapacity) { super(initialCapacity); this.identity = identity; } /** * Set the value at the given location to the specified value, padding the list to the desired length if necessary. Returns the old value at the * location, if there was one, otherwise the identity value that was passed in the constructor. */ public T set(int index, T element) { if (size() > index) { return super.set(index, element); } else { while (size() < index) add(identity); add(element); return identity; } }; /** * Combine the value at the given location with the new value, by calling labmda.apply(oldValue, newValue). The identity value that was passed in * the constructor is used if the index >= size(). Returns the *old* value that was stored at the index before combining, or identity if there was * no old value. */ public T combineAndSet(int index, Lambda2 combineFunc, T newValue) { T oldValue; if (size() > index) { oldValue = get(index); } else { while (size() <= index) add(identity); oldValue = identity; } return super.set(index, combineFunc.apply(oldValue, newValue)); } private static final long serialVersionUID = 1L; } " B11235,"import java.util.Scanner; public class Recyclers { private static int countRecycled(int a, int b) { int recycled = 0; for (int i = a; i <= b; i++) { String s = new Integer(i).toString(); for (int j = 0; j < s.length() - 1; j++) { String o = s.substring(s.length() - j - 1, s.length()).concat( s.substring(0, s.length() - j - 1)); int n = Integer.valueOf(s); int m = Integer.valueOf(o); if (n < m && m <= b) { recycled++; } } } return recycled; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int cases = sc.nextInt(); for (int x = 0; x < cases; x++) { sc.nextLine(); int a = sc.nextInt(); int b = sc.nextInt(); int c = countRecycled(a, b); System.out.println(""Case #"" + (x + 1) + "": "" + c); } } } " B12707,"import java.io.File; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.LinkedList; import java.util.Scanner; public class RecycledNumbers { public static void main(String args[]) throws FileNotFoundException { new RecycledNumbers().Go(); } public void Go() throws FileNotFoundException { Scanner in = new Scanner(new File(""test.txt"")); int tests = Integer.parseInt(in.nextLine()); for (int i = 0; i < tests; i++) { String[] line = in.nextLine().split(""\\s+""); int n = Integer.parseInt(line[0]); int m = Integer.parseInt(line[1]); System.out.println(""Case #"" + (i + 1) + "": "" + countPairs(n, m, 1, 1000)); } } public int countPairs(int n, int m, int A, int B) { HashMap> map = new HashMap>(); int count = 0; for (int i = n; i <= m; i++) { LinkedList intList = permutations(i + """"); map.put(i, intList); for (Integer it : intList) { if (map.containsKey(it)) { LinkedList ints = map.get(it); if (ints.contains(i)) { count++; } } } } return count; } public LinkedList permutations(String str) { LinkedList numList = new LinkedList(); for (int i = 0; i < str.length(); i++) { Integer temp = Integer.parseInt(str); if (!numList.contains(temp)) numList.add(Integer.parseInt(str)); str = leftRotate(str); } numList.removeFirst(); return numList; } public String leftRotate(String str) { StringBuilder build = new StringBuilder(); build.append(str.substring(1, str.length())); build.append(str.charAt(0)); return build.toString(); } } " B12018,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; public class App { public static void main (String[] args){ try{ FileInputStream fstream = new FileInputStream(""input.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); int cases = Integer.parseInt(br.readLine()); String output = """"; for(int i=1;i<=cases;i++){ String line = br.readLine(); String[] arr = line.split("" ""); int a = Integer.parseInt(arr[0]); int b = Integer.parseInt(arr[1]); int count = RecyclePair.Calculate(a, b); output += ""Case #""+i+"": ""+count; if(i+1 <= cases){ output += ""\n""; } } in.close(); System.out.println(output); FileWriter fwstream = new FileWriter(""output.out""); BufferedWriter out = new BufferedWriter(fwstream); out.write(output); out.close(); } catch (Exception e) { } } } " B11378,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; public class Evans2012C { private final String _PROBLEM_NO = ""201201C""; private final String _FILE_DIRECTORY = ""K:/Dropbox/workspace/codejam/"" + _PROBLEM_NO + ""/""; private final String _FILE_PATH = _FILE_DIRECTORY + ""C-small-attempt0""; public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); new Evans2012C().execute(); } public void execute() { BufferedReader br = null; PrintWriter pw = null; try { br = new BufferedReader(new FileReader(_FILE_PATH + "".in"")); pw = new PrintWriter(_FILE_PATH + "".out""); //main int caseno = Integer.parseInt(br.readLine()); Map m = new HashMap(); for(int i=10;i<=1000000;i++) { check(i,m); } // System.out.println(m.get(2)); for (int count = 1; count <= caseno; count++) { // if(count>4)break; pw.print(""Case #"" + count + "": ""); System.out.print(""Case #"" + count + "": ""); String line = br.readLine(); String[] splits = line.split("" ""); int A = Integer.parseInt(splits[0]); int B = Integer.parseInt(splits[1]); int r = 0; if(A < 10 || A >= 1000000 || A==B) { pw.print(""0""); System.out.print(""0""); } else { List tt = m.get((""""+A).length()); for(int t:tt) { // if(t >= A && t <= B) { r += check(A,B,t); // } } pw.print(r); System.out.print(r); } pw.print(""\n""); System.out.print(""\n""); } //end br.close(); pw.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if(pw != null) pw.close(); } catch(Exception e) {} try { if(br != null) br.close(); } catch(Exception e) {} } } private int check(int a, int b, int t) { String tt = """"+t; // System.out.println(tt); int r =0; Set rr = new HashSet(); for(int i=0;i=a&&t<=b) { // System.out.print(tt + ""!""); rr.add(t); } } r=rr.size(); // System.out.println(r); if(r==1) return 0; if(r!=0) r = (r*(r-1))/2; return r; } private void check(int i, Map m) { String in = """" + i; int b = in.length(); if(!dedup(i)) return; dedup.put(i, true); List target = m.get(b); if(target == null) { target = new ArrayList(); m.put(b, target); } target.add(i); } public static Map dedup = new HashMap(); private boolean dedup(int t) { String tt = """"+t; for(int i=0;i list = swap(str); for (int x : list){ if (x >j && x<=b){ count ++; } } } println(""Case #"" + (i+1) + "": "" + count); } //Close the input stream in.close(); }catch (Exception e){ e.printStackTrace(); } } private static HashSet swap(String str){ HashSet list = new HashSet(); for (int i=1; i set = new HashSet(); public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new File(""C-small-attempt0.in.txt"")); PrintStream outfile = new PrintStream(new FileOutputStream(""recycle.out.txt"")); int N = sc.nextInt(); for(int y = 0; y < N; y++) { int A = sc.nextInt(); int B = sc.nextInt(); MIN = A; MAX = B; if( A < 10 && B < 10) outfile.println(""Case #"" + (y+1) + "": 0""); else { for(int x = A; x < B; x++) findPossibilities(x); outfile.println(""Case #"" + (y+1) + "": "" + set.size()); set = new HashSet(); } } } public static void findPossibilities(int y) { String s = Integer.toString(y); for(int x = 1; x < s.length(); x++) { String one = s.substring(x); String two = s.substring(0,x); String com = one + two; int temp = i(com); com = Integer.toString(temp); if(temp > MIN && temp <= MAX && temp > y) { //System.out.println(s + "" "" + com); count++; set.add(new Pair(y,temp)); } } } public static int i(String s) { return Integer.parseInt(s); } } class Pair { public int x; public int y; public Pair(int one, int two) { x = one; y = two; } public boolean equals(Object z) { if(hashCode() == z.hashCode()) return true; return false; } public int hashCode() { String one = Integer.toString(x); String two = Integer.toString(y); return (one + two).hashCode(); } }" B10257,"package com.numbers.recycle.main; import com.numbers.recycle.orchestrator.NumberRecycler; public class NumberRecyclerMain { /** * @param args */ private NumberRecycler reverser = new NumberRecycler(); public static void main(String[] args) { new NumberRecyclerMain().recycle(); } private void recycle(){ reverser.solveAndWriteToOutputFile(""C:/Documents and Settings/Administrator/My Documents/Code Jam/C-sample.in""); } } " B10022,"import java.util.ArrayList; import java.util.HashSet; public class DancingWithTheGooglers { private static String inputFile = ""C:\\PERSONAL-WORKSPACE\\GCJ-2012\\src\\input-output\\Input.txt""; private static String outputFile = ""C:\\PERSONAL-WORKSPACE\\GCJ-2012\\src\\input-output\\Output.txt""; public static void main(String[] args) { InputReader ir = new InputReader(inputFile); OutputWriter ow = new OutputWriter(outputFile); ArrayList lines = ir.loadLines(); for(int i=1;i hs = new HashSet(); String[] sNums = lines.get(i).split("" "",lines.get(i).length()); Long[] minMaxArr = GCJUtils.getLongArray(sNums); for(long l=((minMaxArr[0]<12)?12:minMaxArr[0]);l<=minMaxArr[1];l++){ String sCurrVal = Long.toString(l); for(int j=sCurrVal.length()-1;j>0;j--){ String sTmp = sCurrVal.substring(j)+ sCurrVal.substring(0,j); Long sLong = Long.parseLong(sTmp); if(sLong>l && sLong<=minMaxArr[1]){ hs.add(sLong+""-""+l); } } } ow.writeCaseLine(hs.size()+""""); } ow.flushAndClose(); } } " B11271,"package google.code.jam.problem.c; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class MainClass { public static final String PATH_FILE = ""C:/Temp/""; /** * @param args */ public static void main(String[] args) { try { MainClass mainClass = new MainClass(); // HashSet recycledNumbersCollection = new HashSet (); List recycled = new ArrayList(); // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(PATH_FILE + ""C-small-attempt1.in""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine = br.readLine(); int numOfTestCase = Integer.parseInt(strLine); if ((numOfTestCase >= 1) && (numOfTestCase <= 50)) { int i = 1; // Read File Line By Line while ((strLine = br.readLine()) != null) { StringTokenizer st = new StringTokenizer(strLine, "" ""); int numberA = Integer.parseInt(st.nextToken()); int numberB = Integer.parseInt(st.nextToken()); if ((1 <= numberA) && (numberA <= numberB) && (numberB <= 1000)) { int recycledPair = 0; for (int j = numberA; j < numberB; j++) { String rotateNumber = String.valueOf(j); int currentNumber = j; // System.out.println(""currentNumber: "" + currentNumber); for (int k = 1; k < String.valueOf(j).length(); k++) { String rotateNumberNew = mainClass .rotateNumber(rotateNumber); // System.out.println(rotateNumberNew); if ((!""-1"".equals(rotateNumber)) && (Integer.valueOf(rotateNumberNew) > currentNumber) && (Integer.valueOf(rotateNumberNew) <= numberB) && (rotateNumber != rotateNumberNew)) { recycledPair++; // recycledNumbersCollection.add(rotateNumberNew); recycled.add(currentNumber + "" , "" + rotateNumberNew); // System.out.println("":: recycledPair :: "" + rotateNumberNew); } rotateNumber = rotateNumberNew; } } // int temp = 0; // for (String string : recycled) { // System.out.println(""number "" + ++temp +"": "" + string); // } System.out.println(""Case #"" + i++ + "": "" + recycledPair); // System.out.println(recycledNumbersCollection.size()); } else { throw new Exception(""Condition not 1 <= A <= B <= 1000""); } } } else { throw new Exception(""Number of test case is not valid""); } // Close the input stream in.close(); } catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } public String rotateNumber(String number) { String returnValue = ""-1""; try { if (Integer.parseInt(number) >= 10) { String lastDigit = number.substring(number.length() -1 , number.length()); returnValue = lastDigit + number.substring(0, number.length() -1); // String firstDigit = number.substring(0, 1); // returnValue = number.substring(1) + firstDigit; } else { returnValue = ""-1""; } } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } return returnValue; } } //1111 2222 " B10758,"import java.io.*; import java.util.*; import java.lang.*; public class Recycled { public static int cases = 0; public static int min[] = new int[50]; public static int max[] = new int[50]; public static int answer[] = new int[50]; public static ArrayList results = new ArrayList(); public static void main(String args[]) { File input = new File(""Input.txt""); File output = new File(""Output.txt""); loadGame(input); for(int i = 0; i < cases; i++){ answer[i] = 0; } findAnswer(); saveGame(output); } public static void findAnswer(){ for(int i = 0; i < cases; i++){ for(int j = min[i]; j <= max[i]; j++){ String number = new Integer(j).toString(); ArrayList numberArray = new ArrayList(); for(int m = 0; m < number.length(); m++){ numberArray.add(Character.toString(number.charAt(m))); } for(int k = 1; k < number.length(); k++){ numberArray.add(0, numberArray.remove((number.length()-1))); String temp = """"; ArrayList tempNumberArray = new ArrayList(); tempNumberArray.addAll(numberArray); for(int m = 0; m < number.length(); m++){ temp += tempNumberArray.remove(0); } int result = Integer.parseInt(temp); if(result >= min[i] && result <= max [i] && result > j){ if(!results.contains(result)){ answer[i]++; results.add(result); } } } results.clear(); } } } public static void loadGame(File input){ Scanner in; try { in = new Scanner(input); cases = in.nextInt(); in.nextLine(); for(int i = 0; i < cases; i++){ min[i] = in.nextInt(); max[i] = in.nextInt(); if(min[i] > max[i]){ int temp = min[i]; min[i] = max[i]; max[i] = temp; } in.nextLine(); } in.close(); } catch (StringIndexOutOfBoundsException e) { } catch (FileNotFoundException e) { } catch (NoSuchElementException e) { } catch (NullPointerException e) { } } public static void saveGame(File name){ PrintWriter out; try { out = new PrintWriter(name); for(int i = 1; i <= cases; i++){ out.println(""Case #"" + i + "": "" + answer[(i-1)]); } out.close(); } catch (FileNotFoundException e) { } catch (NullPointerException e) { } } }" B10772,"import java.io.*; public class GoogleCodeJam18 { public static void main(String[] args) throws IOException { FileInputStream getFile = new FileInputStream(""C:\\1\\in1.txt""); PrintWriter out = new PrintWriter(new File(""C:\\1\\output.out"")); BufferedReader br = new BufferedReader(new InputStreamReader(getFile)); String strLine; strLine = br.readLine().trim(); int test = Integer.parseInt(strLine); for (int i=0;i= A && initial < present && present <= B) { sum++; } } return sum; } }" B10795,"import java.io.*; import java.util.*; import java.util.regex.*; import static java.lang.Math.*; public class C { public static void main(String[] args) throws Exception { Scanner in = (args.length > 0) ? new Scanner(new File(args[0])) : new Scanner(System.in); int T = in.nextInt(); for (int zz = 1; zz <= T; zz++) { System.err.format(""#%d\n"", zz); System.out.format(""Case #%d: "", zz); int A = in.nextInt(); int B = in.nextInt(); int y = 0; Set pairs = new HashSet(); int D = (int) Math.log10(A); long p0 = 10; long p1 = (long) Math.pow(10, D); for (int d = 1; d <= D; d++) { for (long n = A; n <= B; n++) { long m = ((n % p1) * p0) + (n / p1); if (m > n && m <= B && !pairs.contains(n + "":"" + m)) { y++; pairs.add(n + "":"" + m); } } p0 *= 10; p1 /= 10; } System.out.format(""%d\n"", y); } } } " B11452," public class ProbQ3 { public static void main(String[] args) { String fileContent = CodeJamTools.readFileAsString(""c:\\temp\\inputQ3.txt""); String[] rows = fileContent.split(""\\n""); int T = new Integer(rows[0]); String output = """"; int counter = 1; for (int i=0; i set = new HashSet(); for (int i = a; i <= b; i++) { String s = Integer.toString(i); char f = s.charAt(0); for (int j = 1, len = s.length(); j < len; j++) { if (s.charAt(j) < f) continue; String t = s.substring(j) + s.substring(0, j); int k = Integer.parseInt(t); if (k > i && k <= b) set.add(new Pair(i, k)); } } return set.size(); } private static class Pair { private int a; private int b; public Pair(int a, int b) { this.a = a; this.b = b; } public int hashCode() { return (a ^ b); } public boolean equals(Object obj) { Pair that = (Pair) obj; return (this.a == that.a && this.b == that.b); } } } " B12967,"package qualification.recycled.numbers; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URISyntaxException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { private static String PREFIX = ""C-small-attempt0""; private static String INPUT_FILE = PREFIX + "".in""; private static String OUTPUT_FILE = PREFIX + "".out""; private static BufferedReader getInput() { return new BufferedReader(new InputStreamReader(RecycledNumbers.class.getResourceAsStream(INPUT_FILE))); } private static PrintWriter getOutput() throws URISyntaxException, FileNotFoundException { File inputFile = new File(RecycledNumbers.class.getResource(INPUT_FILE).toURI()); File packageDirectory = inputFile.getParentFile(); File outputFile = new File(packageDirectory, OUTPUT_FILE); return new PrintWriter(outputFile); } public static void main(String[] args) throws Throwable { BufferedReader br = getInput(); PrintWriter pw = getOutput(); int numTestCases = new Integer(br.readLine().trim()); for (int testCase = 1; testCase <= numTestCases; testCase++) { String line = br.readLine(); Scanner read = new Scanner(line); Set pairs = new HashSet(); int a = read.nextInt(); int b = read.nextInt(); int digits = Integer.toString(a).length(); int lastDigitMultiplier = 1; for (int i = 1; i < digits; i++) { lastDigitMultiplier = lastDigitMultiplier * 10; } for (int num = a; num <= b; num++) { int recycledNum = num; for (int recycles = 1; recycles < digits; recycles++) { int lastDigit = recycledNum % 10; recycledNum = recycledNum / 10; recycledNum = (lastDigit * lastDigitMultiplier) + recycledNum; if (a <= recycledNum && recycledNum <= b && num != recycledNum && num < recycledNum) { RecycledPair pair = new RecycledPair(num, recycledNum); pairs.add(pair); } } } pw.println(""Case #"" + testCase + "": "" + pairs.size()); } pw.close(); br.close(); } } " B13078,"import java.util.Scanner; import java.io.*; public class S1 { public static void main(String []args) throws IOException { int numT=0; Scanner kb=new Scanner(new File(""D:/q2.txt"")); numT = kb.nextInt(); int a[] = new int[numT]; int b[]=new int[numT]; for (int i = 0; i < numT; i++) { a[i] = kb.nextInt(); b[i]=kb.nextInt(); } for (int i = 0; i < numT; i++) { System.out.println(""Case #""+(i+1)+"":""+"" ""+cal(a[i],b[i])); } } public static int cal(int A,int B){ int score=0; for(int n=A;n<=B;n++){ String num=n+""""; for(int j=1;j= A && m != n && m > n) { score++; } } } return score; } } " B12348,"import java.util.*; public class b { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); String ss = sc.nextLine(); int casenum = Integer.parseInt(ss); String answer = """"; for(int i = 1;i<=casenum;i++){ answer = answer.concat(""Case #"".concat(Integer.toString(i)).concat("": "")); ss = sc.nextLine(); String wer = recycledpair(ss); answer = answer.concat(wer); answer = answer.concat(""\n""); } System.out.print(answer); } public static String recycledpair(String a){ int n = Integer.parseInt(a.substring(0, a.indexOf(' '))); int m = Integer.parseInt(a.substring(a.indexOf(' ')+1, a.length())); int nlength = a.substring(0, a.indexOf(' ')).length(); int pairnum = 0; String rcp =""""; for(int i=n; i mylist = new LinkedList(); String sn = Integer.toString(i); //a.substring(0, a.indexOf(' ')); for(int j=1; ji&&newint<=m){ if(!mylist.contains(newint)){ pairnum++; mylist.add(newint); } else{ mylist.add(newint); } } } } String snumreturn = Integer.toString(pairnum); //System.out.print(snumreturn); return snumreturn; } } " B12205,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.math.BigDecimal; import java.math.BigInteger; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class C { private static String FILENAME = ""stdin""; static { //FILENAME = ""C-sample""; FILENAME = ""C-small""; //FILENAME = ""C-large""; } public static void main(String[] args) { new C().run(); } private PrintStream out; private final BufferedReader reader; private StringTokenizer tokenizer = new StringTokenizer(""""); public C() { try { out = System.out; if (FILENAME == ""stdin"") { reader = new BufferedReader(new InputStreamReader(System.in)); } else { out = new PrintStream(new FileOutputStream(""source/"" + FILENAME + "".out"")); reader = new BufferedReader(new FileReader(""source/"" + FILENAME + "".in"")); } } catch (FileNotFoundException e) { throw new RuntimeException(e); } } public void run() { try { runCases(); } finally { closeAll(); } } private void runCode() { int a = getInt(); int b = getInt(); Set visited = new HashSet(); int count = 0; for (int n = a; n <= b; n++) { String s = Integer.toString(n); int length = s.length(); for (int j = 0; j < length; j++) { String s2 = s.substring(j) + s.substring(0, j); int m = Integer.parseInt(s2); if (m > n && m <= b) { String key = s + "","" + s2; if (visited.add(key)) { count++; } } } } out.println(count); } private void runCases() { int cases = getInt(); for (int c = 1; c <= cases; c++) { out.print(""Case #"" + c + "": ""); runCode(); } } private void closeAll() { out.close(); } private String getToken() { try { while (true) { if (tokenizer.hasMoreTokens()) { return tokenizer.nextToken(); } String s = reader.readLine(); if (s == null) { return null; } tokenizer = new StringTokenizer(s, "" \t\n\r""); } } catch (IOException e) { throw new RuntimeException(e); } } public double getDouble() { return Double.parseDouble(getToken()); } public int getInt() { return Integer.parseInt(getToken()); } public long getLong() { return Long.parseLong(getToken()); } public BigInteger getBigInt() { return new BigInteger(getToken()); } public BigDecimal getBigDec() { return new BigDecimal(getToken()); } } " B13251," package com.google.codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { String input = null; //String outputFileLocation = ""C:\\google-code-jam\\output\\C-large-output.txt""; String outputFileLocation = ""C:\\google-code-jam\\output\\C-small-output.txt""; //String inputFileLocation = ""C:\\google-code-jam\\input\\C-large-practice.in""; String inputFileLocation = ""C:\\google-code-jam\\input\\C-small-practice.in""; File outputFile = new File(outputFileLocation); BufferedWriter outputWriter = null; DataInputStream in = null; int caseNum = 1; int count = 0; String appCount = """"; try { outputWriter = new BufferedWriter(new FileWriter(outputFile)); // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(inputFileLocation); // Get the object of DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine = null; int numtestCases = 1; int credit = 0; int numItemsinStore = 0; String[] arrItems = null; int [] arrSoln = null; long startNum = 0; long endNum = 0; int answer = 0; numtestCases = new Integer(br.readLine()).intValue(); // Read File Line By Line for (int i = 1; i <= numtestCases; i++) { //get credit from file input = br.readLine(); String[] a = input.split(""\\s""); answer = 0; startNum = Integer.parseInt(a[0]); endNum = Integer.parseInt(a[1]); for (long j = startNum; j < endNum; j++) { answer = answer + getString(String.valueOf(j), startNum, endNum); } // System.out.println(""Case #"" + i + "": "" + answer); outputWriter.write(""Case #"" + i + "": "" + answer); outputWriter.newLine(); } System.out.println(""Done""); // Close the input stream in.close(); // Close the output stream outputWriter.close(); } catch (IOException e) // Catch exception if any { System.err.println(""IO Error: "" + e.getMessage()); } catch (Exception e) // Catch exception if any { System.err.println(""Error: "" + e.getMessage()); } } public static int getString(String inputString, long startNum, long endNum) { //System.out.println(""Input string is "" + inputString); int length = inputString.length(); int varLength = length; int tempLength = 0; boolean flag = true; int answer = 0; for (int i = 0; i < inputString.length() - 1; i++) { if (inputString.charAt(i) != inputString.charAt(i + 1)) { flag = false; } } if (flag == true) { //System.out.println(""found same digit number""); return 0; } String temp1 = null; String temp2 = null; String newString = null; for (int i = 0; i < length; i++) { tempLength = length - (i + 1); //System.out.println(""varLEnth = "" + varLength + "" tempLength = "" //+ tempLength); if (varLength > tempLength && tempLength != 0) { temp1 = inputString.substring(varLength - 1, length); //System.out.println(""1 = "" + temp1); temp2 = inputString.substring(0, varLength - 1); //System.out.println(""2 = "" + temp2); varLength--; if (temp1.charAt(0) != '0') { newString = temp1 + temp2; } else { //System.out.println(""found leading 0""); newString = null; } //System.out.println(""input string is "" + inputString); //System.out.println(""new string is "" + newString); if (newString != null && Long.valueOf(newString) <= endNum && Long.valueOf(newString) > Long.valueOf(inputString)) { answer++; //System.out.println(""answer incremented by one "" + answer); } } } return answer; } } " B11130,"package com.codegem.zaidansari; import java.io.File; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; class Pair { int n, m; public Pair(int n, int m) { super(); this.n = n; this.m = m; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * (m + n); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if ((m == other.m && n == other.n) || (m == other.n && n == other.m)) return true; return false; } @Override public String toString() { return ""Pair [n="" + n + "", m="" + m + ""]""; } } public class ProblemC { Set pairs = new HashSet(); int startRange, endRange; private boolean isInRange(int value) { return value >= startRange && value <= endRange; } private int processRange() { for (int value = startRange; value <= endRange; value++) { List possiblePairValues = getPossiblePairValue(value); for (int pairValue : possiblePairValues) { pairs.add(new Pair(value, pairValue)); } } return pairs.size(); } private List getPossiblePairValue(int value) { String valueStr = String.valueOf(value); int valueStrLength = valueStr.length(); List possiblePairs = new ArrayList(); int pairValue; for (int index = 0; index < valueStrLength; index++) { String pairValueStr = valueStr.substring(valueStrLength - index - 1) + valueStr.substring(0, (valueStrLength - index - 1)); if (pairValueStr.charAt(0) != '0') { pairValue = Integer.parseInt(pairValueStr); if ((pairValue != value) && (isInRange(pairValue))) { possiblePairs.add(pairValue); } } } return possiblePairs; } public ProblemC(int startRange, int endRange) { super(); this.startRange = startRange; this.endRange = endRange; } public static void main(String[] args) { File file = new File(""/Users/zaansari/Desktop/CodeGem2012/InputFiles/ProblemC-Small.txt""); List inputData = CodeGemUtil.getInputValues(file); int noOfInputs = Integer.parseInt(inputData.get(0)); inputData.remove(0); List outputData = new ArrayList(); for (int index = 0; index < noOfInputs; index++) { String[] inputArray = inputData.get(index).split("" ""); outputData.add("""" + new ProblemC(Integer.parseInt(inputArray[0]), Integer.parseInt(inputArray[1])).processRange()); } boolean createdOutputFile = CodeGemUtil.createOutputFile(outputData, ""ProblemC-Small-Output.txt""); if (createdOutputFile) { System.out.println(""Successfully created output file""); } else { System.out.println(""Failed to create output file""); } } } " B10933,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.StringTokenizer; public class RecycledNumbers { public static ArrayList palindroms = new ArrayList(); public static void main(String[] args) throws FileNotFoundException, IOException { File inFile = new File(""/Users/johannesvietze/Desktop/C-small-attempt0.in""); //read StringTokenizer tok = new StringTokenizer(getContents(inFile),""\n""); tok.nextToken(); //delete first token String result = """"; int counter = 1; //compute while(tok.hasMoreTokens()){ String in = tok.nextToken(); //next line String[] current = in.split("" ""); int a = Integer.parseInt(current[0]); int b = Integer.parseInt(current[1]); double res = 0; palindroms.clear(); for(int n = a; n <= b; n++){ if(n >= 10){ res += getNumberOfRecycledNumbers(a, b, n); } } DecimalFormat df = new DecimalFormat(""#""); result += ""Case #"" + counter++ + "": ""; result += df.format(res); result += ""\n""; } //System.out.println(result); //write File outFile = new File(""/Users/johannesvietze/Desktop/C-small-attempt0.out""); setContents(outFile, result); } public static double getNumberOfRecycledNumbers(int min, int max, int in){ double result = 0; String currentS = Integer.toString(in); int length = currentS.length(); for (int i = 0; i < length; i++) { currentS = currentS.charAt(length-1) + currentS.substring(0, length-1); if(Integer.parseInt(currentS) <= max && Integer.parseInt(currentS) > min && in < Integer.parseInt(currentS)){ if(isPalindrom(String.valueOf(in) + currentS)){ if(!palindroms.contains(Integer.parseInt(String.valueOf(in) + currentS))){ palindroms.add(Integer.parseInt(String.valueOf(in) + currentS)); result++; } }else{ result++; } } } return result; } public static boolean isPalindrom(String s){ return s.equals(new StringBuffer(s).reverse().toString()); } public static String getContents(File aFile) { StringBuilder contents = new StringBuilder(); try { BufferedReader input = new BufferedReader(new FileReader(aFile)); try { String line = null; while (( line = input.readLine()) != null){ contents.append(line); contents.append(System.getProperty(""line.separator"")); } } finally { input.close(); } } catch (IOException ex){ ex.printStackTrace(); } return contents.toString(); } public static void setContents(File aFile, String aContents) throws FileNotFoundException, IOException { Writer output = new BufferedWriter(new FileWriter(aFile)); try { output.write( aContents ); } finally { output.close(); } } } " B12009,"import java.io.File; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Recycle { static Set chosen ; static int a = 0; static int b = 0; public static PrintWriter pw; public static void main(String[] args) throws Exception { try{ File f = new File(""\\\\filesrv/stufiles$/matt.tough/out.txt""); f.createNewFile(); pw = new PrintWriter(f); }catch(Exception e){ } Scanner in = new Scanner(new File(""\\\\filesrv/stufiles$/matt.tough/C-small-attempt0.in"")); //Scanner in = new Scanner(System.in); String line = in.nextLine(); int cases = Integer.parseInt(line); for (int t=0; t < cases; t++){ line = in.nextLine(); Scanner thisLine = new Scanner (line); a = thisLine.nextInt(); b = thisLine.nextInt(); int minDigits = ((int)Math.floor(Math.log10(a)))+1; int maxDigits = ((int)Math.floor(Math.log10(b)))+1; int count = 0; chosen = new HashSet(); for (int digits = minDigits; digits <= maxDigits; digits++){ if (digits < 2){ count += 0; }else{ int minNum =(int) Math.pow(10, digits-1); int maxNum =(int) Math.pow(10, digits); for (int i = minNum; i < maxNum; i++){ if(i > b){ break; } if(i>=a){ String thisNum = i+""""; count += countPairsAdded(thisNum); } } } } pw.printf(""Case #%d: %d\n"", t+1,count); } pw.flush(); } public static int countPairsAdded(String s){ int count =0; int num = Integer.parseInt(s); if (chosen.contains(num)) return 0; for (int shift = 0; shift < s.length() ; shift++){ String test = shift(s,shift); int i = Integer.parseInt(test); if(i <= b && i >=a && i != num && !chosen.contains(i)){ //System.out.println(test); count++; chosen.add(i); } } //System.out.println(count); count *= count+1; count /=2; return count; } public static String shift(String s, int shift){ return s.substring(shift) + s.substring(0,shift); } } " B11045," public class Code3DataStructure { private int a; private int b; private int result; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getResult() { return result; } public void setResult(int result) { this.result = result; } private static int denomination(int baseDenomination, int amount) { int denomination = 1; for (int i = 0; i < amount; i++) { denomination*=baseDenomination; } return denomination; } private static int rotateNumber(int m,int chunkSize) { int chunk = m%(denomination(10,chunkSize)); int leftover = m/(denomination(10,chunkSize)); int leftoverSize = (leftover+"""").length(); int output = chunk*(denomination(10,leftoverSize))+leftover; return output; } public static void main(String[] args) { int x = rotateNumber(12345, 3); System.out.println(x); } } " B12448,"package qual; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; public class C { public static int[] prepare(int m, int base, int k){ int[] res = new int[m]; for (int i = 0; i < m; i++){ int rest = k % 10; k /= 10; k += rest * base; res[i] = k; } return res; } public static void main(String[] args) throws Exception{ String in_file = ""q/c/s_in.txt""; String out_file = in_file.replace(""_in.txt"", ""_out.txt""); BufferedReader in = new BufferedReader(new FileReader(in_file)); BufferedWriter out = new BufferedWriter(new FileWriter(out_file)); int n = Integer.parseInt(in.readLine()); for (int i = 1; i <= n; i++){ String[] s = in.readLine().split("" ""); int a = Integer.parseInt(s[0]); int b = Integer.parseInt(s[1]); int count = 0; int base = 1; int m = 0; while (base * 10 <= a) { base *= 10; m++; } for (int k = a; k < b; k++){ int[] prob = prepare(m, base, k); for (int p : prob){ if (p > k && p <= b) count++; } } out.write(""Case #"" + i + "": "" + count + ""\n""); } in.close(); out.close(); } } " B11252,"/** * @author ShengMin Zhang * @revision 1.0 * - brute force naive solution to make it work for the small input size */ import java.io.*; import java.util.*; public class Sample { boolean isRecycledPair(int n, int m) { String sn = Integer.toString(n); String sm = Integer.toString(m); if(sn.length() != sm.length()) return false; for(int i = 1; i < sn.length(); i++) { String newString = sn.substring(i) + sn.substring(0, i); if(newString.equals(sm)) return true; } return false; } int solve (int A, int B) { int count = 0; for(int n = A; n < B; n++) { for(int m = n + 1; m <= B; m++) { if(isRecycledPair(n, m)) count++; } } return count; } void run(BufferedReader rd) throws Exception { int T = Integer.parseInt(rd.readLine()); PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); for(int i = 1; i <= T; i++) { StringTokenizer st = new StringTokenizer(rd.readLine()); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); writer.printf(""Case #%d: %d"", i, solve(A, B)); writer.println(); } rd.close(); writer.close(); } public static void main(String[] args) throws Exception { BufferedReader rd = new BufferedReader(new InputStreamReader(System.in)); new Sample().run(rd); } } " B10162,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; public class QRProblemC { public static void main(String[] args) { try { char problem = 'C'; int attempt = 1; BufferedReader input = new BufferedReader(new FileReader(problem + ""-small-attempt"" + attempt + "".in"")); BufferedWriter output = new BufferedWriter(new FileWriter(problem + ""-small-attempt"" + attempt + "".out"")); int lines = Integer.parseInt(input.readLine()); for (int i = 0; i < lines; i++) { String in = input.readLine(); System.out.println(in); String out = """"; //Code here String[] numbers = in.split("" ""); int A = Integer.parseInt(numbers[0]); int B = Integer.parseInt(numbers[1]); int count = 0; for (int n = A; n < B; n++) { for (int m = n + 1; m <= B; m++) { String goal = Integer.toString(m); String start = Integer.toString(n); while (start.length() < goal.length()) start = ""0"" + start; for (int j = 1; j < start.length(); j++) { if (start.charAt(j) == goal.charAt(0)) { if (goal.equals(start.substring(j) + start.substring(0, j))) { count++; break; } } } } } out = Integer.toString(count); //End code out = ""Case #"" + (i + 1) + "": "" + out.trim(); System.out.println(out); output.append(out); if (i < lines - 1) output.append(""\n""); } input.close(); output.close(); } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); } } } " B10010,"package google.codejam.com; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.StringTokenizer; public class Solution { public static void main(String[] args) { BufferedReader f = null; PrintWriter out = null; try { f = new BufferedReader(new FileReader(""in.txt"")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { out = new PrintWriter(new BufferedWriter(new FileWriter(""out.txt""))); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { // SOLUTION STARTS HERE int count = new Integer(f.readLine()); for (int i = 1; i <= count; i++) { long sum = 0L; String[] in = f.readLine().split("" ""); int from = new Integer(in[0]); int to = new Integer(in[1]); for (int num = from; num <= to; num++) { String toStr = new Integer(to).toString(); String numStr = new Integer(num).toString(); sum += getSum(numStr, toStr); } out.write(""Case #"" + i + "": "" + sum + ""\n""); System.out.println(""Case #"" + i + "": "" + sum); } // SOLUTION ENDS HERE out.flush(); out.close(); f.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static long getSum(String numStr, String toStr) { String conn = """"; conn = numStr + numStr; HashSet set = new HashSet(); for (int i = 0; i < numStr.length(); i++) { String cand = conn.substring(i, i + numStr.length()); if(cand.compareTo(numStr) > 0 && cand.compareTo(toStr) <= 0) set.add(cand); } return set.size(); } } " B11965,"import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { BufferedReader in; StringTokenizer st; PrintWriter out; private String inFilename = ""in.txt""; private String outFilename = ""out.txt""; boolean can(int a, int b) { String s1 = String.valueOf(a); String s2 = String.valueOf(b); if (s1.length() != s2.length()) return false; for (int i = 1; i < s1.length(); ++i) { String q = s1.substring(i) + s1.substring(0, i); if (q.equals(s2)) return true; } return false; } void solve() throws IOException { int n = ni(); for (int t = 1; t <= n; ++t) { int a = ni(); int b = ni(); int ret = 0; for (int i = a; i <= b; ++i) for (int j = i + 1; j <= b; ++j) { if (can(i, j)) ++ret; } out.println(""Case #"" + t + "": "" + ret); } } public Main() throws IOException { Locale.setDefault(Locale.US); in = new BufferedReader(new FileReader(inFilename)); out = new PrintWriter(outFilename); solve(); in.close(); out.close(); } String ns() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int ni() throws IOException { return Integer.valueOf(ns()); } double nd() throws IOException { return Double.valueOf(ns()); } long nl() throws IOException { return Long.valueOf(ns()); } public static void main(String[] args) throws IOException { new Main(); } } " B12476,"package codejam.recyclednumbers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import codejam.common.AbstractProblemSolver; public class RecycledNumbersProblemSolver extends AbstractProblemSolver { @Override public RecycledNumbersProblem readProblem(BufferedReader reader) throws IOException { return new RecycledNumbersProblem(reader.readLine()); } @Override public Integer solveProblem(RecycledNumbersProblem problem) { return problem.solve(); } @Override public void writeSolution(int solutionNumber, Integer solution, BufferedWriter writer) throws IOException { writer.append(""Case #"" + solutionNumber + "": ""); writer.append(solution.toString()); writer.newLine(); } public static void main(String[] args) { new RecycledNumbersProblemSolver().solve(new File( ""D:/code/codejam/resources/numbers-input.txt""), new File( ""D:/code/codejam/resources/numbers-output.txt"")); } } " B13106,"package com.g0414.a; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; public class Problem { public final String FILE_PATH = ""C:/data/workspace/googleCodeJam/src/"" + ""com/g0414/a/""; public final String FILE_BASE = ""A-small-attempt0""; // public final String FILE_BASE = ""sample""; public final String INPUT_FILE = FILE_PATH + FILE_BASE + "".in""; public final String OUTPUT_FILE = FILE_PATH + FILE_BASE + "".txt""; long testN = -1; ArrayList testList = new ArrayList(); public static void main(String[] args) { try { Problem p = new Problem(); p.init(); p.printResult(); p.end(); } catch (Exception e) { e.printStackTrace(); } } public void printResult() throws ProblemException { long i = 1; for (Test p : testList) { prlong(""Case #"" + i + "": "" + p.check()); i++; } } public static boolean flag = true; FileWriter outputFile = null; public void prlong(String str) throws ProblemException { try { // ƒtƒ@ƒCƒ‹‚̍폜Aƒtƒ@ƒCƒ‹‚̐V‹KƒI[ƒvƒ“ if (flag) { flag = false; File fw01 = new File(OUTPUT_FILE); fw01.delete(); outputFile = new FileWriter(OUTPUT_FILE, true); } outputFile.write(str + ""\r\n""); System.out.println(str); } catch (IOException e) { throw new ProblemException(e.getMessage(),e); } } public void end() throws ProblemException { try { outputFile.close(); } catch (IOException e) { throw new ProblemException(e.getMessage(),e); } } public void init() throws ProblemException { try { FileReader in = new FileReader(INPUT_FILE); BufferedReader br = new BufferedReader(in); String line; testN = Long.parseLong(br.readLine()); while ((line = br.readLine()) != null) { String[] ch = line.split("" ""); System.out.println(line); /* ch = line.split("" ""); long n = Long.parseLong(ch[0]); long s = Long.parseLong(ch[1]); long p = Long.parseLong(ch[2]); ArrayList tList = new ArrayList(); for (int i = 3; i < ch.length; i++) { tList.add(Long.parseLong(ch[i])); } */ testList.add(new Test(line.toCharArray())); } br.close(); in.close(); } catch (IOException e) { System.out.println(e); throw new ProblemException(e.getMessage(),e); } } public class Test { char c[]; public Test (char c[]) { this.c = c; } public String check () { char cc[] = new char[c.length]; for (int i = 0; i < c.length; i++) { cc[i] = replace(c[i]); } return """" + new String(cc); } /* Input 3 ejp mysljylc kd kxveddknmc re jsicpdrysi rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd de kr kd eoya kw aej tysr re ujdr lkgc jv Output our language is impossible to understand there are twenty six factorial possibilities so it is okay if you want to just give up */ private char replace (char cc) { switch (cc) { case 'a': return 'y'; case 'b': return 'h'; case 'c': return 'e'; case 'd': return 's'; case 'e': return 'o'; case 'f': return 'c'; case 'g': return 'v'; case 'h': return 'x'; case 'i': return 'd'; case 'j': return 'u'; case 'k': return 'i'; case 'l': return 'g'; case 'm': return 'l'; case 'n': return 'b'; case 'o': return 'k'; case 'p': return 'r'; case 'q': return 'z'; case 'r': return 't'; case 's': return 'n'; case 't': return 'w'; case 'u': return 'j'; case 'v': return 'p'; case 'w': return 'f'; case 'x': return 'm'; case 'y': return 'a'; case 'z': return 'q'; case ' ': return ' '; } return '!'; } @Override public String toString() { String list = """"; for (int i = 0; i < c.length; i++) { list += c[i]; } return ""("" + list + "")""; } } public class ProblemException extends Exception { private static final long serialVersionUID = 2080823058826051635L; public ProblemException(String message) { super(message); } public ProblemException(String message, Throwable e) { super (message, e); } } /* * Case #1: 1 Case #2: 256 Case #3: 4 Case #4: 674 Case #5: 461 * */ } " B11423,"import java.util.*; public class Recycle { public static void main(String args[]) { int uBound, lBound, count=0, caseNo=1; Scanner input = new Scanner(System.in); input.nextLine(); while(true) { lBound = input.nextInt(); uBound = input.nextInt(); for(int i=lBound; i<=uBound; i++) { int numDigits = new Integer(i).toString().length(); int[] pastPairs = new int[numDigits-1]; for(int j=1; ji && rotatedInt<=uBound) { for(int k=0; k out.txt " B12054,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; import java.io.*; /** * * @author Nah-Abiah */ public class recycledNumbers { /** * @param args the command line arguments */ public static void main(String[] args) { try{ FileInputStream fstream = new FileInputStream(""C-small-attempt1.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; int testCount = 0; int caseCount = 1; String writeFile = """"; while ((strLine = br.readLine()) != null) { if(testCount == 0){ testCount = Integer.parseInt(strLine); } else{ String[] ints = strLine.split("" ""); int n = Integer.parseInt(ints[0]); int limit = Integer.parseInt(ints[1]); int num = 0; if(ints[0].length() != 1){ while (n < limit){ int count = 1; while(count < ints[0].length()){ String m = String.valueOf(n).substring(count)+String.valueOf(n).substring(0, count); if((n> possibleNM (int a, int b) { String bStr = Integer.toString( b ); HashMap> map = new HashMap>(); for ( int i = a; i < b; i++){ LinkedList list = new LinkedList(); if ( Integer.toString(i).length() > bStr.length()) break; for ( int j = i + 1; j <= b; j++) list.add( j ); map.put( i, list); } return map; } public static void main (String[] args) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(""recycle.in"")); int T = Integer.parseInt(reader.readLine()); int output = 0; int a,b; HashMap> possibleNM; LinkedList list; for ( int i = 0; i < T; i++){ StringTokenizer st= new StringTokenizer(reader.readLine()); a = Integer.parseInt( st.nextToken() ); b = Integer.parseInt( st.nextToken() ); possibleNM = possibleNM(a,b); for ( int j = a; j = mul * 10) { mul *= 10; ++pow; } int ans = 0; int[] lastSeen = new int[b + 1]; for (int i = a; i <= b; ++i) { if (i == mul * 10) { mul *= 10; ++pow; } int temp = i; for (int j = 0; j < pow; ++j) { temp = temp / 10 + mul * (temp % 10); if (temp > i && temp <= b && lastSeen[temp] < i) { ++ans; lastSeen[temp] = i; } } } out.println(ans); } @Override public void run() { in = new MyScanner(); try { out = new PrintWriter(new File(""C-small-attempt0.out"")); } catch (FileNotFoundException e) { e.printStackTrace(); } int tests = in.nextInt(); for (int i = 0; i < tests; ++i) { out.print(""Case #"" + (i + 1) + "": ""); solve(); } in.close(); out.close(); } public static void main(String[] args) { new C().run(); } class MyScanner { private BufferedReader br; private StringTokenizer st; public MyScanner() { try { br = new BufferedReader(new FileReader(""C-small-attempt0.in"")); } catch (FileNotFoundException e) { e.printStackTrace(); } } public void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } public boolean hasNext() { while (st == null || !st.hasMoreTokens()) { try { String s = br.readLine(); if (s == null) { return false; } st = new StringTokenizer(s); } catch (IOException e) { e.printStackTrace(); return false; } } return st != null && st.hasMoreTokens(); } private String next() { while (st == null || !st.hasMoreTokens()) { try { String s = br.readLine(); if (s == null) { return null; } st = new StringTokenizer(s); } catch (IOException e) { e.printStackTrace(); return null; } } return st.nextToken(); } public String nextLine() { try { st = null; return br.readLine(); } catch (IOException e) { e.printStackTrace(); return null; } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }" B10161,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; public class crazysolution { /** * @param args * @throws IOException * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException, IOException { // TODO Auto-generated method stub // Scanner sc = new Scanner(System.in); // int N = Integer.parseInt(sc.nextLine()); //System.out.println(getContents(new File(""B-small-attempt1.in""))); setContents(new File(""C-small-attempt.out""),getContents(new File(""C-small-attempt0.in""))); /*System.out.println(getContents(new File(""in""))); setContents(new File(""out""),getContents(new File(""in"")));*/ // File(""A-small-attempt2.in"")); // System.out.println(isSurprising(8,10,8)); //digitsReplacement(""1114""); } public static int recycledNumber(String str) { int counter=0; String[] input = str.split("" ""); int A = Integer.parseInt(input[0]); // lower bound int B = Integer.parseInt(input[1]); // upper bound HashMap tHashMap = new HashMap(); HashSet tHashSet = new HashSet(); for (int i=A; i<=B;i++){ //tHashSet.add(i); tHashMap.put(Integer.toString(i),0); } for (int i=A; i<=B;i++){ String numberStr = Integer.toString(i); String newNumberStr = null; int sizeNumberStr = numberStr.length(); for (int j=1; j testNum) && (newNum <= B)) { boolean bool = false; for (int k = 0; k < index; k++) { if (testing[k] == newNum) { // System.out.println(""fuckfuckfuckfuckfuckfuckfuck""); bool = true; break; } } if (bool == false) { pairs++; testing[index] = newNum; index++; } } } testNum++; } out.write(""Case #"" + (i+1) + "": "" + pairs + ""\n""); i++; } in.close(); out.close(); } }" B11470,"import java.util.HashMap; import java.util.Scanner; public class C1 { public static void main(String arg[]){ Scanner in=new Scanner(System.in); int T= in.nextInt(); for(int i=1;i<=T;i++){ int A = in.nextInt(); int B = in.nextInt(); int count =0; //System.out.println(A); //System.out.println(B); HashMap map = new HashMap(); int no=0; int temp=A; //int temp=0; while(temp>0){ if((temp=temp/10)>0) no++; } //System.out.println(no); for(int n = A;n<=B;n++){ int a=1; while(a<=no){ int m=(int) ((n/Math.pow(10,a)) + (n%Math.pow(10,a))*Math.pow(10,(no-a+1))); a++; if((m<=B)&&(m>n)){ if(!(map.containsKey(n)&&(map.get(n)==m))){ //System.out.println(n+"" ""+m); count++; map.put(n,m); } //else //System.out.println(n+"" ""+m); } } } System.out.println(""Case #""+i+"": ""+count); } } }" B12447,"import java.util.*; import java.io.*; public class recycled { public static void main(String[] args) throws IOException { BufferedReader baca= new BufferedReader(new InputStreamReader(System.in)); int T= Integer.parseInt(baca.readLine()); for(int i=1; i<=T; i++) { StringTokenizer token= new StringTokenizer(baca.readLine()); int A= Integer.parseInt(token.nextToken()); int B= Integer.parseInt(token.nextToken()); int count=0; for(int n=A; n 0) { digits[size] = candidate % 10; candidate /= 10; size++; } if(size > 1) { for(int j=0; j=0; k--) { part1 = part1 * 10 + digits[k]; } for(int k=size-1; k>j; k--) { part2 = part2 * 10 + digits[k]; } if(part1 != 0) { int value = part1 * basePower[size-1-j] + part2; if(value >= A && value <=B && !mask.get(value)) { nCandidates++; mask.set(value); } } } count += (nCandidates-1) * nCandidates/2; } } return count; } public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new FileReader(""C-small-attempt0.in"")); PrintWriter out = new PrintWriter(new FileWriter(""C.out"")); String line = in.readLine(); int T = Integer.parseInt(line); for(int i=1; i<=T; i++) { line = in.readLine(); String[] comp = line.split(""\\s+""); int A = Integer.parseInt(comp[0]); int B = Integer.parseInt(comp[1]); out.print(""Case #"" + i+ "": ""); out.println(solve(A, B)); } out.flush(); in.close(); out.close(); } } " B11934,"import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String line = scanner.nextLine().trim(); int totalCase = Integer.parseInt(line); for (int i = 1; i <= totalCase; i++) { line = scanner.nextLine().trim(); String parts[] = line.split("" +""); int min = Integer.parseInt(parts[0]); int max = Integer.parseInt(parts[1]); int numOfDigits = ("""" + min).length(); int total = 0; for (int num = min; num <= max; num++) { String numString = """" + num; for (int index = 1; index < numOfDigits; index++) { String numPart1 = numString.substring(0, index); String numPart2 = numString.substring(index); String newNumString = numPart2 + numPart1; int newNum = Integer.parseInt(newNumString); if (newNum > num && newNum <= max && num >= min) { // System.out.println(""("" + num +"","" + newNum + "")""); total++; } } } String output = ""Case #"" + i + "": "" + total; System.out.println(output); } System.exit(0); } } " B12043,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.util.*; public class Main { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new FileReader(args[0])); FileWriter out = new FileWriter(args[1]); int T = Integer.parseInt(in.readLine()); for (int t = 1; t <= T; t++) { String data[] = in.readLine().split(""\\ ""); int A = Integer.parseInt(data[0]); int B = Integer.parseInt(data[1]); Set checked = new LinkedHashSet(); int recycledPairNumber = 0; for (int i = A; i <= B; i++) { if (checked.contains(i)) continue; String s = Integer.toString(i); String ss = s + s; Set recycled = new LinkedHashSet(); recycled.add(i); for (int j = 0; j < s.length(); j++) { int candidate = Integer.parseInt(ss.substring(j, j + s.length())); if (candidate >= A && candidate <= B) recycled.add(candidate); } if (recycled.size() == 1) continue; checked.addAll(recycled); recycledPairNumber += (recycled.size() * (recycled.size() - 1)) / 2; } out.write(""Case #"" + t + "": "" + recycledPairNumber + ""\n""); } in.close(); out.close(); } } " B11295,"import java.util.Scanner; public class prob_3 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int cases = in.nextInt(); for (int index = 0; index < cases; index++) { int A = in.nextInt(); int B = in.nextInt(); int possiblePermutations = (A + """").length() - 1; String parse; int count = 0; int m; int[] perms; for (int n = A; n < B; n++) { perms = new int[possiblePermutations]; for (int i = 0; i < possiblePermutations; i++) { parse = n + """"; parse = parse.substring(i + 1) + parse.substring(0, i + 1); m = Integer.parseInt(parse); perms[i] = m; if ((n < m) && (m <= B)) if (counted(perms, i)) count++; } } System.out.println(""Case #"" + (index + 1) + "": "" + count); } } private static boolean counted(int[] perms, int i) { for (int j = 0; j < i; j++) if (perms[i] == perms[j]) return false; return true; } }" B11296,"package codejam2012.qualified; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; public class ProblemC { static BitSet bit = new BitSet(); static BufferedReader buffReader = null; static BufferedWriter buffWriter = null; static FileReader fileReader = null; static FileWriter fileWriter = null; static String input_test = ""/home/qimeng/problemC.test""; static String input_small = ""/home/qimeng/C-small-attempt0.in""; static String input_large = ""/home/qimeng/C-large.in""; static int com = 0; static int result = 0; // static int a = 0; // static int b = 0; static HashMap hashMap = new HashMap(); public static final void main(String[] args){ try { //fileReader = new FileReader(input_test); fileReader = new FileReader(input_small); //fileReader = new FileReader(input_large); buffReader = new BufferedReader(fileReader); fileWriter = new FileWriter(""/home/qimeng/problemC.out""); buffWriter = new BufferedWriter(fileWriter); int total_size = Integer.parseInt(buffReader.readLine()); //iterate through every input line for(int i=1; i<=total_size; i++){ String[] str = buffReader.readLine().split("" ""); int a = Integer.parseInt(str[0]); int b = Integer.parseInt(str[1]); System.out.println(""Case #"" +i+"": "" + recycleAlgorithm(a,b)); buffWriter.write(""Case #"" +i+"": "" + recycleAlgorithm(a,b)); buffWriter.newLine(); buffWriter.flush(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { buffWriter.flush(); buffWriter.close(); buffReader.close(); fileReader.close(); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } public static int recycleAlgorithm(int a,int b){ int count=0; for (int i=b;i>=a;i--){ ArrayList permutations = getPermutations(i+""""); for (Integer ti : permutations){ if (ti>=a && ti<=b && ti getPermutations(String i){ ArrayList permutations = new ArrayList(); String shift=i.substring(1)+i.substring(0,1); while (!shift.equalsIgnoreCase(i)){ int parsedInt=Integer.parseInt(shift); int digits=new String(parsedInt+"""").length(); if (digits==i.length()){ permutations.add(parsedInt); } shift=shift.substring(1)+shift.substring(0,1); } return permutations; } // private static int recycleAlgorithm(int a, int b){ // result = 0; // // for(int i=a; i<=b; i++){ // com = 0; // String str_i = Integer.toString(i); // int len_i = str_i.length(); // // chars --> all combinations // // all combinations --> numbers // // // // for all numbers: // // check each number if in range // // if so, setbit(number), com++ // // // //result + all pairs from com // showPattern("""", str_i); // // } // // return result; // } // private static void showPattern(String st, String chars) { // if (chars.length() <= 1){ // //System.out.println(st + chars); // int num = Integer.parseInt(st+chars); // if(num>= a && num<=b){ // bit.set(num); // } // com++; // } // else{ // for (int i = 0; i < chars.length(); i++) { // try { // String newString = chars.substring(0, i) // + chars.substring(i + 1); // showPattern(st + chars.charAt(i), newString); // } catch (Exception e) { // e.printStackTrace(); // } // } // } // } // private static int permutation(int x){ // return fact(x) / fact(x-2); // } // private static int fact(int x) { // if(hashMap.containsKey(x)){ // return hashMap.get(x); // } // else { // int re = 0; // if(x == 0) return 0; // else if(x == 1) return 1; // else { // re = x*fact(x-1); // hashMap.put(x, re); // return re; // } // } // } } " B10801,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package googlecodejam2012; import java.io.*; import java.util.HashSet; /** * * @author Stephen */ public class GoogleCodeJam2012Num3 { /** * @param args the command line arguments */ public static void main(String[] args) { try { FileInputStream fs = new FileInputStream(""input.txt""); DataInputStream in = new DataInputStream(fs); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter fws = new FileWriter(""output.txt""); BufferedWriter out = new BufferedWriter(fws); String numLine = br.readLine(); System.out.println(numLine); int numCases = Integer.parseInt(numLine); String caseLine; for(int i = 1; i <= numCases; i++) { caseLine = br.readLine(); System.out.println(""Case #""+i); String[] splitted = caseLine.split("" ""); int A = Integer.parseInt(splitted[0]); int B = Integer.parseInt(splitted[1]); System.out.println(A+"" <= n < m <= ""+B); int numLength = String.valueOf(A).length(); System.out.println(""Length of number: ""+numLength); int powerThing = 1; for(int a = 1; a < numLength; a++) powerThing*=10; System.out.println(""Power Multiplier: ""+powerThing); int numPairs = 0; for(int n = A; n < B; n++) { int m = n; HashSet ht = new HashSet(); for(int k = 0; k < numLength; k++) { int rem = m%10; m = m/10+rem*powerThing; if(m <= B && m > n && !ht.contains(m)) { ht.add(m); numPairs++; } } } System.out.println(""Pairs: ""+numPairs); out.write(""Case #""+i+"": ""+numPairs+""\r\n""); } in.close(); out.close(); displayOutput(); } catch (Exception e) { System.err.println(""Oops! Error occured: "" + e.getMessage()); } } public static String gDecode(String input) { String decoded = """"; for(int i = 0; i < input.length(); i++) { if(input.charAt(i) == ' ') decoded += ' '; else decoded += decodeChar(input.charAt(i)-'a'); } return decoded; } public static String googleKey = ""yhesocvxduiglbkrztnwjpfmaq""; public static char decodeChar(int encoded) { return googleKey.charAt(encoded); } public static void displayOutput() { System.out.println(""START OUTPUT\n-------------------""); try { FileInputStream fs = new FileInputStream(""output.txt""); DataInputStream in = new DataInputStream(fs); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String readLine; while ((readLine = br.readLine()) != null) { System.out.println(readLine); } } catch (Exception e) { System.err.println(""Oops! Error occured: "" + e.getMessage()); } System.out.println(""---------------------\nEND OUTPUT""); } } " B11344,"import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashSet; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class C { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(in.readLine()); ExecutorService es = Executors.newFixedThreadPool(Math.min(8, n)); @SuppressWarnings(""unchecked"") Future[] fs = new Future[n]; for (int i = 0; i < n; i++) { String[] parts = in.readLine().split("" ""); final int A = Integer.parseInt(parts[0]); final int B = Integer.parseInt(parts[1]); fs[i] = es.submit(new Callable() { public Integer call() { return wastetime(A, B); } }); } for (int i = 0; i < n; i++) { System.out.println(""Case #"" + (i + 1) + "": "" + fs[i].get()); } es.shutdown(); } public static int wastetime(int A, int B) { HashSet answers = new HashSet(); int len = (int) Math.log10(A) + 1; int m; int div = (int) Math.pow(10, len - 1); if (div <= 0) { return 0; } for (int n = A; n < B; n++) { m = n; for (int i = 0; i < len; i++) { m = ((m % div) * 10) + m / div; if (m > n && m <= B) { long ans = ((n & 0xFFFFFFFFl) << 32) + m; //System.out.println(Long.toHexString(ans)); answers.add(ans); } } } return answers.size();// // return div; } }" B10372,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package solution; import com.sun.xml.internal.ws.server.InvokerTube; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.Vector; /** * * @author Aditya */ import java.io.*; import javax.print.DocFlavor; class Test{ int high,low; int ret=0; Vector vi =new Vector(); public int[] getAsIntegerArray(String line){ String[] elems=line.split("" ""); int[] ret=new int[elems.length]; for(int i=0;i0;j--){ ca[j]=ca[j-1]; } ca[0]=temp; k= new Integer(new String(ca)); if((k>i) && (k<=high)){ ret++; System.out.println(i+"" ""+ k); } }while(k!=i); } } } public class Question3 { public static int numInputs; public static Vector cases= new Vector(); public static BufferedReader br ; public static void readInput(){ String s; try{ br=new BufferedReader(new InputStreamReader(System.in));//new BufferedReader(new FileReader(""f:\\test\\asdasd.in"")); if((s=br.readLine())!=null) numInputs=Integer.parseInt(s); while((numInputs-->0) && (s=br.readLine())!=null){ cases.add(new Test(s)); } }catch(IOException ioex){ ; } } public static void process(){ for(Test t:cases){ t.process(); } } public static void printOutput(){ for(int i=0;i done = new HashMap(); for (int j=1;ji && spinned <=m) { if (done.containsKey(String.valueOf(spinned))) continue; done.put(String.valueOf(spinned), null); counter++; } } } writeln(counter); } /** * @param args * @throws IOException * @throws NumberFormatException */ public static void main(String[] args) throws NumberFormatException, IOException { new C().run(); } } " B12822,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recyclednumbers; import java.io.File; import java.io.PrintWriter; import java.util.Scanner; /** * * @author administrator */ public class RecycledNumbers { /** * @param args the command line arguments */ public static void main(String[] args) { String input = ""c:\\input.in""; String output = ""c:\\output.txt""; System.out.println(""Hello World""); RecycledNumbers code1 = new RecycledNumbers(); File in = new File(input); File out = new File(output); code1.getFileContents(in, out, ""UTF-8""); } public void getFileContents(File input, File output, String charSet) { String temp = """"; try { Scanner scanner = new Scanner(input, charSet); PrintWriter out = new PrintWriter(output); int count = 0; int test_case = 0; while (scanner.hasNext()) { int A = 0, B = 0; String test = scanner.nextLine(); if (count == 0) { test_case = Integer.parseInt(test); count++; } else { String[] line_data = test.split(""\\s""); A = Integer.parseInt(line_data[0]); B = Integer.parseInt(line_data[1]); int result = 0; if (A > B) { int t = A; A = B; B = t; } for (int i = A; i < B; i++) { int list[] = getCycledNumbers(i); for (int j = 0; j < list.length; j++) { if (list[j] > i && list[j] <= B) { result++; } } } System.out.println(""Case #"" + count + "": "" + result); if (count == test_case) { out.print(""Case #"" + count + "": "" + result); } else { out.println(""Case #"" + count + "": "" + result); } count++; } temp = temp + ""\n"" + test; } out.close(); scanner.close(); } catch (Exception e) { System.out.println(""File read/write error""); return; } } private int[] getCycledNumbers(int number) { int cycled[]; int recycled[]; String num = String.valueOf(number); cycled = new int[num.length()]; for (int i = 0; i < num.length(); i++) { int part1 = number / (int) Math.pow(10, i); int part2 = number % (int) Math.pow(10, i); cycled[i] = part2 * (int) Math.pow(10, num.length() - i) + part1; } for (int i = 0; i < (num.length() - 1); i++) { for (int j = 0; j < (num.length() - (i + 1)); j++) { if (cycled[j] > cycled[j + 1]) { int temp = cycled[j]; cycled[j] = cycled[j + 1]; cycled[j + 1] = temp; } } } int save = cycled[0]; int final_len = num.length(); for (int i = 1; i < (num.length()); i++) { if (cycled[i] == save) { final_len--; } save = cycled[i]; } if (final_len == num.length()) { return cycled; } recycled = new int[final_len]; save = recycled[0] = cycled[0]; int ctr = 0; for (int i = 1; i < (num.length()); i++) { if (cycled[i] != save) { ctr++; recycled[ctr] = cycled[i]; } save = cycled[i]; } return recycled; } } " B11645,"package com.jp.common; import java.util.HashMap; import com.codejam.two12.GooglerDance.GooglerDance; import com.codejam.two12.RecyledNumbers.RecycledNumbers; import com.codejam.two12.tongue.SpeakingTongues; import com.jp.storeCredit.StoreCredit; public class PuzzleFactory { public static Puzzle getPuzzleSolution(String puzzleName){ HashMap hmPuzzleSolvers = new HashMap(); hmPuzzleSolvers.put(""StoreCredit"", new StoreCredit()); hmPuzzleSolvers.put(""SpeakingTongues"", new SpeakingTongues()); hmPuzzleSolvers.put(""GooglerDance"", new GooglerDance()); hmPuzzleSolvers.put(""RecycledNumbers"", new RecycledNumbers()); return hmPuzzleSolvers.get(puzzleName); } } " B12733,"/** * Created by IntelliJ IDEA. * User: kingsto * Date: 4/15/12 * Time: 1:10 AM * To change this template use File | Settings | File Templates. */ // to be run with -Xmx1024m import java.util.*; import java.io.*; public class RecycledNumbers { class Testcase { int ans; public Testcase() { } public Testcase(int seed) { Random rnd = new Random(seed); } int A, B; public void loadInput(Scanner sc) { A = sc.nextInt(); B = sc.nextInt(); } public void solveSlow() { } private int numRecycled(int num, int a , int b) { LinkedList number = new LinkedList(); int temp = num; while(temp != 0) { int c = temp % 10; temp /= 10; number.addFirst(c); } int res = 0; while (temp != num) { temp = 0; int last = number.pollLast(); number.addFirst(last); for (Integer e: number) temp = 10*temp + e.intValue(); if (temp > num && temp >= a && temp <= b) res++; } return res; } public void solveFast() { for (int i = A; i <= B; i++) { ans += numRecycled(i, A, B); } } public void printSelf(PrintWriter pw) { pw.println(ans); } public boolean sameAnswers(Testcase other) { return false; } } final String AFTER_CASE = "" ""; public void go() throws Exception { Scanner sc = new Scanner(new FileReader(""input.txt"")); PrintWriter pw = new PrintWriter(new FileWriter(""output.txt"")); int caseCnt = sc.nextInt(); for (int caseNum = 0; caseNum < caseCnt; caseNum++) { System.out.println(""solving case "" + caseNum); Testcase tc = new Testcase(); tc.loadInput(sc); tc.solveFast(); pw.print(""Case #"" + (caseNum + 1) + "":""); pw.print(AFTER_CASE); tc.printSelf(pw); } pw.flush(); pw.close(); sc.close(); } public void stresstest() { int it = 0; Random rnd = new Random(); while (true) { it++; if (it % 1000 == 0) System.out.println(it + "" iterations""); int seed = rnd.nextInt(); Testcase tc1 = new Testcase(seed); tc1.solveFast(); Testcase tc2 = new Testcase(seed); tc2.solveSlow(); if (!tc1.sameAnswers(tc2)) { System.out.println(""ERROR: it failed""); System.exit(0); } } } public static void main(String[] args) throws Exception { new RecycledNumbers().go(); } } " B11669,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class RecycledNumbers { public static void main(String[] args){ List res = new ArrayList(); try { FileInputStream fstream = new FileInputStream(""C-small-attempt0 (1).in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); int cases = Integer.valueOf(br.readLine()); for(int i = 0; i < cases; i++) { String line = br.readLine(); int min = Integer.valueOf(line.split(""[ \r\n\t]+"")[0]); int max = Integer.valueOf(line.split(""[ \r\n\t]+"")[1]); res.add(solve(min, max)); } in.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } try { // Create file File fout = new File(""out.txt""); FileWriter fstream = new FileWriter(fout); BufferedWriter out = new BufferedWriter(fstream); for (int i = 0; i < res.size(); i++){ out.write(""Case #"" + (i+1) + "": "" + res.get(i)); out.newLine(); } // Close the output stream out.close(); } catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } static int solve(int min, int max){ //find number of digits int tmp = min; int size = 0; while(tmp > 0){ tmp /= 10; size++; } if(size == 1) return 0; int res = 0; for(int i = min; i <= max; i++){ int[] digits = toDigits(i, size); Set candidates = asNumbers(digits); for(int candidate : candidates){ if(candidate > i && candidate >= min && candidate <= max) res++; } } return res; } static int[] toDigits(int i, int size){ int[] res = new int[size]; int counter = size-1; while(i > 0){ res[counter--] = i%10; i /= 10; } return res; } static Set asNumbers(int[] digits){ Set res = new HashSet(); int tmp = 0; for(int i = 0; i < digits.length; i++){ tmp *= 10; tmp += digits[i]; } for(int i = 0; i < digits.length-1; i++){ int mod = tmp%10; tmp /= 10; for(int j = 0; j < digits.length-1; j++){ mod *= 10; } tmp += mod; res.add(tmp); } return res; } } " B12953,"package google.contest.C; import google.loader.Challenge; import google.problems.AbstractChallenge; import java.util.HashSet; import java.util.Set; public class CChallenge extends AbstractChallenge implements Challenge { private int B; private int A; private int num; Setpairs ; public CChallenge(int number, String line) { super(number); num=0; pairs = new HashSet(); String[] tokens = line.split("" ""); A = Integer.parseInt(tokens[0]); B = Integer.parseInt(tokens[1]); int i=0; for( i=A ; i<=B; i++){ calcFor(i); } setResult(""""+num); } private void calcFor(int i) { String numString = """"+i; for(int j=1; j<= numString.length()-1; j++){ String first = numString.substring(0,j); String second = numString.substring(j); String third = second+first; check(i, third); } } private void check(int i, String third) { if(third.startsWith(""0"")){ return; } int j = Integer.parseInt(third); if(A<=i && i record = new ArrayList(); String input = in.nextLine().trim(); String parts[] = input.split("" ""); int A = Integer.parseInt(parts[0]); int B = Integer.parseInt(parts[1]); int count = 0; if (!(B <= 9)) { int iFliped = 0; String iFlipedString = """"; String iString = """"; for (int i = A; i <= B; i++) { iString = i + """"; int first = 0; int second = 0; for (int j = 1; j < iString.length(); j++) { System.out.println(); first = (int) (i / (Math.pow(10, j))); second = (int) (i % (Math.pow(10, j))); iFlipedString = """" + second + """" + first; iFliped = Integer.parseInt(iFlipedString); if (iFliped <= B && iFliped > i && !iString.equals(iFlipedString) && !record.contains(iString + iFlipedString)) { count++; record.add(iString + iFlipedString); } } } } String output = count + """"; printOut.append(""Case #"" + zz + "": "" + output + ""\n""); } System.setOut(printOut); } } " B12024,"import java.io.File; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class CodejamC { public static final String TEST = ""test.in"", SMALL = ""C-small-attempt0.in"", LARGE = ""C-large.in""; public static final String OUTPUT = ""out.txt""; static int count = 0; public static void main(String[] args) throws Exception { solve(SMALL); } public static void solve(String filename) throws Exception { Scanner in = new Scanner(new File(filename)); int cases = in.nextInt(); in.nextLine(); PrintWriter out = new PrintWriter(new File(OUTPUT)); for(int num = 1; num <= cases; num++) { int a = in.nextInt(); int b = in.nextInt(); count = 0; in.nextLine(); int result = 0; Set perms = new HashSet(); for(int i = a; i <= b; i++) { String str = String.valueOf(i); for(int j = 0; j < str.length(); j++) { String newStr = str.substring(str.length() - j, str.length()) + str.substring(0, str.length() - j); int val = Integer.parseInt(newStr); if(val >= a && val <= b && !newStr.equals(str) && newStr.charAt(0)!='0') { perms.add(new Pair(str, newStr)); } } //perms.remove(str); } result = perms.size(); out.println(""Case #""+num+"": ""+result); System.out.println(""Case #""+num+"": ""+result); } out.close(); } } class Pair { String n, m; public Pair(String str, String newStr) { n = str; m = newStr; } @Override public boolean equals(Object o) { Pair other = (Pair) o; return (n.equals(other.n)&& m.equals(other.m)) || (m.equals(other.n) && n.equals(other.m)); } @Override public int hashCode() { // TODO Auto-generated method stub return n.hashCode() + m.hashCode(); } } " B13097,"package actual; import java.io.*; import java.util.*; public class C { String line; StringTokenizer inputParser; BufferedReader is; FileInputStream fstream; DataInputStream in; void openInput(String file) { //is = new BufferedReader(new InputStreamReader(System.in));//stdin try{ fstream = new FileInputStream(file); in = new DataInputStream(fstream); is = new BufferedReader(new InputStreamReader(in)); }catch(Exception e) { System.err.println(e); } } void readNextLine() { try { line = is.readLine(); inputParser = new StringTokenizer(line, "" ""); //System.err.println(""Input: "" + line); } catch (IOException e) { System.err.println(""Unexpected IO ERROR: "" + e); } } int NextInt() { String n = inputParser.nextToken(); int val = Integer.parseInt(n); //System.out.println(""I read this number: "" + val); return val; } String NextString() { String n = inputParser.nextToken(); return n; } void closeInput() { try { is.close(); } catch (IOException e) { System.err.println(""Unexpected IO ERROR: "" + e); } } public static void main(String [] argv) { C c = new C(argv[0]); } public C(String inputFile) { openInput(inputFile); readNextLine(); int TC = NextInt(); for(int t=0; t all = new ArrayList(); for(int i=1; ia&&b<=B) { if(all.contains(b))continue; all.add(b); ret++; } } return ret; } } " B11190,"package com.google; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; public class Recycle { public static class Pair { long a; long b; public Pair(long a, long b) { this.a = a; this.b = b; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (a ^ (a >>> 32)); result = prime * result + (int) (b ^ (b >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (a != other.a) return false; if (b != other.b) return false; return true; } } public static void main(String[] args) throws IOException { final Scanner reader = new Scanner(new File(""in.txt"")); final FileWriter writer = new FileWriter(new File(""out.txt"")); final int N = reader.nextInt(); reader.nextLine(); for (int i = 0; i < N; i++) { final long min = reader.nextLong(); final long max = reader.nextLong(); writer.write(MessageFormat.format(""Case #{0}: {1}"", (i + 1), findCount(min, max))); if (i < N - 1) { writer.write(""\n""); } } writer.close(); } public static int findCount(final long min, final long max) { Set allPairs = new HashSet(); int resCount = 0; for (long i = min; i <= max; i++) { int [] num = numToArr(i); for (int j = 0; j < num.length - 1; j++) { num = shift(num); final Pair p = new Pair(i, fromArrToNum(num)); if (isValid(num, i, max) && !allPairs.contains(p)) { resCount++; allPairs.add(p); } } } return resCount; } public static int [] shift(int [] num) { final int [] res = new int [num.length]; res[0] = num[num.length - 1]; for (int i = 1; i < res.length; i++) { res[i] = num[i - 1]; } return res; } public static long fromArrToNum(int [] arr) { long a = 0; for (int i : arr) { a = a + i; a = a * 10; } a = a / 10; return a; } public static boolean isValid(int [] num, long base, long max) { if (num[0] == 0) return false; long a = fromArrToNum(num); return base < a && a <= max; } public static boolean consistOfUniqueDigits(int [] num) { final boolean [] arr = new boolean [10]; for (int i : num) { if (arr[i]) return false; arr[i] = true; } return true; } public static int [] numToArr(final long in) { final List list = new ArrayList(); long a = in; while (a > 0) { list.add((int) (a % 10)); a = a / 10; } final int [] res = new int [list.size()]; for (int i = 0; i < list.size(); i++) { res[res.length - i -1] = list.get(i); } return res; } } " B11199,"import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class RecycledNumbers { public static void readInput(String pFileName, List pInputCases) { File tFile = new File(pFileName); try { BufferedReader tBufferedReader = new BufferedReader( new InputStreamReader(new FileInputStream(tFile)), 4096); String tLineRead = tBufferedReader.readLine().trim(); int tCaseSize = Integer.valueOf(tLineRead); int tLineIndex = 0; while(tLineIndex < tCaseSize) { tLineRead = tBufferedReader.readLine().trim(); pInputCases.add(tLineRead); tLineIndex++; } } catch(FileNotFoundException pException) { pException.printStackTrace(); } catch(IOException pException) { pException.printStackTrace(); } } public static void main(String[] pArgs) { if(pArgs.length == 0) { System.out.println(""no input""); return; } List tInputCases = new ArrayList(); readInput(pArgs[0], tInputCases); for(int tCaseIndex = 0; tCaseIndex < tInputCases.size(); tCaseIndex++) { String[] tInputs = tInputCases.get(tCaseIndex).split(""[ ]+""); int tLower = Integer.valueOf(tInputs[0]); int tUpper = Integer.valueOf(tInputs[1]); int tPairs = 0; Map tMapPairs = new HashMap(); for(int tNumber = tLower; tNumber < tUpper; ++tNumber) { int tLength = String.valueOf(tNumber).length(); int tHighUnit = 1; for(int i = 0; i < tLength - 1; ++i) { tHighUnit *= 10; } int tValue = tNumber; int[] tValues = new int[tLength]; tValues[0] = tNumber; for(int i = 1; i < tLength; ++i) { int tHead = tValue / tHighUnit; int tTail = tValue - tHead * tHighUnit; int tNewValue = tTail * 10 + tHead; tValues[i] = tNewValue; tValue = tNewValue; } for(int i = 0; i < tLength - 1; ++i) { for(int j = i + 1; j < tLength; ++j) { int tOldValue = tValues[i]; int tNewValue = tValues[j]; String tKey = tOldValue + ""-"" + tNewValue; if((tOldValue < tNewValue) && (tLower <= tOldValue) && (tNewValue <= tUpper) && (tOldValue != tNewValue)) { if(!tMapPairs.containsKey(tKey)) { ++tPairs; tMapPairs.put(tKey, 1); } } } } } System.out.println(""Case #"" + (tCaseIndex + 1) + "": "" + tPairs); } } } " B10848,"package codejam; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.LinkedList; import java.util.Queue; public class RecycledNumbers { public static void main(String[] args) throws IOException { String fileName = ""C-small-attempt1""; Queue queue = file(""input/""+fileName+"".in""); File outputFile = new File(""result/""+fileName+"".out""); if(!outputFile.exists()) outputFile.createNewFile(); FileOutputStream output = new FileOutputStream(outputFile); int TestCases = Integer.parseInt(queue.poll()); for(int i=0; i < TestCases; i++) { output.write((""Case #""+(i+1)+"": "").getBytes()); int[] input = parseLine(queue.poll()); int A = input[0]; int B = input[1]; int base = (int)Math.log10(A); int count = 0; if(base > 0) { int zeros = (int)Math.pow(10, base); for(int n=A; n <= B; n++) { int m = n; for(int k=0; k < base; k++) { m = m/10 + (m%10)*zeros; if(n < m && m <= B) count++; } } } output.write(Integer.toString(count).getBytes()); output.write('\n'); } } public static int recycleRoutine(int n, int m, int digits) { int count = 0; int base = (int)Math.pow(10, digits-1); for(int i=0; i < digits; i++) { n = n/10 + (n%10)*base; for(int j=0; j < digits; j++) { m = m/10 + (m%10)*base; if(m >= n) count++; } } return count; } public static int[] parseLine(String line) { String[] array = line.split(""\\s""); int[] result = new int[array.length]; for(int i=0; i < result.length; i++) result[i] = Integer.parseInt(array[i]); return result; } /* given a file name ... fetches the file from war folder */ public static byte[] getFile(String fileName) throws IOException { FileInputStream in = new FileInputStream(fileName); int size = in.available(); byte[] imageBytes = new byte[size]; /* read the whole image into array */ int read = 0; while(read < size) read += in.read(imageBytes, read, size-read); return imageBytes; } /* mimic php functions */ public static Queue file(String filename) throws IOException { byte[] fileBytes = getFile(filename); Queue queue = new LinkedList(); StringBuilder builder = new StringBuilder(); for(int i=0; i < fileBytes.length; i++) { if(fileBytes[i] == '\n') { queue.add(builder.toString()); builder.delete(0, builder.length()); continue; } if(fileBytes[i] == '\r') continue; builder.append((char)fileBytes[i]); } return queue; } } " B10090,"package codeJam; import java.util.Scanner; public class C { public static void main(String[] args) { Scanner s = new Scanner(System.in); int testCases = s.nextInt(); for(int i=1; i<=testCases; i++) { int lowerBound = s.nextInt(); int upperBound = s.nextInt(); int midway = (upperBound+lowerBound)/2; int cases=0; for(int j=0; j<=upperBound; j++) { int num = lowerBound+j; String temp = """" + num; for(int k=1; k=lowerBound && check<=upperBound && check!=num && check>num) { cases++; } } } System.out.println(""Case #"" + i + "": "" + cases); } } } " B10296,"package qualifs; import gcj.Gcj; import java.util.HashSet; import java.util.Set; public class C { final private String file; C (String f) { file = f; } public void run() { Gcj gcj = new Gcj(file); gcj.readLine(); int ncase = gcj.iToken(); for (int cas=1 ; cas <= ncase ; cas++) { gcj.readLine(); String A = gcj.sToken(); String B = gcj.sToken(); int a = Integer.parseInt(A); int b = Integer.parseInt(B); int[] aa = gcj.breakdownNumber(A); int[] mm = gcj.breakdownNumber(A); int[] bb = gcj.breakdownNumber(B); int n = aa.length; int count = b-a; int rp = 0; Set dejavu = new HashSet(); if (n >= 2) while (count-- > 0) { for (int c=1 ; c mm[i]) rok = true; } if ( ! bok) { if (mm[p] > bb[i]) break; if (mm[p] < bb[i] || i == n-1) bok = true; } } // dejavu if (rok && bok) { String u="""",v=""""; for (int i=0 ; i=0 ; i--) { if (mm[i] == 9) mm[i] = 0; else { mm[i]++; break; } } } Gcj.outcase(cas, false); System.out.println(rp); } gcj.terminate(); } } " B12872,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class C { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(""C-small-attempt0.in"")); String li; int tcn = Integer.parseInt(in.readLine()); Scanner sc; String A, B, is, tmp; List ar = new ArrayList(); for (int tc = 0; tc < tcn; tc++) { ar.clear(); li = in.readLine(); sc = new Scanner(li); A = sc.next(); B = sc.next(); int a = Integer.parseInt(A), b = Integer.parseInt(B), tmpi; int result = 0; if (a > 9) { for (int i = a; i <= b; i++) { is = String.valueOf(i); if (!isSame(is)) { for (int j = 1, l = is.length(); j < l; j++) { tmp = is.substring(j) + is.substring(0, j); tmpi = Integer.valueOf(tmp); if (i != tmpi) { Pair p = new Pair(i, tmpi); if (!ar.contains(p) && tmpi > a && tmpi < b) { ar.add(p); result++; } } } } } } System.out.println(""Case #"" + (tc + 1) + "": "" + result); } in.close(); } static boolean isSame(String s) { char[] ds = s.toCharArray(); char fd = ds[0]; for (char d : ds) { if (d != fd) return false; } return true; } static class Pair { final int f; final int s; Pair(int f, int s) { this.f = f; this.s = s; } public boolean equals(Object o) { Pair that = (Pair) o; return ((this.f == that.f && this.s == that.s) || (this.f == that.s && this.s == that.f)); } public String toString() { return ""("" + f + "","" + s + "")""; } } } " B11771," public class Number { int A ; int B ; int length ; public Number(String str) { String[] tmpArr = str.split("" ""); A = Integer.parseInt(tmpArr[0]); B = Integer.parseInt(tmpArr[1]); length = tmpArr[0].length(); } public int getRecycledPairCount() { int count = 0 ; for (int i=A; i=pair || pair>maxNumber) { continue; } if (alreadyGet.indexOf(s) > -1) { continue; } pairCount++; alreadyGet.append("" "").append(pair); } return pairCount ; } } " B12295,"/** * Created by IntelliJ IDEA. * User: SONY * Date: 19.02.12 * Time: 13:12 * To change this template use File | Settings | File Templates. */ import java.io.*; import java.util.*; public class Main extends Thread { public Main(String inputFileName, String outputFileName) { try { this.input = new BufferedReader(new FileReader(inputFileName)); this.output = new PrintWriter(outputFileName); this.setPriority(Thread.MAX_PRIORITY); } catch (Throwable e) { System.err.println(e.getMessage()); e.printStackTrace(); System.exit(666); } } static int pow[] = new int[7]; static int transform[][] = new int[2000001][]; static { pow[0] = 1; HashSet helper = new HashSet(); for (int i = 1; i <= 6; ++i) pow[i] = pow[i - 1] * 10; for (int init = 1; init < transform.length; ++init) { int shiftsCount = getDigitsCount(init), n = 0; helper.clear(); for (int currentShift = 1; currentShift < shiftsCount; ++currentShift) { int left = init / pow[currentShift], right = init % pow[currentShift]; int result = right * pow[shiftsCount - currentShift] + left; if (result != init) helper.add(result); } transform[init] = new int[helper.size()]; for (int t : helper) { transform[init][n++] = t; } } } static final int getDigitsCount(int what) { String represents = Integer.toString(what); return represents.length(); } final long doit2() throws Throwable { int A = nextInt(), B = nextInt(); long result = 0; for (int i = A; i <= B; ++i) { for (int j = 0; j < transform[i].length; ++j) { if (transform[i][j] >= A && transform[i][j] <= B) ++result; } } return result / 2; } final String doit(int ID) throws Throwable { return String.format(""Case #%d: %d"", ID, doit2()); } private void solve() throws Throwable { int testCases = nextInt(); for (int i = 1; i <= testCases; ++i) { output.println(doit(i)); } } public void run() { try { solve(); } catch (Throwable e) { System.err.println(e.getMessage()); e.printStackTrace(); System.exit(666); } finally { output.close(); } } public static void main(String... args) { new Main(""input.txt"", ""output.txt"").start(); } private int nextInt() throws IOException { return Integer.parseInt(next()); } private double nextDouble() throws IOException { return Double.parseDouble(next()); } private long nextLong() throws IOException { return Long.parseLong(next()); } private String next() throws IOException { while (tokens == null || !tokens.hasMoreTokens()) { tokens = new StringTokenizer(input.readLine()); } return tokens.nextToken(); } private StringTokenizer tokens; private BufferedReader input; private PrintWriter output; } " B10741,"import java.io.BufferedReader; import java.io.FileReader; public class RecycledNumberTest { public static void main(String[] args) { int numCase = 0; int caseIndex = 0; int[] minValues = null; int[] maxValues = null; try { FileReader reader = new FileReader(""C:\\Users\\CheeMeng\\Downloads\\C-small-attempt1.in""); BufferedReader br = new BufferedReader(reader); String s = br.readLine(); numCase = new Integer(s).intValue(); minValues = new int[numCase]; maxValues = new int[numCase]; while((s = br.readLine()) != null) { String s1[] = s.split("" ""); minValues[caseIndex] = new Integer(s1[0]).intValue(); maxValues[caseIndex] = new Integer(s1[1]).intValue(); caseIndex++; } reader.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // numCase = 4; // minValues = new int[numCase]; // maxValues = new int[numCase]; // minValues[0] = 1; // maxValues[0] = 9; // minValues[1] = 10; // maxValues[1] = 40; // minValues[2] = 100; // maxValues[2] = 500; // minValues[3] = 1111; // maxValues[3] = 2222; for (int i = 1; i <= numCase; i++) { System.out.println(""Case #"" + i + "": "" + recycledTest(minValues[i - 1], maxValues[i - 1])); } } public static int recycledTest(int min, int max) { int count = 0; int numDigits = (int) Math.ceil(Math.log10((float) max)); if (numDigits == 2) { for (int a0 = 1; a0 <= 9; a0++) { for (int a1 = 0; a1 <= 9; a1++) { if (a0 < a1) { int actualNum = 10 * a0 + a1; int recycledNum = 10 * a1 + a0; if ((actualNum >= min) && (actualNum <= max) && (recycledNum >= min) && (recycledNum <= max) && (actualNum < recycledNum)) { count++; } } } } } else if (numDigits == 3) { for (int a0 = 1; a0 <= 9; a0++) { for (int a1 = 0; a1 <= 9; a1++) { for (int a2 = 0; a2 <= 9; a2++) { int actualNum = 100 * a0 + 10* a1 + a2; int recycledNum = 100 * a1 + 10 * a2 + a0; if (a1 > 0) { if ((actualNum >= min) && (actualNum <= max) && (recycledNum >= min) && (recycledNum <= max) && (actualNum < recycledNum)) { count++; } } recycledNum = 100 * a2 + 10 * a0 + a1; if (a2 > 0) { if ((actualNum >= min) && (actualNum <= max) && (recycledNum >= min) && (recycledNum <= max) && (actualNum < recycledNum)) { count++; } } } } } } return count; } } " B13249,"import java.io.BufferedReader; import java.io.InputStreamReader; class RN { private static BufferedReader br = null; private static int numCases; private static int lowerBound, upperBound; private static String[] input; public static void main(String[] args) throws Exception { try { br = new BufferedReader(new InputStreamReader(System.in)); numCases = Integer.parseInt(br.readLine().trim()); for(int i = 0; i < numCases; i++) { int numRecycled = 0; input = br.readLine().split("" ""); lowerBound = Integer.parseInt(input[0]); upperBound = Integer.parseInt(input[1]); for(int j = lowerBound; j < upperBound; j++) { String s = j + """"; for(int k = 0; k < s.length()-1; k++) { String temp = s.substring(s.length()-1-k) + s.substring(0, s.length()-k-1); //System.out.println(""From "" + s + "" to "" + temp + "" with k = "" + k); int num = Integer.parseInt(temp); if(num == j) continue; //if(num >= lowerBound && num <= upperBound && !used[num]) { if(num >= lowerBound && num <= upperBound && num > j) { //System.out.println(""From "" + s + "" to "" + temp + "" with k = "" + k); //System.out.println(""\t"" + j + ""\t"" + num); numRecycled++; //used[num] = true; //used[j] = true; } } } System.out.println(""Case #"" + (i+1) + "": "" + numRecycled); } } catch(Exception e) { e.getMessage(); e.printStackTrace(); } } } " B11571,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; public class C { public static void main(String[] args) { try { BufferedReader input = new BufferedReader(new FileReader(""/home/ramzy/Desktop/codejam/C-small.in"")); PrintWriter output = new PrintWriter(""/home/ramzy/Desktop/codejam/C-small.out""); String line = input.readLine(); int T = Integer.valueOf(line); for(int i = 0; i < T; i++) { line = input.readLine(); String[] numbers = line.split("" ""); int A = Integer.valueOf(numbers[0]); int B = Integer.valueOf(numbers[1]); int result = 0; ArrayList chosen = new ArrayList(); for(int j = A; j <= B; j++) { String str = String.valueOf(j); for(int k = 1; k < str.length(); k++) { int n = Integer.valueOf(str.substring(k) + str.substring(0, k)); if(n >= A && n<= B && n != j && !chosen.contains(n + "" "" + j) && !chosen.contains(j + "" "" + n)) { chosen.add(n + "" "" + j); result++; } } } output.println(""Case #"" + (i+1) + "": "" + result); System.out.println(""Case #"" + (i+1) + "": "" + result); } output.close(); input.close(); } catch(IOException e) { System.err.println(e); } } } " B10160,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package cj2012; /** * * @author aaron */ public class ACj2012 { public static void main(String[] args) { //System.out.println(recyclePairs(""1111 2222"")); dataOut(processData(getData(""C-small-attempt0.in""))); } public static int dataOut(String data){ java.io.BufferedWriter dst; try{ dst = new java.io.BufferedWriter( new java.io.FileWriter(""cj.out"")); dst.write(data); dst.close(); System.out.println(""""); } catch (java.io.IOException e2) { System.out.println(e2.getMessage()); } return 0; } static boolean isDistinct(String str1, String str2,String strlong){ String[] pairs = strlong.split("";""); for (int i = 0 ; i < pairs.length; i++){ if (pairs[i].equals(str1 + "","" + str2)){ return false; } else if (pairs[i].equals(str2 + "","" + str1)){ return false; } } return true; } static int recyclePairs(String data){ int num1 = Integer.valueOf(data.split("" "")[0]); int num2 = Integer.valueOf(data.split("" "")[1]); String distinct = """"; int c = 0; if (num1 >= 10){ for (int i = num1; i <= num2; i++){ for (int j = num1; j <= num2 ; j++){ if (i!=j){ if (isPair(Integer.toString(i),Integer.toString(j))){ if (isDistinct(Integer.toString(i),Integer.toString(j),distinct)){ c++; distinct += Integer.toString(i) + "","" + Integer.toString(j) + "";"" ; } } } } } } return c; } static boolean isPair(String str1, String str2){ String strT = str2; for (int i = 0; i < str1.length() ; i++){ strT = strT.substring(strT.length() -1,strT.length())+strT.substring(0,strT.length()-1); if (strT.substring(0,1).equals(""0"")){ return false; } else if (str1.equals(strT)) { return true; } } return false; } public static String[] getData( String filename){ java.io.BufferedReader src; String str = """"; String[] in = new String[1]; int lines = 0; try{ src = new java.io.BufferedReader(new java.io.FileReader(filename)); str = src.readLine(); lines = Integer.parseInt(str); in = new String[lines]; for (int i = 0; i extends HashMap> { private static final long serialVersionUID = 1L; /** Returns whether the dual map contains the given key in the K1 space */ @Override public boolean containsKey(Object key) { return this.containsKey(key); } public boolean containsKey(K1 key1, K2 key2) { HashMap map2 = this.get(key1); if (map2 == null) return false; else return map2.containsKey(key2); } /** Searches all (K1, K2) pairs to see if any of them map to the value. Runs in O(K1) time. */ public boolean containsValueAll(Object value) { for (HashMap map2 : this.values()) if (map2 != null && map2.containsValue(value)) return true; return false; } public V get(K1 key1, K2 key2) { HashMap map2 = this.get(key1); if (map2 == null) return null; else return map2.get(key2); } public Set keySet(K1 key1) { HashMap map2 = this.get(key1); if (map2 == null) return null; else return map2.keySet(); } public V put(K1 key1, K2 key2, V value) { HashMap map2 = this.get(key1); if (map2 == null) this.put(key1, map2 = new HashMap()); return map2.put(key2, value); } public void putAll(ArrayList> items) { for (Tuple3 item : items) put(item.getField0(), item.getField1(), item.getField2()); } public void putAllListOfLists(ArrayList>>> listOfLists) { for (Pair>> pair1 : listOfLists) { K1 k1 = pair1.getLeft(); for (Pair pair2 : pair1.getRight()) put(k1, pair2.getLeft(), pair2.getRight()); } } @Override public HashMap remove(Object key1) { return this.remove(key1); } public V remove(K1 key1, K2 key2) { HashMap map2 = this.get(key1); if (map2 == null) return null; V ret = map2.remove(key2); if (map2.isEmpty()) this.remove(key1); return ret; } /** Returns size across all (K1, K2) pairs. Runs in O(K1) time. */ public int sizeAll() { int size = 0; for (HashMap map2 : this.values()) if (map2 != null) size += map2.size(); return size; } /** Returns union of values across all (K1, K2) pairs. Runs in O(N) time. */ public HashSet valuesAll() { HashSet values = new HashSet(); for (HashMap map2 : this.values()) if (map2 != null) values.addAll(map2.values()); return values; } /** Returns the map as a list of Tuple3. Runs in O(N) time. */ public ArrayList> getAsList() { ArrayList> result = new ArrayList>(); for (Entry> ent1 : this.entrySet()) { K1 k1 = ent1.getKey(); HashMap map2 = ent1.getValue(); if (map2 != null) { for (Entry ent2 : map2.entrySet()) { K2 k2 = ent2.getKey(); V v = ent2.getValue(); result.add(Tuple3.make(k1, k2, v)); } } } return result; } /** Returns the map as a list of Pair>>. Runs in O(N) time. */ public ArrayList>>> getAsListOfLists() { ArrayList>>> result = new ArrayList>>>(this.size()); for (Entry> ent1 : this.entrySet()) { K1 k1 = ent1.getKey(); HashMap map2 = ent1.getValue(); if (map2 != null) { ArrayList> listOfK2VPairs = new ArrayList>(map2.size()); for (Entry ent2 : map2.entrySet()) { K2 k2 = ent2.getKey(); V v = ent2.getValue(); listOfK2VPairs.add(Pair.make(k2, v)); } result.add(Pair.make(k1, listOfK2VPairs)); } } return result; } } " B11751,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class CodeJamTextOutputWriter { private final BufferedWriter writer; CodeJamTextOutputWriter(File outputFile) throws IOException { writer = new BufferedWriter(new FileWriter(outputFile)); } public void outputTestCase(int num, String out) throws IOException { writer.append(""Case #""); writer.append(Integer.toString(num)); writer.append("": ""); writer.append(out); writer.newLine(); } public void close() throws IOException { writer.close(); } } " B10466,"package com.ravi; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { private static boolean matches(String a, String b) { if (a.equals(b)) { return false; } for (int j = 0; j < a.length(); j++) { if (!b.contains("""" + a.charAt(j))) { return false; } // Remove the matched character b = b.replaceFirst("""" + a.charAt(j), """"); } return true; } private static Integer getRecycledPairs(String A, String B) { int a = Integer.parseInt(A); int b = Integer.parseInt(B); if (a < 10 || b < 10) { return 0; } Set pairs = new HashSet<>(); for (int n = a; n <= b; n++) { for (int m = a + 1; m <= b; m++) { if (n < m) { String nStr = n + """"; String mStr = m + """"; if (matches(nStr, mStr)) { for (int i = 0; i < nStr.length() - 1; i++) { String newNStr = nStr.substring(i + 1) + nStr.substring(0, i + 1); if (newNStr.equals(mStr)) { pairs.add(nStr + "","" + mStr); } } } } } } return pairs.size(); } /** * @param args */ public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); in.nextLine(); for (int i = 1; i <= T; i++) { String thisLine = in.nextLine(); String[] AB = thisLine.split("" ""); System.out.println(""Case #"" + i + "": "" + getRecycledPairs(AB[0], AB[1])); } } }" B12081,"package jp.funnything.competition.util; import java.util.Iterator; /** * Do NOT change the element in iteration */ public class Combination implements Iterable< int[] > , Iterator< int[] > { private final int _n; private final int _k; private int[] _data; public Combination( final int n , final int k ) { if ( k < 0 || k > n ) { throw new IllegalArgumentException(); } _n = n; _k = k; } @Override public boolean hasNext() { return _data == null || _data.length > 0 && _data[ 0 ] < _n - _k; } @Override public Iterator< int[] > iterator() { return this; } @Override public int[] next() { if ( _data == null ) { _data = new int[ _k ]; for ( int index = 0 ; index < _k ; index++ ) { _data[ index ] = index; } } else { int i = 0; while ( i < _k - 1 && _data[ i + 1 ] == _data[ i ] + 1 ) { _data[ i ] = i++; } _data[ i ]++; } return _data; } @Override public void remove() { } } " B12226,"package round1; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.Scanner; public class Recycled { private int noCases; private int[] minBounds; private int[] maxBounds; private int[] noDigits; private void readFile(String filepath) { try { Scanner sc = new Scanner(new FileInputStream(new File(filepath))); noCases = Integer.parseInt(sc.nextLine()); noDigits = new int[noCases]; minBounds = new int[noCases]; maxBounds = new int[noCases]; for (int i = 0; i < noCases; i++) { String[] line = sc.nextLine().split("" ""); noDigits[i] = line[0].length(); minBounds[i] = Integer.parseInt(line[0]); maxBounds[i] = Integer.parseInt(line[1]); } } catch (FileNotFoundException e) { e.printStackTrace(); } } private int answer(int min, int max, int digits) { HashSet pairs = new HashSet(); for (int n = min; n < max; n++) { for (int d = 1; d < digits; d++) { int m = n / (int) Math.pow(10, d) + n % (int) Math.pow(10, d) * (int) Math.pow(10, digits - d); if (m > n && m <= max) { pairs.add(new Pair(n,m)); } } } return pairs.size(); } public static void main(String args[]) { Recycled r = new Recycled(); r.readFile(args[0]); for (int i = 1; i <= r.noCases; i++) { System.out.println(""Case #"" + i + "": "" + r.answer(r.minBounds[i - 1], r.maxBounds[i - 1], r.noDigits[i - 1])); } } private class Pair { int n, m; public Pair(int n, int m) { this.n = n; this.m = m; } @Override public boolean equals(Object o) { if (!(o instanceof Pair)) return false; Pair p = (Pair) o; if (this.n != p.n) return false; if (this.m != p.m) return false; return true; } @Override public int hashCode() { return (n + m) % 3571; } } } " B11503,"package com.prob1; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class ClassB { public static void main(String args[]){ try{ BufferedReader in = new BufferedReader(new FileReader(""D://NewFolder2//C-small-attempt0.in"")); //BufferedReader in = new BufferedReader(new FileReader(""D://NewFolder2//C-large.in"")); PrintWriter out = new PrintWriter(new FileWriter(""D://NewFolder2//test1.txt"")); int c =1; //int x =0; while (in.ready()){ String text = in.readLine(); if(c != 1){ StringTokenizer tokenizer = new StringTokenizer(text,"" ""); String[] allText = new String[2]; int pos = 0; while (tokenizer.hasMoreTokens()) allText[pos++] = tokenizer.nextToken(); long lower_limit = Long.parseLong(allText[0]); long upper_limit = Long.parseLong(allText[1]); long result = countRecycledNums(lower_limit,upper_limit); String text1 = ""Case #""+(c-1)+"": ""+result; out.println(text1); c++; } else{ // x = Integer.parseInt(text); c++; } } out.close(); in.close(); }catch(IOException e){ System.out.print(""Exception""); } } //end of main private static int countNumDigits( long number) { int count = 1; count = 1 + (int)Math.floor(Math.log10(number)); return count; } //Rotate a number by specified positioon private static long cyclicRotate( long num, int numLen, int pos ) { long new_num, suffix,prefix; long compute_by = (long)(Math.pow((double)10,(numLen - pos ))); suffix = num / compute_by ; prefix = num % compute_by ; new_num = prefix * (long)Math.pow((double)10, pos ) + suffix; return new_num; } static long countRecycledNums(long lower_limit, long upper_limit) { long uniq_recycle_pair_count = 0; int num_digits = countNumDigits ( lower_limit); if ( num_digits == 1 ){ return 0; } for ( int counter = (int)lower_limit ; counter < upper_limit ; counter++) { Set set = new HashSet(); for ( int pos = 1 ; pos < num_digits ; pos++ ) { long recycled_num = cyclicRotate(counter,num_digits,pos); if ( recycled_num <= counter) { continue; } if ( lower_limit <= recycled_num && upper_limit >= recycled_num ) { uniq_recycle_pair_count++; set.add(recycled_num); } } } return uniq_recycle_pair_count; } }" B10581,"package com.codejam; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; public class CodeJam13 { char map[]; public static void main(String[] args) { Scanner fileIn = null; FileWriter fileOut = null; try { fileIn = new Scanner(new File(""input.txt"")); fileOut = new FileWriter(new File(""output.in"")); int noOfTestCases = Integer.parseInt(fileIn.nextLine()); int testCase = 0; while (fileIn.hasNextLine()) { testCase++; int count=0; String sa = fileIn.next(); int len = sa.length(); int factor = (int)Math.pow(10,len-1); int a = Integer.parseInt(sa); int a1=a; int b = fileIn.nextInt(); fileIn.nextLine(); while(a1<=b){ HashSet set = new HashSet(); for(int i=0;i=a1 && newA<=b){ if(set.add(newA)){ count++; } } a=newA; } //System.out.println(a1 + "" "" + count); a=++a1; } fileOut.write(""Case #"" + testCase + "": "" + count + ""\n""); } fileIn.close(); fileOut.close(); } catch (IOException ex) { System.out.println(ex.getMessage()); } } } " B12946," import java.util.*; class Main { public static void main( String[ ] args ) { Scanner in=new Scanner(System.in); int cin=in.nextInt(); for (int ci=1;ci<=cin;ci++){ int a=in.nextInt(),b=in.nextInt(); int ans=0; for (int i=a;i la=new HashSet(); int ttmp=1; int tmp=10; int tgmp=10; while (tgmp<=i){ tgmp*=10; } while (i>tmp){ tgmp/=10; int m=i%tmp*tgmp+i/tmp; if (m>i&&m<=b&&i%tmp>=ttmp) {la.add(m);} ttmp=tmp; tmp*=10; } ans+=la.size(); } System.out.println(""Case #""+ci+"": ""+ans); } } } " B12411,"import java.io.*; public class ProCOpt { public static void main(String args[]) { try { BufferedReader br = new BufferedReader(new FileReader(""E:\\test.txt"")); int n; n= Integer.parseInt(br.readLine()); int casen=0,i,j; int a,b,count; String temp,t,u; String outp; outp=""""; String spl[]; String memory,fp,lp; while( casen < n ) { temp = br.readLine(); outp += ""Case #""+(casen+1)+"": ""; spl = temp.split("" ""); a = Integer.parseInt(spl[0]); b = Integer.parseInt(spl[1]); count = 0; memory = """"; for(i=a;i<=b; i++) { t = i+""""; for(j=1;j= a) { if( t.length() % 2 == 0 ) { fp= t.substring(0,t.length()/2); lp = t.substring(t.length()/2); if( fp.equals(lp) ) { if(!memory.contains(Integer.parseInt(u)+"" ""+i)) { count++; memory += Integer.parseInt(u) + "" "" + i+""\n""; } } else { count++; } } else { count++; } /*if( memory.contains(Integer.parseInt(u)+"" ""+i) ) System.out.println(Integer.parseInt(u)+"" ""+i); else { count++; memory += Integer.parseInt(u) + "" "" + i+""\n""; }*/ } } } outp += count; if( casen != n-1 ) outp += ""\n""; casen++; } System.out.println(outp); BufferedWriter bw = new BufferedWriter( new FileWriter(""E:\\result.txt"")); bw.write(outp); bw.close(); br.close(); } catch( Exception e ) { e.printStackTrace(); } } } " B11127,"package codejam; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.*; public class Third { public static void main(String[] args) throws FileNotFoundException { String path = ClassLoader.getSystemClassLoader().getResource(""codejam/"").getPath(); Third worker = new Third(); worker.scan(new File(path, ""third-s.in""), new File(path, ""third-s.out"")); // worker.scan(new File(path, ""third-x.in""), new File(path, ""third-x.out"")); } private void scan(File input, File output) throws FileNotFoundException { Scanner in = new Scanner(input); PrintWriter out = new PrintWriter(output); int n = Integer.parseInt(in.nextLine()); for (int i = 0; i < n; i++) { out.printf(""Case #%d: %s\n"", i + 1, solve(in.nextLine())); } out.flush(); out.close(); in.close(); } public String solve(String line) { String[] splited = line.split("" ""); return """" + solve(Integer.parseInt(splited[0]), Integer.parseInt(splited[1])); } public int solve(int a, int b) { if (a < 10 || a == b) { return 0; } int shiftCount = String.valueOf(a).length() - 1; int counter = 0; Map duplicate = new HashMap(shiftCount); for (int n = a; n <= b; n++) { duplicate.clear(); for (int i = 1; i <= shiftCount; i++) { int m = shift(n, i); if (m < a || m > b || m == n || m > n) { continue; } String key = """" + n + "":"" + m; if (!duplicate.containsKey(key)) { counter++; duplicate.put(key, Boolean.TRUE); } //System.out.println(""("" + n + "", "" + m + "") ""); //System.out.print(""\'"" + n + "":"" + m + ""\', ""); } } return counter; } private int shift(int a, int n) { String s = String.valueOf(a); String head = s.substring(0, s.length() - n); String tail = s.substring(s.length() - n); return Integer.parseInt(tail + head); } } " B10217,"import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Main { public static void main(String[] args) throws Exception{ File inFile=new File(""C-small-attempt1.in""); File outFile=new File(inFile.getName().substring(0,inFile.getName().length()-3)+"".out""); BufferedReader in=new BufferedReader(new FileReader(inFile)); //BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); int cases=Integer.parseInt(in.readLine()); Recycler r[]=new Recycler[cases]; ExecutorService executor=Executors.newFixedThreadPool(10); for(int i=0;i 9) { for (int x = a; x <= b; x++) { sb = new StringBuilder(Integer.toString(x)); for (int y = 0; y < sb.length() - 1; y++) { int v = backToFront(sb); recycled += isRecycled(v, x, b); } } } out.println(recycled); } in.close(); out.close(); } public int backToFront(StringBuilder sb) { char c = sb.charAt(sb.length() - 1); sb.deleteCharAt(sb.length() - 1); sb.insert(0, c); int x = Integer.parseInt(sb.toString()); return x; } public int isRecycled(int v, int x, int b) { int r = 0; if (v > x && v <= b) for (int i = x; i <= b; i++) { if (v == i) r++; } return r; } public static void main(String[] args) throws FileNotFoundException { new Dancers().solve(); } }" B10857,"package be.mokarea.gcj.common; public abstract class TestCase { private final int caseNumber; protected TestCase(int caseNumber) { this.caseNumber = caseNumber; } public int getCaseNumber() { return caseNumber; } } " B11022,"package org.moriraaca.codejam.recyclednumbers; import java.io.InputStream; import org.moriraaca.codejam.GeneralDataParser; public class RecycledNumberDataParser extends GeneralDataParser { public RecycledNumberDataParser(InputStream input) { super(input); } @Override protected void doParse() { for (int i = 0; i < testCases.length; i++) { RecycledNumbersTestCase tc = new RecycledNumbersTestCase(); tc.A = scanner.nextInt(); tc.B = scanner.nextInt(); testCases[i] = tc; } } } " B10325,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class RecycledNumbers { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(bf.readLine()); int x = 1; while (t > 0) { int y = 0; String[] g = bf.readLine().trim().split(""\\s+""); int a = Integer.parseInt(g[0]); int b = Integer.parseInt(g[1]); for (int i = a; i < b; i++) { boolean[] flag = new boolean [b-a+1]; String s= Integer.toString(i); for (int j = 0; j < g[0].length()-1; j++) { int ss = Integer.parseInt(s.substring(j+1)+s.substring(0,j+1)); if (ss>i&&ss<=b&&!flag[ss-a]) { y++; flag[ss-a]=true; } } } System.out.println(""Case #"" + x + "": "" + y); x++; t--; } } } " B10483,"import java.io.BufferedReader; import java.io.FileReader; import java.sql.Array; import java.util.ArrayList; import java.util.concurrent.BlockingDeque; public class RN { public static void main (String[] args) throws Exception { BufferedReader sr = new BufferedReader(new FileReader(""c:\\Projects\\RN.txt"")); int total = Integer.parseInt(sr.readLine()); for (int i=0; i 0) { rest = rest / 10; num++; } int[] result = new int[num]; for (int i=0; i variants = new ArrayList(); int first = dec[0]; for (int i=1; i= first) { int candidate = toNumber(dec, i); if (candidate > Curr && candidate <= B) { if (!variants.contains(candidate)) { variants.add(candidate); total++; } } } } } return total; } } " B10063,"import java.util.*; import java.io.*; public class recycled { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new File(""input"")); int size = sc.nextInt(); for (int x = 0; x < size; x++) { TreeSet set = new TreeSet(); TreeSet set1 = new TreeSet(); int A = sc.nextInt(); int B = sc.nextInt(); int comb = 0; for (int w = A; w <= B; w++) { String str = w + """"; if (str.length() >= 2 && good(str)) { //System.out.println(str); for (int y = 1; y < str.length(); y++) { int cons = Integer.parseInt(str.substring(y, str .length()) + str.substring(0, y)); if (cons <= B && cons>=w) { comb++; set.add(str + "" "" + str.substring(y, str .length()) + str.substring(0, y)); } } } } int comp = 0; for (int y = A; y <= B; y++) for (int z = y + 1; z <= B; z++) { boolean good = false; String yy = y + """"; String zz = z + """"; for (int k = 1; k < zz.length(); k++) { String cons = (zz .substring(k, zz.length()) + zz.substring(0, k)); if ((cons + """").equals(yy)) { comp++; set1.add(yy + "" "" + zz); break; } } } // System.out.println(set); // set1.removeAll(set); // System.out.println(set1); // System.out.println(comb); System.out.println(""Case #""+(x+1)+"": ""+comp); } } public static boolean good(String str) { int temp=str.charAt(0); for (int x = 1; x < str.length() - 1; x++) if (str.charAt(x)=='0')temp=0; else if(str.charAt(x)=m_low && tempInt <= m_high && tempInt != i && curNumS.length() == intLength && m_numArray[tempInt-m_low] == false){ tempCount++; m_numArray[tempInt-m_low] = true; } } if(tempCount > 0){ m_numArray[i-m_low] = true; m_pairsCount += chooseArray[tempCount+1]; } tempCount = 0; } return m_pairsCount; } public static void main(String[] args) { try { // Code for accessing the file goes here FileReader dataFile = new FileReader(""/Users/benedictliang/Documents/workspace/CodeJam2012/src/C-small-attempt0.in""); BufferedReader bufferedDataFile = new BufferedReader(dataFile); String num = bufferedDataFile.readLine(); int numOfLines = Integer.parseInt(num); BufferedWriter out = new BufferedWriter(new FileWriter(""/Users/benedictliang/Documents/workspace/CodeJam2012/src/output.txt"")); for(int i=1; i<=numOfLines; i++){ String line = bufferedDataFile.readLine(); String[] data = line.split("" ""); int num1 = Integer.parseInt(data[0]); int num2 = Integer.parseInt(data[1]); RecyclingNumbers rn = new RecyclingNumbers(Math.min(num1, num2), Math.max(num1, num2)); out.write(""Case #"" + i + "": "" + rn.getPairsCount() + ""\n""); } dataFile.close(); out.close(); } catch (Exception e) { System.out.println(e); } } } " B12525,"import java.util.*; public class Recycled { private static int solve(int A, int B) { int count = 0; HashSet s = new HashSet(); for (int n = A; n < B; n++) { String i = n + """"; s.clear(); int t = i.length(); while (i.charAt(t-1) == '0') t--; for (int j = 1; j < t; j++) { int m = Integer.parseInt(i.substring(j) + i.substring(0, j)); if (n < m && m <= B) s.add(m); } count += s.size(); } return count; } public static void main(String args[]) { Scanner in = new Scanner(System.in); int N = in.nextInt(); for (int i = 0; i < N; i++) { System.out.println(""Case #"" + (i+1) + "": "" + solve(in.nextInt(), in.nextInt())); } } } " B12502,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class C { public void solve() throws FileNotFoundException { Scanner in = new Scanner(new File(""C-small-attempt0.in"")); PrintWriter out = new PrintWriter(""C-small-attempt0.out""); int testN = in.nextInt(); for (int i = 1; i <= testN; i++) { out.print(""Case #"" + i + "": ""); int a = in.nextInt(); int b = in.nextInt(); int recycled = 0; StringBuilder sb; if (b > 9) { for (int x = a; x <= b; x++) { sb = new StringBuilder(Integer.toString(x)); for (int y = 0; y < sb.length() - 1; y++) { int v = backToFront(sb); recycled += isRecycled(v, x, b); } } } out.println(recycled); } in.close(); out.close(); } public int backToFront(StringBuilder sb) { char c = sb.charAt(sb.length() - 1); sb.deleteCharAt(sb.length() - 1); sb.insert(0, c); int x = Integer.parseInt(sb.toString()); return x; } public int isRecycled(int v, int x, int b) { int r = 0; if (v > x && v <= b) for (int i = x; i <= b; i++) { if (v == i) { r++; } } return r; } public static void main(String[] args) throws FileNotFoundException { new C().solve(); } } " B12948,"package google.solver; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; public class ProblemPackageCreator implements ChallengeConstants{ private final String packageName; private String directoryName; private String challengeDef; private String readerName; private String challengeName; private String packagePath; ProblemPackageCreator(String packageName){ this.packageName = packageName; packagePath = ""google.contest.""+packageName; directoryName = BASE_DIR+DELIMITER+packageName; challengeDef = BASE_DIR+DELIMITER+packageName+DELIMITER+CHALLENGE_DEFINITION; readerName = packageName.substring(0,1).toUpperCase()+packageName.substring(1)+""Reader""; challengeName = packageName.substring(0,1).toUpperCase()+packageName.substring(1)+""Challenge""; } private void create() { try{ createDirectory(); createTestIn(); createChallengeDefinition2(); createReader(); createChallenge(); } catch(Exception e){ throw new RuntimeException(e); } } private void createTestIn() { writeToPath(TEST_IN, """"); } private void createChallenge() { String def =""package ""+packagePath+"";\n\n""+ ""import google.loader.Challenge;\n""+ ""import google.problems.AbstractChallenge;\n\n""+ ""public class ""+challengeName+"" extends AbstractChallenge implements Challenge {\n\n""+ ""public ""+challengeName+""(int number) {\n""+ ""super(number);\n""+ ""setResult(\""\"");\n""+ ""}\n""+ ""}\n""; writeJava(challengeName, def); } private void createReader() { String def = ""package ""+packagePath+"";\n\n""+ ""import google.loader.Challenge;\n""+ ""import google.problems.AbstractReader;\n\n""+ ""public class ""+readerName+"" extends AbstractReader {\n \n""+ ""@Override\n""+ ""protected Challenge createChallenge(int number) {\n""+ ""int theLine = getActualLine();\n""+ ""String[] lines = getLines();\n""+ ""int value = Integer.parseInt(getLines()[theLine]);\n""+ challengeName+"" chal = new ""+challengeName+""(number);\n""+ ""setActualLine(theLine+1);\n""+ ""return chal;\n""+ ""}\n""+ ""\n""+ ""}\n""; writeJava(readerName, def); } private void writeToPath(String fileName, String text){ write(directoryName+DELIMITER+fileName, text); } private void writeJava(String baseName, String text) { writeToPath(baseName+"".java"", text); } private void createChallengeDefinition() { String def = ""fileName=""+TEST_IN+""\n""+ ""# fileName=A-small-practice.in\n""+ ""# fileName=A-large-practice.in\n""+ ""# fileName=B-small-practice.in\n""+ ""# fileName=B-large-practice.in\n""+ ""# fileName=C-small-practice.in\n""+ ""# fileName=C-large-practice.in\n""+ ""readerClassName=""+packagePath+"".""+readerName; write(challengeDef, def); } private void createChallengeDefinition2() { String def = ""fileName=""+TEST_IN+""\n""+ ""# fileName=""+packageName+""-small-practice.in\n""+ ""# fileName=""+packageName+""-large-practice.in\n""+ ""readerClassName=""+packagePath+"".""+readerName; write(challengeDef, def); } private void createDirectory() throws Exception{ File file = new File(directoryName); if(! file.exists()){ file.mkdir(); }else{ throw new RuntimeException(""alreadyExisting""); } } public static void main(String[] args) { String packageName =CHALLENGE_NAME; ProblemPackageCreator creator = new ProblemPackageCreator(""A""); creator.create(); creator = new ProblemPackageCreator(""B""); creator.create(); creator = new ProblemPackageCreator(""C""); creator.create(); } public static void write(String aFileName, String text) { try{ FileWriter fstream = new FileWriter(aFileName); BufferedWriter out = new BufferedWriter(fstream); out.write(text); out.close(); }catch (Exception e){ throw new RuntimeException(e); } } } " B11326,"package recycledNumbers; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class Flow { public static InputData Readin(String filename){ try { FileReader fr = new FileReader(filename); Scanner sc = new Scanner(fr); int Test_Number = sc.nextInt(); System.out.println(""The Number of Tests: ""+Test_Number); int[] A = new int[Test_Number]; int [] B = new int[Test_Number]; for(int i=0;i m = new LinkedList(); for (int i=0; i < n ; i++) { String l = fr.getLine(); Scanner sc = new Scanner(l); int tres = 0; int tn = 0; int tm = 0; int newnum = 0; int A = sc.nextInt(); int B = sc.nextInt(); int length = Integer.toString(A).length(); length--; for(int j=A ; j <= B ; j++) { int tlength = length; m.clear(); while(tlength>0) { tn = (int) (j % (Math.pow(10,tlength))); tm = (int) (j / (Math.pow(10,tlength))); newnum = (int) (tn*(Math.pow(10, Integer.toString(tm).length())) + tm); if (!m.contains(newnum) &&newnum <= B && j < newnum && Integer.toString(tn).length() == tlength && Integer.toString(tm).length() == (length+1 - tlength)) if (newnum <= B && tn!=0 && j < newnum) { tres++; m.add(newnum); } tlength--; } } res.addCase(String.valueOf(tres)); } fw.writeResult(res); } } " B10763,"import java.util.*; import java.io.*; public class c{ public static void main(String[] args)throws IOException{ Scanner br = new Scanner(new File(""c.in"")); PrintWriter out = new PrintWriter(new File(""c.out"")); int cases = br.nextInt(); for(int i = 0;i seen = new HashSet(); for(int k = 1;k b){ continue; } count++; } } } out.println(""Case #""+(i+1)+"": ""+count); } out.close(); } } " B10751,"import java.util.HashSet; import java.util.Scanner; public class recycled { public static void main(String[] args){ int t; Scanner s = new Scanner(System.in); t=s.nextInt(); for(int k=1;k<=t;k++){ int a,b; a=s.nextInt(); b=s.nextInt(); int al=a/10,d=1; while(al>0){ d++; al/=10; } int count=0; for(int i=a;i<=b;i++){ HashSet hs = new HashSet(); for(int j=1;j=a && n<=b && n!=i) { if(!hs.contains(n)){ count++; hs.add(n); } } } } System.out.println(""Case #""+k+"": ""+(count/2)); } } } " B11639,"import java.util.*; public class RecycledNumbers extends Thread { private int bottom; private int top; private static int numCases; private static int caseIndex = 0; private static int lower[]; private static int upper[]; private long thisCount = 0; public static void main(String[] args) { int n = 1; long startTime = System.currentTimeMillis(); for (int i = 1; i < args.length; i++) { if(args[i - 1].equals(""-n"")) { try { n = Integer.parseInt(args[i]); } catch (Exception e) { } } } //System.out.println(n + "" threads will be used.\n""); //GATHER INPUT Scanner sc = new Scanner(System.in); numCases = sc.nextInt(); int currentCaseNum = 1; String[] outputBuffer = new String[numCases]; lower = new int[numCases]; upper = new int[numCases]; sc.nextLine(); for(int i = 0; i < numCases; i++) { lower[i] = sc.nextInt(); upper[i] = sc.nextInt(); } for(int m = 0; m < numCases; m++) { Thread[] threadArray = new Thread[n]; RecycledNumbers[] speedupArray = new RecycledNumbers[n]; int nextLower = lower[m]; int nextUpper = ((upper[m] - lower[m]) / n) + lower[m]; for (int j = 0; j < n; j++) { speedupArray[j] = new RecycledNumbers(nextLower, nextUpper); threadArray[j] = new Thread(speedupArray[j]); threadArray[j].start(); nextLower = nextUpper + 1; nextUpper = ((j + 2) * (upper[m] - lower[m]) / n) + lower[m]; } for (int k = 0; k < threadArray.length; k++) { try { threadArray[k].join(); } catch (InterruptedException e) {} } int totalCount = 0; for (int k = 0; k < threadArray.length; k++) { totalCount += speedupArray[k].thisCount; } System.out.println(""Case #"" + (m + 1) + "": "" + totalCount); //System.out.println(""""); } //System.out.println(""\nDONE! Execution time of "" + ((double)(System.currentTimeMillis() - startTime) / 1000) + "" seconds.""); } public RecycledNumbers(int rangeBottom, int rangeTop) { bottom = rangeBottom; top = rangeTop; //System.out.println(""This class instance will handle "" + bottom + "" to "" + top + "".""); } private long countDistinct(int lowerBound, int upperBound) { long count = 0; for(int i = lowerBound; i < upperBound; i++) { count += countUniquePermutations(i, upperBound); } return count; } private int countUniquePermutations(int subject, int topBound) { int count = 0; String intString = Integer.toString(subject); String tempNewString = """"; int tempNewInt = 0; int tempIntLength = 0; int[] distinctInt = new int[intString.length() - 1]; for(int j = 1; j < intString.length(); j++) { tempNewString = intString.substring(j, intString.length()) + intString.substring(0, j); tempNewInt = Integer.parseInt(tempNewString); tempIntLength = Integer.toString(tempNewInt).length(); if((intString.length() == tempIntLength) && (subject != tempNewInt) && (tempNewInt >= subject) && (tempNewInt <= topBound)) { distinctInt[j -1] = tempNewInt; } Set s = new HashSet(); for (int i : distinctInt) { if(i != 0) { s.add(i); } } count = s.size(); } return count; } public void run() { thisCount = countDistinct(bottom, top); } } " B13046,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class ProblemC { // ************************************************************************************* // *********************************** FRAMEWORK *************************************** // ************************************************************************************* public static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); public static boolean isStandardInput = false; public static File input; public static FileReader inputreader; public static BufferedReader in; public static File output; public static FileWriter outputwriter; public static BufferedWriter out; public static StringTokenizer st; public static void main(String[] args) throws Exception { doSTDIN(true); setOutput(""test.out""); run(); close(); } public static void run() throws Exception { init(""E:\\workspace\\2012\\src\\C-small""); int cases = INT(); for(int cc = 1;cc<=cases;cc++) { String a = TOKEN(); String b = TOKEN(); int count = 0; if (a.length() < 2){ print(""Case #""+cc+"": ""); println(0); continue; } int aa = Integer.parseInt(a); int bb = Integer.parseInt(b); for (int i = aa; i<=bb; i++){ String s = """"+i; List strings = new ArrayList(); strings.add(s); for (int j=0; j recNumbers = new TreeSet(); for (int j = rep.length() - 1; j > 0; j--) { if (rep.charAt(j) != '0') { String replaced = rep.substring(j) + rep.substring(0, j); Integer num = new Integer(replaced); if (num.intValue() <= B && num.intValue() > first) { recNumbers.add(num); } } } res += recNumbers.size(); } return res; } } " B10196,"import java.io.*; import java.util.*; public class recycle { public static StringTokenizer st; public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(""C-small-attempt0.in""))); PrintWriter pw = new PrintWriter(new FileWriter(""output.out"")); int T = Integer.parseInt(br.readLine()); int t = 1; while (t <= T) { st = new StringTokenizer(br.readLine(), "" "", false); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); boolean[] arr = new boolean[B-A+1]; int order = 0; for (int i = A; i <= B; i++) if (!arr[i-A]) order += cycleOrder(i, A, B, arr); pw.println(""Case #""+t+"": ""+order); t++; } pw.flush(); pw.close(); br.close(); } catch (IOException ie) { ie.printStackTrace(); } } public static int cycleOrder(int i, int A, int B, boolean[] arr) { arr[i-A] = true; String s = i+""""; int order = 1; for (int j = 1; j < s.length(); j++) { String s2 = s.substring(j,s.length())+s.substring(0,j); if (s2.equals(s)) break; if (!s2.startsWith(""0"")) { int j2 = Integer.parseInt(s2); if (j2 >= A && j2 <= B) { order++; arr[j2-A] = true; } } } return order*(order-1)/2; } }" B11538,"package template; import java.io.*; import java.util.ArrayList; import java.util.Random; public class Utils { static String logfile = """"; public static BufferedWriter newBufferedWriter(String filename, boolean append) { BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter(filename, append)); } catch (IOException ex) { die(""Exception in newBufferedWriter""); } return bw; } public static void writeLn(BufferedWriter bw, String line) { try { bw.write(line); bw.newLine(); } catch (IOException ex) { die(""Exception in writeLn""); } } public static void closeBw(BufferedWriter bw) { try { bw.flush(); bw.close(); } catch (IOException ex) { die(""Exception in closeBw""); } } public static BufferedReader newBufferedReader(String filename) { BufferedReader br = null; try { br = new BufferedReader(new FileReader(filename)); } catch (IOException ex) { die(""Exception in newBufferedReader""); } return br; } public static String readLn(BufferedReader br) { String s = null; try { s = br.readLine(); } catch (IOException ex) { die(""Exception in readLn""); } return s; } public static Integer readInteger(BufferedReader br) { return new Integer(readLn(br)); } public static ArrayList readIntegerList(BufferedReader br) { return readIntegerList(br, null); } public static ArrayList readIntegerList(BufferedReader br, Integer expectedLength) { String[] s = readLn(br).split("" ""); ArrayList l = new ArrayList<>(); for (int x = 0; x < s.length; x++) { l.add(new Integer(s[x])); } if (expectedLength != null) { if (l.size() != expectedLength.intValue()) { die(""Incorrect length in readIntegerList""); } } return l; } public static ArrayList readMultipleIntegers(BufferedReader br, Integer rows) { ArrayList l = new ArrayList<>(); for (int x = 0; x < rows; x++) { String s = readLn(br); l.add(new Integer(s)); } return l; } public static ArrayList> readIntegerMatrix(BufferedReader br, Integer rows) { return readIntegerMatrix(br, rows, null); } public static ArrayList> readIntegerMatrix(BufferedReader br, Integer rows, Integer expectedLength) { ArrayList> l = new ArrayList<>(); for (int x = 0; x < rows.intValue(); x++) { l.add(readIntegerList(br, expectedLength)); } return l; } public static Double readDouble(BufferedReader br) { return new Double(readLn(br)); } public static ArrayList readDoubleList(BufferedReader br) { return readDoubleList(br, null); } public static ArrayList readDoubleList(BufferedReader br, Integer expectedLength) { String[] s = readLn(br).split("" ""); ArrayList l = new ArrayList<>(); for (int x = 0; x < s.length; x++) { l.add(new Double(s[x])); } if (expectedLength != null) { if (l.size() != expectedLength.intValue()) { die(""Incorrect length in readDoubleList""); } } return l; } public static ArrayList readMultipleDoubles(BufferedReader br, Integer rows) { ArrayList l = new ArrayList<>(); for (int x = 0; x < rows; x++) { String s = readLn(br); l.add(new Double(s)); } return l; } public static ArrayList> readDoubleMatrix(BufferedReader br, Integer rows) { return readDoubleMatrix(br, rows, null); } public static ArrayList> readDoubleMatrix(BufferedReader br, Integer rows, Integer expectedLength) { ArrayList> l = new ArrayList<>(); for (int x = 0; x < rows.intValue(); x++) { l.add(readDoubleList(br, expectedLength)); } return l; } public static Long readLong(BufferedReader br) { return new Long(readLn(br)); } public static ArrayList readLongList(BufferedReader br) { return readLongList(br, null); } public static ArrayList readLongList(BufferedReader br, Integer expectedLength) { String[] s = readLn(br).split("" ""); ArrayList l = new ArrayList<>(); for (int x = 0; x < s.length; x++) { l.add(new Long(s[x])); } if (expectedLength != null) { if (l.size() != expectedLength.intValue()) { die(""Incorrect length in readLongList""); } } return l; } public static ArrayList readMultipleLongs(BufferedReader br, Integer rows) { ArrayList l = new ArrayList<>(); for (int x = 0; x < rows; x++) { String s = readLn(br); l.add(new Long(s)); } return l; } public static ArrayList> readLongMatrix(BufferedReader br, Integer rows) { return readLongMatrix(br, rows, null); } public static ArrayList> readLongMatrix(BufferedReader br, Integer rows, Integer expectedLength) { ArrayList> l = new ArrayList<>(); for (int x = 0; x < rows.intValue(); x++) { l.add(readLongList(br, expectedLength)); } return l; } public static String readString(BufferedReader br) { return new String(readLn(br)); } public static ArrayList readStringList(BufferedReader br) { return readStringList(br, null); } public static ArrayList readStringList(BufferedReader br, Integer expectedLength) { String[] s = readLn(br).split("" ""); ArrayList l = new ArrayList<>(); for (int x = 0; x < s.length; x++) { l.add(new String(s[x])); } if (expectedLength != null) { if (l.size() != expectedLength.intValue()) { die(""Incorrect length in readStringList""); } } return l; } public static ArrayList readMultipleStrings(BufferedReader br, Integer rows) { ArrayList l = new ArrayList<>(); for (int x = 0; x < rows; x++) { String s = readLn(br); l.add(new String(s)); } return l; } public static ArrayList> readStringMatrix(BufferedReader br, Integer rows) { return readStringMatrix(br, rows, null); } public static ArrayList> readStringMatrix(BufferedReader br, Integer rows, Integer expectedLength) { ArrayList> l = new ArrayList<>(); for (int x = 0; x < rows.intValue(); x++) { l.add(readStringList(br, expectedLength)); } return l; } public static Boolean readBoolean(BufferedReader br) { return new Boolean(readLn(br)); } public static ArrayList readBooleanList(BufferedReader br) { return readBooleanList(br, null); } public static ArrayList readBooleanList(BufferedReader br, Integer expectedLength) { String[] s = readLn(br).split("" ""); ArrayList l = new ArrayList<>(); for (int x = 0; x < s.length; x++) { l.add(new Boolean(s[x])); } if (expectedLength != null) { if (l.size() != expectedLength.intValue()) { die(""Incorrect length in readBooleanList""); } } return l; } public static ArrayList readMultipleBooleans(BufferedReader br, Integer rows) { ArrayList l = new ArrayList<>(); for (int x = 0; x < rows; x++) { String s = readLn(br); l.add(new Boolean(s)); } return l; } public static ArrayList> readBooleanMatrix(BufferedReader br, Integer rows) { return readBooleanMatrix(br, rows, null); } public static ArrayList> readBooleanMatrix(BufferedReader br, Integer rows, Integer expectedLength) { ArrayList> l = new ArrayList<>(); for (int x = 0; x < rows.intValue(); x++) { l.add(readBooleanList(br, expectedLength)); } return l; } public static void closeBr(BufferedReader br) { try { br.close(); } catch (IOException ex) { die(""Exception in closeBr""); } } public static void die(String reason) { sout(""Die: "" + reason); System.exit(0); } public static void sout(String s) { System.out.println(s); } public static void sout(int i) { System.out.println(i); } public static void sout(Object o) { System.out.println(o); } public static void log(String line) { BufferedWriter bw = newBufferedWriter(logfile, true); writeLn(bw, line); closeBw(bw); } public static void clearFile(String filename) { BufferedWriter bw = newBufferedWriter(filename, false); closeBw(bw); } public static int minInt(ArrayList l) { int i = l.get(0).intValue(); for (Integer j : l) { if (j.intValue() < i) { i = j.intValue(); } } return i; } public static int maxInt(ArrayList l) { int i = l.get(0).intValue(); for (Integer j : l) { if (j.intValue() > i) { i = j.intValue(); } } return i; } public static String joinArray(ArrayList l, String delim) { String s = """"; for (int i = 0; i < l.size(); i++) { s += l.get(i).toString(); if (i < (l.size() - 1)) { s += delim; } } return s; } public static ArrayList splitToChars(String source) { ArrayList chars = new ArrayList<>(); for (int i = 0; i < source.length(); i++) { chars.add(source.substring(i, i + 1)); } return chars; } public static ArrayList splitToDigits(int in) { ArrayList chars = new ArrayList<>(); String s = in + """"; for (int i = 0; i < s.length(); i++) { chars.add(new Integer(s.substring(i, i + 1))); } return chars; } public static ArrayList> allPairs(int lower1, int upper1, int lower2, int upper2, int style) { //Style: //0 all pairs //1 (1) <= (2) //2 (1) < (2) ArrayList> out = new ArrayList<>(); for (int index1 = lower1; index1 <= upper1; index1++) { for (int index2 = lower2; index2 <= upper2; index2++) { ArrayList thisPair = new ArrayList<>(); thisPair.add(new Integer(index1)); thisPair.add(new Integer(index2)); switch (style) { case 0: out.add(thisPair); break; case 1: if (index1 <= index2) { out.add(thisPair); } break; case 2: if (index1 < index2) { out.add(thisPair); } break; default: die(""Unrecognised case in allPairs""); } } } return out; } public static ArrayList> cloneALALI(ArrayList> in) { ArrayList> out = new ArrayList<>(); for (ArrayList inALI : in) { ArrayList outALI = new ArrayList<>(inALI); out.add(outALI); } return out; } public static int[][] cloneInt2D(int[][] in) { if (in.length == 0) {return new int[0][0];} int[][] out = new int[in.length][]; for (int i = 0; i < in.length; i++) { out[i] = new int[in[i].length]; System.arraycopy(in[i], 0, out[i], 0, in[i].length); } return out; } public static double[][] cloneDouble2D(double[][] in) { if (in.length == 0) {return new double[0][0];} double[][] out = new double[in.length][]; for (int i = 0; i < in.length; i++) { out[i] = new double[in[i].length]; System.arraycopy(in[i], 0, out[i], 0, in[i].length); } return out; } public static ArrayList> allPerms(int n) { //returns an arraylist of arraylists of integers //showing all permutations of Integers 0 to n-1 //works realistically up to n=10 if (n == 0) { return new ArrayList>(); } return allPerms_recurse(n, n); } public static ArrayList> allPerms_recurse(int level, int n) { if (level == 1) { ArrayList single = new ArrayList<>(); single.add(new Integer(n - level)); ArrayList> list = new ArrayList<>(); list.add(single); return list; } ArrayList> prev = allPerms_recurse(level - 1, n); ArrayList> out = new ArrayList<>(); for (int placeAt = 0; placeAt < level; placeAt++) { //clone prev ArrayList> prevClone = cloneALALI(prev); //insert for (ArrayList prevItem : prevClone) { prevItem.add(placeAt, new Integer(n - level)); } //append to out out.addAll(prevClone); } return out; } public static ArrayList> allCombs(int n) { //returns an arraylist of arraylists of integers //showing all combinations of Integers 0 to n-1 //works realistically up to n=7 if (n == 0) { return new ArrayList>(); } return allCombs_recurse(n, n); } public static ArrayList> nCombs(int count, int n) { //returns an arraylist of arraylists of integers //showing all combinations of Integers 0 to n-1 --- of length ""count"" //i.e. base ""n"" counting up to (n^count - 1). In order. if (count == 0) { return new ArrayList>(); } return allCombs_recurse(count, n); } public static ArrayList> allCombs_recurse(int level, int n) { if (level == 1) { ArrayList> list = new ArrayList<>(); for (int i = 0; i < n; i++) { ArrayList single = new ArrayList<>(); single.add(new Integer(i)); list.add(single); } return list; } ArrayList> prev = allCombs_recurse(level - 1, n); ArrayList> out = new ArrayList<>(); for (int initial = 0; initial < n; initial++) { //clone prev ArrayList> prevClone = cloneALALI(prev); //insert for (ArrayList prevItem : prevClone) { prevItem.add(0, new Integer(initial)); } //append to out out.addAll(prevClone); } return out; } public static ArrayList grepFull(ArrayList inList, String pattern) { //pattern must match full text ArrayList outList = new ArrayList<>(); for (String s : inList) { if (s.matches(pattern)) { outList.add(new String(s)); } } return outList; } public static int[] randomIntegerArray(int count, int low, int high, long seed) { //a list of ""count"" ints from low to high inclusive. Random rng = new Random(); if (seed != -1) { rng.setSeed(seed); } int[] out = new int[count]; for (int x = 0; x < count; x++) { out[x] = rng.nextInt(high - low + 1) + low; } return out; } public static double[] randomDoubleArray(int count, double low, double high, long seed) { //a list of ""count"" ints from low inclusive to high exclusive. Random rng = new Random(); if (seed != -1) { rng.setSeed(seed); } double[] out = new double[count]; for (int x = 0; x < count; x++) { out[x] = rng.nextDouble() * (high - low) + low; } return out; } public static int[] randomPermutation(int count, long seed) { //random permutation of the array 0..(count-1). Random rng = new Random(); if (seed != -1) { rng.setSeed(seed); } int[] out = new int[count]; for (int x = 0; x < count; x++) { out[x] = x; } for (int x = 0; x < count - 1; x++) { int takeFrom = rng.nextInt(count - x) + x; int tmp = out[takeFrom]; out[takeFrom] = out[x]; out[x] = tmp; } return out; } public static ArrayList randomiseArray(ArrayList in, long seed) { //alternatively, Collections.shuffle(in, new Random(seed)) ArrayList out = new ArrayList(); int[] r = randomPermutation(in.size(), seed); for (int i : r) { out.add(in.get(i)); } return out; } public static ArrayList arrayToArrayList(int[] in) { ArrayList out = new ArrayList<>(); for (int i : in) { out.add(i); } return out; } public static ArrayList arrayToArrayList(double[] in) { ArrayList out = new ArrayList<>(); for (double d : in) { out.add(d); } return out; } public static int[] arrayListToArrayInt(ArrayList in) { int[] out = new int[in.size()]; int x = 0; for (Integer i : in) { out[x] = i.intValue(); x++; } return out; } public static double[] arrayListToArrayDouble(ArrayList in) { double[] out = new double[in.size()]; int x = 0; for (Double d : in) { out[x] = d.doubleValue(); x++; } return out; } public static String toString(int[] in) { if (in.length == 0) { return ""[]""; } String s = ""[""; for (int x = 0; x < in.length - 1; x++) { s += in[x] + "", ""; } s += in[in.length - 1] + ""]""; return s; } public static String toString(double[] in) { if (in.length == 0) { return ""[]""; } String s = ""[""; for (int x = 0; x < in.length - 1; x++) { s += in[x] + "", ""; } s += in[in.length - 1] + ""]""; return s; } public static String toString(int[][] in) { if (in.length == 0) { return ""[]""; } String s = ""[""; for (int x = 0; x < in.length - 1; x++) { s += toString(in[x]) + "", ""; } s += toString(in[in.length - 1]) + ""]""; return s; } public static String toString(double[][] in) { if (in.length == 0) { return ""[]""; } String s = ""[""; for (int x = 0; x < in.length - 1; x++) { s += toString(in[x]) + "", ""; } s += toString(in[in.length - 1]) + ""]""; return s; } } " B11382,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; public class Tools { public static ArrayList getInput(String filename) throws IOException { BufferedReader br = new BufferedReader(new FileReader(filename)); ArrayList output = new ArrayList(); String line; while ((line = br.readLine()) != null) output.add(line.split("" "")); br.close(); return output; } public static ArrayList getInputSingle(String filename) throws IOException { BufferedReader br = new BufferedReader(new FileReader(filename)); ArrayList output = new ArrayList(); String line; while ((line = br.readLine()) != null) output.add(line); br.close(); return output; } public static void saveOutput(String filename, ArrayList output) throws IOException { BufferedWriter bw = new BufferedWriter(new FileWriter(filename)); for(int i=0; i output) throws IOException { BufferedWriter bw = new BufferedWriter(new FileWriter(filename)); for(int i=0; i 1) { out.write(""\n""); } String text = fin.readLine(); Scanner scanner = new Scanner(text); int[] inputs = {0,0}; int count = 0; while(scanner.hasNext()) { inputs[count] = scanner.nextInt(); count++; } if( j >0) { out.write(""Case #"" + j + "": "" + numPairs(inputs[0],inputs[1])); ; } j++; } out.close(); } catch(FileNotFoundException e) { System.out.println(""Error""); } catch(IOException e) { System.out.println(""Error""); } } public static int numPairs(int input1, int input2) { int totalnum=0; int count = 0; if(input2 < input1) input2 = input1; ArrayList[] usedValues = new ArrayList[input2+1]; for(int i = 0; i <= input2; i++) { usedValues[i] = new ArrayList(); } int numDigits = (int)Math.floor(Math.log10((double)input1)+ 1); for(int i = input1; i <= input2; i++) { int val = i; for(int j = 0; j < numDigits; j++) { int lastDigit = val % 10; val = val / 10; val += Math.pow(10,numDigits-1) * lastDigit; if(input1 <= val && input2 >= val && val != i && !usedValues[i].contains(val)) { usedValues[i].add(val); usedValues[val].add(i); count++; } } } //System.out.println(totalnum); return count; } }" B10579,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class Recycled { public static void main(String[] args) throws IOException { ArrayList al = new ArrayList(); int count = 0; for (int r = 0; r <= 2000000; r++) { if (r % 1000 == 0) { System.out.println(r); } String A = Integer.toString(r); for (int r1 = 1; r1 < A.length(); r1++) { String B = A.substring(r1) + A.substring(0, r1); if (!A.equals(B) && Integer.parseInt(A) > Integer.parseInt(B)) { al.add(new Pair(Integer.parseInt(A), Integer.parseInt(B))); // System.out.println((count++)+"" ""+A + "" "" + B); } } } Collections.sort(al); //remove duplicates Pair last=null; for (int r=0;r=A &&ala[u]<=B){ // System.out.println(ala[u]+"" ""+alb[u]); count++; } } System.out.println(""Case #"" + (r + 1) + "": "" + (count)); outp.write(""Case #"" + (r + 1) + "": "" + (count)+""\n""); // outp.write(""Case #"" + (r + 1) + "": "" + fin + ""\n""); } outp.flush(); fstream.close(); } public static int rank(int key, int[] a) { int lo = 0; int hi = a.length - 1; while (lo <= hi) { // Key is in a[lo..hi] or not present. int mid = lo + (hi - lo) / 2; // System.out.println(lo+"" ""+mid+"" ""+hi); if (key < a[mid]) hi = mid - 1; else if (key > a[mid]) lo = mid + 1; if ((mid>0 && mid a[mid - 1])||key==a[mid]) return mid; if (mid==0)return 0; if (mid==a.length-1)return a.length-1; } return -1; // return lo + (hi - lo) / 2; } static class Pair implements Comparable { int A; int B; public Pair(int a, int b) { A = a; B = b; } @Override public int compareTo(Pair arg0) { if (this.A < arg0.A) return -1; if (this.A == arg0.A) return 0; return 1; } @Override public int hashCode(){ return A*10000000+B; } @Override public boolean equals(Object other){ if (other==null)return false; if (other==this)return true; if (A==((Pair)other).A&&B==((Pair)other).B)return true; return false; } } } " B10780,"import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.HashMap; public class RecycledNumbers{ /** * @param args */ public static void main(String[] args) { try { File inf = new File(""/home/jeyram/Downloads/""+""C-small-attempt1.in""); File of = new File(""/home/jeyram/Downloads/""+""rl-rn2-output.in""); FileInputStream in = new FileInputStream(inf); FileOutputStream out = new FileOutputStream(of); // Get the object of DataInputStream //DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; //Read File Line By Line if ((strLine = br.readLine()) != null) { System.out.println (strLine); int itrs= Integer.parseInt(strLine); int count=0; //#test cases while (count < itrs) { if ((strLine = br.readLine()) != null){ // input str String[] inst = strLine.split("" ""); //start no final int A = Integer.parseInt(inst[0]); //end no final int B = Integer.parseInt(inst[1]); //no of numbers int y=0; //no of iterations check 3 for 4 digit number int exp = (String.valueOf(A)).length()-1; int exC=1; while (exC<=exp){ int n =A; while(n<=B){ int pow =1; for(int p1=1;p1n) && (String.valueOf(n)).length()==(String.valueOf(m)).length()){//valid pair //System.out.println("":""+n +"":""+m); y++; } } n++; } exC++; } System.out.println(""output string""+y); //write as Case #1: 2 3 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out)); bw.write(""Case #""+(count+1)+"": ""+y); bw.newLine(); bw.flush(); } count++; } } //Close the input stream in.close(); out.close(); }catch (Exception e) { e.printStackTrace(); } finally{ } } }" B12274,"package year2012.qualification.c; import java.io.File; import java.io.PrintWriter; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) throws Exception{ //GCJ共通 String filename = ""src/year2012/qualification/c/C-small-attempt0""; PrintWriter out = new PrintWriter(new File(filename + "".out"")); Scanner scan = new Scanner(new File(filename + "".in"")); final int T = scan.nextInt(); for(int i=0;i=in.length){ throw new IllegalArgumentException(""n= "" + n + "", in.length = "" + in.length + ""となっています。n seenit = new HashSet(); for(int i=start; i <= end; i++){ String x = """"+i; cnt += permutationsInRange(i, start , end, seenit); } return """"+cnt; } public static String rev(String in){ //p(""in: "" + in); StringBuffer sb = new StringBuffer(); for(int i=in.length()-1; i>=0; i--){ sb.append(in.charAt(i)); } String out = sb.toString(); //p(""o: "" + out); return out; } public static String solveLine(String in){ String[] s = in.split("" ""); int start = Integer.parseInt(s[0]); int end = Integer.parseInt(s[1]); //System.out.println(totals); return recycled(start, end); } public static void solveStrings(String[] input) { for(int i=1; i seenit) { int count = 0; p(""in: "" + in + "" min_s "" + min + "" "" + max); String in_s = """"+in; StringBuffer sb = new StringBuffer(in_s); String rev = rev(sb.toString()); for(int i=0; i =min && test<=max){ p(""match: "" + test + "" in: "" + in); seenit.add(low + ""_"" + hi); count++; } } return count; } public static String[] getLines(String fileName) { String[] lines = null; try { FileInputStream fis = new FileInputStream(fileName); int nxtchar = 0; StringBuffer sb = new StringBuffer(); while((nxtchar=fis.read())!=-1){ sb.append((char)nxtchar); } lines = sb.toString().split(""\r\n|\n""); } catch (Exception e) { e.printStackTrace(); } return lines; } public static void main(String[] args) { solveStrings(getLines(args[0])); } public static void p(Object a){ //System.out.println(""""+a); } public static void p2(Object a){ System.out.println(""""+a); } } " B12532,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; public class RecycledNumbers { String inputFilePath = ""C:\\Temp\\Google\\C-small-attempt0.in""; String outputFilePath = ""C:\\Temp\\Google\\output.txt""; public static void main(String[] args) throws NumberFormatException, IOException{ new RecycledNumbers().go(); } public void go() throws NumberFormatException, IOException{ FileReader input = new FileReader(inputFilePath); BufferedReader reader = new BufferedReader(input); int numTests = Integer.parseInt(reader.readLine()); ArrayList results = new ArrayList(); for (int i = 0; i < numTests; i++){ String[] details = reader.readLine().split("" ""); int low = Integer.parseInt(details[0]); int high = Integer.parseInt(details[1]); results.add(solve(low, high)); } PrintWriter out = new PrintWriter(new FileOutputStream(outputFilePath)); for (int i = 0; i used = new ArrayList(); for (int j = 1; j i && (!used.contains(test))){ numberPossible++; used.add(test); } } } return numberPossible; } } " B11162,"import java.util.*; public class JuanjeProblemaC { public static void main(String[] args){ Scanner entrada = new Scanner(System.in); int tam = entrada.nextInt(); for(int problema = 1; problema <= tam;problema++) { int A = entrada.nextInt(); int B = entrada.nextInt(); int resultado = 0; for(int indice=A;indice<=B;indice++) { ArrayList pares = new ArrayList(); String ns = indice+""""; for (int j=ns.length()-1;j>0;j--) { String k = ns.substring(j); String nuevoVal = k + ns.substring(0,j); int m = Integer.parseInt(nuevoVal); if (m>indice && A=m) { if (pares.indexOf(m)==-1) pares.add(m); } } int tamPares = pares.size(); resultado += tamPares; } System.out.format(""Case #%d: %d\n"", problema, resultado); } } }" B12698,"import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; public class recycle { static Scanner kb ; public static void main(String[] args) throws FileNotFoundException { // TODO Auto-generated method stub PrintWriter out = new PrintWriter(""answerrecycle.txt""); kb = new Scanner(System.in); int testcase = kb.nextInt(); for(int i=0;i mem = new ArrayList(); String number = Integer.toString(i); int s = (int)number.charAt(0)-48; for(int k=1;k=s){ String news = number.substring(k,number.length())+number.substring(0,k); int numbernew = Integer.parseInt(news); if(numbernew<=maxnumber&&(!(numbernew<=i))&&news.length()==number.length()&&!mem.contains(numbernew)){ answer++; //System.out.println(number+""_n>s_""+news); mem.add(numbernew); } } } } return answer; } } " B10437," package problemc; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; public class Main { public static void main(String[] args) { BufferedReader input = null; try { input = new BufferedReader(new FileReader(""input.txt"")); FileOutputStream output = new FileOutputStream(""output.txt""); int N = Integer.parseInt(input.readLine()); for(int i=0; i=a && num<=b && num!=k){ boolean found = false; for(int j=1; jFor writing to standard output, the output methods in this class pretty much * duplicate the functionality of System.out, and System.out can be used interchangeably with them. *

This class does not use optimal Java programming practices. It is designed specifically to be easily * usable even by a beginning programmer who has not yet learned about objects and exceptions. Therefore, * everything is in a single source file that compiles into a single class file, all the methods are * static methods, and none of the methods throw exceptions that would require try...catch statements. * Also for this reason, all exceptions are converted into IllegalArgumentExceptions, even when this * exception type doesn't really make sense. *

This class requires Java 5.0 or higher. (A previous version of TextIO required only Java 1.1; * this version should work with any source code that used the previous version, but it has some new * features, including the type of formatted output that was introduced in Java 5 and the ability to * use files and streams.) */ public class TextIO { /* Modified November 2007 to empty the TextIO input buffer when switching from one * input source to another. This fixes a bug that allows input from the previous input * source to be read after the new source has been selected. */ /** * The value returned by the peek() method when the input is at end-of-file. * (The value of this constant is (char)0xFFFF.) */ public final static char EOF = (char)0xFFFF; /** * The value returned by the peek() method when the input is at end-of-line. * The value of this constant is the character '\n'. */ public final static char EOLN = '\n'; // The value returned by peek() when at end-of-line. /** * After this method is called, input will be read from standard input (as it * is in the default state). If a file or stream was previously the input source, that file * or stream is closed. */ public static void readStandardInput() { if (readingStandardInput) return; try { in.close(); } catch (Exception e) { } emptyBuffer(); // Added November 2007 in = standardInput; inputFileName = null; readingStandardInput = true; inputErrorCount = 0; } /** * After this method is called, input will be read from inputStream, provided it * is non-null. If inputStream is null, then this method has the same effect * as calling readStandardInput(); that is, future input will come from the * standard input stream. */ public static void readStream(InputStream inputStream) { if (inputStream == null) readStandardInput(); else readStream(new InputStreamReader(inputStream)); } /** * After this method is called, input will be read from inputStream, provided it * is non-null. If inputStream is null, then this method has the same effect * as calling readStandardInput(); that is, future input will come from the * standard input stream. */ public static void readStream(Reader inputStream) { if (inputStream == null) readStandardInput(); else { if ( inputStream instanceof BufferedReader) in = (BufferedReader)inputStream; else in = new BufferedReader(inputStream); emptyBuffer(); // Added November 2007 inputFileName = null; readingStandardInput = false; inputErrorCount = 0; } } /** * Opens a file with a specified name for input. If the file name is null, this has * the same effect as calling readStandardInput(); that is, input will be read from standard * input. If an * error occurs while trying to open the file, an exception of type IllegalArgumentException * is thrown, and the input source is not changed. If the file is opened * successfully, then after this method is called, all of the input routines will read * from the file, instead of from standard input. */ public static void readFile(String fileName) { if (fileName == null) // Go back to reading standard input readStandardInput(); else { BufferedReader newin; try { newin = new BufferedReader( new FileReader(fileName) ); } catch (Exception e) { throw new IllegalArgumentException(""Can't open file \"""" + fileName + ""\"" for input.\n"" + ""(Error :"" + e + "")""); } if (! readingStandardInput) { // close current input stream try { in.close(); } catch (Exception e) { } } emptyBuffer(); // Added November 2007 in = newin; readingStandardInput = false; inputErrorCount = 0; inputFileName = fileName; } } /** * Puts a GUI file-selection dialog box on the screen in which the user can select * an input file. If the user cancels the dialog instead of selecting a file, it is * not considered an error, but the return value of the subroutine is false. * If the user does select a file, but there is an error while trying to open the * file, then an exception of type IllegalArgumentException is thrown. Finally, if * the user selects a file and it is successfully opened, then the return value of the * subroutine is true, and the input routines will read from the file, instead of * from standard input. If the user cancels, or if any error occurs, then the * previous input source is not changed. *

NOTE: Calling this method starts a GUI user interface thread, which can continue * to run even if the thread that runs the main program ends. If you use this method * in a non-GUI program, it might be necessary to call System.exit(0) at the end of the main() * routine to shut down the Java virtual machine completely. */ public static boolean readUserSelectedFile() { if (fileDialog == null) fileDialog = new JFileChooser(); fileDialog.setDialogTitle(""Select File for Input""); int option = fileDialog.showOpenDialog(null); if (option != JFileChooser.APPROVE_OPTION) return false; File selectedFile = fileDialog.getSelectedFile(); BufferedReader newin; try { newin = new BufferedReader( new FileReader(selectedFile) ); } catch (Exception e) { throw new IllegalArgumentException(""Can't open file \"""" + selectedFile.getName() + ""\"" for input.\n"" + ""(Error :"" + e + "")""); } if (!readingStandardInput) { // close current file try { in.close(); } catch (Exception e) { } } emptyBuffer(); // Added November 2007 in = newin; inputFileName = selectedFile.getName(); readingStandardInput = false; inputErrorCount = 0; return true; } /** * After this method is called, output will be written to standard output (as it * is in the default state). If a file or stream was previously open for output, it * will be closed. */ public static void writeStandardOutput() { if (writingStandardOutput) return; try { out.close(); } catch (Exception e) { } outputFileName = null; outputErrorCount = 0; out = standardOutput; writingStandardOutput = true; } /** * After this method is called, output will be sent to outputStream, provided it * is non-null. If outputStream is null, then this method has the same effect * as calling writeStandardOutput(); that is, future output will be sent to the * standard output stream. */ public static void writeStream(OutputStream outputStream) { if (outputStream == null) writeStandardOutput(); else writeStream(new PrintWriter(outputStream)); } /** * After this method is called, output will be sent to outputStream, provided it * is non-null. If outputStream is null, then this method has the same effect * as calling writeStandardOutput(); that is, future output will be sent to the * standard output stream. */ public static void writeStream(PrintWriter outputStream) { if (outputStream == null) writeStandardOutput(); else { out = outputStream; outputFileName = null; outputErrorCount = 0; writingStandardOutput = false; } } /** * Opens a file with a specified name for output. If the file name is null, this has * the same effect as calling writeStandardOutput(); that is, output will be sent to standard * output. If an * error occurs while trying to open the file, an exception of type IllegalArgumentException * is thrown. If the file is opened successfully, then after this method is called, * all of the output routines will write to the file, instead of to standard output. * If an error occurs, the output destination is not changed. *

NOTE: Calling this method starts a GUI user interface thread, which can continue * to run even if the thread that runs the main program ends. If you use this method * in a non-GUI program, it might be necessary to call System.exit(0) at the end of the main() * routine to shut down the Java virtual machine completely. */ public static void writeFile(String fileName) { if (fileName == null) // Go back to reading standard output writeStandardOutput(); else { PrintWriter newout; try { newout = new PrintWriter(new FileWriter(fileName)); } catch (Exception e) { throw new IllegalArgumentException(""Can't open file \"""" + fileName + ""\"" for output.\n"" + ""(Error :"" + e + "")""); } if (!writingStandardOutput) { try { out.close(); } catch (Exception e) { } } out = newout; writingStandardOutput = false; outputFileName = fileName; outputErrorCount = 0; } } /** * Puts a GUI file-selection dialog box on the screen in which the user can select * an output file. If the user cancels the dialog instead of selecting a file, it is * not considered an error, but the return value of the subroutine is false. * If the user does select a file, but there is an error while trying to open the * file, then an exception of type IllegalArgumentException is thrown. Finally, if * the user selects a file and it is successfully opened, then the return value of the * subroutine is true, and the output routines will write to the file, instead of * to standard output. If the user cancels, or if an error occurs, then the current * output destination is not changed. */ public static boolean writeUserSelectedFile() { if (fileDialog == null) fileDialog = new JFileChooser(); fileDialog.setDialogTitle(""Select File for Output""); File selectedFile; while (true) { int option = fileDialog.showSaveDialog(null); if (option != JFileChooser.APPROVE_OPTION) return false; // user canceled selectedFile = fileDialog.getSelectedFile(); if (selectedFile.exists()) { int response = JOptionPane.showConfirmDialog(null, ""The file \"""" + selectedFile.getName() + ""\"" already exists. Do you want to replace it?"", ""Replace existing file?"", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (response == JOptionPane.YES_OPTION) break; } else { break; } } PrintWriter newout; try { newout = new PrintWriter(new FileWriter(selectedFile)); } catch (Exception e) { throw new IllegalArgumentException(""Can't open file \"""" + selectedFile.getName() + ""\"" for output.\n"" + ""(Error :"" + e + "")""); } if (!writingStandardOutput) { try { out.close(); } catch (Exception e) { } } out = newout; writingStandardOutput = false; outputFileName = selectedFile.getName(); outputErrorCount = 0; return true; } /** * If TextIO is currently reading from a file, then the return value is the name of the file. * If the class is reading from standard input or from a stream, then the return value is null. */ public static String getInputFileName() { return inputFileName; } /** * If TextIO is currently writing to a file, then the return value is the name of the file. * If the class is writing to standard output or to a stream, then the return value is null. */ public static String getOutputFileName() { return outputFileName; } // *************************** Output Methods ********************************* /** * Write a single value to the current output destination, using the default format * and no extra spaces. This method will handle any type of parameter, even one * whose type is one of the primitive types. */ public static void put(Object x) { out.print(x); out.flush(); if (out.checkError()) outputError(""Error while writing output.""); } /** * Write a single value to the current output destination, using the default format * and outputting at least minChars characters (with extra spaces added before the * output value if necessary). This method will handle any type of parameter, even one * whose type is one of the primitive types. * @param x The value to be output, which can be of any type. * @param minChars The minimum number of characters to use for the output. If x requires fewer * then this number of characters, then extra spaces are added to the front of x to bring * the total up to minChars. If minChars is less than or equal to zero, then x will be printed * in the minumum number of spaces possible. */ public static void put(Object x, int minChars) { if (minChars <= 0) out.print(x); else out.printf(""%"" + minChars + ""s"", x); out.flush(); if (out.checkError()) outputError(""Error while writing output.""); } /** * This is equivalent to put(x), followed by an end-of-line. */ public static void putln(Object x) { out.println(x); out.flush(); if (out.checkError()) outputError(""Error while writing output.""); } /** * This is equivalent to put(x,minChars), followed by an end-of-line. */ public static void putln(Object x, int minChars) { put(x,minChars); out.println(); out.flush(); if (out.checkError()) outputError(""Error while writing output.""); } /** * Write an end-of-line character to the current output destination. */ public static void putln() { out.println(); out.flush(); if (out.checkError()) outputError(""Error while writing output.""); } /** * Writes formatted output values to the current output destination. This method has the * same function as System.out.printf(); the details of formatted output are not discussed * here. The first parameter is a string that describes the format of the output. There * can be any number of additional parameters; these specify the values to be output and * can be of any type. This method will throw an IllegalArgumentException if the * format string is null or if the format string is illegal for the values that are being * output. */ public static void putf(String format, Object... items) { if (format == null) throw new IllegalArgumentException(""Null format string in TextIO.putf() method.""); try { out.printf(format,items); } catch (IllegalFormatException e) { throw new IllegalArgumentException(""Illegal format string in TextIO.putf() method.""); } out.flush(); if (out.checkError()) outputError(""Error while writing output.""); } // *************************** Input Methods ********************************* /** * Test whether the next character in the current input source is an end-of-line. Note that * this method does NOT skip whitespace before testing for end-of-line -- if you want to do * that, call skipBlanks() first. */ public static boolean eoln() { return peek() == '\n'; } /** * Test whether the next character in the current input source is an end-of-file. Note that * this method does NOT skip whitespace before testing for end-of-line -- if you want to do * that, call skipBlanks() or skipWhitespace() first. */ public static boolean eof() { return peek() == EOF; } /** * Reads the next character from the current input source. The character can be a whitespace * character; compare this to the getChar() method, which skips over whitespace and returns the * next non-whitespace character. An end-of-line is always returned as the character '\n', even * when the actual end-of-line in the input source is something else, such as '\r' or ""\r\n"". * This method will throw an IllegalArgumentException if the input is at end-of-file (which will * not ordinarily happen if reading from standard input). */ public static char getAnyChar() { return readChar(); } /** * Returns the next character in the current input source, without actually removing that * character from the input. The character can be a whitespace character and can be the * end-of-file character (specified by the constant TextIO.EOF).An end-of-line is always returned * as the character '\n', even when the actual end-of-line in the input source is something else, * such as '\r' or ""\r\n"". This method never causes an error. */ public static char peek() { return lookChar(); } /** * Skips over any whitespace characters, except for end-of-lines. After this method is called, * the next input character is either an end-of-line, an end-of-file, or a non-whitespace character. * This method never causes an error. (Ordinarily, end-of-file is not possible when reading from * standard input.) */ public static void skipBlanks() { char ch=lookChar(); while (ch != EOF && ch != '\n' && Character.isWhitespace(ch)) { readChar(); ch = lookChar(); } } /** * Skips over any whitespace characters, including for end-of-lines. After this method is called, * the next input character is either an end-of-file or a non-whitespace character. * This method never causes an error. (Ordinarily, end-of-file is not possible when reading from * standard input.) */ private static void skipWhitespace() { char ch=lookChar(); while (ch != EOF && Character.isWhitespace(ch)) { readChar(); if (ch == '\n' && readingStandardInput && writingStandardOutput) { out.print(""? ""); out.flush(); } ch = lookChar(); } } /** * Skips whitespace characters and then reads a value of type byte from input, discarding the rest of * the current line of input (including the next end-of-line character, if any). When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. */ public static byte getlnByte() { byte x=getByte(); emptyBuffer(); return x; } /** * Skips whitespace characters and then reads a value of type short from input, discarding the rest of * the current line of input (including the next end-of-line character, if any). When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. */ public static short getlnShort() { short x=getShort(); emptyBuffer(); return x; } /** * Skips whitespace characters and then reads a value of type int from input, discarding the rest of * the current line of input (including the next end-of-line character, if any). When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. */ public static int getlnInt() { int x=getInt(); emptyBuffer(); return x; } /** * Skips whitespace characters and then reads a value of type long from input, discarding the rest of * the current line of input (including the next end-of-line character, if any). When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. */ public static long getlnLong() { long x=getLong(); emptyBuffer(); return x; } /** * Skips whitespace characters and then reads a value of type float from input, discarding the rest of * the current line of input (including the next end-of-line character, if any). When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. */ public static float getlnFloat() { float x=getFloat(); emptyBuffer(); return x; } /** * Skips whitespace characters and then reads a value of type double from input, discarding the rest of * the current line of input (including the next end-of-line character, if any). When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. */ public static double getlnDouble() { double x=getDouble(); emptyBuffer(); return x; } /** * Skips whitespace characters and then reads a value of type char from input, discarding the rest of * the current line of input (including the next end-of-line character, if any). Note that the value * that is returned will be a non-whitespace character; compare this with the getAnyChar() method. * When using standard IO, this will not produce an error. In other cases, an error can occur if * an end-of-file is encountered. */ public static char getlnChar() { char x=getChar(); emptyBuffer(); return x; } /** * Skips whitespace characters and then reads a value of type boolean from input, discarding the rest of * the current line of input (including the next end-of-line character, if any). When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. *

Legal inputs for a boolean input are: true, t, yes, y, 1, false, f, no, n, and 0; letters can be * either upper case or lower case. One ""word"" of input is read, using the getWord() method, and it * must be one of these; note that the ""word"" must be terminated by a whitespace character (or end-of-file). */ public static boolean getlnBoolean() { boolean x=getBoolean(); emptyBuffer(); return x; } /** * Skips whitespace characters and then reads one ""word"" from input, discarding the rest of * the current line of input (including the next end-of-line character, if any). A word is defined as * a sequence of non-whitespace characters (not just letters!). When using standard IO, * this will not produce an error. In other cases, an IllegalArgumentException will be thrown * if an end-of-file is encountered. */ public static String getlnWord() { String x=getWord(); emptyBuffer(); return x; } /** * This is identical to getln(). */ public static String getlnString() { return getln(); } /** * Reads all the characters from the current input source, up to the next end-of-line. The end-of-line * is read but is not included in the return value. Any other whitespace characters on the line are retained, * even if they occur at the start of input. The return value will be an empty string if there are no * no characters before the end-of-line. When using standard IO, this will not produce an error. * In other cases, an IllegalArgumentException will be thrown if an end-of-file is encountered. */ public static String getln() { StringBuffer s = new StringBuffer(100); char ch = readChar(); while (ch != '\n') { s.append(ch); ch = readChar(); } return s.toString(); } /** * Skips whitespace characters and then reads a value of type byte from input. Any additional characters on * the current line of input are retained, and will be read by the next input operation. When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. */ public static byte getByte() { return (byte)readInteger(-128L,127L); } /** * Skips whitespace characters and then reads a value of type short from input. Any additional characters on * the current line of input are retained, and will be read by the next input operation. When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. */ public static short getShort() { return (short)readInteger(-32768L,32767L); } /** * Skips whitespace characters and then reads a value of type int from input. Any additional characters on * the current line of input are retained, and will be read by the next input operation. When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. */ public static int getInt() { return (int)readInteger(Integer.MIN_VALUE, Integer.MAX_VALUE); } /** * Skips whitespace characters and then reads a value of type long from input. Any additional characters on * the current line of input are retained, and will be read by the next input operation. When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. */ public static long getLong() { return readInteger(Long.MIN_VALUE, Long.MAX_VALUE); } /** * Skips whitespace characters and then reads a single non-whitespace character from input. Any additional characters on * the current line of input are retained, and will be read by the next input operation. When using standard IO, * this will not produce an error. In other cases, an IllegalArgumentException will be thrown if an end-of-file * is encountered. */ public static char getChar() { skipWhitespace(); return readChar(); } /** * Skips whitespace characters and then reads a value of type float from input. Any additional characters on * the current line of input are retained, and will be read by the next input operation. When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. */ public static float getFloat() { float x = 0.0F; while (true) { String str = readRealString(); if (str == null) { errorMessage(""Floating point number not found."", ""Real number in the range "" + (-Float.MAX_VALUE) + "" to "" + Float.MAX_VALUE); } else { try { x = Float.parseFloat(str); } catch (NumberFormatException e) { errorMessage(""Illegal floating point input, "" + str + ""."", ""Real number in the range "" + (-Float.MAX_VALUE) + "" to "" + Float.MAX_VALUE); continue; } if (Float.isInfinite(x)) { errorMessage(""Floating point input outside of legal range, "" + str + ""."", ""Real number in the range "" + (-Float.MAX_VALUE) + "" to "" + Float.MAX_VALUE); continue; } break; } } inputErrorCount = 0; return x; } /** * Skips whitespace characters and then reads a value of type double from input. Any additional characters on * the current line of input are retained, and will be read by the next input operation. When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. */ public static double getDouble() { double x = 0.0; while (true) { String str = readRealString(); if (str == null) { errorMessage(""Floating point number not found."", ""Real number in the range "" + (-Double.MAX_VALUE) + "" to "" + Double.MAX_VALUE); } else { try { x = Double.parseDouble(str); } catch (NumberFormatException e) { errorMessage(""Illegal floating point input, "" + str + ""."", ""Real number in the range "" + (-Double.MAX_VALUE) + "" to "" + Double.MAX_VALUE); continue; } if (Double.isInfinite(x)) { errorMessage(""Floating point input outside of legal range, "" + str + ""."", ""Real number in the range "" + (-Double.MAX_VALUE) + "" to "" + Double.MAX_VALUE); continue; } break; } } inputErrorCount = 0; return x; } /** * Skips whitespace characters and then reads one ""word"" from input. Any additional characters on * the current line of input are retained, and will be read by the next input operation. A word is defined as * a sequence of non-whitespace characters (not just letters!). When using standard IO, * this will not produce an error. In other cases, an IllegalArgumentException will be thrown * if an end-of-file is encountered. */ public static String getWord() { skipWhitespace(); StringBuffer str = new StringBuffer(50); char ch = lookChar(); while (ch == EOF || !Character.isWhitespace(ch)) { str.append(readChar()); ch = lookChar(); } return str.toString(); } /** * Skips whitespace characters and then reads a value of type boolean from input. Any additional characters on * the current line of input are retained, and will be read by the next input operation. When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. *

Legal inputs for a boolean input are: true, t, yes, y, 1, false, f, no, n, and 0; letters can be * either upper case or lower case. One ""word"" of input is read, using the getWord() method, and it * must be one of these; note that the ""word"" must be terminated by a whitespace character (or end-of-file). */ public static boolean getBoolean() { boolean ans = false; while (true) { String s = getWord(); if ( s.equalsIgnoreCase(""true"") || s.equalsIgnoreCase(""t"") || s.equalsIgnoreCase(""yes"") || s.equalsIgnoreCase(""y"") || s.equals(""1"") ) { ans = true; break; } else if ( s.equalsIgnoreCase(""false"") || s.equalsIgnoreCase(""f"") || s.equalsIgnoreCase(""no"") || s.equalsIgnoreCase(""n"") || s.equals(""0"") ) { ans = false; break; } else errorMessage(""Illegal boolean input value."", ""one of: true, false, t, f, yes, no, y, n, 0, or 1""); } inputErrorCount = 0; return ans; } // ***************** Everything beyond this point is private implementation detail ******************* private static String inputFileName; // Name of file that is the current input source, or null if the source is not a file. private static String outputFileName; // Name of file that is the current output destination, or null if the destination is not a file. private static JFileChooser fileDialog; // Dialog used by readUserSelectedFile() and writeUserSelectedFile() private final static BufferedReader standardInput = new BufferedReader(new InputStreamReader(System.in)); // wraps standard input stream private final static PrintWriter standardOutput = new PrintWriter(System.out); // wraps standard output stream private static BufferedReader in = standardInput; // Stream that data is read from; the current input source. private static PrintWriter out = standardOutput; // Stream that data is written to; the current output destination. private static boolean readingStandardInput = true; private static boolean writingStandardOutput = true; private static int inputErrorCount; // Number of consecutive errors on standard input; reset to 0 when a successful read occurs. private static int outputErrorCount; // Number of errors on standard output since it was selected as the output destination. private static Matcher integerMatcher; // Used for reading integer numbers; created from the integer Regex Pattern. private static Matcher floatMatcher; // Used for reading floating point numbers; created from the floatRegex Pattern. private final static Pattern integerRegex = Pattern.compile(""(\\+|-)?[0-9]+""); private final static Pattern floatRegex = Pattern.compile(""(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))((e|E)(\\+|-)?[0-9]+)?""); private static String buffer = null; // One line read from input. private static int pos = 0; // Position of next char in input line that has not yet been processed. private static String readRealString() { // read chars from input following syntax of real numbers skipWhitespace(); if (lookChar() == EOF) return null; if (floatMatcher == null) floatMatcher = floatRegex.matcher(buffer); floatMatcher.region(pos,buffer.length()); if (floatMatcher.lookingAt()) { String str = floatMatcher.group(); pos = floatMatcher.end(); return str; } else return null; } private static String readIntegerString() { // read chars from input following syntax of integers skipWhitespace(); if (lookChar() == EOF) return null; if (integerMatcher == null) integerMatcher = integerRegex.matcher(buffer); integerMatcher.region(pos,buffer.length()); if (integerMatcher.lookingAt()) { String str = integerMatcher.group(); pos = integerMatcher.end(); return str; } else return null; } private static long readInteger(long min, long max) { // read long integer, limited to specified range long x=0; while (true) { String s = readIntegerString(); if (s == null){ errorMessage(""Integer value not found in input."", ""Integer in the range "" + min + "" to "" + max); } else { String str = s.toString(); try { x = Long.parseLong(str); } catch (NumberFormatException e) { errorMessage(""Illegal integer input, "" + str + ""."", ""Integer in the range "" + min + "" to "" + max); continue; } if (x < min || x > max) { errorMessage(""Integer input outside of legal range, "" + str + ""."", ""Integer in the range "" + min + "" to "" + max); continue; } break; } } inputErrorCount = 0; return x; } private static void errorMessage(String message, String expecting) { // Report error on input. if (readingStandardInput && writingStandardOutput) { // inform user of error and force user to re-enter. out.println(); out.print("" *** Error in input: "" + message + ""\n""); out.print("" *** Expecting: "" + expecting + ""\n""); out.print("" *** Discarding Input: ""); if (lookChar() == '\n') out.print(""(end-of-line)\n\n""); else { while (lookChar() != '\n') // Discard and echo remaining chars on the current line of input. out.print(readChar()); out.print(""\n\n""); } out.print(""Please re-enter: ""); out.flush(); readChar(); // discard the end-of-line character inputErrorCount++; if (inputErrorCount >= 10) throw new IllegalArgumentException(""Too many input consecutive input errors on standard input.""); } else if (inputFileName != null) throw new IllegalArgumentException(""Error while reading from file \"""" + inputFileName + ""\"":\n"" + message + ""\nExpecting "" + expecting); else throw new IllegalArgumentException(""Error while reading from inptu stream:\n"" + message + ""\nExpecting "" + expecting); } private static char lookChar() { // return next character from input if (buffer == null || pos > buffer.length()) fillBuffer(); if (buffer == null) return EOF; else if (pos == buffer.length()) return '\n'; else return buffer.charAt(pos); } private static char readChar() { // return and discard next character from input char ch = lookChar(); if (buffer == null) { if (readingStandardInput) throw new IllegalArgumentException(""Attempt to read past end-of-file in standard input???""); else throw new IllegalArgumentException(""Attempt to read past end-of-file in file \"""" + inputFileName + ""\"".""); } pos++; return ch; } private static void fillBuffer() { // Wait for user to type a line and press return, try { buffer = in.readLine(); } catch (Exception e) { if (readingStandardInput) throw new IllegalArgumentException(""Error while reading standard input???""); else if (inputFileName != null) throw new IllegalArgumentException(""Error while attempting to read from file \"""" + inputFileName + ""\"".""); else throw new IllegalArgumentException(""Errow while attempting to read form an input stream.""); } pos = 0; floatMatcher = null; integerMatcher = null; } private static void emptyBuffer() { // discard the rest of the current line of input buffer = null; } private static void outputError(String message) { // Report an error on output. if (writingStandardOutput) { System.err.println(""Error occurred in TextIO while writing to standard output!!""); outputErrorCount++; if (outputErrorCount >= 10) { outputErrorCount = 0; throw new IllegalArgumentException(""Too many errors while writing to standard output.""); } } else if (outputFileName != null){ throw new IllegalArgumentException(""Error occurred while writing to file \"""" + outputFileName+ ""\"":\n "" + message); } else { throw new IllegalArgumentException(""Error occurred while writing to output stream:\n "" + message); } } } // end of class TextIO " B11662,"package codejam2012Qualification; import java.io.*; import java.util.*; public class C { public static void main(String[] args) throws IOException { boolean large = false; //large = true; String dir = ""C://Users//Aayush//Desktop//""; String InputFile = dir + (large ? ""C-large.in"" : ""C-small-attempt0.in""); String OutputFile = dir + (large ? ""C-large.out"" : ""C-small.out""); File file = new File(InputFile); Scanner st = new Scanner(file); FileWriter fw = new FileWriter(OutputFile); int T = st.nextInt(); for(int cases = 1; cases <= T; cases++){ int A = st.nextInt(); int B = st.nextInt(); int digits = 0; int A1 = A; while(A1 > 0){ A1 /= 10; digits++; } //Efficient solution int count = 0; for(int n = A; n < B; n++){ for(int i = 1; i < digits; i++){ int d = (int) Math.pow(10, i); int d1 = (int) Math.pow(10, digits - i); int r = n % d; int m = d1 * r + n / d; if(m > n && m <= B){ count++; } } } System.out.print(""Case #"" + cases + "": "" + count); fw.write(""Case #"" + cases + "": "" + count); System.out.println(); fw.write(""\n""); } fw.flush(); fw.close(); } } " B10503,"package year2012.RecycledNumbers; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; final class RecycledNumbers { /** * @param args * @throws IOException */ static int solve(int upper, int value) { if (value < 12) return 0; String strNum = value + """"; int length = strNum.length(); Set setNewNumber = new HashSet (); for (int i = 1; i < length; i++) { if (strNum.charAt(i) != '0') { String first = strNum.substring(0, i); String last = strNum.substring(i, length); int newNum = Integer.parseInt(last + first); if (newNum <= upper && newNum > value ) setNewNumber.add(new Integer(newNum)) ; } } return setNewNumber.size(); } public static void main(String[] args) throws IOException { String file = ""C-small-attempt0""; Scanner sc = new Scanner(new FileReader(file + "".in"")); PrintWriter pw = new PrintWriter(new FileWriter(file + "".out"")); int T = sc.nextInt(); int A = 0; int B = 0; sc.nextLine(); for (int i = 0; i < T; i++) { A = sc.nextInt(); B = sc.nextInt(); int result = 0; for (int ii = A; ii <= B; ii++) { result += solve(B, ii); } pw.println(""Case #"" + (i + 1) + "": "" + result); } pw.flush(); pw.close(); sc.close(); } } " B10991,"package c; import java.io.*; import java.lang.Math.*; import java.util.Arrays; public class C { public static void main(String[] args) { try { BufferedReader input = new BufferedReader(new FileReader(""C:/CodeJam/C-small-attempt0.in"")); BufferedWriter output = new BufferedWriter(new FileWriter(""C:/CodeJam/C-small-attempt0.out"")); try { int T = Integer.parseInt(input.readLine()); //Process each case for (int i = 0; i < T; i++) { String line = input.readLine(); String[] AB = line.split("" ""); int A = Integer.parseInt(AB[0]); int B = Integer.parseInt(AB[1]); String max = String.valueOf(B); //Check every n,m pair for cur case int count = 0; for (int j = A; j < B; j++) { String n = String.valueOf(j); String m = n; int len = m.length(); //For single digit numbers, no matches possible if (len == 1) { break; } //Check each possible match for current n int[] matches = new int[len]; int subcount = 0; for (int k = 0; k < len; k++) { //Check current permutation of m for valid range if (m.compareTo(n) > 0 && m.compareTo(max) <= 0) { matches[subcount] = Integer.parseInt(m); subcount++; } //Move the last digit to the front m = m.substring(len - 1, len) + m.substring(0, len - 1); } //Check the matches for duplicates and uncount them Arrays.sort(matches); for (int k = 0; k < len - 1; k++) { if(matches[k] != 0 && matches[k+1] != 0 && matches[k] == matches[k+1]) { subcount--; } } count += subcount; } System.out.println(""Case #"" + (i + 1) + "": "" + count); output.write(""Case #"" + (i + 1) + "": "" + count + ""\n""); } } finally { input.close(); output.close(); } } catch (IOException ex) { ex.printStackTrace(); } } } " B13166,"//input file must be in.txt in this directory //output file will be out.txt import java.io.*; import java.util.*; public class C { public static Scanner in; public static PrintStream out; public static void main(String [] args) throws Throwable { in = new Scanner(new File(""in.txt"")); int cases = in.nextInt(); in.nextLine(); out = new PrintStream(new File(""out.txt"")); for (int i = 1; i <= cases; i++) { out.print(""Case #"" + i + "": ""); printResult(); out.println(); } } public static void printResult() { int a,b; a = in.nextInt(); b = in.nextInt(); int i = a; int firstDigit = 1; int numDigits = 0; while (i > 0) { i /= 10; firstDigit *= 10; numDigits++; } int [] alreadyDone = new int[numDigits]; firstDigit /= 10; int cur,m; int tot = 0; boolean notDone; for (i = a; i < b; i++) { cur = i; for (int j = 1; j < numDigits; j++) alreadyDone[j] = -1; for (int j = 1; j < numDigits; j++) { m = cur % 10; cur = (cur / 10) + (m * firstDigit); if (cur > i && cur <= b) { notDone = true; for (int k = 1; k < j; k++) { if (alreadyDone[k] == cur) { notDone = false; break; } } if (notDone) { alreadyDone[j] = cur; tot++; } } } } out.print(tot); } } " B12818,"import java.util.*; import java.io.*; public class RecycledNumbers { public RecycledNumbers() { Scanner inFile = null; try { inFile = new Scanner(new File(""input.txt"")); } catch(Exception e) { System.out.println(""Problem opening input file. Exiting...""); System.exit(0); } int t = inFile.nextInt(); int [] results = new int [t]; RecycledNumbersCounter [] rnc = new RecycledNumbersCounter[t]; int i; for(i = 0; i < t; i++) { rnc[i] = new RecycledNumbersCounter(i, inFile.nextInt(), inFile.nextInt(), results); rnc[i].start(); } inFile.close(); boolean done = false; while(!done) { done = true; for(i = 0; i < t; i++) if(rnc[i].isAlive()) { done = false; break; } } PrintWriter outFile = null; try { outFile = new PrintWriter(new File(""output.txt"")); } catch(Exception e) { System.out.println(""Problem opening output file. Exiting...""); System.exit(0); } for(i = 0; i < results.length; i++) outFile.printf(""Case #%d: %d\n"", i+1, results[i]); outFile.close(); } public static void main(String [] args) { new RecycledNumbers(); } public static String intToString(int i) { String res = """"; while(i > 0) { res =(i%10)+res; i /= 10; } return res; } private class RecycledNumbersCounter extends Thread { int id; int a, b; int [] results; public RecycledNumbersCounter(int i, int first, int second, int [] res) { id = i; a = first; b = second; results = res; } public void run() { int count = 0; for(int i = a; i < b; i++) { for(int j = i+1; j <= b; j++) if(recycled(i, j)) { count++; } } results[id] = count; } public boolean recycled(int a, int b) { String c = intToString(a); String d = intToString(b); boolean found = false; if(c.length() != d.length()) return false; int d_index = d.indexOf(c.charAt(0)); while(d_index >= 0) { found = true; for(int i = 1; i < c.length(); i++) { if(c.charAt(i) != d.charAt((d_index + i)%d.length())) { found = false; break; } } if(found) return true; d_index = d.indexOf(c.charAt(0), d_index+1); } return false; } } }" B10204,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.StringTokenizer; public class JamInputReader { int numItem; String thisLine = null; BufferedReader in; StringTokenizer tokenizer; public JamInputReader(String fileName) { try { in = new BufferedReader(new FileReader(fileName)); /* String text = in.readLine(); numItem = Integer.parseInt(text);*/ readNextLine(); tokenizer = new StringTokenizer(thisLine, "" ""); } catch (FileNotFoundException e) { e.printStackTrace(); } } void readNextLine() { try { thisLine = in.readLine(); } catch (IOException e) { e.printStackTrace(); } } int getNumItems() { numItem = Integer.parseInt(tokenizer.nextToken()); return numItem; } String getNextItem() { if(false == tokenizer.hasMoreTokens()) { readNextLine(); tokenizer = new StringTokenizer(thisLine, "" ""); } return tokenizer.nextToken(); } String getNextLine() { readNextLine(); return thisLine; } int getNextInt() { return Integer.parseInt(getNextItem()); } long getNextLong() { return Long.parseLong(getNextItem()); } byte[] getNextLineByte() { readNextLine(); return thisLine.getBytes(); } } " B10218,"package googlecodejam2012_qualification; /** * @author neil */ import java.io.*; import java.util.*; public class NewMain { /** * @param args the command line arguments */ static boolean recycle(int n,int m) { String N = Integer.toString(n); String M = Integer.toString(m); for(int i=1;i B || n1 <= j) continue; if(!a[n1]) { count++; a[n1] = true; } } } if(i == lines-1) writeLine(""Case #"" + (i+1) + "": "" + count); else writeLine(""Case #"" + (i+1) + "": "" + count + ""\n""); } o.close(); } BufferedReader f = null; public String readLine() throws Exception { if(f == null) f = new BufferedReader(new FileReader(new File(""C:\\Users\\raj617\\workspace\\srm\\dat\\C-small-attempt0.in""))); return f.readLine(); } BufferedWriter o = null; public void writeLine(String line) throws Exception { if(o == null) o = new BufferedWriter(new FileWriter(new File(""C:\\Users\\raj617\\workspace\\srm\\dat\\out.txt""))); o.write(line ); o.flush(); } } " B10746,"package qualification; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Collection; import java.util.HashSet; import java.util.Scanner; public class RecycledNumber { public static void main(String[] args) throws IOException { String inputFile = ""C-small-attempt0.in""; Scanner input = new Scanner(new FileInputStream(inputFile)); FileOutputStream out = new FileOutputStream(inputFile + "".out"", false); slove(input, out); out.close(); } private static void slove(Scanner input, FileOutputStream out) throws IOException { int cases = input.nextInt(); for (int caseOrder = 1; caseOrder <= cases; caseOrder++) { int a = input.nextInt(); int b = input.nextInt(); long r = 0; for (int i = a; i <= b; i++) { for (int x: getRecycled(i)) { if (x >= a && x <= b && i < x && x > 0) { // System.out.printf(""(%d, %d)\n"", i, x); r++; } } } String outline = String.format(""Case #%d: %d\r\n"", caseOrder, r); System.out.print(outline); out.write(outline.getBytes()); } } private static Collection getRecycled(int a) { String s = Integer.toString(a); HashSet ret = new HashSet(); for (int i = 1; i < s.length(); i++) { String s2 = s.substring(i) + s.substring(0, i); if (!s2.startsWith(""0"")) { ret.add(Integer.parseInt(s2)); } } return ret; } } " B11779," import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class RecycledNumber { public static void main(String[] args) throws NumberFormatException, IOException { File file = new File(""/home/leandro/workspaces/googleCodeJam/RecycledNumbers/cases/C-small-attempt0.bin""); BufferedReader br; br = new BufferedReader(new FileReader(file)); int cases = Integer.parseInt(br.readLine()); for (int i = 1; i <= cases; i++) { String line = br.readLine(); StringTokenizer tokenizer = new StringTokenizer(line); Integer intA = Integer.parseInt(tokenizer.nextToken()); Integer intB = Integer.parseInt(tokenizer.nextToken()); int count = 0; for (int n = intA; n <= intB; n++) { for (Integer m : shift(n)) { if(intA <= n && n < m && m <= intB){ //System.out.println(n + "" - "" + m); count++; } } } System.out.println(""Case #""+ i + "": "" + count); } /* String A = ""1111""; String B = ""2222""; Integer intA = Integer.parseInt(A); Integer intB = Integer.parseInt(B); int count = 0; for (int n = intA; n <= intB; n++) { for (Integer m : shift(n)) { if(intA <= n && n < m && m <= intB){ System.out.println(n + "" - "" + m); count++; } } } System.out.println(""Total: ""+ count); */ } private static Set shift(int value){ Set retorno = new HashSet(); // length = 1 have no possibilities if(value < 10 ){ return retorno; } String strValue = Integer.toString(value); String nextToAnalyze = strValue; for (int i = 1; i <= strValue.length()-1 ; i++) { char[] shifted = new char[nextToAnalyze.length()]; for (int j = 0; j < nextToAnalyze.length(); j++) { if(j == 0){ shifted[nextToAnalyze.length()-1] = nextToAnalyze.charAt(j); } else { shifted[j-1] = nextToAnalyze.charAt(j); } } nextToAnalyze = new String(shifted); // check for leading zeros if(nextToAnalyze.charAt(0) != '0'){ retorno.add(Integer.parseInt(nextToAnalyze)); } } return retorno; } } " B12553,"import java.util.*; public class Recycle { public static int deg(int x) { int i = 0; while(x > 0) {x = x / 10; i++;} return i; } public static void main (String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for(int t = 1; t <= T; t++) { int A = sc.nextInt(), B = sc.nextInt(), num = 0; for(int i = A; i < B; i++) { int degree = deg(i); long coeff = (long) Math.pow(10, degree), n = i * coeff + i; LinkedList lst = new LinkedList(); for(int j = 0; j < degree; j++) { n = n / 10; long m = n % coeff; if(m > i && m <= B && !lst.contains(m)) { lst.add(m); num++;} } } System.out.println(""Case #"" + t + "": "" + num); } } } " B11433,"import java.io.*; public class mains { public static void main(String[] args) { BufferedReader input; BufferedWriter output; try { input = new BufferedReader(new FileReader(""C-small-attempt0.in"")); output = new BufferedWriter(new FileWriter(""output.out"")); int caseCount = Integer.parseInt(input.readLine()); String buf; String[] values; int minValue; int maxValue; int currentValue; int highest; int next; int result = 0; int numLength; for(int index = 1 ; index <= caseCount; ++index) { buf = input.readLine(); values = buf.split("" ""); minValue = Integer.parseInt(values[0]); maxValue = Integer.parseInt(values[1]); numLength = values[1].length(); highest = (int)Math.pow(10, numLength - 1); result = 0; if(highest != 1) { for(int num = minValue; num <= maxValue ; ++num) { currentValue = num; for(int i = 0 ; i < numLength ; ++i) { next = currentValue / highest; currentValue %= highest; currentValue *= 10; currentValue += next; if(num < currentValue && currentValue <= maxValue) ++result; } } output.write(""Case #"" + index + "": "" + result); output.newLine(); } else { output.write(""Case #"" + index + "": 0""); output.newLine(); } } output.close(); input.close(); } catch(Exception e) { return; } } } " B10985,"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.List; public class ProblemC { public int countDistinctRecycledPairsBetween(int min, int max) { int count = 0; int digit = Integer.toString(min).length(); for (int i = min; i <= max; i++) { count += this.countDistinctRecycledPairOf(i, min, max, digit); } return count; } public int countDistinctRecycledPairOf(int number, int min, int max, int digit) { List used = new ArrayList(digit); int count = 0; int rotated = number; for (int i = 0, rotateCount = digit - 1; i < rotateCount; i++) { rotated = this.shiftRightAndRotate(rotated, digit); if (rotated > number && rotated <= max && used.indexOf(rotated) == -1) { count++; used.add(rotated); } } return count; } private int shiftRightAndRotate(int number, int digit) { return (number % 10) * (int)Math.pow(10, digit - 1) + (number / 10); } public void solve(String inputFileName, String outputFileName) { try { BufferedReader reader = new BufferedReader(new FileReader(new File(inputFileName))); BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileName)); int testCount = Integer.parseInt(reader.readLine()); for (int i = 0; i < testCount; i++) { String testCase = reader.readLine(); String[] fields = testCase.split("" ""); int min = Integer.parseInt(fields[0]); int max = Integer.parseInt(fields[1]); int count = this.countDistinctRecycledPairsBetween(min, max); writer.write(""Case #"" + (i + 1) + "": "" + count); writer.newLine(); } reader.close(); writer.close(); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } public static void main(String[] args) { ProblemC problem = new ProblemC(); // problem.solve(""C-small-attempt.in"", ""C-small-attempt.out""); problem.solve(""C-small-attempt0.in"", ""C-small-attempt0.out""); // problem.solve(""B-large.in"", ""B-large.out""); } } " B11234,"import java.util.*; public class RecycledNumbers { public static void main(String[] args) { System.out.println(""Enter case input:""); Scanner sc = new Scanner(System.in); int T = sc.nextInt(); sc.nextLine(); int[][] numbers = new int[T][2]; for (int t = 0; t < T; t++) { numbers[t][0] = sc.nextInt(); numbers[t][1] = sc.nextInt(); sc.nextLine(); } for (int t = 1; t <= T; t++) { int a = numbers[t - 1][0]; int b = numbers[t - 1][1]; int numRecycledPairs = 0; for (int n = a; n < b; n++) { String N = n + """"; int[] matches = new int[N.length()]; boolean duplicate = false; for (int digitFromBack = 1; digitFromBack <= N.length() - 1; digitFromBack++) { int newInt = Integer.parseInt(N.substring(N.length() - digitFromBack) + N.substring(0, N.length() - digitFromBack)); if (newInt > n && newInt <= b) { for (int match : matches) { if (newInt == match) duplicate = true; } //System.out.print(n + "":"" + newInt + "" ""); if (!duplicate) { matches[digitFromBack] = newInt; numRecycledPairs++; } } } } System.out.println(""Case #"" + t + "": "" + numRecycledPairs); } } } " B11042," import java.util.*; import java.io.*; class recycled_numbers { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new FileReader(""recnum.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""recnum.out""))); int n = Integer.parseInt(in.readLine()); int ans = 0; for(int x = 0; x mset = new HashSetFactory().create(); for(int j=0;j caseIndexToSolve = createCaseIndicesToSolve(casen, caseIndices); ExecutorService executor = Executors.newFixedThreadPool(threadNumber); for(int i=0;i createCaseIndicesToSolve(int casen, Integer... caseIndices) { final java.util.Set set = new java.util.TreeSet(); if(caseIndices.length == 0) { for(int i=1;i<=casen;i++) set.add(i); } else { for(int v : caseIndices) { if(v < 1 || v > casen) throw new RuntimeException(""invalid index : "" + v); set.add(v); } } return set; } private static void printLine() { for(int i=0;i<100;i++) System.out.print(""-""); System.out.println(); } private static int countNotNull(final String[] results) { int solved = 0; for(String s : results) if(s != null) solved++; return solved; } private static void outputProgess(long startTime, int solved, int caseNumberToSolve) { long duration = System.currentTimeMillis() - startTime; long estimation = (long)Math.round((double)duration * caseNumberToSolve / solved / 1000); System.out.printf(""%.03fs : %d/%d solved (estimated : %dm %ds)\n"", (double)duration / 1000, solved, caseNumberToSolve, estimation / 60, estimation % 60); } private static void outputResult(final String[] results, String outputFilePath) throws FileNotFoundException { PrintStream ps = new PrintStream(outputFilePath); for(int i=0;i Set create() { return new SetWrapper(new HashSet()); } } interface Set extends Container { void clear(); void insert(T v); void insertAll(Iterable a); boolean contains(T v); void remove(T v); } interface Container extends Iterable { int size(); boolean isEmpty(); } interface SetFactory { Set create(); } class SetWrapper extends AbstractSet { private final java.util.Set set; public SetWrapper(java.util.Set set) { this.set = set; } public void clear() { set.clear(); } public boolean contains(T v) { return set.contains(v); } public void insert(T v) { set.add(v); } public Iterator iterator() { return set.iterator(); } public int size() { return set.size(); } public void remove(T v) { set.remove(v); } } abstract class AbstractSet implements Set { final public void insertAll(Iterable a) { for(T v : a) insert(v); } @Override final public boolean isEmpty() { return size() == 0; } final public String toString() { String r = """"; for(T v : this) { if(!r.isEmpty()) r += "",""; r += v; } return ""{"" + r + ""}""; } } " B12073,"package jp.funnything.competition.util; import java.math.BigDecimal; /** * Utility for BigDeciaml */ public class BD { public static BigDecimal ZERO = BigDecimal.ZERO; public static BigDecimal ONE = BigDecimal.ONE; public static BigDecimal add( final BigDecimal x , final BigDecimal y ) { return x.add( y ); } public static BigDecimal add( final BigDecimal x , final double y ) { return add( x , v( y ) ); } public static BigDecimal add( final double x , final BigDecimal y ) { return add( v( x ) , y ); } public static int cmp( final BigDecimal x , final BigDecimal y ) { return x.compareTo( y ); } public static int cmp( final BigDecimal x , final double y ) { return cmp( x , v( y ) ); } public static int cmp( final double x , final BigDecimal y ) { return cmp( v( x ) , y ); } public static BigDecimal div( final BigDecimal x , final BigDecimal y ) { return x.divide( y ); } public static BigDecimal div( final BigDecimal x , final double y ) { return div( x , v( y ) ); } public static BigDecimal div( final double x , final BigDecimal y ) { return div( v( x ) , y ); } public static BigDecimal mul( final BigDecimal x , final BigDecimal y ) { return x.multiply( y ); } public static BigDecimal mul( final BigDecimal x , final double y ) { return mul( x , v( y ) ); } public static BigDecimal mul( final double x , final BigDecimal y ) { return mul( v( x ) , y ); } public static BigDecimal sub( final BigDecimal x , final BigDecimal y ) { return x.subtract( y ); } public static BigDecimal sub( final BigDecimal x , final double y ) { return sub( x , v( y ) ); } public static BigDecimal sub( final double x , final BigDecimal y ) { return sub( v( x ) , y ); } public static BigDecimal v( final double value ) { return BigDecimal.valueOf( value ); } } " B12811,"import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Scanner; public class RecycledNumbers { static ArrayList perm(int j){ ArrayList ret = new ArrayList(); String num = j+""""; int aux; for(int i=0; i>conj= new HashSet>(); HashMapaux; a= in.nextInt(); b= in.nextInt(); for(int j=a; j<=b; j++){ ArrayList arr=perm(j); for(int h=0; h(); aux.put(Math.min(j, arr.get(h)), Math.max(j, arr.get(h))); if(arr.get(h)!=j && arr.get(h)<=b && arr.get(h)>=a && !conj.contains(aux)){ res++; conj.add(aux); } } } out.println(""Case #""+i+"": ""+res); } out.close(); System.exit(0); } } " B10464,"package ulohy; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class codejam_3 { static byte cases; static int A, B; static List l1 = new ArrayList(); static List l2 = new ArrayList(); static int[] pairs; static int[] rotated_array = new int[10]; public static void read_input() { Scanner s = null; try { s = new Scanner(new FileReader(""./src/ulohy/C-small-attempt1.in"")); } catch (FileNotFoundException e) { e.printStackTrace(); } cases = s.nextByte(); pairs = new int[cases]; for (int i = 0; i < cases; i++) { l1.add(s.nextInt()); l2.add(s.nextInt()); } s.close(); } public static void write_output() { FileWriter outFile; try { outFile = new FileWriter(""./src/ulohy/output""); PrintWriter out = new PrintWriter(outFile); for (int i = 1; i <= cases; i++) { out.println(""Case #""+i+"": ""+pairs[i-1]); } out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static int rotateNumber(int number, int mul) { return number / 10 + mul * (number % 10); } public static void main(String args[]) { int rotated; read_input(); for (int i = 0; i < cases; i++) { int numdigits = (int) Math.log10((double)l1.get(i)); // would return numdigits - 1 int multiplier = (int) Math.pow(10.0, (double)numdigits); for (int j = l1.get(i); j <= l2.get(i); j++) { rotated = rotateNumber(j, multiplier); for (int k = 0; k <= numdigits; k++) { if (j < rotated && rotated <= l2.get(i)) { for (int k2 = 0; k2 < k; k2++) { if (rotated == rotated_array[k2]) { pairs[i]--; } } pairs[i]++; } rotated_array[k] = rotated; rotated = rotateNumber(rotated, multiplier); } } } write_output(); } }" B10710,"// Mario Morales import java.util.*; import java.io.*; public class p3{ public static void main(String[] args) throws Exception{ BufferedReader f = new BufferedReader(new FileReader(""input3small.txt"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""answer3small.txt""))); //Brute Force Solution int t = Integer.parseInt(f.readLine()); //# of test cases StringTokenizer st; int a, b, d, res; String aNew; for(int i=0; i result = new HashSet(); for(Integer i=A;i<=B;i++){ char[] num = i.toString().toCharArray(); for(int j= 0;j0;k--){ num[k] = num[k-1]; } num[0] = x; String newStr = new String(num); if(!newStr.startsWith(""0"") && !newStr.equals(i.toString())){ Integer newNum = new Integer(new String(num)); if(newNum>=A && newNum <=B){ result.add(i.toString()+newStr); result.add(newStr+i.toString()); } } } } System.out.format(""Case #%d: %d\n"", zz, result.size()/2); } } } " B12944,"package lt.kasrud.gcj.common; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class IO { public static Data readFile(String filename) throws IOException { Data results = new Data(); BufferedReader reader = new BufferedReader(new FileReader(filename)); String line = null; while ((line = reader.readLine()) != null) { results.add(new Record(line)); } reader.close(); return results; } private static String formatCase(int caseNr, String output) { return String.format(""Case #%d: %s"", caseNr, output); } public static void writeFile(String filename, List data) throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(filename)); for (int i = 0; i < data.size(); i++) { String output = formatCase(i + 1, data.get(i).toString()); writer.write(output + ""\n""); } writer.close(); } public static class Data { List records = new ArrayList(); public void add(Record record){ records.add(record); } public String getString(int recNr, int i){ Record record = records.get(recNr); return record.getString(i); } public Integer getInt(int recNr, int i){ Record record = records.get(recNr); return record.getInt(i); } public List getRecords(int from){ return getRecords(from, records.size()); } public List getRecords(int from, int to){ return records.subList(from, to); } } public static class Record { String raw; String[] tokens; Record(String raw) { this(raw, "" ""); } Record(String raw, String separator) { this.raw = raw; tokens = raw.trim().split(separator); } public String getRaw() { return raw; } public String getString(int i) { return tokens[i]; } public int getInt(int i) { return Integer.valueOf(getString(i)); } public List getStringList(int from){ return getStringList(from, tokens.length); } public List getStringList(int from, int to){ return Arrays.asList(tokens).subList(from, to); } public List getIntList(int from){ return getIntList(from, tokens.length); } public List getIntList(int from, int to){ List strings = Arrays.asList(tokens).subList(from, to); List ints = new ArrayList(strings.size()); for (String s : strings){ ints.add(Integer.valueOf(s)); } return ints; } } } " B12616,"package util; import java.math.BigInteger; public class CombinationGenerator { private int[] a; private int n; private int r; private BigInteger numLeft; private BigInteger total; //------------ // Constructor //------------ public CombinationGenerator (int n, int r) { if (r > n) { throw new IllegalArgumentException (); } if (n < 1) { throw new IllegalArgumentException (); } this.n = n; this.r = r; a = new int[r]; BigInteger nFact = getFactorial (n); BigInteger rFact = getFactorial (r); BigInteger nminusrFact = getFactorial (n - r); total = nFact.divide (rFact.multiply (nminusrFact)); reset (); } //------ // Reset //------ public void reset () { for (int i = 0; i < a.length; i++) { a[i] = i; } numLeft = new BigInteger (total.toString ()); } //------------------------------------------------ // Return number of combinations not yet generated //------------------------------------------------ public BigInteger getNumLeft () { return numLeft; } //----------------------------- // Are there more combinations? //----------------------------- public boolean hasMore () { return numLeft.compareTo (BigInteger.ZERO) == 1; } //------------------------------------ // Return total number of combinations //------------------------------------ public BigInteger getTotal () { return total; } //------------------ // Compute factorial //------------------ private static BigInteger getFactorial (int n) { BigInteger fact = BigInteger.ONE; for (int i = n; i > 1; i--) { fact = fact.multiply (new BigInteger (Integer.toString (i))); } return fact; } //-------------------------------------------------------- // Generate next combination (algorithm from Rosen p. 286) //-------------------------------------------------------- public int[] getNext () { if (numLeft.equals (total)) { numLeft = numLeft.subtract (BigInteger.ONE); return a; } int i = r - 1; while (a[i] == n - r + i) { i--; } a[i] = a[i] + 1; for (int j = i + 1; j < r; j++) { a[j] = a[i] + j - i; } numLeft = numLeft.subtract (BigInteger.ONE); return a; } } " B11238,"import java.util.Scanner; import java.io.File; public class RecycledNumbers { public static void main(String[] args) { Scanner input = null; boolean[][] counted; try { input = new Scanner(new File(args[0])); } catch (Exception e) { System.out.println(""Please pass a correct filename as a program parameter""); System.exit(1); } int t, a, b; t = input.nextInt(); input.nextLine(); int recycledCount = 0; for (int testNumber = 0; testNumber < t; testNumber++) { a = input.nextInt(); b = input.nextInt(); input.nextLine(); counted = getFalseArray(b-a+1); // For each test case, look at all numbers between A and B as a possibleN for (int possibleN = a; possibleN <= b; possibleN++) { // For each possibleN, consider each recycled form for (int offset = 1; offset < String.valueOf(possibleN).length(); offset++) { int cycledN = Integer.parseInt(cycleRight("""" + possibleN, offset)); // For each recycled form, consider whether it is within the appropriate range if (cycledN >= a && cycledN <= b) { // These numbers are cycled forms of eachother. Are they suitable? if (possibleN != cycledN && counted[min(possibleN, cycledN)-a][max(possibleN, cycledN)-a] == false) { counted[min(possibleN, cycledN)-a][max(possibleN, cycledN)-a] = true; recycledCount++; } } } } System.out.println(""Case #"" + (testNumber+1) + "": "" + recycledCount); recycledCount = 0; } } public static String cycleRight(String number, int positions) { int intLen = number.length(); while (positions > 0) { // Cycle one right number = number.charAt(intLen-1)+number.substring(0, intLen-1); positions--; } return number; } public static boolean[][] getFalseArray(int size) { boolean[][] array = new boolean[size][size]; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { array[i][j] = false; } } return array; } public static int min(int a, int b) { return (a < b ? a : b); } public static int max(int a, int b) { return (a < b ? b : a); } }" B10417,"package com.google.codjam.problems; import java.util.ArrayList; import java.util.HashMap; import java.util.StringTokenizer; public class RecycledNumbers implements ProblemInterface { public String run(ArrayList dataCase) { ArrayList numbers= dataCase; String aString = numbers.get(0).toString().split("" "")[0]; String bString = numbers.get(0).toString().split("" "")[1]; HashMap map = new HashMap(); int A = Integer.parseInt(aString) ; int B = Integer.parseInt( bString) ; int counter =0; int minMov=1; int currentM=minMov; int maxMov=aString.length(); System.out.println(""***************INICIO""); while(maxMov>currentM) { for ( int i=A ; i A-1&&m iso=new ArrayList(); for (int i=0; i store = new ArrayList(); //system.out.print(x+"" => ""); int count = 0; String num = x+""""; int a = 0; int b = 0; for(int i=1;i= A && !store.contains(val+"""")) { count++; store.add(val+""""); //system.out.print("" ""+val); //system.out.print(""*""); } } //system.out.println(); //system.out.println(count+""c""); ////system.out.println(""-----""); return count; } class InputScanner { BufferedReader br; StringTokenizer strtok = null; public InputScanner(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } public InputScanner(File file) throws FileNotFoundException { br = new BufferedReader(new FileReader(file)); } public String next() { if (strtok == null || !strtok.hasMoreTokens()) { try { strtok = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return strtok.nextToken(); } public int nextInt() { int i; try { i = Integer.parseInt(next()); } catch (NumberFormatException e) { throw new RuntimeException(e); } return i; } public String nextLine() { if (strtok == null || !strtok.hasMoreTokens()) { try { strtok = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return strtok.nextToken(""\n"").trim(); } } }" B10252,"import java.util.Scanner; import java.io.File; public class Main{ public static void main(String[] args) throws Exception{ Scanner s = new Scanner(new File(""C-small-attempt0.in"")); int test = Integer.parseInt(s.nextLine()); for(int i=1; i<=test; i++){ int a = s.nextInt(); int b = s.nextInt(); int pairs = 0; for(int n=a; n= 1){// 4 digits int one = (t%1000) * 10 + t/1000; if(one <= M && one >= N && one != t && !dp[one]){ answer++; } one = (t%100) * 100 + t/100; if(one <= M && one >= N && one != t && !dp[one]){ answer++; } one = (t%10)*1000 + t/10; if(one <= M && one >= N && one != t && !dp[one]){ answer++; } } else if(t / 100 >= 1){ // 3digits int one = (t % 100) * 10 + t/100; if(one <= M && one >= N && one != t && !dp[one]){ answer++; } one = (t % 10) * 100 + t/10; if(one <= M && one >= N && one != t && !dp[one]){ answer++; } } else if(t / 10 >= 1){ // 2digits int one = (t % 10) * 10 + t/10; if(one <= M && one >= N && one != t && !dp[one]){ answer++; } } else{ // 1 digit } dp[t] = true; return answer; } public static void main(String[] args) throws FileNotFoundException { int answer = 0; Scanner scan = new Scanner(System.in); int max = scan.nextInt(); for(int i = 1; i <= max; i++){ for(int j = 0; j < 1000; j++){ dp[j] = false; } int N = scan.nextInt(); int M = scan.nextInt(); for(int j = N; j <= M; j++){ answer = answer + store(j, N, M); } System.out.println(""Case #"" + i + "": "" + answer); answer = 0; } } } " B12442,"import java.io.File; import java.io.FileNotFoundException; import java.util.Collections; import java.util.LinkedList; import java.util.Scanner; public class CSmall { LinkedList[] map; public static void main(String[] args) throws FileNotFoundException { CSmall csmall = new CSmall(); csmall.generateMap(1005); Scanner scanf = new Scanner(new File(""CSmall_in.txt"")); int T = scanf.nextInt(); for (int t = 1; t <= T; t++) { int A = scanf.nextInt(); int B = scanf.nextInt(); System.out.println(""Case #"" + t + "": "" + csmall.result(A, B)); } } int result( int a, int b) { int total = 0; for (int n = a; n <= b; n++) { int current = countBetween(n, a, b); total += current; } return total; } int countBetween( int n, int low, int high) { LinkedList list = map[n]; int lowIndex = 0; for (; lowIndex < list.size() && list.get(lowIndex) < low; lowIndex++) ; int highIndex = lowIndex; for (; highIndex < list.size() && list.get(highIndex) <= high; highIndex++) ; return highIndex - lowIndex; } void generateMap( int size) { map = new LinkedList[size + 1]; for (int i = 0; i < map.length; i++) { map[i] = new LinkedList(); } for (int n = 1; n <= map.length; n++) { char[] charsInN = Integer.toString(n).toCharArray(); for (int j = 0; j < charsInN.length; j++) { int rotation = rotateLeft(charsInN); if (rotation > size) { continue; } if (rotation < n) { map[rotation].add(n); } } } for (int i = 0; i < map.length; i++) { Collections.sort(map[i]); } } int rotateLeft( char[] chars) { int l = chars.length - 1; char c = chars[0]; for (int i = 0; i < l; chars[i] = chars[++i]) ; chars[l] = c; return Integer.parseInt(new String(chars)); } } " B12585," import java.util.Scanner; /** * * @author krishna */ public class Recycled { public static void main(String[] args) { Program(); } public static void Program() { Scanner inp = new Scanner(System.in); String line; String nor[]; int num1, num2; int test = Integer.parseInt(inp.nextLine()); int num = 1; while (num <= test) { line = inp.nextLine(); nor = line.split("" ""); num1 = Integer.parseInt(nor[0]); num2 = Integer.parseInt(nor[1]); System.out.println(""Case #""+num+"": ""+CountNum(num1, num2)); num++; } } public static int CountNum(int num1, int num2) { int count = 0; int goMax[]={9,99,999,9999,99999,999999}; int goMin[]={0,10,100,1000,10000,100000}; int length; for (int x = num1; (x < num2) && !leadingZeros(x); x++) { { length=Integer.valueOf(x).toString().length(); count +=found(x,Math.max(num1,(int)goMin[length-1]),(int)Math.min(num2,goMax[length-1])); } } return count; } private static int found(int num, int min, int max) { int part1; int part2; int zero=10; String join; int rem; int count=0; while(num/zero !=0) { rem=num%zero; part1=rem; part2=num/zero; join=part1+""""+part2; zero =zero*10; if(Integer.parseInt(join)>=min && Integer.parseInt(join)<=max && Integer.parseInt(join) > num && checkLength(num,join) ){ count++; } if(alternate(join,max)) count--; } return count; } public static boolean leadingZeros(int num) { String str=num+""""; if(str.charAt(0)=='0') return true; else return false; } public static boolean checkLength(int num1,String str2) { String str1=num1+""""; if(str1.length() == str2.length()) return true; else return false; } public static boolean alternate(String str,int max) { String str2=str.substring(1); str2=str2+str.charAt(0); if(str==str2) { return true; } else return false; } } " B10685,"import java.io.*; import java.util.*; public class RecycledNumbers { public static void main(String [] args) throws Exception { BufferedReader br = new BufferedReader(new FileReader(""CI.txt"")); String write = """"; int i = Integer.parseInt(br.readLine()); for(int j = 1; j <= i; j++) { String ra = br.readLine(); int c = 0; Integer [] ir = c(ra.split("" "")); for(int k = ir[0]; k < ir[1]; k++) { String number1 = """" + k; String number2 = """"; int m = 0; HashSet size= new HashSet (); for(int l = 1; l < number1.length(); l++) { if(number1.charAt(0) <= number1.charAt(l)) { number2 = number1.substring(l) + number1.substring(0,l); m = Integer.parseInt(number2); if(m <= ir[1] && m > k) { if(!size.contains(number2)) { //System.out.println(k + "" "" + m); c = c + 1; } size.add(number2); } } } } String newLine = ""\n""; if(j == i) newLine = """"; write = write + ""Case #"" + j + "": "" + c + newLine; //System.out.println(""Case #"" + j + "": "" + c); } BufferedWriter bw = new BufferedWriter(new FileWriter(""CO.txt"")); bw.write(write); bw.flush(); bw.close(); System.out.println(write); } static Integer [] c(String [] args) { Integer [] array = new Integer[args.length]; for(int i = 0; i < args.length; i++) { array [i] = Integer.parseInt(args[i]); } return array; } }" B12048,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.PriorityQueue; import java.util.SortedSet; import java.util.TreeSet; import java.util.Vector; public class User { private static final String FILENAME = ""C-small-attempt0.in""; private static final String OUTFILENAME = ""C-small-attempt0.out""; public static String newline = System.getProperty(""line.separator""); public static void main(String[] args) throws Exception { // System.out.println(decoder.keySet()); // System.out.println(decoder.values()); PrintWriter out = new PrintWriter(new FileWriter(OUTFILENAME)); // PrintStream out = System.out; FileReader fr = null; try { fr = new FileReader(FILENAME); } catch (FileNotFoundException e) { e.printStackTrace(); } BufferedReader input = new BufferedReader(fr); String[] line; String n; int digCount; String m; int recycledPairs = 0; int T = Integer.parseInt(input.readLine()); for (int t=0; t> digitMap = new HashMap> (); recycledPairs = 0; line = input.readLine().split("" ""); n = line[0]; m = line[1]; int nInt = Integer.parseInt(n); int mInt = Integer.parseInt(m); for (int i = nInt; i<=mInt; i++){ String myChars = findChars(i); if (digitMap.containsKey(myChars)){ digitMap.get(myChars).add(i); // System.out.println (""adding ""+ i + "" to ""+ myChars + "" new size is "" + digitMap.get(myChars).size()); } else { TreeSet myTreeSet = new TreeSet(); myTreeSet.add(i); digitMap.put(myChars, myTreeSet); // System.out.println (""adding ""+ i + "" to ""+ myChars + "" new size is "" + digitMap.get(myChars).size()); } } for (TreeSet myTreeSet : digitMap.values()){ if (myTreeSet.size()>1){ Integer[] setArray = myTreeSet.toArray(new Integer[0]); int saLen = setArray.length; for (int i = 0; i recyclings = (number > 9) ? getRecyclings(number) : Collections.emptySet(); if (!recyclings.isEmpty()) ignore(recyclings); int numberOfDistinctPairs = recyclings.isEmpty() ? 0 : getNumberOfDistinctPairs(recyclings); distinctPairs += numberOfDistinctPairs; } } return distinctPairs; } private int getNumberOfDistinctPairs(Set recyclings) { int recyclingsThatCount = 0; for (String s : recyclings) { int number = Integer.parseInt(s); if (withinBounds(number) && doesntStartWithZero(s)) recyclingsThatCount++; } int pairs = recyclingsThatCount * (recyclingsThatCount - 1) / 2; return pairs; } private boolean doesntStartWithZero(String s) { boolean result = s.charAt(0) != '0'; return result; } private boolean withinBounds(int number) { boolean result = number >= A && number <= B; return result; } private void ignore(Set recyclings) { //set them to true in the array for (String s : recyclings) { int number = Integer.parseInt(s); if (withinBounds(number)) allNumbers[numberToIndex(number)] = true; } } private int numberToIndex(int number) { return number - A; } private int indexToNumber(int i) { return i + A; } private Set getRecyclings(int number) { String numberAsString = Integer.toString(number); int totalDigits = numberAsString.length(); Set recyclings = new HashSet(); for (int i = totalDigits - 1; i >= 0; i--) { recyclings.add(numberAsString.substring(i, totalDigits) + numberAsString.substring(0, i)); } return recyclings; } } " B10120,"package GCJ; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class ProblemC { public static void main(String args[]) throws IOException{ File file = new File(""I:/res/ACMCS/GCJ/C-small-attempt0.in""); File outFile = new File(""I:/res/ACMCS/GCJ/problemC.out.txt""); FileWriter fw = new FileWriter(outFile); BufferedWriter bw = new BufferedWriter(fw); //FileReader fileReader = new FileReader(file); Scanner in = new Scanner(file); int cs = in.nextInt(); int c = 0; while(cs -- > 0){ ++ c; int ans = 0; int A = in.nextInt(); int B = in.nextInt(); for(int i = A; i <= B; ++ i) for(int j = i + 1; j <= B; ++ j) if(isRecycle(i, j)) ++ ans; bw.write(""Case #""); bw.write(String.valueOf(c)); bw.write("": ""); bw.write(String.valueOf(ans)); bw.newLine(); } bw.close(); } public static boolean isRecycle(int n, int m){ String str = String.valueOf(n); int len = str.length(); int mapN[] = new int[len]; for(int i = len - 1; i >= 0; -- i){ mapN[i] = n % 10; n /= 10; } int mapM[] = new int[len]; for(int i = len - 1; i >= 0; -- i){ mapM[i] = m % 10; m /= 10; } for(int i = 0; i < len; ++ i){ boolean flag = true; for(int j = i, k = 0; k < len; ++ k){ if(mapN[(j + k) % len] != mapM[k]) {flag = false;break;} } if(flag) return true; } return false; } } " B11384,"import java.util.Scanner; import java.io.BufferedInputStream; import java.util.HashSet; public class C { public static void main(String[] args) { Scanner scanner = new Scanner(new BufferedInputStream(System.in)); int n = scanner.nextInt(); for (int i = 0; i < n; i++) { int count = 0; int low = scanner.nextInt(); int high = scanner.nextInt(); for (int j = low; j < high; j++) { String s = Integer.toString(j); String s2; int len = s.length(); HashSet set = new HashSet(); for (int k = 0; k < len-1; k++) { s2 = s.substring(len-k-1, len) + s.substring(0, len-k-1); int num = Integer.parseInt(s2); //System.out.println(num); if (num >= low && num <= high && num > j && !set.contains(num)) { count++; set.add(num); } } } System.out.println(""Case #"" + (i+1) + "": "" + count); } } } " B11334,"import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class ProblemSample implements Problem { private int solution; private int A; @Override public void solve() { int resultat = 0; for (int n = A; n <= B; n++) { // on trouve toutes les rotations de n String stringN = Integer.toString(n); int size = stringN.length(); Set mySet = new HashSet(); for (int i = 0; i < size; i++) { String actuel = rotation(stringN, size, i); // le set contient les candidats mais pas les doublons mySet.add(Integer.parseInt(actuel)); } // on vérifie si les rotations trouvées sont bonnes ou pas. for (Integer candidat : mySet) { if (candidat > n && candidat <= B) { // si la solution est bonne alors on incrémente. resultat++; } } } this.setSolution(resultat); } private String rotation(String stringN, int size, int nbRotation) { String res = stringN; return res.substring(size - nbRotation, size) + res.substring(0, size - nbRotation); } @Override public Object getSolution() { return solution; } public void setSolution(int solution) { this.solution = solution; } public int getA() { return A; } public void setA(int a) { A = a; } public int getB() { return B; } public void setB(int b) { B = b; } public List getSums() { return sums; } public void setSums(List sums) { this.sums = sums; } private int B; private List sums = new ArrayList(); }" B11687,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; public class C { public static void main(String args[]){ try{ BufferedReader br = new BufferedReader(new FileReader(args[0])); String strTmp = br.readLine(); BufferedWriter bw = new BufferedWriter(new FileWriter( new File(""output.txt""),false)); int inputSize = Integer.parseInt(strTmp); for(int i=0;i uniqList = new ArrayList(); for(int k=0;k - 51234 - 45123 - 34512 - 23451 - Since leading 0 is not count, 100, 001 are not pairs, so any number if the swap number start with 0 will not have pairs. - Divide the number into 2 parts, left, right by a mid point. - Then compare the left right to the range-left, range-right, if within that range that marks as pairs - There must be another number which is this number pairs - Same Digit - The number of pairs within a range = Num of itm in range * (Num of Digit - 1), e.g. 1111~2222 => (2222-1111+1) * (4-1) = 3336. - Since n=nw) continue; if (r>al[k] && r=A && nw<=B){ if (!contains(used, nw)){ res++; used[usedcnt++]=nw; //System.out.println(""j=""+j+""(""+l+"",""+r+""); add2(""+i+"") nw=""+nw); } } } } } return res; } public void doMain() throws Exception{ try{ Scanner sc1 = null; BufferedReader br = new BufferedReader(new FileReader(IN_FILE)); BufferedWriter bw = new BufferedWriter(new FileWriter(OUT_FILE)); int T = Integer.parseInt(br.readLine()); for (int a=0; a set = new HashSet(); public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new File(""C-small-attempt0.in"")); FileWriter fw = new FileWriter(""C-output.txt""); int total = sc.nextInt(); for(int i = 1; i <= total; i++) { set.clear(); int count = 0, st = sc.nextInt(), end = sc.nextInt(); for(int j = st; j < end; j++) process(j, end); fw.write(""Case #"" + i + "": "" + set.size() + ""\n""); System.out.println(""Case #"" + i + "": "" + set.size()); } fw.close(); } private static void process(int num, int max) { int digit = 10; while(digit < num) { int div = num / digit, rem = num % digit; int switched = Integer.parseInt("""" + rem + div); if(num < switched && switched <= max) { String s = num + "", "" + switched; set.add(s); } digit *= 10; } } } " B13173,"package gcj; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.InputStreamReader; import java.io.PrintStream; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) throws Exception { BufferedReader br=null; if(args.length>=1) br=new BufferedReader(new FileReader(new File(args[0]))); else br=new BufferedReader(new InputStreamReader(System.in)); if(args.length>=2) System.setOut(new PrintStream(new FileOutputStream(args[1]))); int T=Integer.valueOf(br.readLine().trim()); for(int t=1;t<=T;++t) { String[] temp=br.readLine().trim().split("" ""); int A=Integer.valueOf(temp[0]); int B=Integer.valueOf(temp[1]); int ret=0; for(int i=A;i<=B;++i) { for(int j=i+1;j<=B;++j) { String ai=""""+i; String bj=""""+j; if(ai.length()!=bj.length()) continue; boolean yes=false; for(int k=0;k map = new HashMap(); for (int i = 1; i < len; i++) { long tmp = Long.parseLong(str.substring(len - i) + str.substring(0, len - i)); if (min <= tmp && tmp <= max && tmp > no) { if (!map.containsKey(tmp)) { res++; map.put(tmp, 0); } } } return res; } } " B11029,"package org.moriraaca.codejam; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface SolverConfiguration { OutputDestination outputDestination() default OutputDestination.STDOUT; String inputFileName() default ""sample.in""; DebugOutputLevel debugOutputLevel() default DebugOutputLevel.SOLUTION; Class parser(); } " B12262,"import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Scanner; import java.io.BufferedWriter; public class D { public static void main(String[] args) throws IOException { int n; InputStreamReader reader = new InputStreamReader(new FileInputStream( args[0])); BufferedReader read = new BufferedReader(reader); BufferedWriter write = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(args[1]))); // Scanner scan = new Scanner(System.in); n = Integer.parseInt(read.readLine()); // n = scan.nextInt(); for (int i = 0; i < n; i++) { String p = read.readLine(); write.write(""Case #"" + (i + 1) + "": "" + holy(p, read)); write.newLine(); } write.flush(); write.close(); } static int holy(String r, BufferedReader read) throws IOException { String p = r; String s, temp, m; int a = 0; int b = 0; int panjang = 0; int result = 0; a = Integer.parseInt(p.substring(0, p.indexOf("" ""))); b = Integer.parseInt(p.substring(p.indexOf("" "") + 1, p.length())); for (int i = a; i <= b; i++) { s = Integer.toString(i); panjang = s.length(); for (int j = 1; j < panjang; j++) { temp = s.substring(0, j); m = s.substring(j, panjang) + temp; if (Integer.parseInt(m) == i) { } else if (Integer.parseInt(m) <= b && Integer.parseInt(m) >= a) { result++; } } } if ((result % 2) == 0) { result = result/2; } else if (result % 2 == 1) { result = result/2+1; } return result; } }" B11489,"import java.util.Scanner; public class ProblemC { static Scanner in = new Scanner(System.in); public static void main(String[] args) { int lineCount = Integer.valueOf(in.nextLine()); int[] T = new int[lineCount]; for(int t = 0; t < lineCount; t++) { int A = in.nextInt(), B = in.nextInt(), count = 0; for (int n = A; n <= B; n++) { int digits = String.valueOf(n).length() - 1; String m = """" + n, lastAdded = """"; for (int i = 0; i < digits; i++) { int mi = Integer.valueOf(m = m.charAt(digits) + m.substring(0, digits)); if (mi <= B && mi > n && !lastAdded.contains("""" + mi)) { lastAdded += mi + "" ""; count++; } } } T[t] = count; } for(int i = 1; i <= lineCount; i++) { System.out.println(""Case #"" + i + "": "" + T[i-1]); } } } " B12744,"import java.io.*; import java.util.*; public class q3 { public static void main(String []args) throws IOException { PrintWriter pw=new PrintWriter(new BufferedWriter(new FileWriter(""output.txt""))); BufferedReader br=new BufferedReader(new FileReader(""input.txt"")); int arr[]=new int[2]; int limit=Integer.parseInt(br.readLine()); String x2; int count=0; for(int li=1;li<=limit;li++) {count=0; x2=br.readLine(); int j=0; StringTokenizer st =new StringTokenizer(x2); while (st.hasMoreElements()) { String token = st.nextElement().toString(); arr[j]=Integer.parseInt(token); j++; } for(int a1=arr[0];a1<=arr[1];a1++) { String x1=String.valueOf(a1); int l=x1.length(); String final1=""""; for(int x=1;x<=(l-1);x++) { final1=x1.substring(l-x,l)+x1.substring(0,l-x); int check=Integer.parseInt(final1); if(a10) writer.append(""\n""); int s1 = solve(A,B); //int s2 = solveAlt(A,B); //if(s1!=s2) System.out.println(""$$$ - "" + i); writer.append(""Case #""+(i+1)+"": "" + s1); } writer.flush(); } private static int solveAlt(int A, int B) { Set used = new HashSet(); int res = 0; for(int i=A;ii && p<=B) { if(used.contains(pp)) continue; used.add(pp); res++; } } } return res; } private static int solve(int A, int B) { Set used = new HashSet(); int res = 0; for(int i=A;ii && p<=B) { if(used.contains(p)) continue; used.add(p); res++; } } } return res; } private static int getShifted(int i, int j, int len) { int v = (int)Math.pow(10,j); int x = (int)Math.pow(10,len-j); return i/v + i%v*x; } private static int getLen(int i) { int len = 1; int val = 10; while (i>val-1) { len++; val*=10; } return len; } } " B10825,"import java.io.FileReader; import java.io.BufferedReader; import java.io.FileWriter; import java.io.BufferedWriter; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { try{ //read file FileReader filein = new FileReader(args[0]); BufferedReader in = new BufferedReader(filein); //write file FileWriter fileout = new FileWriter(""output.txt""); BufferedWriter out = new BufferedWriter(fileout); //process data int numcases = Integer.valueOf(in.readLine()).intValue(); for(int i=0; i seen = new HashSet(); //System.out.println(""("" + lowB + "", "" + highB + ""), "" + ""bits = "" + bits + "", mod = "" + mod); for (int i = lowB; i <= highB; i++){ int num1 = i; int num2 = i; seen.clear(); for (int j = 1; j < bits; j++){ int div = num2 / mod; int modular = num2 % mod; num2 = modular * 10 + div; if (num2 < lowB || num2 <= num1 || num2 > highB || seen.contains(num2)) continue; //System.out.println(""("" + num1 + "", "" + num2 + "")""); pairCount++; seen.add(num2); } } System.out.println(""Case #"" + count+ "": "" + pairCount); } } } " B10786,"package jam_q_c_s; import java.util.*; public class Jam_Q_C_S { public static void main(String[] args) { int[] A = {116,144,168,240,165,169,170,142,202,162,15,171,10,164,135,169,120,10,125,177,142,135,146,180,160,142,156,183,173,158,103,11,164,1,144,190,110,146,158,6,100,122,187,823,123,319,100,248,115,188}; int[] B = {963,996,994,925,918,924,926,911,353,970,53,952,99,972,954,913,965,99,990,931,942,910,924,950,918,944,996,967,996,970,999,34,926,1,923,956,944,977,978,7,101,941,924,823,941,319,920,857,939,990}; for(int i=0; i T = new HashSet(); String x = """" + X; for (int i = 0; i < x.length() - 1; i++) { int Y = Integer.parseInt(x = x.substring(1) + x.charAt(0)); if (Y > X && Y <= B) T.add(Y); } r += T.size(); } return r; } }" B10914,"import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int testCases = sc.nextInt(); for (int i = 1; i <= testCases; i++) { int A = sc.nextInt(); int B = sc.nextInt(); int digit = ("""" + A).toCharArray().length; int result = 0; for (int j = A; j <= B; j++) { char[] cs = ("""" + j).toCharArray(); Set set = new HashSet(); for (int k = 1; k < digit; k++) { String str = """"; for (int l = 0; l < digit; l++) { str += cs[(k + l) % digit]; } int temp = Integer.parseInt(str); if (j < temp && temp <= B) { set.add(temp); } } result += set.size(); } System.out.println(""Case #"" + i +"": "" + result); } } } " B12045,"package RecycledNumbers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.StringTokenizer; public class RecyledNumbers { public RecyledNumbers() { } public static int findRecycled(int low, int high) { Set pairs = new HashSet(); for (int i = low; i <= high; i++) { String s = String.valueOf(i); for (int j = 1; j < s.length(); j++) { String newString = s.substring(j) + s.substring(0, j); int newValue = Integer.parseInt(newString); if (newValue <= high && newValue >= low && newValue != i && !newString.startsWith(""0"")) { if (!pairs.contains(new Pair(newValue, i))) { pairs.add(new Pair(i, newValue)); } } } } return pairs.size(); } private static int parse(String input) { StringTokenizer st = new StringTokenizer(input, "" ""); if (st.countTokens() != 2) throw new IllegalArgumentException(""Wrong no of values""); int low = Integer.parseInt(st.nextToken()); int high = Integer.parseInt(st.nextToken()); return findRecycled(low, high); } public static void main(String[] args) { if (args.length != 2) throw new IllegalArgumentException(""No file specified""); List data = new ArrayList(); List results = new ArrayList(); try { FileInputStream fstream = new FileInputStream(args[0]); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { data.add(strLine); } in.close(); } catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } if (data.size() == 0) throw new IllegalArgumentException(""No data in file""); int noTestCases = Integer.parseInt(data.get(0)); if (data.size() != noTestCases + 1) throw new IllegalArgumentException(""Number of test cases is not "" + noTestCases); for (int i = 1; i <= noTestCases; i++) { results.add(""Case #"" + i + "": "" + parse(data.get(i))); } try { FileWriter fostream = new FileWriter(args[1]); BufferedWriter out = new BufferedWriter(fostream); for (int i =0;i mMap = new HashMap(); int results = 0; final int digits = 1 + (int)Math.floor(Math.log10(A)); for (int n = A; n < B; n++){ if (digits == 1) break; //System.out.println(n); m = flipNumber(n, 1); mMap.put(m, m); if (n < m && m <= B) results++; if (digits > 2){ m = flipNumber(n, 2); if (n < m && m <= B && !mMap.containsKey(m)){ mMap.put(m, m); results++; } } if (digits > 3){ m = flipNumber(n, 3); if (n < m && m <= B && !mMap.containsKey(m)){ mMap.put(m, m); results++; } } mMap.clear(); } System.out.println(""Case #"" + (i + 1) + "": "" + results); } } private static int flipNumber(int x, int way){ String num = """" + x; if (way == 1) num = num.substring(num.length() - 1) + num.substring(0, num.length() - 1); else if (way == 2) num = num.substring(num.length() - 2) + num.substring(0, num.length() - 2); else if (way == 3) num = num.substring(num.length() - 3) + num.substring(0, num.length() - 3); int p = Integer.parseInt(num); return p; } } " B12191,"import java.io.*; import java.math.BigInteger; import java.util.Arrays; import java.util.InputMismatchException; /** * @author Mikeldi Latorre (mikeldi10@gmail.com) */ public class RecycledNumbers implements Runnable { private InputReader in; private PrintWriter out; public static void main(String[] args) { new Thread(new RecycledNumbers()).start(); } public RecycledNumbers() { try { System.setIn(new FileInputStream(""C-small-attempt0.in"")); System.setOut(new PrintStream(new FileOutputStream(""C-small-attempt0.out""))); } catch (FileNotFoundException e) { throw new RuntimeException(); } in = new InputReader(System.in); out = new PrintWriter(System.out); } public void run() { int numTests = in.readInt(); for (int testNumber = 0; testNumber < numTests; testNumber++) { out.println(""Case #"" + (testNumber + 1) + "": ""+algorithm()); } out.close(); } private int b; private int algorithm(){ int a = in.readInt(); b = in.readInt(); int x = (int)Math.pow(10, (""""+a).length()-1); int ret = 0; for (int i = a; i <= b; i++) { ret += check(i,i,x); } return ret; } private int check(int num, int base, int x){ num = num%10*x+num/10; int ret = 0; if(num == base){ return 0; } if((num > base)&&(num <=b)){ ret++; } ret += check(num,base,x); return ret; } private static class InputReader { private InputStream stream; private byte[] buf = new byte[1000]; private int curChar, numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuffer buf = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { buf.appendCodePoint(c); c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) s = readLine0(); return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) return readLine(); else return readLine0(); } public BigInteger readBigInteger() { try { return new BigInteger(readString()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } public double readDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } } } " B11972,"import java.util.*; public class CodeJamC { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int t = scan.nextInt(); for (int i = 1; i <= t; i++) { int n = 0; int a = scan.nextInt(); int b = scan.nextInt(); for (int j = a; j <= b; j++) { int x = j; int m = 1; while (true) { x = rotate(x); if (x == j) { // Cycled n += m * (m - 1) / 2; break; } else if (a <= x && x <= b) { if (x < j) // Duplicate break; else m++; } } } System.out.printf(""Case #%d: %d%n"", i, n); } } private static int rotate(int x) { String s = x + """"; while (true) { s = s.substring(1) + s.charAt(0); if (s.charAt(0) != '0') return Integer.parseInt(s); } } }" B12331,"import java.io.*; import java.util.*; public class RecycledNumbers { private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private static Scanner sc = new Scanner(br); public static void main ( String [] args ) throws IOException { int N = Integer.parseInt(br.readLine()); for(int i = 0;i < N; i++) { System.out.print(""Case #"" + (i+1) + "": ""); new RecycledNumbers().cal(); } } private void cal() throws IOException { int A = sc.nextInt(); int B = sc.nextInt(); String aString = Integer.toString(A); int length = aString.length(); String testString; String testTemp; int checkingNumber; int counter = 0; boolean check = false; for(checkingNumber = A; checkingNumber < B; checkingNumber++ ){ int[] stack = new int[length-1]; testString = Integer.toString(checkingNumber); check = true; for(int i = 0; i < length-1; i++ ){ testTemp = testString.substring(1, length) + testString.substring(0, 1); testString = testTemp; if( checkingNumber < Integer.parseInt(testString)){ if( Integer.parseInt(testString) <= B ){ for(int k = 0; k < i; k++) if( stack[k] == Integer.parseInt(testString) ) check = false; if(check){ counter++; //System.out.println(checkingNumber + "" "" + testString+ "" ""+ counter); stack[i] = Integer.parseInt(testString); } } } } } System.out.println(counter); } } " B10428,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.HashSet; public class Recycle { public static void main(String[] args) throws IOException{ FileInputStream inFile = new FileInputStream(""C-small-attempt0.in""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(inFile); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String inputCnt = br.readLine(); FileOutputStream outFile = new FileOutputStream(""output.txt""); DataOutputStream out = new DataOutputStream(outFile); BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(out)); int cnt = Integer.parseInt(inputCnt); for(int line=1;line<=cnt;line++){ String inputString = br.readLine(); String[] splited = inputString.split("" ""); int A = Integer.parseInt(splited[0]); int B = Integer.parseInt(splited[1]); String outputString = ""Case #""+line+"": ""; int result = 0; for(Integer num = A; num<=B; num++){ //for each number String s = num.toString(); result += permute(s,num,B); } outputString += result+""""; wr.write(outputString); wr.newLine(); wr.flush(); } wr.close(); out.close(); br.close(); in.close(); inFile.close(); outFile.close(); } public static int permute(String original, int min, int max) { String target = original; HashSet resultSet = new HashSet(); for(int i = 1;imin && potential <= max) resultSet.add(potential); target = shifted; } return resultSet.size(); } } " B10650,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; public class RecycledNumbers { public static File input; public static FileReader inputreader; public static BufferedReader in; public static File output; public static FileWriter outputwriter; public static BufferedWriter out; public static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); public static StringTokenizer st; public static void main(String[] args) { try { String name = ""input-3""; setInput(name); setOutput(name + "".out""); int cases = getInt(); for(int caseNr = 1; caseNr <= cases; caseNr++) { int A = getInt(), B = getInt(); print(""Case #""+caseNr+"": ""); print(""""+getRecycledPairs(A, B)); print(""\n""); } out.flush(); out.close(); in.close(); } catch(Exception e) { e.printStackTrace(); } } public static int getRecycledPairs(int start, int stop) { int pairs = 0; ArrayList pairsList = new ArrayList(); String startAsString = """"+start; int numberOfDigits = startAsString.length(); for(int i = start+1; i <= stop; i++) { int oldVersion = i; int newVersion = i; String rotator = i+""""; for(int j = 1; j < numberOfDigits; j++) { rotator = moveDigitFromBackToFront(rotator); newVersion = Integer.parseInt(rotator); if (newVersion >= start && newVersion <= stop && newVersion < oldVersion) { //System.out.println(""Found pair ("" + newVersion + "", "" + oldVersion + "")""); MyTuple pairTuple = new MyTuple(newVersion, oldVersion); if (!pairsList.contains(pairTuple)) { pairs++; pairsList.add(pairTuple); } } } } return pairs; } public static String moveDigitFromBackToFront(String toMove) { String lastDigit = toMove.substring(toMove.length()-1); String toReturn = lastDigit + toMove.substring(0, toMove.length()-1); return toReturn; } private static class MyTuple { public int x, y; public MyTuple(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) { if (o instanceof MyTuple) { MyTuple t = (MyTuple) o; if (this.x == t.x && this.y == t.y) return true; } return false; } } // -------------------- I/O stuff ------------------------- public static void setInput(String filename) throws IOException { input = new File(filename); inputreader = new FileReader(input); in = new BufferedReader(inputreader); } public static void setOutput(String filename) throws IOException { output = new File(filename); outputwriter = new FileWriter(output); out = new BufferedWriter(outputwriter); } static void print(String s) throws IOException { System.out.print(s); out.write(s); } static String readLine() throws IOException { //return stdin.readLine(); return in.readLine(); } static String getToken() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(readLine()); return st.nextToken(); } static int getInt() throws IOException { return Integer.parseInt(getToken()); } static String getChar() throws IOException { return getToken(); } static String getLine() throws IOException { return readLine(); } } " B11134,"import java.util.Scanner; public class Problem3 { public static void main(String args[]){ Scanner in= new Scanner(System.in); Scanner rin= new Scanner(in.nextLine()); int T = rin.nextInt(); for(int l=0;l0;i--){ strC[i]=strC[i-1]; } strC[i]=temp; return (new String(strC)); } static boolean isRecycledPair(int n,int m){ String nS=Integer.toString(n); String mS=Integer.toString(m); if(nS.matches(mS)) return true; for(int i=0;i=subdigit2) && (subdigit1<=(B/Math.pow(10,digitcount-j)))) { newnumber = (int) (subdigit1*Math.pow(10, digitcount-j)+ (int)((i/Math.pow(10,j)))); if ((newnumber>i)&&(newnumber<=B)){ for (int k=0; knumValue)&&(num>=start)&&(num<=end)){ found++; System.out.println(""hello""); } } } out[i] = found; } } private static void writeOutput(String string) throws IOException { BufferedWriter bw = new BufferedWriter(new FileWriter(string)); for (int i = 0; i < out.length; i++) { bw.write(""Case #"" + (i + 1) + "": "" + out[i]); if (i != out.length - 1) { bw.write(""\r\n""); } } bw.close(); } } " B12449,"import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class Main2 { private static final String IN_FILE = ""in.txt""; private static final String OUT_FILE = ""out.txt""; private static List parseFile() throws IOException { BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(IN_FILE))); int count = Integer.parseInt(r.readLine()); List res = new ArrayList(); for(int i = 0; i < count; i++){ String line = r.readLine(); String[] tupel = line.split("" ""); Xxx d = new Xxx(); d.min = Integer.parseInt(tupel[0]); d.max = Integer.parseInt(tupel[1]); res.add(d); } r.close(); return res; } private static List process(List dl){ List res = new ArrayList(); for(Xxx d : dl){ int count = 0; // System.out.println(""-----------------------------------------""); List xxx = new ArrayList(); for(int x = d.min; x < d.max; x++){ String sx_orig = String.valueOf(x); int len = sx_orig.length(); String sy = null; xxx.clear(); if(len > 1){ for(int y = x + 1; y <= d.max && (sy = String.valueOf(y)).length() == len; y++){ String sx = sx_orig; for(int i = 1; i < sx.length(); i++){ char c = sx.charAt(sx.length()-1); sx = c + sx.substring(0, sx.length() - 1); if(sx.equals(sy)){ if(!xxx.contains(sx)){ xxx.add(sx); // System.out.println(sx_orig +""\t"" +sx); count++; continue; } } } } } } res.add(count); } return res; } private static void writeOutput(List data) throws IOException { BufferedWriter w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(OUT_FILE))); for(int i = 0; i < data.size(); i++){ if(i > 0){ w.write(""\n""); } String s = ""Case #"" +(i+1) +"": "" +data.get(i); w.write(s); } w.close(); } /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { List l = parseFile(); List r = process(l); writeOutput(r); System.out.println(""Done""); } private static class Xxx { public int min; public int max; } }" B12200," import java.io.*; import java.util.*; public class Q3 { public static void main(String[] args) { Q3 q = new Q3(); //System.out.println(q.calculate(10, 2000000)); //q.test(); q.answerSmall(); //q.answerLarge(); } public void answerSmall(){ read(""C-small-attempt0.IN"", ""Q3_small_output.txt""); } public void answerLarge(){ read(""C-large.IN"", ""Q3_large_output.txt""); } public void test(){ read(""Test3_input.txt"", ""Test3_output.txt""); } public void read(String readFrom, String writeTo){ try{ Scanner in = new Scanner(new File(readFrom)); File f = new File(writeTo); FileWriter fw = new FileWriter(f); int T = Integer.parseInt(in.nextLine()); int A, B; String[] input; String answer; for(int i = 1; i <= T; i++) { input = in.nextLine().split("" ""); A = Integer.parseInt(input[0]); B = Integer.parseInt(input[1]); answer = """" + calculate(A, B); if(i + 1 <= T) answer += ""\r\n""; fw.write(""Case #"" + i + "": "" + answer); } fw.close(); }catch(Exception ex) { System.out.println(ex); } } public int calculate(int A, int B) { int num = 0, m; String hold; ArrayList distinct = new ArrayList(); for(int n = A; n <= B; n++) { if(n > 10) { hold = """" + n; distinct.clear(); for(int i = 1; i < hold.length(); i++) { m = Integer.parseInt((hold.substring(i) + hold.substring(0,i))); if(m <= B && n < m && !distinct.contains(m)) { distinct.add(m); num++; } } } } return num; } } " B10566,"package code; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; public class C { final static String CASE_NO = ""Case #""; final static String SUFFIX = "": ""; /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { int total; int T; // nuber of test cases BufferedReader br = readFile(""testC""); T = Integer.parseInt(br.readLine()); total = T; while (T > 0) { T--; int pairs = 0; String line = br.readLine(); String[] input = line.split("" ""); int i = 0; int A = Integer.parseInt(input[i++]); int B = Integer.parseInt(input[i++]); for (int x = A; x < B; x++) { int mulFact = getMulFactor(x); int num = getPrefix(x, mulFact) + getSuffix(x); while (num != x) { if (num > x && num <= B) { pairs++; } num = getPrefix(num, mulFact) + getSuffix(num); } } System.out.println(CASE_NO + (total - T) + SUFFIX + pairs); } } private static BufferedReader readFile(String fileName) throws FileNotFoundException { FileReader fr = new FileReader(fileName); BufferedReader br = new BufferedReader(fr); return br; } private static int getMulFactor(int num) { int m = 1; while ((num / m) > 9) { m = m * 10; } return m; } private static int getPrefix(int num, int mul) { int i = 10; int mod = num % i; while (mod == 0) { i = i * 10; mod = num % i; mul = mul / 10; } return mul * mod; } private static int getSuffix(int num) { int i = 1; int mod; do { i = i * 10; mod = num % i; } while (mod == 0); return num / i; } } " B12040,"/** QProblemC.java * * Solves Problem C of the Qualification round of the Google Code Jam 2012 * Tests for the */ import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class QProblemC { public static void main(String[] args) { try { Scanner in = new Scanner(new BufferedReader( new FileReader(""C-small-attempt3.in""))); BufferedWriter out = new BufferedWriter(new FileWriter( new File(""C-small.out""))); int numberOfTests = in.nextInt(); // Given integers int A = 0; int B = 0; // Variables for recycled pairs int n = 0; String nString; // To check the number of digits for equality with m String m = """"; // String avoids problem of losing 0 as a digit int mInt = 0; String mTemp; // Remove leading 0s before length equality // Reference for m to test when a full rotation has occurred String originalM = """"; int count = 0; for(int i = 0; i < numberOfTests; i++) { System.out.print(""Case #"" + (i+1) + "": ""); out.write(""Case #"" + (i+1) + "": ""); A = in.nextInt(); B = in.nextInt(); n = A; nString = """" + n; // Run through all the numbers between A and B looking for // recycled pairs while(n < B) { m = """" + n; originalM = m; m = rotate(m); // Run through all possible recycles of n while(!m.equals(originalM)) { mInt = Integer.parseInt(m); mTemp = """" + mInt; // For check without leading 0s // If a recycle fits our constraints, count it if(mInt > n && mInt <= B && mTemp.length() == nString.length()) { count++; } m = rotate(m); } n++; nString = """" + n; } System.out.println(count); out.write(count + ""\n""); count = 0; } in.close(); out.close(); } catch (IOException e) { System.out.println(""Error reading file. "" + e); } } /** * ""Rotates"" the given string so that the last character becomes the first * character. * * @param x. The string to rotate. * @return String. The rotated string */ public static String rotate(String x) { // Only take action if there are multiple characters if (x.length() > 1) { char lastChar = x.charAt(x.length() - 1); // Remove last char from buffer string, then add it to the front x = """" + lastChar + x.substring(0, x.length() - 1); } return x; } } " B13129,"package com.example; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class ProblemCSolver { private static boolean debug = false; private static List testCases; public static void main(String[] args) throws NumberFormatException, IOException { loadCase(new File(args[0])); for (int i = 0; i < testCases.size(); i++) { Solve(testCases.get(i)); } } private static void Debug(String s) { if (debug) { System.out.println(s); } } private static class TestCase { int caseNo; // Test specific properties int A; int B; public TestCase(int caseNo, int A, int B) { super(); this.caseNo = caseNo; this.A = A; this.B = B; } @Override public String toString() { return ""TestCase [caseNo="" + caseNo + "", A="" + A + "", B="" + B + ""]""; } } private static void loadCase(File inputFile) throws NumberFormatException, IOException { BufferedReader r = null; try { r = new BufferedReader(new FileReader(inputFile)); // Problem specific loading routine int count = Integer.parseInt(r.readLine()); testCases = new ArrayList(count); for (int i = 1; i <= count; i++) { String line = r.readLine(); StringTokenizer token = new StringTokenizer(line); TestCase thisCase = new TestCase(i, Integer.parseInt(token .nextToken()), Integer.parseInt(token.nextToken())); testCases.add(thisCase); } } finally { if (r != null) { r.close(); } } } private static void Solve(TestCase t) { Debug(""Solving:"" + t); String res = null; // TODO: implement the test int count = 0; for (int i = t.A; i < t.B; i++) { for (int j = i + 1; j <= t.B; j++) { if (isRecycled(i, j)) { count++; } } } res = """" + count; // Standard output format System.out.printf(""Case #%d: %s%n"", t.caseNo, res); } private static boolean isRecycled(int A, int B) { String aString = String.valueOf(A); String bString = String.valueOf(B); for (int i = 1; i < aString.length(); i++) { if ((aString.substring(i) + aString.substring(0, i)) .equals(bString)) { return true; } } return false; } } " B12704,"import java.io.FileInputStream; import java.util.*; import java.math.*; public class Main { static int[] toDigits(int val) { int count = 1; int temp = val / 10; while (temp > 0) { count++; temp /= 10; } int[] arr = new int[count]; temp = val; for (int i = 0; i < arr.length; i++) { arr[i] = temp % 10; temp /= 10; } return arr; } static int toInt(int[] digits) { int res = 0; int p = 1; for (int i = 0; i < digits.length; i++) { res += p * digits[i]; p *= 10; } return res; } public static void main(String[] args) throws Exception{ Scanner scan = new Scanner(System.in); //Scanner scan = new Scanner(new FileInputStream(""C:\\Users\\wd\\Desktop\\"")); char[] map = ""yhesocvxduiglbkrztnwjpfmaq"".toCharArray(); int taskCount = scan.nextInt(); scan.nextLine(); for (int taskIndex = 1; taskIndex <= taskCount; taskIndex++) { int A = scan.nextInt(); int B = scan.nextInt(); long result = 0; for (int i = A; i <= B; i++) { HashSet checker = new HashSet(); int[] base = toDigits(i); int[] copy = new int[base.length]; for (int j = 0; j < base.length; j++) { int index = base.length - 1; for (int k = j; k >= 0; k--) { copy[index--] = base[k]; } for (int k = base.length - 1; k > j; k--) { copy[index--] = base[k]; } int convert = toInt(copy); if (convert <= i || convert > B || checker.contains(convert)) { continue; } //System.out.println(i + "" "" + convert); checker.add(convert); result++; } } System.out.println(""Case #"" + taskIndex + "": "" + result); } } }" B10609,"import java.util.*; import java.io.*; public class C { public static String convert(int num) { char[] arr = Integer.toString(num).toCharArray(); Arrays.sort(arr); return new String(arr); } public static void main(String[] args) throws Exception{ Scanner in = new Scanner(System.in); int T = in.nextInt(); HashMap map = new HashMap(); int A, B; long ans; for(int caseNo = 1;caseNo <= T; caseNo++) { A = in.nextInt(); B = in.nextInt(); ans = 0; map.clear(); for(int num = A; num <= B; num++) { String s = convert(num); long curCount = 0; if (map.containsKey(s)) { curCount = map.get(s); } //System.out.println(""NUM: ""+num+"" ""+s+"" count: ""+curCount); ans += curCount; map.put(s, curCount + 1); } ans = 0; for(String s : map.keySet()) { long cnt = map.get(s); if (cnt > 1) ++ans; } System.out.println(""Case #""+caseNo+"": ""+ans); } } }" B10886,"package de.at.codejam.util; import java.io.IOException; public interface InputFileParser { void initialize(TaskStatus taskStatus); TaskStatus getTaskStatus(); boolean hasNextCase(); CASE getNextCase() throws IOException; } " B11830,"package codejam; import java.util.*; import java.text.*; import java.lang.*; public class Recycle extends CodeJam { ArrayList pairNumber; static public void main(String[] args) { Recycle codeCycle = new Recycle(); codeCycle.init(""D:\\work\\dev\\codejam\\bin\\codejam\\Recycle\\small.in"", ""D:\\work\\dev\\codejam\\bin\\codejam\\Recycle\\small.out""); codeCycle.run(); } public Recycle() { pairNumber = new ArrayList(); } public String getAnswer(String in) { pairNumber.clear(); System.out.format(""getAnswer:%s%n"", in); String ret; StringTokenizer st = new StringTokenizer(in,"" ""); Long start=0L, end=0L; if(st.hasMoreTokens()) { start = Long.parseLong(st.nextToken()); end = Long.parseLong(st.nextToken()); } ret = String.format(""%d"", getCount(start,end)); // int result = board.getBoardRow(yearMonth,monthDay,weekDay); return ret; } public long getCount(Long start, Long end) { long ret=0; long source=0, target=0; int loopCount = String.format(""%d"", start).length(); Pair pair; for(source=start;source=start && target <= end && target != source) { pair = new Pair(target, source); int index=-1; for(int i=0;i=0) { continue; } else { ret++; pairNumber.add(pair); } } } } return ret; } public Long rotate(Long in,int strlen) { Long ret; String tmp; char[] zeros = new char[strlen]; Arrays.fill(zeros, '0'); // format number as String DecimalFormat df = new DecimalFormat(String.valueOf(zeros)); tmp = df.format(in); ret = Long.parseLong(String.format(""%s%s"", tmp.substring(1),tmp.substring(0, 1))); // System.out.format(""%d->%d%n"",in,ret); return ret; } } " B12388,"import java.util.ArrayList; import java.util.Collection; /** * User: avokin * Date: 4/14/12 */ public class ProblemC { private static int[] deg = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000}; private static int recycled(int a, int b, int n) { int result = 0; int i = 1; Collection counted = new ArrayList(); while (i < n) { int a1 = a / deg[i]; int a2 = a % deg[i]; int a3 = a2 * deg[n - i] + a1; if (a < a3 && a3 <= b) { if (!counted.contains(a3)) { result++; } counted.add(a3); } i++; } return result; } private static int solve(int a, int b) { int result = 0; int n = ("""" + a).length(); for (int i = a; i < b; i++) { result += recycled(i, b, n); } return result; } public static void main(String[] args) { String input = ""50\n"" + ""173 996\n"" + ""166 983\n"" + ""130 970\n"" + ""172 382\n"" + ""15 28\n"" + ""150 943\n"" + ""10 11\n"" + ""116 976\n"" + ""100 999\n"" + ""158 918\n"" + ""142 946\n"" + ""178 963\n"" + ""147 923\n"" + ""167 965\n"" + ""28 28\n"" + ""174 362\n"" + ""100 914\n"" + ""164 982\n"" + ""104 990\n"" + ""185 990\n"" + ""114 940\n"" + ""3 4\n"" + ""147 980\n"" + ""100 999\n"" + ""104 993\n"" + ""146 967\n"" + ""138 916\n"" + ""10 10\n"" + ""163 983\n"" + ""76 99\n"" + ""917 917\n"" + ""155 994\n"" + ""562 858\n"" + ""162 933\n"" + ""164 913\n"" + ""162 947\n"" + ""113 928\n"" + ""164 911\n"" + ""140 995\n"" + ""167 927\n"" + ""137 974\n"" + ""142 953\n"" + ""156 922\n"" + ""104 999\n"" + ""162 965\n"" + ""124 962\n"" + ""175 919\n"" + ""141 960\n"" + ""168 982\n"" + ""109 920\n""; String[] lines = input.split(""\n""); int T = Integer.parseInt(lines[0]); for (int i = 1; i <= T; i++) { String line = lines[i]; String[] items = line.split("" ""); int a = Integer.parseInt(items[0]); int b = Integer.parseInt(items[1]); int solution = solve(a, b); System.out.println(""Case #"" + i + "": "" + solution); } } } " B11026,"package org.moriraaca.codejam; public enum OutputDestination { STDOUT, FILE; } " B11963,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Qualification; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author abdallah gaber */ public class RecycledNumbers { ///////////////////////////variables//////////////// public static void main(String[] args) { int res= 0 ,A,B,counter,number; String sA,sB,temp; int[] array = new int[7]; int cntarray=0; boolean flag = true; PrintWriter pw = null; Scanner sc = null; try { sc = new Scanner(new FileReader(""C:\\Users\\abdallah gaber\\Documents\\NetBeansProjects\\CodeJam2012\\src\\Qualification\\Recinput.in"")); pw = new PrintWriter(new FileWriter(""C:\\Users\\abdallah gaber\\Documents\\NetBeansProjects\\CodeJam2012\\src\\Qualification\\Recoutput.out"")); int casCnt=Integer.parseInt(sc.nextLine()); for(int cnt=0;cnt1) { //System.out.println(sA.substring(((counter-count)+1), (counter))+"" ""+sA.substring((counter-count))); temp = temp.substring(1,counter) + temp.charAt(0); number = Integer.parseInt(temp); for (int t=0;t=A&&j possibles = new ArrayList(); public C() { int ncases = in.nextInt(); for (int i = 0; i < ncases; i++) { sols = 0; int n = in.nextInt(); int m = in.nextInt(); findSolutions(n, m); System.out.println(""Case #"" + (i + 1) + "": "" + sols); possibles.clear(); } } private void findSolutions(int n, int m) { while (n < m) { findPairs(n, m); checkdups(); possibles.clear(); n++; } } private void findPairs(int n, int m) { String value = Integer.toString(n); for (int i = 1; i < value.length(); i++) { String nose = value.substring(0, i); String ass = value.substring(i, value.length()); String news = ass.concat(nose); compare(value, news, m); } } private void compare(String value, String curvalue, int m) { if (Integer.toString(Integer.parseInt(value)).length() == Integer.toString( Integer.parseInt(curvalue)).length()) { if (Integer.parseInt(curvalue) <= m && Integer.parseInt(value) < Integer.parseInt(curvalue)) { possibles.add(curvalue); } } } private void checkdups() { for (int i = 0; i < possibles.size(); i++) { for (int x = i + 1; x < possibles.size(); x++) { if (possibles.get(i).equals(possibles.get(x))) { possibles.remove(x); } } } sols += possibles.size(); } public static void main(String[] args) { new C(); } } " B13130,"package com.google.code.codejam._2012.qualification; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * Problem * * Do you ever become frustrated with television because you keep seeing the same things, recycled * over and over again? Well I personally don't care about television, but I do sometimes feel that * way about numbers. * * Let's say a pair of distinct positive integers (n, m) is recycled if you can obtain m by moving * some digits from the back of n to the front without changing their order. For example, (12345, * 34512) is a recycled pair since you can obtain 34512 by moving 345 from the end of 12345 to the * front. Note that n and m must have the same number of digits in order to be a recycled pair. * Neither n nor m can have leading zeros. * * Given integers A and B with the same number of digits and no leading zeros, how many distinct * recycled pairs (n, m) are there with A ≤ n < m ≤ B? * * The RecycledNumbers is the second problem. * *

* Apr 14, 2012 9:25:48 PST AM *

* * @author Marcello de Sales (marcello.desales@gmail.com) * */ public class RecycledNumbers extends CommandLineClient { /** * Input * * The first line of the input gives the number of test cases, T. T test cases follow. Each test * case consists of a single line containing the integers A and B. * * Output * * For each test case, output one line containing ""Case #x: y"", where x is the case number * (starting from 1), and y is the number of recycled pairs (n, m) with A ≤ n < m ≤ B. * * Limits * * 1 ≤ T ≤ 50. A and B have the same number of digits. * * Small dataset * * 1 ≤ A ≤ B ≤ 1000. * * Large dataset * * 1 ≤ A ≤ B ≤ 2000000. * * Sample * * * Input * 4 1 9 10 40 100 500 1111 2222 * Output * Case #1: 0 Case #2: 3 Case #3: 156 Case #4: 287 * * @param args the input arguments from the stdin. */ public static void main(String[] args) { try { new RecycledNumbers().execute(args); System.exit(0); } catch (Throwable t) { t.printStackTrace(); System.exit(1); } } @Override public void process(Scanner input, PrintWriter output) throws Exception { int numberOfTestCases = Integer.valueOf(input.nextLine()); StringBuilder builder = null; for (int testIndex = 0; testIndex < numberOfTestCases; testIndex++) { int numberOfPairs = 0; output.printf(""Case #%d: "", testIndex + 1); // get the value of A and B String[] aAndB = input.nextLine().split("" ""); // if the number is only one digit, then leave as it is zero. if (aAndB[0].length() == 1 || aAndB[1].length() == 1) { output.printf(""%d\n"", numberOfPairs); continue; } // the inputs A and B int a = Integer.valueOf(aAndB[0]); int b = Integer.valueOf(aAndB[1]); // caching the current results to avoid counting the same value twice. Set resultsSoFar = new HashSet<>(); // Generating all the numbers between a and b, inclusive [a, b] String[] ranges = new String[b - a]; for (int i = 0, rangeValue = a; i < ranges.length; i++) { ranges[i] = String.valueOf(rangeValue++); } String n = """"; String m = """"; for (int i = 0; i < ranges.length; i++) { n = ranges[i]; m = ranges[i]; int length = String.valueOf(ranges[i]).length(); for (int j = 0; j < length; j++) { // rotate number m String stringValue = String.valueOf(m); builder = new StringBuilder(); builder.append(stringValue.charAt(stringValue.length() - 1)); builder.append(stringValue.subSequence(0, stringValue.length() - 1)); m = builder.toString(); // a recycle pair is one such that A ≤ n < m ≤ B if (a <= Integer.valueOf(n) && Integer.valueOf(n) < Integer.valueOf(m) && Integer.valueOf(m) <= b) { if (!resultsSoFar.contains(n + m)) { resultsSoFar.add(n+m); numberOfPairs++; } //output.printf(""%s, %s count: %d \n"", n, m, numberOfPairs); // could see the repeated value!!! } } } output.printf(""%d\n"", numberOfPairs); } } } " B10164,"import java.io.File; import java.util.Scanner; import java.util.Vector; class C { static int count=0; public static void main(String[] args) { if(args.length==100){ System.out.println(""Error :: Please provide input file name as first command line argument""); System.out.println(""Usage :: java Main ""); System.out.println(""Example :: java Main A-small-practice.in""); } else{ try{ Scanner input=new Scanner(new File(""C-small-attempt2 (1).in"")); //Scanner input=new Scanner(new File(""input.txt"")); //System.out.println(""Reading Input from ""+ args[0]+"" file""); int no=input.nextInt(); int lim[][]=new int[no][2]; for(int i=0;i0;j--){ String newS=s.substring(j, s.length())+s.substring(i, j); if(!newS.startsWith(""0"")&&!s.equals(newS)&&new Integer(newS).intValue()>new Integer(s).intValue()&&new Integer(newS).intValue()<=limit){ if(!old.contains(newS)){ old.add(newS); //System.out.println(newS); count++; } } } } }" B12773," import java.util.Scanner; public class RecycledNumber { public int deal(int A, int B) { int ans = 0; for (int i = A; i<= B ; i ++) { int left = i; int k = 1; int tk = 1; UniqueList newInts = new UniqueList(10); while (left >= 10) { left = left / 10; tk = tk * 10; } left = i; while (k * 10 <= left) { k = k * 10; int x = (left % k) * (tk * 10 / k) + (left / k); //System.out.println(i + "": "" + x); if (x > i && x <= B) newInts.add(x); } ans += newInts.getSize(); } return ans; } public void solve() { Scanner scan = new Scanner(System.in); int T = scan.nextInt();scan.nextLine(); for (int i = 1; i <= T; i ++) { int A = scan.nextInt(); int B = scan.nextInt(); System.out.println(""Case #"" + i + "": "" + this.deal(A, B)); } } public static void main(String args[]) { RecycledNumber r = new RecycledNumber(); r.solve(); } } " B12096,"import java.io.*; public class Recycle { public void cal(String filename) throws NumberFormatException, IOException { BufferedReader in = new BufferedReader(new FileReader(filename)); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""bar.txt""))); int count = 1; String s = in.readLine(); int all = Integer.parseInt(s); while((s = in.readLine()) != null) { int result = 0; if(count > all) { System.out.println(""error""); break; } String[] elements = s.split("" ""); int start = Integer.parseInt(elements[0]); int end = Integer.parseInt(elements[1]); for(int i = start; i < end; i++) { for(int j = i + 1; j <= end; j++) { if(isRecycle(i,j)) { result = result + 1; } } } out.println(""Case #"" + count +"": "" + result); count = count + 1; } out.close(); } public Boolean isRecycle(Integer a, Integer b) { String a_string = a.toString(); String b_string = b.toString(); if(a_string.length() != b_string.length()) return false; for(int i = 1; i < a_string.length(); i++) { String temp = a_string.substring(i, a_string.length()); temp = temp.concat(a_string.substring(0, i)); if(temp.equals(b_string)) return true; } return false; } public static void main(String[] args) throws NumberFormatException, IOException { Recycle r = new Recycle(); r.cal(""C-small-attempt0.in""); } } " B11620,"import java.util.*; import java.io.*; public class C { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new FileReader(args[0])); in.readLine(); int caseNum = 0; while (in.ready()) { solve(++caseNum, in.readLine()); } } public static void solve(int caseNum, String caseInput) { String[] inputSegments = caseInput.split("" ""); String i1 = inputSegments[0]; String i2 = inputSegments[1]; int v1 = Integer.parseInt(i1); int v2 = Integer.parseInt(i2); int d = i1.length(); int baseValue = (int) Math.pow(10, d); HashSet uniquePair = new HashSet(); if (baseValue == 1) { // do nothing } else { String n; int value; for (int i = v1; i <= v2; ++i) { n = String.valueOf(i); for (int j = 1; j < d; ++j) { value = Integer.parseInt(n.substring(j) + n.substring(0, j)); if (value >= v1 && value <= v2 & value != i) { uniquePair.add(n + "" - "" + value); } } } } System.out.printf(""Case #%d: %d\n"", caseNum, uniquePair.size()/2); } }" B11694,"import java.io.InputStreamReader; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) { Scanner inputFile = new Scanner(new InputStreamReader(System.in)); String inputLine = null; String[] numberArray; int testCaseCount = 0; int startNumber = 0; int endNumber = 0; int recycledPairCount = 0; int digitCount = 0; StringBuilder recycleNumber = new StringBuilder(); int newNumber = 0; String newNumberString; HashSet recycleNumbers = new HashSet(); while (inputFile.hasNextLine()) { inputLine = inputFile.nextLine(); numberArray = inputLine.split("" ""); if(numberArray != null && numberArray.length == 1) { /*numberOfTestCases = Integer.parseInt(numberArray[0]);*/ } else if (numberArray != null && numberArray.length == 2) { digitCount = numberArray[0].length(); startNumber = Integer.parseInt(numberArray[0]); endNumber = Integer.parseInt(numberArray[1]); while(startNumber <= endNumber) { newNumberString = """" + startNumber; for(int i = 1; i < digitCount; i++) { recycleNumber = recycleNumber.append(newNumberString.substring(i) + newNumberString.substring(0, i)); newNumber = Integer.parseInt(recycleNumber.toString()); if(newNumber > startNumber && newNumber <= endNumber) { recycleNumbers.add(recycleNumber.toString()); } recycleNumber.delete(0, digitCount); } recycledPairCount = recycledPairCount + recycleNumbers.size(); startNumber++; recycleNumbers.clear(); } System.out.println(""Case #"" + testCaseCount + "": "" + recycledPairCount); } testCaseCount++; recycledPairCount = 0; startNumber = 0; endNumber = 0; digitCount = 0; newNumber = 0; recycleNumber.delete(0, digitCount); } } } " B13144,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class Principal { public static void main(String[] args) { Reader reader = new Reader(); Case[] cases = reader.read(); try { File file = new File(""out.txt""); file.delete(); BufferedWriter bf = new BufferedWriter(new FileWriter(file)); for(Case c : cases) bf.write(c.resolver()); bf.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }//endClass " B10839," import java.io.BufferedReader; import java.io.FileReader; import java.io.PrintStream; import java.util.HashSet; /** * * @author peterboyen */ public class RecycledNumbers { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new FileReader(""/Users/peterboyen/Downloads/C-small-attempt1.in"")); String line = br.readLine(); int testCases = Integer.parseInt(line); PrintStream ps = new PrintStream(""/Users/peterboyen/Downloads/C-small-attempt1.out""); for (int i = 1; i <= testCases; i++) { line = br.readLine(); ps.println(""Case #"" + i + "": "" + solve(line)); } br.close(); ps.close(); } private static int solve(String line) { String[] split = line.split("" ""); int A = Integer.parseInt(split[0]); int B = Integer.parseInt(split[1]); int result = 0; for (int m = A + 1; m <= B; m++) { result += getRecycled(m, A); } return result; } private static int getRecycled(int m, int A) { String M = """" + m; HashSet set = new HashSet(); int result = 0; for (int i = 0; i < M.length() - 1; i++) { M = M.substring(1) + M.charAt(0); if (M.charAt(0) != '0') { int n = Integer.parseInt(M); if (n >= A && n < m && !set.contains(n)) { result++; set.add(n); } } } return result; } } " B11878,"package gcj; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; public class Recycled { public static void main(String args[]) throws Exception { BufferedReader br=new BufferedReader(new FileReader(""c:/c.in"")); BufferedWriter out=new BufferedWriter(new FileWriter(""c:/out.txt"")); String s; int t=Integer.parseInt(br.readLine()); for(int i=0;i0) { s=s.substring(s.length()-1)+s.substring(0,s.length()-1); if(s.charAt(0)=='0') { l--; continue; } else { if(Integer.parseInt(s)==j) { l--; continue; } if(check(arr,dupidx,Integer.parseInt(s))&Integer.parseInt(s)>j&&Integer.parseInt(s)<=b&&Integer.parseInt(s)>=a) { arr[dupidx]=Integer.parseInt(s); dupidx++; res++; } } l--; } } out.write(""Case #""+(i+1)+"": ""+res+""\n""); } out.close(); } public static boolean check(int arr[],int maxid,int val) { for(int i=0;i= 100) { int next = 100*(i%10) + i/10; if(next > i && next <= b) count++; next = 10*(i%100) + i/100; if(next > i && next <= b) count++; } else if(i >= 10) { int next = 10*(i%10) + i/10; if(next > i && next <=b) count++; } } System.out.println(count); } } } " B11309,"/** * Copyright 2012 Christopher Schmitz. All Rights Reserved. */ package com.isotopeent.codejam.lib.converters; import com.isotopeent.codejam.lib.InputConverter; public class DynamicMultiLineConverter implements InputConverter { private static final int MAX_PARAM_COUNT = 10; private IntArrayLine paramConverter; private InputConverter converter; private Object[] input; private int lineNumber; public DynamicMultiLineConverter(InputConverter lineConverter) { this(lineConverter, 0); } public DynamicMultiLineConverter(InputConverter lineConverter, int paramCount) { this.converter = lineConverter; if (paramCount > 0) { paramConverter = new IntArrayLine(paramCount); } else { paramConverter = new IntArrayLine(new int[MAX_PARAM_COUNT]); } } @Override public boolean readLine(String data) { if (lineNumber == 0) { paramConverter.readLine(data); int[] params = paramConverter.generateObject(); int count = getCount(params); input = new Object[count + 1]; input[lineNumber++] = params; } else { if (!converter.readLine(data)) { input[lineNumber++] = converter.generateObject(); } } if (lineNumber >= input.length){ lineNumber = 0; } return lineNumber == 0; } @Override public Object[] generateObject() { return input; } /** * default implementation, just uses first parameter value */ protected int getCount(int[] parameters) { return parameters[0]; } } " B13127,"package com.nbarraille.gcj; import java.io.IOException; public class GCJ extends GCJHelper { protected static final String TEST_CASE = ""C-small""; // CHANGE THIS WHEN CHANGING PROBLEM protected static final boolean RUN_ALL_CASES = true; protected static final boolean DEBUG = true; // DO WHATEVER TO SOLVE THE CASE // AND APPEND THE OUTPUT TO SB protected static void solveCase() throws IOException { long[] inp = readLongArray(); int a = (int) inp[0]; int b = (int) inp[1]; int nbDigits = String.valueOf(a).length(); int nbOk = 0; for (int i = a; i <= b; i++) { int i2 = i; for (int j = 1; j < nbDigits; j++) { i2 = shift(i2, nbDigits); if (i2 >= a && i2 <= b && i < i2) { nbOk++; } } } sb.append(nbOk); } private static int shift(int i, int nbDigits) { String s = String.valueOf(i); while (s.length() < nbDigits) { s = ""0"" + s; } return Integer.valueOf(s.charAt(s.length() - 1) + s.substring(0, s.length() - 1)); } // DONT TOUCH THIS public static void main(String[] args) throws Exception { run(); } } " B13172," import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; public class RecycledNumber { private void solve(BufferedReader f, PrintWriter out) throws IOException { int T = read(f); HashSet set = new HashSet(); for (int i=0; i n && m <= B) { count++; } } set.clear(); } out.println(""Case #"" + (i+1) + "": "" + count); } } public int read(BufferedReader f) throws IOException { return Integer.parseInt(f.readLine()); } public int[] read(BufferedReader f, int N) throws IOException { String[] t = f.readLine().split("" ""); int[] a = new int[N]; for (int i=0; i set = new HashSet(); for (int i = 0; i< strE.length(); i++){ set.add(""case '"" + strG.charAt(i) + ""':\treturn '"" + strE.charAt(i) + ""';""); //System.out.println(""case '"" + strG.charAt(i) + ""':\treturn '"" + strE.charAt(i) + ""';""); } ArrayList list = new ArrayList(set); Collections.sort(list); for(String s : list){ System.out.println(s); } **/ switch (c){ case 'a': return 'y'; case 'b': return 'h'; case 'c': return 'e'; case 'd': return 's'; case 'e': return 'o'; case 'f': return 'c'; case 'g': return 'v'; case 'h': return 'x'; case 'i': return 'd'; case 'j': return 'u'; case 'k': return 'i'; case 'l': return 'g'; case 'm': return 'l'; case 'n': return 'b'; case 'o': return 'k'; case 'p': return 'r'; case 'q': return 'z'; case 'r': return 't'; case 's': return 'n'; case 't': return 'w'; case 'u': return 'j'; case 'v': return 'p'; case 'w': return 'f'; case 'x': return 'm'; case 'y': return 'a'; case 'z': return 'q'; case ' ': return ' '; default: throw new RuntimeException(""Not valid character: '"" + c + ""'""); } } } " B11509,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class RecycledNumbers { private PrintWriter out; private Scanner in; private void init() { } private void solve() { int A = in.nextInt(); int B = in.nextInt(); int r = 0; for (int i = A; i <= B; i++) { int j = rotate(i); while (i != j) { if (i < j && j <= B) { r++; } j = rotate(j); } } out.println(r); } private int rotate(int number) { int pos = 1; while (number % 10 == 0) { pos *= 10; number /= 10; } int rest = number % 10; number /= 10; int numberCopy = number; while (numberCopy > 0) { pos *= 10; numberCopy /= 10; } return rest * pos + number; } private void runTests() { init(); int T = Integer.parseInt(in.nextLine()); for (int i = 0; i < T; i++) { out.print(""Case #"" + (i + 1) + "": ""); solve(); } } private void run() { try { runTests(); } finally { close(); } } private void close() { out.close(); in.close(); } public RecycledNumbers() throws FileNotFoundException { this.in = new Scanner(new File(""C-small-attempt0.in"")); this.out = new PrintWriter(new File(""C-small-attempt0.out"")); } public static void main(String[] args) throws FileNotFoundException { new RecycledNumbers().run(); } } " B12500," //Author KNIGHT0X300 import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s=new Scanner(System.in); int t=s.nextInt(); long time = System.nanoTime(); for(int i=0;iA;j--) { int y=j ; for(int k=1;k=A)){tot++; System.out.println(j+"" ""+y); // if(j-y<=0) // System.out.println(""wfjhdddddhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh""); // if((p==0))//&&(p==0)) // System.out.println(""fahnsfjqnfjqfdjqn""); } } } System.out.println(""Case #""+(i+1)+"": ""+tot); } System.out.println(""Finished in: "" + (System.nanoTime() - time) / Math.pow(10, 6) + ""ms""); } } " B12012,"import java.util.*; import java.io.*; public class C { public static int computeDigits(int x){ if(x<10){ return 1; }else{ return 1+computeDigits(x/10); } } public static boolean recycled(int x, int y){ int n = computeDigits(x); for(int i = 1;i set = new TreeSet(); for (int j = 0; j < n.length(); j++) { set.add(n.substring(j) + n.substring(0, j)); } for (String s : set) { if (n.compareTo(s) < 0 && b.compareTo(s) >= 0) { answer++; } } } System.out.printf(""Case #%d: %d\n"", t + 1, answer); System.err.printf(""Case #%d: %d\n"", t + 1, answer); } } } " B11935,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class testC { public static void main(String args[]){ int count=0; int A=1111; int B=2222; String str=""""; String a=""""; String b=""""; int n=0; int m=0; boolean flag=false; char s[] = ((B)+"""").toCharArray(); char t[]; int digits = 0; List list = new ArrayList(); try{ FileReader fr = new FileReader(""2.txt""); BufferedReader br = new BufferedReader(fr); int size = Integer.parseInt(br.readLine()); for(int loop=0;loop=A && n>i && !list.contains(n) && i>=A) { count++; // System.out.println(i+"" ""+n); list.add(n); } } list.clear(); } System.out.println(""Case #""+(loop+1)+"": ""+count); //System.out.println(""Case #""+(loop+1)+"": ""+count+"" For ""+A+"" ""+B); } br.close(); fr.close(); }catch(IOException ex){ ex.printStackTrace(); } } private static char[] findRecyclingNumber(char[] s,int digits) { // TODO Auto-generated method stub char t[] = new char[s.length]; for(int i=0;i<=digits;i++){ t[i] = s[s.length-digits-1+i]; } int index=0; for(int i=digits+1;i arr = new ArrayList(); for(int i =a[0];i<= a[1];i++) { m=i; k=10; n=0; arr.clear(); // System.out.print( m + "" : ""); while(m != 0) { l = m%10; m=m/10; n=(l*k/10)+n; l=Integer.parseInt((String.valueOf(n) + String.valueOf(m))); if(l>=a[0] && l <= a[1] && l > i && !arr.contains(String.valueOf(l))) { // System.out.print(l +"" ""); arr.add(String.valueOf(l)); count++; } k*=10; } // System.out.println(); } return count; } } " B11862," import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class ProblemC { public static int eval(int A, String n, int B){ int r = 0; for(int i = 1; i < n.length(); i++){ int nn = Integer.parseInt((n)); String ini = n.substring(0, n.length() - i); String end = n.substring(n.length() - i); if(Integer.parseInt(String.valueOf(end.charAt(0))) >= Integer.parseInt(String.valueOf(ini.charAt(0)))){ int m = Integer.parseInt((end+ini)); if( A <= m && nn < m && m <= B ){ r++; } } } return r; } public static void main(String[] args) throws IOException { Scanner s = new Scanner(System.in); PrintWriter pw = new PrintWriter(new FileWriter(""C.out"")); int cas = s.nextInt(); for( int i = 0; i < cas; i++){ int r = 0; int A = s.nextInt(); int B = s.nextInt(); for(int n = A; n <= B; n++){ r += eval(A,String.valueOf(n),B); } //System.out.println(""Case #""+(i+1)+"": ""+r); pw.println(""Case #""+(i+1)+"": ""+r); } pw.close(); s.close(); } } " B11770,"import java.io.*; import java.util.*; public class RecycledNumbers { public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(new File(""input"")); int n=sc.nextInt(); for (int i = 1; i <= n; i++) { int N=sc.nextInt(); int M=sc.nextInt(); Set set=new HashSet(); for(int j=N;j<=M;j++) { String currentNumber=String.valueOf(j); if(currentNumber.length()==1) { continue; } for(int k=1;k=N && num1<=M) { set.add(Math.min(j,num1)+"":""+Math.max(j,num1)); } } } System.out.println(""Case #"" + i + "": ""+set.size()); } } } " B12137,"import java.io.*; public class C { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine()); String[] line; for(int i=1;i<=T;i++) { line = br.readLine().split(""\\W+""); int a = Integer.parseInt(line[0]); int b = Integer.parseInt(line[1]); System.out.println(""Case #""+i+"": ""+recycled(a,b)); } } public static long recycled(int a,int b) { long ret = 0; for(int i=a;i b) continue; //System.out.println(i+"" ""+n); ret++; } } return ret; } } " B11781,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.Hashtable; /** * Input * @author jiptan * */ public class SolveC { static int isRecycledNum(char[] val, int n, int a, int b) { int recNum = 0; for (int i=0; i= a && shiftVal > n && shiftVal <= b) { recNum = recNum + 1; // System.out.println(n + "" "" + shiftVal); } } return recNum; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader(args[0])); int num = Integer.parseInt(br.readLine()); FileWriter fw = new FileWriter(new File(""test"")); StringBuilder sb2 = new StringBuilder(); String[] values = null; for (int i=1; i<=num; i++) { String line = br.readLine(); String[] abPair = line.split("" ""); int a = Integer.parseInt(abPair[0]); int b = Integer.parseInt(abPair[1]); // System.out.println(a + "" "" + b); int recNum = 0; for (int j=a; j<=b; j++) { int tmp = isRecycledNum(String.valueOf(j).toCharArray(), j, a, b); if (tmp > 0) { recNum = recNum + tmp; } } // System.out.println(recNum); String output = String.format(""Case #%d: %d"", i, recNum); sb2.append(output + ""\n""); } fw.write(sb2.toString()); fw.close(); } }" B10665," import java.io.File; import java.io.PrintWriter; import java.util.Scanner; /** * * @author yilianz */ public class RecycleNumber{ /** * @param args the command line arguments */ public static void main(String[] args) throws Exception{ // Read file Scanner inFile = new Scanner(new File(""file.in"")); PrintWriter outFile = new PrintWriter(new File(""out.file"")); int caseN =inFile.nextInt(); // TODO code application logic here for(int i = 1; in && m<=B && flag==0){ count++; //System.out.println(count); //System.out.println(""(""+n+"",""+m+"")""); c[k]=m; flag=0; } } } System.out.println(""Case #""+i+"": ""+count); outFile.println(""Case #""+i+"": ""+count); } //close the file inFile.close(); outFile.close(); } } " B12189,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package google; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Set; import java.util.StringTokenizer; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author TOSHIBA */ public class NewClass1 { public NewClass1() { FileReader f = null; try { int n = 0; int m = 0; f = new FileReader(""E:\\t.txt""); BufferedReader br=new BufferedReader(f); String line; line = br.readLine(); int numebr=1; while ((line = br.readLine()) != null) { // Print the content on the console StringTokenizer st=new StringTokenizer(line); int A=Integer.parseInt(st.nextToken()); int B=Integer.parseInt(st.nextToken()); System.out.println(""Case #""+numebr+"": ""+getNumberOfRecylecs(A, B)); numebr++; } } catch (Exception ex) { Logger.getLogger(NewClass1.class.getName()).log(Level.SEVERE, null, ex); } } private int getNumberOfRecylecs(int A, int B) { //A<=n //n aa=new HashMap(); for (int m = B; m > A ; m--) { Vector temp=rotateInteger(m); for (int i = 0; i < temp.size(); i++) { int tempInt=Integer.parseInt((String)temp.get(i)); String ff=m+""""; if ( tempInt= A && ff.length()==((String)temp.get(i)).length()) { //System.out.println(""nnnnn= ""+m+"" ttttt= ""+tempInt); //System.out.println(n); //if (!aa.containsKey(n)) { // aa.put(tempInt, 0); // aa.put(n, 0); //if (!nums.contains(tempInt)) { Vector vv=new Vector(); vv.add(m); vv.add(tempInt); nums.add(vv); //} //} } } } Vector newe=removeDublication(nums); //System.out.println(newe.size()); return newe.size(); } public static void main(String[] args) { new NewClass1(); } private Vector rotateInteger(int x) { String number=x+""""; Vector v=new Vector(); for (int i = 0; i < number.length()-1; i++) { String newNum=number.charAt(number.length()-1)+number.substring(0, number.length()-1); v.add(newNum); number=newNum; } // for (int i = 0; i < v.size(); i++) { // System.out.println(v.get(i)); // // } return v; } private Vector removeDublication(Vector nums) { Vector newData=new Vector(); for (int i = 0; i < nums.size(); i++) { Vector temp=(Vector) nums.get(i); if (!isInVector(newData,temp)) { newData.add(temp); } } return newData; } private boolean isInVector(Vector newData, Vector temp) { for (int i = 0; i < newData.size(); i++) { Vector tempNewData=(Vector) newData.get(i); if ((tempNewData.get(0)== temp.get(1)) &&(tempNewData.get(1)== temp.get(0))) { return true; } } return false; } } " B11351,"import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Scanner; public class QualC { private int [] ten = new int[]{ 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; public void run()throws IOException { Scanner in = new Scanner(new File(""c.in"")); PrintWriter out = new PrintWriter(""c.out""); int nt = in.nextInt(); in.nextLine(); for(int it = 1;it <= nt; it++) { int a = in.nextInt(); int b = in.nextInt(); HashMap mapPair = new HashMap(); int n = ("""" + a).length(); for(int i=a;i<=b;i++) { int c = i; for(int j=0;j i && c <= b) { //System.err.println(i + "" "" + c); //if(mapPair.containsKey(i + "" "" + c)) // System.err.println(i + "" "" + c); mapPair.put(i + "" "" + c, 1); //ret++; } } } //System.err.println(mapPair.size()); out.println(""Case #"" + it + "": "" + mapPair.size()); } out.close(); } /** * @param args */ public static void main(String[] args)throws IOException { new QualC().run(); } } " B11071,"package fixjava; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class CollectionUtils { /** * @return the single value in the collection, throws an exception if there isn't exactly one item. * @throws IllegalArgumentException * if there is more than one value in the set. */ public static T getSingleVal(Collection collection) { if (collection.size() != 1) throw new IllegalArgumentException(collection.size() + "" objects in collection, expected exactly 1""); T ret = null; for (T val : collection) { ret = val; break; } return ret; } /** * @return the first value returned by an iterator on the collection, throws an exception if there isn't exactly one item. * @throws IllegalArgumentException * if collection is empty */ public static T getFirstVal(Collection collection) { if (collection.size() == 0) throw new IllegalArgumentException(collection.size() + "" objects in collection, expected at least 1""); T ret = null; for (T val : collection) { ret = val; break; } return ret; } // --------------------------------------------------------------------------------------------------------------------- /** * Pass values in an Iterable through a function to produce an ArrayList of mapped values, one output value generated per input * value. Returns null if input is null. */ public static ArrayList map(Iterable values, Lambda mapFunction) { if (values == null) return null; ArrayList result = new ArrayList(); for (S val : values) result.add(mapFunction.apply(val)); return result; } /** * Pass values in an Iterable through a function to produce an ArrayList of mapped values, one output value generated per input * value. Returns null if input is null. */ public static ArrayList map(S[] values, Lambda mapFunction) { if (values == null) return null; ArrayList result = new ArrayList(); for (S val : values) result.add(mapFunction.apply(val)); return result; } /** * Pass values in an Iterable through a function to produce an ArrayList of mapped values, zero or more output values generated * per input value. Returns null if input is null. */ public static ArrayList mapMultiple(Iterable values, Lambda> mapFunction) { if (values == null) return null; ArrayList result = new ArrayList(); for (S val : values) result.addAll(mapFunction.apply(val)); return result; } /** * Pass values in an Iterable through a function to produce a HashSet of mapped values, one output value generated per input * value. Returns null if input is null. */ public static HashSet mapSet(Iterable values, Lambda mapFunction) { if (values == null) return null; HashSet result = new HashSet(); for (S val : values) result.add(mapFunction.apply(val)); return result; } /** * Pass values in an Iterable through a function to produce a HashSet of mapped values, one output value generated per input * value. Returns null if input is null. */ public static HashSet mapSet(S[] values, Lambda mapFunction) { if (values == null) return null; HashSet result = new HashSet(); for (S val : values) result.add(mapFunction.apply(val)); return result; } /** * Pass values in an Iterable through a function to produce a HashSet of mapped values, zero or more output values generated per * input value. Returns null if input is null. */ public static HashSet mapSetMultiple(Iterable values, Lambda> mapFunction) { if (values == null) return null; HashSet result = new HashSet(); for (S val : values) result.addAll(mapFunction.apply(val)); return result; } // --------------------------------------------------------------------------------------------------------------------- public static HashSet filterSet(Iterable values, Lambda filterFunction) { if (values == null) return null; HashSet result = new HashSet(); for (T val : values) if (filterFunction.apply(val)) result.add(val); return result; } public static ArrayList filter(Iterable values, Lambda filterFunction) { if (values == null) return null; ArrayList result = new ArrayList(); for (T val : values) if (filterFunction.apply(val)) result.add(val); return result; } public static HashSet filterSet(T[] values, Lambda filterFunction) { if (values == null) return null; HashSet result = new HashSet(); for (T val : values) if (filterFunction.apply(val)) result.add(val); return result; } public static ArrayList filter(T[] values, Lambda filterFunction) { if (values == null) return null; ArrayList result = new ArrayList(); for (T val : values) if (filterFunction.apply(val)) result.add(val); return result; } // --------------------------------------------------------------------------------------------------------------------- /** * Iterate through multiple Iterables of the same element type, e.g. for (Integer i : CollectionUtils.iterateThroughAllOf(x, y, * z)) { } * * N.B. you will get a warning ""Type safety: A generic array of type Iterable is created for a Varargs parameter"" (lame * Java). */ @SafeVarargs public static Iterable iterateThroughAllOf(final Iterable... iterables) { if (iterables.length == 0) { return (Iterable) new ArrayList(); } else { return new Iterable() { @Override public Iterator iterator() { return new Iterator() { Iterable[] iters = iterables; int iterIdx = -1; Iterator currIter = null; private void advanceIfNecessary() { if (currIter == null || (iterIdx < iters.length - 1 && !currIter.hasNext())) currIter = iterables[++iterIdx].iterator(); } @Override public boolean hasNext() { advanceIfNecessary(); return iterIdx < iters.length && (iterIdx < iters.length - 1 || currIter.hasNext()); } @Override public T next() { advanceIfNecessary(); if (iterIdx == iters.length) throw new RuntimeException(""Out of elements""); return currIter.next(); } @Override public void remove() { advanceIfNecessary(); if (iterIdx == iters.length) throw new RuntimeException(""Out of elements""); else currIter.remove(); } }; } }; } } /** * Iterate through multiple Arrays of the same element type, e.g. for (Integer i : CollectionUtils.iterateThroughAllOf(x, y, z)) * { } */ @SafeVarargs public static Iterable iterateThroughAllOf(final T[]... arrays) { if (arrays.length == 0) { return (Iterable) new ArrayList(); } else { return new Iterable() { @Override public Iterator iterator() { return new Iterator() { T[][] arrs = arrays; int arrIdx = 0, arrSubIdx = 0; private void advanceIfNecessary() { if (arrIdx < arrs.length && arrSubIdx == arrs[arrIdx].length) { arrIdx++; arrSubIdx = 0; } } @Override public boolean hasNext() { advanceIfNecessary(); return arrIdx < arrs.length && (arrIdx < arrs.length - 1 || arrSubIdx < arrs[arrIdx].length); } @Override public T next() { advanceIfNecessary(); if (arrIdx == arrs.length) throw new RuntimeException(""Out of elements""); return arrs[arrIdx][arrSubIdx++]; } @Override public void remove() { throw new RuntimeException(""Not implemented""); } }; } }; } } /** * Iterate through multiple Iterables of the same element type (skipping over null iterables, *not* null elements), e.g. for * (Integer i : CollectionUtils.iterateThroughAllOf(x, y, z)) { } * * N.B. you will get a warning ""Type safety: A generic array of type Iterable is created for a Varargs parameter"" (lame * Java). */ @SuppressWarnings(""unchecked"") public static Iterable iterateThroughAllOfIgnoringNulls(Iterable... iterables) { ArrayList> filter = filter(iterables, new Lambda, Boolean>() { @Override public Boolean apply(Iterable param) { return param != null; } }); Iterable[] nonNulls = new Iterable[filter.size()]; filter.toArray(nonNulls); return iterateThroughAllOf(nonNulls); } /** * Iterate through multiple arrays of the same element type (skipping over null arrays, *not* null elements), e.g. for (Integer * i : CollectionUtils.iterateThroughAllOf(x, y, z)) { } */ @SuppressWarnings(""unchecked"") public static Iterable iterateThroughAllOfIgnoringNulls(T[]... arrays) { ArrayList filter = filter(arrays, new Lambda() { @Override public Boolean apply(T[] param) { return param != null; } }); Iterable[] nonNulls = new Iterable[filter.size()]; filter.toArray(nonNulls); return iterateThroughAllOf(nonNulls); } // public static void main(String[] args) { // ArrayList x = new ArrayList(); // ArrayList y = new ArrayList(); // ArrayList z = new ArrayList(); // x.add(1); // x.add(2); // x.add(3); // y.add(19); // y.add(23); // z.add(100); // z.add(999); // for (Integer i : iterateThroughAllOf(x, y, z)) // System.out.println(i); // Integer[] a = new Integer[3]; // Integer[] b = new Integer[2]; // a[0] = 10; // a[1] = 11; // a[2] = 12; // b[0] = 7; // b[1] = 8; // for (Integer i : iterateThroughAllOf(a, b)) // System.out.println(i); // } /** * Iterate through a varargs list of iterable objects of type T, and return all the objects in a list. Null iterables are * skipped. */ @SafeVarargs public static ArrayList toListIgnoringNulls(Iterable... iterables) { ArrayList result = new ArrayList(); for (T item : iterateThroughAllOfIgnoringNulls(iterables)) result.add(item); return result; } /** * Iterate through a varargs list of iterable objects of type T, and return all the objects in a set (removing duplicates). Null * iterables are skipped. */ @SafeVarargs public static HashSet toSetIgnoringNulls(Iterable... iterables) { return new HashSet(toListIgnoringNulls(iterables)); } // --------------------------------------------------------------------------------------------------------------------- /** * Look up keys in the map, and return a collection of the corresponding values. Returns null if 'keys' is null. * * @throw IllegalArgumentException if key doesn't exist in map or if a key is null, depending on params. */ public static > C lookup(Collection keys, Map map, LambdaVoid applyIfKeyIsNullWithoutAddingValue, Lambda applyIfKeyIsNullAndAddReturnedValue, LambdaVoid applyWhenKeyDoesntExistWithoutAddingValue, Lambda applyWhenKeyDoesntExistAndAddReturnedValue, C result) { if (keys == null) return null; for (K key : keys) { V val = null; boolean addValue = false; if (applyIfKeyIsNullWithoutAddingValue != null && key == null) { applyIfKeyIsNullWithoutAddingValue.apply(key); } else if (applyIfKeyIsNullAndAddReturnedValue != null && key == null) { val = applyIfKeyIsNullAndAddReturnedValue.apply(key); addValue = true; } else if (applyWhenKeyDoesntExistWithoutAddingValue != null && !map.containsKey(key)) { applyWhenKeyDoesntExistWithoutAddingValue.apply(key); } else if (applyWhenKeyDoesntExistAndAddReturnedValue != null && !map.containsKey(key)) { val = applyWhenKeyDoesntExistAndAddReturnedValue.apply(key); addValue = true; } else { val = map.get(key); addValue = true; } if (addValue) result.add(val); } return result; } /** * Look up keys in the map, and return an ArrayList of the corresponding values. Returns null if 'keys' is null. * * @throw IllegalArgumentException if key doesn't exist in map or if a key is null, depending on params. */ public static ArrayList lookup(Collection keys, Map map, boolean throwExceptionIfKeyNull, boolean throwExceptionIfKeyDoesntExist) { if (keys == null) return null; return lookup(keys, map, throwExceptionIfKeyNull ? new LambdaVoid() { @Override public void apply(K key) { throw new IllegalArgumentException(""Key is null""); } } : null, null, throwExceptionIfKeyDoesntExist ? new LambdaVoid() { @Override public void apply(K key) { throw new IllegalArgumentException(""Could not find key "" + key + "" in map""); } } : null, null, new ArrayList()); } /** * Look up keys in the map, and return an ArrayList of the corresponding values. Performs no checking. Returns null if 'keys' is * null. */ public static ArrayList lookup(Collection keys, Map map) { if (keys == null) return null; ArrayList vals = new ArrayList(keys.size()); for (K key : keys) { // Simple version for speed V val = map.get(key); vals.add(val); } return vals; } /** * Look up keys in the map, and return an ArrayList of the corresponding values. Applies the given function if the key doesn't * exist. Returns null if 'keys' is null. */ public static ArrayList lookup(Collection keys, Map map, LambdaVoid applyWhenKeyDoesntExist) { return lookup(keys, map, null, null, applyWhenKeyDoesntExist, null, new ArrayList()); } /** * Look up keys in the map, and return an ArrayList of the corresponding values. Applies the given function if the key doesn't * exist to produce a default value. Returns null if 'keys' is null. */ public static ArrayList lookup(Collection keys, Map map, Lambda applyWhenKeyDoesntExistToGetDefaultVal) { return lookup(keys, map, null, null, null, applyWhenKeyDoesntExistToGetDefaultVal, new ArrayList()); } /** * Look up keys in the map, and return a HashSet of the corresponding values. Returns null if 'keys' is null. * * @throw IllegalArgumentException if key doesn't exist in map or if a key is null, depending on params. */ public static HashSet lookupAsSet(Collection keys, Map map, boolean throwExceptionIfKeyNull, boolean throwExceptionIfKeyDoesntExist) { if (keys == null) return null; return lookup(keys, map, throwExceptionIfKeyNull ? new LambdaVoid() { @Override public void apply(K key) { throw new IllegalArgumentException(""Key is null""); } } : null, null, throwExceptionIfKeyDoesntExist ? new LambdaVoid() { @Override public void apply(K key) { throw new IllegalArgumentException(""Could not find key "" + key + "" in map""); } } : null, null, new HashSet()); } /** * Look up keys in the map, and return a HashSet of the corresponding values. Performs no checking. Returns null if 'keys' is * null. */ public static HashSet lookupAsSet(Collection keys, Map map) { if (keys == null) return null; HashSet vals = new HashSet(keys.size()); for (K key : keys) { // Simple version for speed V val = map.get(key); vals.add(val); } return vals; } /** * Look up keys in the map, and return a HashSet of the corresponding values. Applies the given function if the key doesn't * exist. Returns null if 'keys' is null. */ public static HashSet lookupAsSet(Collection keys, Map map, LambdaVoid applyWhenKeyDoesntExist) { return lookup(keys, map, null, null, applyWhenKeyDoesntExist, null, new HashSet()); } /** * Look up keys in the map, and return a HashSet of the corresponding values. Applies the given function if the key doesn't * exist to produce a default value. Returns null if 'keys' is null. */ public static HashSet lookupAsSet(Collection keys, Map map, Lambda applyWhenKeyDoesntExistToGetDefaultVal) { return lookup(keys, map, null, null, null, applyWhenKeyDoesntExistToGetDefaultVal, new HashSet()); } // --------------------------------------------------------------------------------------------------------------------- /** Take the union of all items in all passed collections/Iterables */ public static HashSet union(Iterable> iterables) { HashSet result = new HashSet(); for (Iterable iterable : iterables) for (T item : iterable) result.add(item); return result; } /** Put each item in an array into a set. c.f. makeSet(), toSetIgnoringNulls(). */ public static HashSet union(T[] items) { HashSet result = new HashSet(); for (T item : items) result.add(item); return result; } // --------------------------------------------------------------------------------------------------------------------- /** Varargs constructor for a typed set */ @SafeVarargs public static HashSet makeSet(T... items) { HashSet set = new HashSet(items.length); for (T it : items) set.add(it); return set; } /** Varargs constructor for a typed list */ @SafeVarargs public static ArrayList makeList(T... items) { ArrayList list = new ArrayList(items.length); for (T it : items) list.add(it); return list; } /** Varargs constructor for a typed list, specifying initial capacity */ @SafeVarargs public static ArrayList makeListWithInitialCapacity(int initialCapacity, T... items) { ArrayList list = new ArrayList(Math.max(items.length, initialCapacity)); for (T it : items) list.add(it); return list; } // --------------------------------------------------------------------------------------------------------------------- public static ArrayList> mapToListOfPairs(Map map) { ArrayList> result = new ArrayList>(); for (Entry ent : map.entrySet()) result.add(Pair.make(ent.getKey(), ent.getValue())); return result; } // --------------------------------------------------------------------------------------------------------------------- /** * Generate a sorted ArrayList of values from any collection. Does not sort in-place, but rather sorts a copy of the collection. */ public static > ArrayList sortCopy(Collection vals) { ArrayList sorted = new ArrayList(vals); Collections.sort(sorted); return sorted; } /** * Generate a sorted ArrayList of values from any collection, using the specified comparator. Does not sort in-place, but rather * sorts a copy of the collection. */ public static ArrayList sortCopy(Collection vals, Comparator comparator) { ArrayList sorted = new ArrayList(vals); Collections.sort(sorted, comparator); return sorted; } /** * Make a comparator by passing in a lambda that simply returns a comparable field for an object, e.g. * * * CollectionUtils.sort(nodeList, CollectionUtils.makeComparator(new Lambda() { * public String apply(Node obj) { * return obj.getName(); * } * }); * * * This is not much shorter than declaring a comparator in the sort call (and has more overhead), but may be a little simpler or * could reduce code duplication in the comparator. * * @param * The type of the objects to compare * @param * The type of the field to compare * @param getFieldToCompare * A simple getter for the field to compare * @return A comparator that can be used for sorting */ public static > Comparator makeComparator(final Lambda getFieldToCompare) { return new Comparator() { @Override public int compare(O o1, O o2) { return getFieldToCompare.apply(o1).compareTo(getFieldToCompare.apply(o2)); } }; } // --------------------------------------------------------------------------------------------------------------------- /** * Build a map from objects in an Iterable to an index mapping that object to its index in the Iterable. Objects must be unique * (!equals()) or an exception is thrown. */ public static HashMap buildIndex(Iterable collection) { HashMap map = new HashMap(); for (IndexedItem it : IndexedItem.iterate(collection)) if (map.put(it.getItem(), it.getIndex()) != null) throw new IllegalArgumentException( ""Duplicate object in collection, cannot uniquely map objects to indices (try buildIndexMulti()?): "" + it.getItem()); return map; } /** * Build a map from objects in an array to an index mapping that object to its index in the array. Objects must be unique * (!equals()) or an exception is thrown. */ public static HashMap buildIndex(T[] arr) { HashMap map = new HashMap(); for (IndexedItem it : IndexedItem.iterate(arr)) if (map.put(it.getItem(), it.getIndex()) != null) throw new IllegalArgumentException( ""Duplicate object in collection, cannot uniquely map objects to indices (try buildIndexMulti()?): "" + it.getItem()); return map; } /** Build a map from objects in a collection to a list of indices containing equal objects. */ public static MultiMapKeyToList buildIndexMulti(Iterable collection) { MultiMapKeyToList map = new MultiMapKeyToList(); for (IndexedItem it : IndexedItem.iterate(collection)) { T o = it.getItem(); map.put(o, it.getIndex()); } return map; } // --------------------------------------------------------------------------------------------------------------------- /** * Count the number of .equal() occurrences of objects of type T in the collection, and produce histogram of the results. The * histogram can be sorted in order of ascending count if desired. */ public static ArrayList> countEqualOccurrences(Iterable collection) { CountedSet set = new CountedSet(collection); ArrayList> result = new ArrayList>(); for (Entry ent : set.iteratableWithCounts()) result.add(Pair.make(ent.getKey(), ent.getValue())); return result; } /** * Build a histogram of the number of unique objects that occur each number of times. Objects occur multiple times if there are * multiple instances that match with .equals(). Returns a Pair with number of occurrences of each unique * object as left and number of unique objects with that number of occurrences as right. */ public static ArrayList> buildHistogramOfNumObjectsThatOccurGivenNumberOfTimesSparse( Iterable collection) { // Count unique occurrences of the objects of type T ArrayList> counts = countEqualOccurrences(collection); // Now count unique occurrences each of the count values to build the histogram ArrayList> countCounts = countEqualOccurrences(Pair.getAllRights(counts)); // Sort the result in order of number of occurrences (i.e. left) Pair.sortPairsByLeft(countCounts, true); return countCounts; } /** * Build a histogram of the number of unique objects that occur each number of times. Objects occur multiple times if there are * multiple instances that match with .equals(). Returns an array with the number of occurrences of each unique object as the * index and number of unique objects with that number of occurrences as the value of the array at that index. */ public static int[] buildHistogramOfNumObjectsThatOccurGivenNumberOfTimesNonSparse(Iterable collection) { // Build histogram ArrayList> histList = buildHistogramOfNumObjectsThatOccurGivenNumberOfTimesSparse(collection); // Desparsify into an array and return int maxAbscissa = histList.isEmpty() ? -1 : histList.get(histList.size() - 1).getLeft(); int[] result = new int[maxAbscissa + 1]; for (Pair pair : histList) result[pair.getLeft()] = pair.getRight(); return result; } // --------------------------------------------------------------------------------------------------------------------- /** Reverse a list */ public static ArrayList reverse(List list) { ArrayList result = new ArrayList(list.size()); for (int i = list.size() - 1; i >= 0; --i) result.add(list.get(i)); return result; } /** * Arrayify/rectangularize a list of lists, inserting the given filler element to make the result rectangular if lists are not * the same length */ public static ArrayList> rectangularize(List> input, T filler) { int numRows = input.size(); int numCols = 0; for (int i = 0; i < numRows; i++) numCols = Math.max(numCols, input.get(i).size()); ArrayList> output = new ArrayList>(numRows); for (int i = 0; i < numRows; i++) { ArrayList outRow = new ArrayList(input.get(i)); output.add(outRow); while (outRow.size() < numCols) outRow.add(filler); } return output; } public static MultiMapKeyToSet invertMap(HashMap map) { MultiMapKeyToSet result = new MultiMapKeyToSet(); for (Entry ent : map.entrySet()) result.put(ent.getValue(), ent.getKey()); return result; } } " B12002,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Recycle { private BufferedReader br; private int numCases; public Recycle(String input){ try{ FileInputStream fstream = new FileInputStream(input); DataInputStream in = new DataInputStream(fstream); br = new BufferedReader(new InputStreamReader(in)); numCases = Integer.parseInt(br.readLine()); for(int i=0;i=0 || j-1>=0 )sum[i][j]=sum[i-1][j-1]+1; else sum[i][j]=1; } else sum[i][j]=0; } } for(int i=1;i0){ if(sum[n1.length()-i][n1.length()]==(n1.length()-sum[n1.length()][i])){ return true; } } } return false; } public static void main(String[] args) { Recycle r = new Recycle(""input3.txt""); } } " B11624,"import java.io.IOException; import java.util.ArrayList; import java.util.Vector; public class RecycledNumbers { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub ReadFile.read(""C:\\test\\input.txt""); ArrayList elements = ReadFile.getElements(); //Number of cases to test int numberCases = Integer.valueOf(elements.get(0)); if(numberCases > elements.size()) { System.out.println(""Error in number of tests""); System.exit(-1); } elements.remove(0);// remove the first element, so only lines to translate are left in the file StringBuilder outputFile = new StringBuilder(); for(int i = 1; i <= elements.size(); i++){ String[] numbers = elements.get(i-1).split("" ""); outputFile.append(""Case #"" + i + "": "" + countRecycledNumbers(new Integer(numbers[0]), new Integer(numbers[1]) ) ); outputFile.append(""\r\n""); } WriteFile.write(""C:\\test\\output.txt"", outputFile.toString()); } private static int countRecycledNumbers(Integer integer1, Integer integer2) { int countRecycled = 0; for(int i = integer1; i 0) countRecycled+=countRecyclablePerNumber; } return countRecycled; } private static int countRecyclablePerNumber(int number, int min, int max) { if(number < 10 ) return 0; int count = 0; String value = String.valueOf(number); char[] charValues = value.toCharArray(); Vector vectorRecycledNumbers = new Vector(); for(int i=0; i= min && number < newIntValue && !vectorRecycledNumbers.contains(newIntValue)){ count++; vectorRecycledNumbers.add(newIntValue); } } vectorRecycledNumbers.clear(); return count; } } " B10757,"package recycledNumbers; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { public static String processaCaso(String linha, int i) { String[] nums = linha.split("" ""); int a = Integer.parseInt(nums[0]); int b = Integer.parseInt(nums[1]); int numDistincPairs = 0; int lenNum = Integer.toString(a).length()-1; Set ms = new HashSet(); for (; a < b; a++) { String n = Integer.toString(a); ms.clear(); for (int j = 0; j < lenNum; j++) { int indice = lenNum-j; String strM = n.substring(indice)+n.substring(0,indice); int m = Integer.parseInt(strM); if (!(a < m && m <= b)) continue; ms.add(m); } numDistincPairs += ms.size(); } return String.format(""Case #%d: %d"", i, numDistincPairs); } /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { Scanner scan = new Scanner(new File(args[0])); int numTestCases = scan.nextInt(); scan.nextLine(); Writer saida = new FileWriter(args[0]+"".out""); for (int i = 1 ; i <= numTestCases; i++) { saida.write(processaCaso(scan.nextLine(),i)+""\n""); } saida.close(); } } " B12701,"package jam2012.numbers; import java.io.File; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.Scanner; import commons.FileUtilities; public class Recycle { public static void main(String[] args) throws IOException { List strings = FileUtilities.readFile(new File(""C-small-attempt1.in"")); int number = Integer.parseInt(strings.get(0)); List result = new LinkedList(); for (int i = 1; i <= number; i++) { Scanner s = new Scanner(strings.get(i)); int lower = s.nextInt(); int upper = s.nextInt(); int[] lowerArray = createArray(lower); int[] upperArray = createArray(upper); int tresult = 0; for (int j = lower; j <= upper; j++) { int[] test = createArray(j); LinkedList poss = new LinkedList(); for (int k = 1; k < test.length; k++) { if (isBigger(test, k, lowerArray, 0) == 1 && isBigger(test, k, upperArray, 0) <= 0 && isBigger(test, k, test, 0) == 1) { boolean dup = false; for (int l : poss) { if (isBigger(test, k, test, l) == 0) { dup = true; } } if (!dup) { tresult++; poss.add(k); } } } } result.add(Integer.toString(tresult)); } FileUtilities.writeFile(result, new File(""C-small-attempt1.out"")); } private static int isBigger(int[] a, int aStart, int[] b, int bStart) { for (int i = 0; i < a.length; i++) { int aPtr = a[(i+aStart)%a.length]; int bPtr = b[(i+bStart)%b.length]; if (aPtr > bPtr) { return 1; } else if (aPtr < bPtr) { return -1; } } return 0; } private static int[] createArray(int i) { String iS = Integer.toString(i); int[] iA = new int[iS.length()]; for (int j = 0; j < iA.length; j++) { iA[j] = Character.getNumericValue(iS.charAt(j)); } return iA; } } " B10130,"import java.io.FileReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Main { class Pair { int a; int b; Pair(int a, int b) { this.a = a; this.b = b; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getOuterType().hashCode(); result = prime * result + a; result = prime * result + b; return result; } @Override public boolean equals(Object o) { Pair second = (Pair) o; if (second == null) { return false; } return this.a == second.a && this.b == second.b || this.a == second.b && this.b == second.b; } private Main getOuterType() { return Main.this; } } Scanner in; PrintWriter out; // class Scanner { // StreamTokenizer in; // // Scanner(InputStream stream) { // in = new StreamTokenizer(new BufferedReader(new // InputStreamReader(stream))); // in.resetSyntax(); // in.whitespaceChars(0, 32); // in.wordChars(33, 255); // } // // String next() { // try { // in.nextToken(); // return in.sval; // } catch (Exception e) { // throw new Error(); // } // } // // long nextLong() { // return Long.parseLong(next()); // } // // int nextInt() { // return Integer.parseInt(next()); // } // } void asserT(boolean e) { if (!e) { throw new Error(); } } void solve() { int nTests = in.nextInt(); for (int i = 1; i <= nTests; i++) { out.println(""Case #"" + i + "": "" + solveOne()); } } long solveOne() { int a = in.nextInt(); int b = in.nextInt(); int size = (a + """").length(); Set set = new HashSet(); for (int i = a; i <= b; i++) { String temp = i + """"; for (int j = 1; j < size; j++) { temp = temp.charAt(size - 1) + temp.substring(0, size - 1); int m = Integer.parseInt(temp); if (a <= m && m <= b && (m + """").length() == (i + """").length() && i != m) { Pair p = new Pair(i, m); set.add(p); } } } return set.size() / 2; } void run() { try{ in = new Scanner(new FileReader(""C-small-attempt0.in"")); out = new PrintWriter(""output.txt""); }catch (Exception e) { // TODO: handle exception } try { solve(); } finally { out.close(); } } public static void main(String[] args) { new Main().run(); } }" B12008,"package gjc.recyclednumber; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.StringTokenizer; public class Solution { List list = new LinkedList(); /** * @param args */ public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader(""C-small-attempt0.in"")); BufferedWriter bw = new BufferedWriter(new FileWriter(""C-small-attempt0.txt"")); int nTestCases = Integer.parseInt(br.readLine()); for (int i=0; i resultSet = new HashSet(); String line = br.readLine(); StringTokenizer st = new StringTokenizer(line); int bottom = Integer.parseInt(st.nextToken()); int top= Integer.parseInt(st.nextToken()); for (int j=bottom; j<=top; j++) { String str = j+""""; // Rotate and check if existing number exists. String temp = str; for (int k=0; k=bottom) { resultSet.add(number+"",""+j); } } } } // Display the results. bw.write(""Case #""+(i+1)+"": ""); bw.write(resultSet.size()+""\n""); } bw.close(); } } " B12190,"package luis.miguel.serrano.utilities; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; import luis.miguel.serrano.settings.GlobalSettings; /** * Data class for processing input and generating output * @author Luis Miguel Serrano * */ public class DataC { private File inputFile; private File outputFile; public DataC(String inputFilePath, String outputFilePath) { this.inputFile = new File(inputFilePath); outputFile = new File(outputFilePath); } public DataC(File inputFile) { this.inputFile = inputFile; outputFile = new File(GlobalSettings.OUTPUT_FILE_PATH); } /** * Processes the file passed as argument in the constructor * @throws FileNotFoundException */ public void processFile() throws FileNotFoundException { if(outputFile.exists()) outputFile.delete(); Scanner scanner = new Scanner(inputFile); final int casesNumber = scanner.nextInt(); scanner.nextLine(); for(int i = 0; i!=casesNumber; ++i) processCase(scanner, i); System.out.println(""Done processing file: ""+inputFile); } //Format-specific private void processCase(Scanner scanner, int caseNumber) { //System.out.println(""New Case""); int a = scanner.nextInt(); int b = scanner.nextInt(); int solution; solution = getSolution(a, b); //Write solution to file try { FileWriter fw = new FileWriter(outputFile, true); fw.write(""Case #""+(caseNumber+1)+"": ""+solution+""\r\n""); fw.flush(); fw.close(); } catch (IOException e) { e.printStackTrace(); } } //Problem-specific private int getSolution(int a, int b){ int solution = 0; for(int i = b; i!=a; --i) { for(int j = a; j saida.txt */ public static void main(String[] args) throws Exception { BufferedReader buf = new BufferedReader(new InputStreamReader(System.in)); String line = buf.readLine(); int j = 1; while((line = buf.readLine()) != null) { String[] l = line.split("" ""); System.out.println(""Case #""+j+"": ""+count(l[0], l[1])); j++; } } public static int count(String aa, String bb) { Integer a = Integer.valueOf(aa); Integer b = Integer.valueOf(bb); int count = 0; for (int i = a; i <= b; i++) { count = count + checkRec(i, a, b); } return count; } //Checa se é recicle pairs entre n e m public static int checkRec(int n, int a, int b) { ArrayList rep = new ArrayList(); int count = 0; String v = String.valueOf(n); for (int i = 0; i < v.length()-1; i++) { char aux = v.charAt(v.length()-1); v = v.substring(0, v.length()-1); v = aux+v; int m = Integer.valueOf(v); if(a <= n && n < m && m <= b && !rep.contains(v)) { rep.add(v); count++; } } return count; } } " B10953,"package codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public abstract class Task { private String inputFileName; private BufferedReader in; private PrintWriter out; public Task(String[] args) { inputFileName = args[0]; } public void execute() throws IOException { File f = new File(inputFileName); in = new BufferedReader(new FileReader(f)); catchInputData(); in.close(); processInputData(); f = new File(inputFileName.substring(0, inputFileName.length() - 2) + ""out""); f.createNewFile(); out = new PrintWriter(new BufferedWriter(new FileWriter(f))); generateOutputFile(); out.flush(); out.close(); } protected abstract void generateOutputFile() throws IOException; protected abstract void processInputData(); protected abstract void catchInputData() throws IOException; protected String readLine() throws IOException { return in.readLine(); } protected void writeLine(String line) throws IOException { out.println(line); } } " B11612,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; public class Recycled { public static void main(String args[]) { try { File file = new File(""input.txt""); FileReader filereader = new FileReader(file); BufferedReader br = new BufferedReader(filereader); File out = new File(""output.txt""); FileWriter filewriter = new FileWriter(out); BufferedWriter bw = new BufferedWriter(filewriter); PrintWriter pw = new PrintWriter(bw); String str = br.readLine(); int line = Integer.valueOf(str); for (int i = 0; i < line; i++) { int x = i + 1; pw.print(""Case #"" + x + "": ""); str = br.readLine(); int ans = solve(str); pw.println(ans); } pw.close(); bw.close(); } catch (IOException ie) { ie.printStackTrace(); } } private static int solve(String s) { List list = new ArrayList(); int count = 0; String[] elems = s.split("" ""); int A = Integer.valueOf(elems[0]); int B = Integer.valueOf(elems[1]); for (int i = A; i <= B; i++) { String str = String.valueOf(i); if(str.length() <= 1) continue; for(int j = 0; j < str.length() - 1; j++) { String after = str.substring(0, j+1); String before = str.substring(j+1,str.length()); String strRecycled = before + after; int recycled = Integer.valueOf(strRecycled); if(i res[] = new LinkedList[until+1]; static Object speed[][] = new Object[until+1][]; public static void main(String []args) { for(int i=1;i<=until;i++) GO(i); for(int i=1;i<=until;i++) speed[i] = res[i].toArray(); Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); for(int num=1;num<=N;num++) { int ret = 0; int A = scanner.nextInt(); int B = scanner.nextInt(); for(int i=A;i<=B;i++) { int len = res[i].size(); for(int j=0;j(); String str = Integer.toString(num); int len = str.length(); for(int i=0;inum) res[num].add(rev); } } } " B12870," import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author edemairy */ public class Main { private final static Logger logger = Logger.getLogger(Main.class.getName()); private static int nbTC; private static StringBuilder result = new StringBuilder(); /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { logger.setLevel(Level.OFF); // Scanner scanner = new Scanner(System.in); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); nbTC = readInt(reader); // scanner.nextLine(); for (int tc = 1; tc <= nbTC; ++tc) { result.append(""Case #"" + tc + "": ""); result.append(oneTestCase(reader)); result.append('\n'); } System.out.print(result); } private static TreeSet found = new TreeSet(); private static TreeSet cycle = new TreeSet(); private static int[] p10 = {1, 10, 100, 1000, 10000, 100000, 1000000}; private static StringBuilder oneTestCase(BufferedReader reader) throws IOException { int A = readInt(reader); int B = readInt(reader); int rnum = 0; found.clear(); fori: for (int i = A; i <= B; ++i) { cycle.clear(); int lg = (int) Math.floor(Math.log10(i)); if (lg == 0) { continue fori; } if (found.contains(i)) { continue fori; } do { if (i >= p10[lg]) { if ((i >= A) && (i <= B)) { cycle.add(i); } } int ld = i % 10; i /= 10; i += p10[lg] * ld; } while (!cycle.contains(i)); int n = cycle.size(); if (n != 1) { rnum += n * (n - 1) / 2; found.addAll(cycle); } } Formatter formatter = new Formatter(); StringBuilder result = new StringBuilder(); // for (int i = 0; i < 5; ++i) { // formatter.format(""%3d"", n[i]); // } // result.append(formatter.out()); result.append(rnum); return result; } private static int readInt(BufferedReader reader) throws IOException { int result = 0; boolean positive = true; char currentChar = (char) reader.read(); while ((currentChar == ' ') || (currentChar == '\n')) { currentChar = (char) reader.read(); } if (currentChar == (char) -1) { throw new IOException(""end of stream""); } if (currentChar == '-') { positive = false; currentChar = (char) reader.read(); } while ((currentChar >= '0') && (currentChar <= '9')) { result = result * 10 + currentChar - '0'; currentChar = (char) reader.read(); } if (positive) { return result; } else { return -result; } } private static char readChar(BufferedReader reader) throws IOException { return (char) reader.read(); } } " B12987,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.io.PrintWriter; import java.util.*; public class C { Scanner sc; PrintStream ps; public void solve() { int A = sc.nextInt(); int B = sc.nextInt(); int nr = 0; for (int n=A; n<=B; n++) { String s = n+""""; HashSet set = new HashSet(); for (int i=0; in+1;m2--) { n1 = (new Integer(n)).toString().toCharArray(); m1 = (new Integer(m2)).toString().toCharArray(); for(int index=0; index= start && t <= end && !val.toString().equals(val1.toString())) { // System.out.println(""iNPUT :; "" + val + "" :: Output : "" + val1 + "" t :: "" + t ); if (inputSet.add(val + "","" + val1)) { finalSet.add(t); } //// System.out.println(""dding :: "" + t); // String key = val.toString() + "","" + val1.toString(); // String key1 = val1.toString() + "","" + val.toString(); // if(!(finalSet.containsKey(key)|| finalSet.containsKey(key1))) { // finalSet.put(key, t); // } //// finalSet.put(Integer.valueOf(val1.toString())); // } // System.out.println(""num :: "" + val1); } } return true; } private static ArrayList getInputList(BufferedReader stdin) throws IOException { ArrayList stringList = new ArrayList(); String line; int inputLineCount = 0; Integer testCaseCount = 0; while ((line = stdin.readLine()) != null && line.length() != 0 && inputLineCount <= testCaseCount.intValue()) { // System.out.println(""line :: "" + line); if (inputLineCount == 0) { try { testCaseCount = Integer.valueOf(line); } catch (NumberFormatException pe) { System.out.println(""Invalid input for # of test cases""); System.exit(0); } inputLineCount++; continue; } stringList.add(line); inputLineCount++; if (inputLineCount == testCaseCount + 1) { break; } } return stringList; } } " B11802,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package util; import java.util.ArrayList; import java.util.List; /** * * @author bohmd */ public class Util { public static List getIntList(String listString) { String[] listArray = listString.split("" ""); List list = new ArrayList(); for (String str : listArray) { list.add(Integer.parseInt(str)); } return list; } public static int getInt(String string) { return Integer.parseInt(string); } public static List getLongList(String listString) { String[] listArray = listString.split("" ""); List list = new ArrayList(); for (String str : listArray) { list.add(Long.parseLong(str)); } return list; } } " B10302," import java.io.*; import java.util.ArrayList; import java.util.List; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author home */ public class RecycledNumbers { public static void main(String args[])throws IOException{ FileReader reader = new FileReader(""D:\\NetBeansProjects\\DBInteractionWithWS\\src\\java\\C-small-attempt0.in""); BufferedReader br = new BufferedReader(reader); File file = new File(""rloutput.txt""); FileWriter fw = new FileWriter(file); int count = Integer.parseInt(br.readLine()); for(int s=0;s list = new ArrayList(); if(end<=10) break; else{ if(i<=10) continue; String temp1 = i+""""; for(int j=1;j list = getPairs(index); for (int j = 0; j < list.size(); j++) { if (list.get(j) <= B && list.get(j)>index) { //System.out.println(""""+index+"" ""+list.get(j)); pairs++; } } } return pairs; } private static ArrayList getPairs(int index) { ArrayList list = new ArrayList(); String temp = Integer.toString(index); int length = temp.length(); char[] buffer = temp.toCharArray(); if (index < 10) { return list; } else { for (int numbers = 1; numbers < length; numbers++) { char c=buffer[length-1]; for(int k=buffer.length-1;k>0;k--) { buffer[k]=buffer[k-1]; } buffer[0]=c; String s=new String(buffer); int number=Integer.parseInt(s); if(!list.contains(number)) list.add(number); } return list; } } private static void writeToFile(int a,int N) { try { // Create file FileWriter fstream = new FileWriter(new File(""D:/Academic Work/Semester 5/Code Jam/out.txt""),true); BufferedWriter out = new BufferedWriter(fstream); String str=""Case #""+(N+1)+"": ""+a+""\r\n""; out.append(str); //Close the output stream out.close(); } catch (Exception e) {//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } } " B12022,"import java.util.*; import java.util.regex.*; import java.text.*; import java.math.*; public class C { void start() { Scanner sc=new Scanner(System.in); int nt=sc.nextInt(); for (int tc=1; tc<=nt; tc++) { int a=sc.nextInt(), b=sc.nextInt(), re=0; if (a9) { int p=1; while (p*10x && z>=a && z<=b) re++; } while (z!=x); } } System.out.printf(""Case #%d: %d\n"", tc, re); } } public static void main(String[] args) throws Exception { new C().start(); } }" B12855,"package problemC; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class RecycledNumbers { private static BufferedWriter out = null; private static int numberOfTestCases; static String[] testCases; private static void loadData() { BufferedReader in = null; try { in = new BufferedReader(new FileReader(""C-small-attempt0.in"")); // in = new BufferedReader(new FileReader(""inputC.small"")); // in = new BufferedReader(new FileReader(""C-large.in"")); } catch (FileNotFoundException e) { e.printStackTrace(); } try { numberOfTestCases = Integer.parseInt(in.readLine()); } catch (NumberFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // System.out.println(numberOfTestCases); testCases = new String[numberOfTestCases]; String testCase = null; for (int i=0; i(); try { // in.readLine(); testCases[i] = in.readLine(); // System.out.println(testCases[i]); } catch (IOException e) { e.printStackTrace(); } } try { in.close(); } catch (IOException e) { e.printStackTrace(); } } private static boolean isRP(String a, String b) { String c = a.concat(a); if (c.contains(b)) return true; return false; } public static void main(String argv[]) { loadData(); try { out = new BufferedWriter(new FileWriter(""outputC.small"")); } catch (IOException e) { e.printStackTrace(); } int pairC = 0; for (int i=0; i>== 1; } *****/ } } " B13190,"import java.util.*; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; public class Main { private void solve() throws Exception { int test = in.nextInt(); for(int t=1; t <= test; ++t) { solveTest(t); out.println(); } } private void solveTest(int testNum) { int a=in.nextInt(); int b=in.nextInt(); int ans = 0; int[] used = new int[10000000]; int T=1; for(int n=a; n <= b; ++n) { String str=Integer.toString(n); ++T; for(int shift=0; shift < str.length(); ++shift) { str = str.substring(1) + str.charAt(0); if (str.charAt(0) == '0') continue; int m = Integer.parseInt(str); if (m < a || m > b || m <= n || used[m] == T) continue; used[m] = T; //out.println(n + "" "" + m); ++ans; } } out.print(""Case #"" + testNum + "": "" + ans); } private void run() { try { long start = System.currentTimeMillis(); in = new FastScanner(""input.txt"", ""output.txt""); solve(); out.flush(); System.err.print(""running time = "" + (System.currentTimeMillis() - start) * 1e-3); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { Main main = new Main(); main.run(); } FastScanner in; static PrintWriter out; static class FastScanner { public BufferedReader reader; private StringTokenizer tokenizer; public FastScanner(String input, String output) { try { reader = new BufferedReader(new FileReader(new File(input))); out = new PrintWriter(new File(output)); tokenizer = null; } catch (Exception e) { reader = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); tokenizer = null; } } public double nextDouble() { return Double.parseDouble(nextToken()); } public String nextToken() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (Exception e) { e.printStackTrace(); } } return tokenizer.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } } }" B11908,"package recycledNumbers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class RecycledNumbers { private BufferedReader reader; private BufferedWriter writer; private static String fileName; private Map twoTongues; public static void main(String[] args) throws IOException { fileName = args[0]; RecycledNumbers numbers = new RecycledNumbers(); numbers.findTheNumbers(); } /** * ""Find the numbers, fast as you can * recycling's uncouth, so don't or you'll be banned"" */ public void findTheNumbers() { try { writer = new BufferedWriter( new FileWriter(""recycling.txt"")); reader = new BufferedReader( new InputStreamReader( new DataInputStream( new FileInputStream(fileName)))); Integer numTestCases = Integer.parseInt(reader.readLine()); for(int i = 0; i < numTestCases; ++i) { int numNumbers = solve(reader.readLine()); writer.write(""Case #"" + (i+1) + "": "" + numNumbers + ""\n""); } writer.close(); } catch (Exception e) { e.printStackTrace(); System.out.println(""Shizzle""); System.exit(1); } } private int solve(String readLine) { Set results = new TreeSet(); Scanner scanner = new Scanner(readLine); String numberOne = scanner.next(); String numberTwo = scanner.next(); int counter = 0; if(numberOne.length() == 1) { return 0; } //from A - B for(int i = Integer.parseInt(numberOne); i < Integer.parseInt(numberTwo); ++i) { results.clear(); String numToSwitch = Integer.toString(i); System.out.println(""numToSwitch: "" + numToSwitch + "" and length: "" + numToSwitch.length()); System.out.println(""n: "" + i); //from start of A to end of A String numToMove; String numToUse; String finishedNum = numToSwitch; for(int j = 0; j < numToSwitch.length() - 1; ++j) { numToMove = finishedNum.substring(finishedNum.length() - 1); numToUse = finishedNum.substring(0, finishedNum.length() - 1); finishedNum = numToMove.concat(numToUse); System.out.println(""n: "" + i + "" and m: "" + finishedNum); if(Integer.parseInt(finishedNum) <= Integer.parseInt(numberTwo)) { if(i < Integer.parseInt(finishedNum)) { System.out.println(""got counted""); results.add(Integer.parseInt(finishedNum)); } } } counter = counter + results.size(); } System.out.println(""counter: "" + counter); return counter; } } " B11302,"import java.util.*; public class C { public static void main(String args[]) { Scanner scan = new Scanner(System.in); int T = scan.nextInt(); for(int ca=1;ca <= T;ca++) { int A = scan.nextInt(); int B = scan.nextInt(); int rtn = 0; String str = ""1""; while(str.length() < (A+"""").length()) str += ""0""; int MOD = Integer.parseInt(str); for(int i=A;i <= B;i++) { int k = i; HashSet h = new HashSet(); for(int j=0;j < str.length();j++) { //str = str.substring(1) + str.substring(0,1); //int k = Integer.parseInt(str); k = (k % MOD) * 10 + (k / MOD); if(k > i && k <= B && !h.contains(k)) rtn++; h.add(k); } } System.out.println(""Case #"" + ca + "": ""+ rtn); } } }" B10816,"import java.io.*; import java.util.*; public class C2012 { public static void main(String[] args) throws IOException { PrintWriter out; BufferedReader f; try { f = new BufferedReader(new FileReader(""C2012.in"")); out = new PrintWriter(new BufferedWriter(new FileWriter( ""C2012.out""))); } catch (Exception e) { f = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } int n=Integer.parseInt(f.readLine()); for(int i=1;i<=n;i++){ StringTokenizer token = new StringTokenizer(f.readLine()); int a=Integer.parseInt(token.nextToken()); int b=Integer.parseInt(token.nextToken()); int numDigits=numDigits(a); int answer=0; int last=0; for(int j=a;j<=b;j++){ int hm=j; int hm2=hm; int tenmultiply=0; for(int k=1;khm&&last!=hm2){ last=hm2; answer++; } } } out.print(""Case #""); out.print(i+"": ""); out.println(answer); } out.close(); System.exit(0); } public static int numDigits(int x){ if (x >= 10000) { if (x >= 10000000) { if (x >= 100000000) { if (x >= 1000000000) return 10; return 9; } return 8; } if (x >= 100000) { if (x >= 1000000) return 7; return 6; } return 5; } if (x >= 100) { if (x >= 1000) return 4; return 3; } if (x >= 10) return 2; return 1; } }" B12272,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author binny */ import java.io.*; import java.util.ArrayList; public class RecycledNumber { public static void main(String args[]) throws Exception { String inputPath = ""//C-small-attempt0.in""; String outputPath = ""//C-small-attempt0.out""; RecycledNumber rw = new RecycledNumber(); String[] str = rw.readFromFile(inputPath); String[] solution = getSolution(str); rw.writeToFile(outputPath, solution); } private static String[] getSolution(String[] str) { int noOftestCases = Integer.parseInt(str[0]); String[] output = new String[noOftestCases]; for (int i = 1; i <= noOftestCases; i++) { String[] arr = str[i].split("" ""); int lowerLimit = Integer.parseInt(arr[0]); int upperLimit = Integer.parseInt(arr[1]); int count = 0; while (upperLimit > lowerLimit) { for (int j = 0; j < upperLimit - lowerLimit; j++) { count = count + isRecycledPossible(String.valueOf(lowerLimit + j), String.valueOf(upperLimit)); } upperLimit--; } output[i - 1] = ""Case #"" + i + "": "" + count; } return output; } public static int isRecycledPossible(String a, String b) { int countInRecycledPossible = 0; for (int i = 0; i < a.length(); i++) { for (int j = i; j < a.length(); j++) { if (Integer.parseInt(rotate(a,j)) - Integer.parseInt(b) == 0) { countInRecycledPossible++; break; } } if(countInRecycledPossible>0){ break; } } return countInRecycledPossible; } public static String rotate(String a, int i) { String substring = a.substring(a.length() - i); String rotatedDigit = substring + a.substring(0,a.length() - i); return rotatedDigit; } public String[] readFromFile(String inputPath) throws FileNotFoundException, IOException { FileInputStream fis = null; DataInputStream dis = null; BufferedReader br = null; ArrayList strArrList = new ArrayList(); try { fis = new FileInputStream(inputPath); dis = new DataInputStream(fis); br = new BufferedReader(new InputStreamReader(dis)); String strLine; while ((strLine = br.readLine()) != null) { strArrList.add(strLine); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) { br.close(); } if (dis != null) { dis.close(); } if (fis != null) { fis.close(); } } catch (IOException e) { e.printStackTrace(); } } return strArrList.toArray(new String[strArrList.size()]); } public void writeToFile(String outputPath, String[] strArr) { BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter(outputPath)); for (int i = 0; i < strArr.length; i++) { bw.write(strArr[i]); bw.newLine(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (bw != null) { bw.flush(); bw.close(); } } catch (IOException e) { e.printStackTrace(); } } } } " B12836,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { String filename; BufferedReader br; PrintWriter pw; public RecycledNumbers(String filename) throws FileNotFoundException { this.filename = filename; br = new BufferedReader(new FileReader(filename)); pw = new PrintWriter(""output-3.txt""); } public void processInput() throws NumberFormatException, IOException { StringBuffer sb = new StringBuffer(); int numCases = Integer.parseInt(br.readLine()); for(int i=0; i visitedSet; private int processCase(String inputCase) { String[] s = inputCase.split("" ""); int A = Integer.parseInt(s[0]); int B = Integer.parseInt(s[1]); visitedSet = new HashSet(); int res = 0; for(int i=A; i<=B; i++) { if(!visitedSet.contains(i)) res+= process(i, A, B); } return res; } private int process(final int n, final int A, final int B) { String s = Integer.toString(n); int count=0; for(int i=s.length()-1; i>0; i--) { String s1 = s.substring(i) + s.substring(0, i); int num = Integer.parseInt(s1); visitedSet.add(num); if(num!=n && num>=A && num<=B) { if(num hashRes = new HashSet(); for (int p = 1; p < aStr.length(); p++) { String moved = currAStr.substring(p) + currAStr.substring(0, p); if ((moved.compareTo(bStr) <= 0) && (moved.compareTo(currAStr) > 0)) { hashRes.add(moved); } } res += hashRes.size(); } bw.write(""Case #"" + (testCaseI + 1) + "": "" + res); bw.newLine(); } br.close(); bw.close(); } catch (Exception ex) { ex.printStackTrace(); } } } " B11866,"package codejam.codejam_2012; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; /** * Created by IntelliJ IDEA. * User: csrazvan * Date: 14.04.2012 * Time: 13:44 * To change this template use File | Settings | File Templates. */ public class RecycledNumbers { public int formNumber(ArrayList rotation) { int nr = 0; for (Integer i : rotation) { nr = nr * 10 + i; } return nr; } public ArrayList getRotations(int nr) { ArrayList result = new ArrayList(); ArrayList rotation = new ArrayList(); int digits = 0; while (nr > 0) { rotation.add(0, nr % 10); digits++; nr = nr / 10; } for (int i = 0; i < digits - 1; i++) { rotation.add(rotation.get(0)); rotation.remove(0); result.add(formNumber(rotation)); } return result; } public void solve(File f) throws Exception { Scanner scanner = new Scanner(f); File w = new File(""recycled.out""); BufferedWriter bw = new BufferedWriter(new FileWriter(w)); int t = scanner.nextInt(); for (int i = 1; i <= t; i++) { int a = scanner.nextInt(); int b = scanner.nextInt(); int count = 0; HashMap map = new HashMap(); for (int startValue = a; startValue <= b; startValue++) { ArrayList rotations = getRotations(startValue); for (int rotation : rotations) { if (rotation >= a && rotation <= b && startValue < rotation) { if (map.containsKey(startValue) && map.get(startValue) == rotation) { } else if (map.containsKey(rotation) && map.get(rotation) == startValue) { } else { map.put(startValue, rotation); count++; } } } } bw.write(String.format(""Case #%s: %s\n"",i,count)); } bw.close(); } public static void main(String[] args) { try { new RecycledNumbers().solve(new File(""recycled.in"")); } catch (Exception e) { e.printStackTrace(); } } } " B13239,"package Qualifier; import java.io.*; import java.util.*; public class C_Small { private static Scanner in; private static PrintWriter out; private static String testCase = ""C-small""; public static void main(String[] args) throws Exception { Locale.setDefault(Locale.ENGLISH); out = new PrintWriter(new FileOutputStream(testCase + "".out"")); in = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream(testCase + "".in"")))); int tests = in.nextInt(); in.nextLine(); for (int t = 1; t <= tests; ++t) { out.print(""Case #"" + t + "": ""); new C_Small().solve(); } in.close(); out.close(); } void solve() throws Exception { int A = in.nextInt(); int B = in.nextInt(); long result = 0; if(B < A || String.valueOf(A).trim().length() != String.valueOf(B).trim().length()){ return; } for(int n=A; n<=B; n++){ String nString = String.valueOf(n); int length = nString.length(); for(int j = 1; j < length; j++){ String c = nString.substring(j, length) + nString.substring(0 , j); int mCase = Integer.parseInt(c); if(mCase >= A && mCase <= B && mCase > n){ result++; } } } out.println(result); } } " B12038,"import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import com.ibm.db2.jcc.am.s; public class C { private static final String INPUT_FILE = ""d:/C-small-attempt0.in""; private static final String OUTPUT_FILE = ""d:/result.txt""; private static final int MAX_VALUE = 2000000; private static int T; static int[] d = new int[1 + MAX_VALUE]; static int a, b; static long[] result; static void init() { for (int i = 1; i <= MAX_VALUE; ++i) { if (d[i] != 0) { continue; } d[i] = i; String s = """" + i; for (int j = 0; j < s.length(); ++j) { s = s.substring(1) + s.charAt(0); if (s.charAt(0) != '0') { int v = Integer.parseInt(s); if (v > MAX_VALUE) continue; d[Integer.parseInt(s)] = i; } } } } static void Input() throws Exception { InputStream in = new FileInputStream(INPUT_FILE); // InputStream in = System.in; Scanner scanner = new Scanner(in); T = scanner.nextInt(); result = new long[T + 1]; for (int i = 0; i < T; ++i) { a = scanner.nextInt(); b = scanner.nextInt(); solve(i, a, b); } } static void solve(int c, int a, int b) { long rst = 0; int[] map = new int[MAX_VALUE + 1]; for (int i = a; i <= b; ++i) { ++map[d[i]]; } for (int i = a; i <= b; ++i) { if (map[d[i]] > 0) { int v = map[d[i]]; rst += 1L * v * (v - 1) / 2; map[d[i]] = 0; } } result[c] = rst; } static void Output() throws Exception { FileWriter writer = new FileWriter(new File(OUTPUT_FILE)); for (int i = 0; i < T; ++i) { String rs = ""Case #"" + (i + 1) + "": "" + (result[i]) + ""\n""; writer.write(rs); System.out.println(rs); } writer.close(); } /** * @param args */ public static void main(String[] args) throws Exception { long start = System.currentTimeMillis(); init(); // System.out.println(System.currentTimeMillis() - start); Input(); Output(); } } " B11425,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; /* Jin Hao Chong * Google Code Jam 2012 Qualification Round Question 3 * In this program, I used the Java standard library of java.io and java.util; */ public class RecycledNumbers { public static void main(String args[]){ BufferedReader in = null; BufferedWriter out = null; try{ //input and output in = new BufferedReader(new FileReader(""C-small-attempt0.in"")); out = new BufferedWriter(new FileWriter(""Output.txt"")); int totalround, round, total, integerA, integerB; String read, output; String[] split; //get rounds read = in.readLine(); round = Integer.parseInt(read); totalround = round; //Calculation while(round > 0){ output = ""Case #"" + (totalround - round + 1) + "": ""; read = in.readLine(); split = read.split("" ""); integerA = Integer.parseInt(split[0]); integerB = Integer.parseInt(split[1]); total = 0; //try every possibility for(int i = integerA; i < integerB; i++){ String num = Integer.toString(i); ArrayList array = new ArrayList(); //try to move digits from back to front for(int j = 1; j < num.length(); j++){ String front = num.substring(0, j); String back = num.substring(j); back += front; int compare = Integer.parseInt(back); //check if the digit after moved falls in range if((!array.contains(compare)) && (compare > i) && (compare <= integerB)){ array.add(compare); total++; } } } output += total; //write output to file out.write(output); if(round != 1) out.newLine(); round--; } in.close(); out.close(); }catch(Exception e){ System.err.print(e); } } } " B10743,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; import java.util.*; import java.util.Scanner; /** * * @author Mash */ public class Main { public static void main(String args[]) throws FileNotFoundException { Scanner in = new Scanner(new FileReader(""C:\\ima\\ans.txt"")); int T=in.nextInt(); int A,B; String a,b,perm; char[] per; String filler=""0000000""; for(int i=1;i<=T;i++){ int res=0; A=in.nextInt(); B=in.nextInt(); b=Integer.toString(B); for(int j=A;j<=B;j++){ int ans; // Set list= new HashSet(); Set list=new HashSet(); a=Integer.toString(j); int des=b.length()-a.length(); perm=filler.substring(0, des)+j; //System.out.println(perm); //per=perm.toCharArray(); //permute(per, 0, b.length()); String add; for(int s=0;s<=perm.length();s++){ add=perm.substring(s)+perm.substring(0,s); list.add(add); } ans=0; Iterator it=list.iterator(); //System.out.println(""j is""+j); while(it.hasNext()) { String comp=(String) it.next(); //System.out.println(comp); int com=Integer.parseInt(comp); if(com>j&&com<=B)ans++; } //System.out.println(""answer is""+ans); res+=ans; } System.out.println(""Case #""+i+"": ""+res); } } } " B10531,"/** * */ package hu.herba.codejam; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; /** * Base functionality, helper functions for CodeJam problem solver utilities. * * @author csorbazoli */ public abstract class AbstractCodeJamBase { private static final String EXT_OUT = "".out""; protected static final int STREAM_TYPE = 0; protected static final int FILE_TYPE = 1; protected static final int READER_TYPE = 2; private static final String DEFAULT_INPUT = ""test_input""; private static final String DEFAULT_OUTPUT = ""test_output""; private final File inputFolder; private final File outputFolder; public AbstractCodeJamBase(String[] args, int type) { String inputFolderName = AbstractCodeJamBase.DEFAULT_INPUT; String outputFolderName = AbstractCodeJamBase.DEFAULT_OUTPUT; if (args.length > 0) { inputFolderName = args[0]; } this.inputFolder = new File(inputFolderName); if (!this.inputFolder.exists()) { this.showUsage(""Input folder '"" + this.inputFolder.getAbsolutePath() + ""' not exists!""); } if (args.length > 1) { outputFolderName = args[1]; } this.outputFolder = new File(outputFolderName); if (this.outputFolder.exists() && !this.outputFolder.canWrite()) { this.showUsage(""Output folder '"" + this.outputFolder.getAbsolutePath() + ""' not writeable!""); } else if (!this.outputFolder.exists() && !this.outputFolder.mkdirs()) { this.showUsage(""Could not create output folder '"" + this.outputFolder.getAbsolutePath() + ""'!""); } File[] inputFiles = this.inputFolder.listFiles(); for (File inputFile : inputFiles) { this.processInputFile(inputFile, type); } } /** * @return the inputFolder */ public File getInputFolder() { return this.inputFolder; } /** * @return the outputFolder */ public File getOutputFolder() { return this.outputFolder; } /** * @param input * input reader * @param output * output writer * @throws IOException * in case input or output fails * @throws IllegalArgumentException * in case the given input is invalid */ @SuppressWarnings(""unused"") protected void process(BufferedReader reader, PrintWriter pw) throws IOException, IllegalArgumentException { System.out.println(""NEED TO IMPLEMENT (reader/writer)!!!""); System.exit(-2); } /** * @param input * input file * @param output * output file (will be overwritten) * @throws IOException * in case input or output fails * @throws IllegalArgumentException * in case the given input is invalid */ protected void process(File input, File output) throws IOException, IllegalArgumentException { System.out.println(""NEED TO IMPLEMENT (file/file)!!!""); System.exit(-2); } /** * @param input * input stream * @param output * output stream * @throws IOException * in case input or output fails * @throws IllegalArgumentException * in case the given input is invalid */ protected void process(InputStream input, OutputStream output) throws IOException, IllegalArgumentException { System.out.println(""NEED TO IMPLEMENT (stream/stream)!!!""); System.exit(-2); } /** * @param type * @param input * @param output */ private void processInputFile(File input, int type) { long starttime = System.currentTimeMillis(); System.out.println(""Processing '"" + input.getAbsolutePath() + ""'...""); File output = new File(this.outputFolder, input.getName() + AbstractCodeJamBase.EXT_OUT); if (type == AbstractCodeJamBase.STREAM_TYPE) { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(input); os = new FileOutputStream(output); this.process(is, os); } catch (FileNotFoundException e) { this.showUsage(""FileNotFound: "" + e.getLocalizedMessage()); } catch (IllegalArgumentException excIA) { this.showUsage(excIA.getLocalizedMessage()); } catch (Exception exc) { System.out.println(""Program failed: "" + exc.getLocalizedMessage()); exc.printStackTrace(System.out); } finally { if (is != null) { try { is.close(); } catch (IOException e) { System.out.println(""Failed to close input: "" + e.getLocalizedMessage()); } } if (os != null) { try { os.close(); } catch (IOException e) { System.out.println(""Failed to close output: "" + e.getLocalizedMessage()); } } } } else if (type == AbstractCodeJamBase.READER_TYPE) { BufferedReader reader = null; PrintWriter pw = null; try { reader = new BufferedReader(new FileReader(input)); pw = new PrintWriter(output); this.process(reader, pw); } catch (FileNotFoundException e) { this.showUsage(""FileNotFound: "" + e.getLocalizedMessage()); } catch (IllegalArgumentException excIA) { this.showUsage(excIA.getLocalizedMessage()); } catch (Exception exc) { System.out.println(""Program failed: "" + exc.getLocalizedMessage()); exc.printStackTrace(System.out); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { System.out.println(""Failed to close input: "" + e.getLocalizedMessage()); } } if (pw != null) { pw.close(); } } } else if (type == AbstractCodeJamBase.FILE_TYPE) { try { this.process(input, output); } catch (IllegalArgumentException excIA) { this.showUsage(excIA.getLocalizedMessage()); } catch (Exception exc) { System.out.println(""Program failed: "" + exc.getLocalizedMessage()); exc.printStackTrace(System.out); } } else { this.showUsage(""Unknown type given: "" + type + "" (accepted values: 0,1)""); } System.out.println("" READY ("" + (System.currentTimeMillis() - starttime) + "" ms)""); } /** * Read a single number from input * * @param reader * @param purpose * What is the purpose of given data * @return * @throws IOException * @throws IllegalArgumentException */ protected int readInt(BufferedReader reader, String purpose) throws IOException, IllegalArgumentException { int ret = 0; String line = reader.readLine(); if (line == null) { throw new IllegalArgumentException(""Invalid input: line is empty, it should be an integer ("" + purpose + "")!""); } try { ret = Integer.parseInt(line); } catch (NumberFormatException excNF) { throw new IllegalArgumentException(""Invalid input: the first line '"" + line + ""' should be an integer ("" + purpose + "")!""); } return ret; } /** * Read array of integers * * @param reader * @param purpose * @return */ protected int[] readIntArray(BufferedReader reader, String purpose) throws IOException { int[] ret = null; String line = reader.readLine(); if (line == null) { throw new IllegalArgumentException(""Invalid input: line is empty, it should be an integer list ("" + purpose + "")!""); } String[] strArr = line.split(""\\s""); int len = strArr.length; ret = new int[len]; for (int i = 0; i < len; i++) { try { ret[i] = Integer.parseInt(strArr[i]); } catch (NumberFormatException excNF) { throw new IllegalArgumentException(""Invalid input: line '"" + line + ""' should be an integer list ("" + purpose + "")!""); } } return ret; } /** * Read array of strings * * @param reader * @param purpose * @return */ protected String[] readStringArray(BufferedReader reader, String purpose) throws IOException { String[] ret = null; String line = reader.readLine(); if (line == null) { throw new IllegalArgumentException(""Invalid input: line is empty, it should be a string list ("" + purpose + "")!""); } ret = line.split(""\\s""); return ret == null ? new String[0] : ret; } /** * Basic usage pattern. Can be overwritten by current implementation * * @param message * Short message, describing the problem with given program * arguments */ protected void showUsage(String message) { if (message != null) { System.out.println(message); } System.out.println(""Usage:""); System.out.println(""\t"" + this.getClass().getName() + "" program""); System.out.println(""\tArguments:""); System.out.println(""\t\t:\tpath of input folder (default: "" + AbstractCodeJamBase.DEFAULT_INPUT + "").""); System.out.println(""\t\t \tAll files will be processed in the folder""); System.out.println(""\t\t:\tpath of output folder (default: "" + AbstractCodeJamBase.DEFAULT_OUTPUT + "")""); System.out.println(""\t\t \tOutput file name will be the same as input""); System.out.println(""\t\t \tinput with extension '.out'""); System.exit(-1); } } " B13034,"package qualification.q1; import java.util.HashMap; import java.util.Map; /** * Created by IntelliJ IDEA. * User: ofer * Date: 14/04/12 * Time: 17:10 * To change this template use File | Settings | File Templates. */ public class Q1Solver { private Map mapping; public Q1Solver(){ mapping = new HashMap(); mapping.put('y','a'); mapping.put('n','b'); mapping.put('f','c'); mapping.put('i','d'); mapping.put('c','e'); mapping.put('w','f'); mapping.put('l','g'); mapping.put('b','h'); mapping.put('k','i'); mapping.put('u','j'); mapping.put('o','k'); mapping.put('m','l'); mapping.put('x','m'); mapping.put('s','n'); mapping.put('e','o'); mapping.put('v','p'); mapping.put('z','q'); mapping.put('p','r'); mapping.put('d','s'); mapping.put('r','t'); mapping.put('j','u'); mapping.put('g','v'); mapping.put('t','w'); mapping.put('h','x'); mapping.put('a','y'); mapping.put('q','z'); mapping.put(' ',' '); } public String convertString(String encrypted){ StringBuilder resString = new StringBuilder(""""); for (int i = 0 ; i < encrypted.length() ; i++){ char decryptedChar = mapping.get(encrypted.charAt(i)); resString.append(decryptedChar); } return resString.toString(); } } " B10477,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class RecycledNumbers { public static int len(int A){ int k = 1 ; int r = 0; while( k < A){ k = k * 10; r = r + 1; } return r; } public static int count(int A , int B){ int r = 0; for(int i = A ; i < B ; i ++){ int mul = 1 ; int len = 0; while(mul <= A){ mul = mul * 10; len = len + 1; } int[] prev = new int[len - 1]; int it = 10; for(int j = 0 ; j < len - 1 ; j ++){ int right = i % it; int left = i / it; mul = mul / 10; int result = right * mul + left; it = it * 10; boolean duplicate = false; for(int k = 0 ; k < j ; k ++){ if(result == prev[k]){ duplicate = true; break; } } if(result > i && result >= A && result <= B && !duplicate){ System.out.println(result + ""\t"" + i); r ++; prev[j] = result; } } } return r; } public static void main(String args[]) throws IOException{ //System.out.println(count(531 , 976)); BufferedReader reader = new BufferedReader(new FileReader(new File(""C-small-attempt1.in""))); BufferedWriter writer = new BufferedWriter(new FileWriter(new File(""output.txt""))); String line = reader.readLine(); int T = Integer.parseInt(line); for(int i = 0 ; i < T ; i ++){ line = reader.readLine(); String tokens[] = line.split(""\\s+""); int N = Integer.parseInt(tokens[0]); int S = Integer.parseInt(tokens[1]); int count = count(N , S); writer.write(""Case #"" + (i + 1) + "": "" + count + ""\r\n""); } reader.close(); writer.close(); } } " B10459,"import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; public class RecycledNumbers { BufferedReader reader; char [] charInput; String [] inputArray; int index; RecycledNumbers()throws Exception{ String input=null; reader = new BufferedReader(new InputStreamReader(System.in)); while(reader.ready()){ if (input==null){ input =reader.readLine(); } else{ input =input+ "" "" + reader.readLine(); } } inputArray=input.trim().split("" ""); index=0; } String nextInput()throws Exception{ if(index prevMatches=new LinkedList(); int numCases=Integer.parseInt(nextInput()); int A; int B; int numRecycledPairs=0; int [] numArray; int digits; int testNum=0; boolean prevExists=false; for(int i=0;i=0;k--){ testNum=testNum/10; if(k==digits-1){ testNum=j; } numArray[k]=testNum%10; } for (int k=1;k=A && testNum<=B && testNum>j && prevExists==false){ numRecycledPairs++; prevMatches.add(new Integer(testNum)); } } } System.out.printf(""Case #%d: %d"", i+1,numRecycledPairs); if (i!=numCases-1){ System.out.println(); } } } //credit to Marian //http://stackoverflow.com/questions/1306727/way-to-get-number-of-digits-in-an-int int numDigits(int n){ if (n < 100000) { // 5 or less if (n < 100) { // 1 or 2 if (n < 10) return 1; else return 2; } else { // 3 or 4 or 5 if (n < 1000) return 3; else { // 4 or 5 if (n < 10000) return 4; else return 5; } } } else { // 6 or more if (n < 10000000) { // 6 or 7 if (n < 1000000) return 6; else return 7; } else { // 8 to 10 if (n < 100000000) return 8; else { // 9 or 10 if (n < 1000000000) return 9; else return 10; } } } } } " B12046,"package codejam; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.HashMap; public class RecyledNumbers { public static void main(String[] args) { String filename = ""C:\\Users\\maheswaran\\Desktop\\C-small-attempt0.in""; String fileContents = readFile(filename); String[] lines = fileContents.split(""\n""); int noOfLines = Integer.parseInt(lines[0]); for(int i = 1; i <= noOfLines; i++) { int noOfRecyclables = 0; HashMap recyclables = new HashMap(); String[] numbers = lines[i].split("" "",2); int start = Integer.parseInt(numbers[0]); int end = Integer.parseInt(numbers[1]); for( int j = start; j<=end; j++) { int digits = (start+"""").length(); for(int k = 1; k< digits;k++) { String numString = j+""""; String shiftString = shift(numString,k); if(numString.equals(shiftString)) { continue; } int shiftNum = Integer.parseInt(shiftString); if(shiftNum <= end && shiftNum>=start) { if(shiftNum > j) { recyclables.put(numString+"",""+shiftNum,""12""); //noOfRecyclables++; continue; } } } } noOfRecyclables = recyclables.size(); System.out.println(""Case #""+i+"": ""+noOfRecyclables); } } private static String shift(String num, int numToShift) { String shiftedNum; int positionToSplit = num.length() - numToShift; shiftedNum = num.substring(positionToSplit) + num.substring(0,positionToSplit); return shiftedNum; } private static String readFile(String filename) { StringBuffer file = new StringBuffer(); try{ // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(filename); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; //Read File Line By Line while ((strLine = br.readLine()) != null) { // Print the content on the console file.append(strLine).append(""\n""); } //Close the input stream in.close(); }catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } return file.toString(); } } " B10993,"import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; public class Recycled { public static String shift(String x){ return (x.substring(x.length() - 1) + x.substring(0, x.length() - 1)); } public static void main(String[] args) { int t, x = 1; String a, b, s; Scanner scan = new Scanner(System.in); t = scan.nextInt(); for(int i=0; i al = new ArrayList(); int n = Integer.parseInt(a); while(n <= Integer.parseInt(b)){ s = """" + n; String orig = """"+n; for(int j=0; j= Integer.parseInt(orig) && Integer.parseInt(s) <= Integer.parseInt(b) && !al.contains(s)){ al.add(orig+""-""+s); } } n++; } // for(int j=0; j M = new HashSet(); String s = """" + n; int L = s.length(); for (int i = 0; i < L; ++i) { s = s.charAt(L-1) + s.substring(0, L-1); int m = Integer.parseInt(s); if (m > n && m <= B && M.add(m)) ++cnt; } } return cnt; } void init () { } //////////////////////////////////////////////////////////////////////////////////// public C () throws IOException { init(); int N = sc.nextInt(); start(); for (int n = 1; n <= N; ++n) print(""Case #"" + n + "": "" + solve()); exit(); } static MyScanner sc; static long t; static void print (Object o) { System.out.println(o); if (DEBUG) System.err.println(o + "" ("" + ((millis() - t) / 1000.0) + "")""); } static void exit () { if (DEBUG) { System.err.println(); System.err.println((millis() - t) / 1000.0); } System.exit(0); } static void run () throws IOException { sc = new MyScanner (); new C(); } public static void main(String[] args) throws IOException { run(); } static long millis() { return System.currentTimeMillis(); } static void start() { t = millis(); } static class MyScanner { String next() throws IOException { newLine(); return line[index++]; } char [] nextChars() throws IOException { return next().toCharArray(); } double nextDouble() throws IOException { return Double.parseDouble(next()); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } String nextLine() throws IOException { line = null; return r.readLine(); } String [] nextStrings() throws IOException { line = null; return r.readLine().split("" ""); } int [] nextInts() throws IOException { String [] L = nextStrings(); int [] res = new int [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Integer.parseInt(L[i]); return res; } long [] nextLongs() throws IOException { String [] L = nextStrings(); long [] res = new long [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Long.parseLong(L[i]); return res; } boolean eol() { return index == line.length; } ////////////////////////////////////////////// private final BufferedReader r; MyScanner () throws IOException { this(new BufferedReader(new InputStreamReader(System.in))); } MyScanner(BufferedReader r) throws IOException { this.r = r; } private String [] line; private int index; private void newLine() throws IOException { if (line == null || index == line.length) { line = r.readLine().split("" ""); index = 0; } } } static class MyWriter { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); void print(Object o) { pw.print(o); } void println(Object o) { pw.println(o); } void println() { pw.println(); } public String toString() { return sw.toString(); } } char [] toArray (Character [] C) { char [] c = new char[C.length]; for (int i = 0; i < C.length; ++i) c[i] = C[i]; return c; } char [] toArray (Collection C) { char [] c = new char[C.size()]; int i = 0; for (char z : C) c[i++] = z; return c; } Object [] toArray(int [] a) { Object [] A = new Object[a.length]; for (int i = 0; i < A.length; ++i) A[i] = a[i]; return A; } String toString(Object [] a) { StringBuffer b = new StringBuffer(); for (Object o : a) b.append("" "" + o); return b.toString().trim(); } String toString(int [] a) { return toString(toArray(a)); } } " B11720,"package codejam.network172.com; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.LinkedList; public class CodeJam { public static void main(String[] args) { try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(""/home/harry/Downloads/cj.in""))); PrintWriter out = new PrintWriter(new FileWriter(""/home/harry/Downloads/cj.out"")); jam(in, out); out.close(); } catch (Exception e) { System.out.print(""Exception thrown: "" + e.toString()); } } private static void jam(BufferedReader in, PrintWriter out) throws NumberFormatException, IOException { int cases = Integer.parseInt(in.readLine()); for (int i = 0; i < cases; i++) { solveCase(i, in, out); } } private static void solveCase(int i, BufferedReader in, PrintWriter out) throws NumberFormatException, IOException { String[] inStrs = in.readLine().split("" ""); int a = Integer.parseInt(inStrs[0]); int b = Integer.parseInt(inStrs[1]); int cnt = 0; LinkedList seen = new LinkedList(); for (int j = a; j < b; j++) { String n = Integer.toString(j); seen.clear(); for (int k = 1; k < n.length(); k++) { int r = Integer.parseInt(n.substring(k) + n.substring(0, k)); if ((r > j) && (r <= b) && !seen.contains(r)) { seen.add(r); cnt++; } } } out.printf(""Case #%d: %d\n"", i+1, cnt); } } " B11385,"package com.stc; import java.io.BufferedReader; import java.io.InputStreamReader; import java.nio.CharBuffer; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; public class RecycledNumbers { public RecycledNumbers(LinkedList lines) { StringBuilder out = new StringBuilder(); int i=0; for(String line : lines) { String[] ab = line.split("" ""); out.append(""Case #"").append((i+1)).append("": ""); out.append(distinctRecycledNumberCountFromAtoB(ab)); out.append(""\r\n""); i++; } System.out.println(out.toString()); } private HashMap>> allDistinctRecycledNumbersByLength = new HashMap>>(); private int distinctRecycledNumberCountFromAtoB(String[] ab) { HashSet ad = new HashSet(); String a = ab[0]; String b = ab[1]; int ilena = a.length(); String lena = """"+ilena; fillRecycledNumberSet(lena); HashMap> allrecnums = allDistinctRecycledNumbersByLength.get(lena); Set allrecnumskeys = allrecnums.keySet(); for(String n : allrecnumskeys) { HashSet ms = allrecnums.get(n); for(String m : ms) { if(isAlteNlteMlteB(a, n, m, b)){ad.add(n+"",""+m);} } } String disp = """"; //for(String ads : ad){disp+=""[""+ads+""], "";} return ad.size(); } private void fillRecycledNumberSet(String lena) { int ilena = Integer.parseInt(lena); if(!allDistinctRecycledNumbersByLength.containsKey(lena)) { HashMap> rn = new HashMap>(); String zeros = """"; String nines = """"; for(int i=0;i recnums = recycle(is); rn.put(is,recnums); } allDistinctRecycledNumbersByLength.put(lena, rn); } } public HashSet recycle(String n) { if(n.startsWith(""0"")){return new HashSet();} HashSet rtn = new HashSet(); for(int i=n.length()-1;i>0;i--) { String end = n.substring(i); String begin = n.substring(0,i); String rcd = end+begin; if(!rcd.startsWith(""0"")) { if(!n.equals(rcd)) { rtn.add(rcd); } } //System.out.println(rcd); } return rtn; } private boolean isAlteNlteMlteB(String a,String n,String m,String b) { return ( (Integer.parseInt(a)<=Integer.parseInt(n)) && (Integer.parseInt(n)<=Integer.parseInt(m)) && (Integer.parseInt(m)<=Integer.parseInt(b)) ); } /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { InputStreamReader inr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(inr); LinkedList lines=new LinkedList(); String line = br.readLine(); int ncases = Integer.parseInt(line); for(int i=0;i0)) { lines.addLast(line); } } char[] tc = new char[1]; String lastLine = """"; int len = 0; while(true) { br.read(tc, 0, 1); if(tc[0]!=' '){lastLine+=tc[0];len++;} else { lastLine+="" ""; for(int i=0;i gused = new TreeSet(); for (int xx = s; xx < e; xx++) { String n = """" + xx; ArrayList alt = new ArrayList(); for (char c : n.toCharArray()) alt.add(c); for (int i = 0; i < n.length(); i++) { Collections.rotate(alt, 1); String t = """"; for (Character c : alt) t += """" + c; //pl(t); //pl(n); if (!gused.contains(t+""|""+n) && pi(n) >= s && pi(t) <= e && pi(n) < pi(t)) { gused.add(t+""|""+n); } } } pl(""Case #"" + da + "": "" + gused.size()); } } }" B10624,"package CaseSolvers; import java.util.ArrayList; import Controller.IO; public class DancingGooglersCase extends CaseSolver { public DancingGooglersCase(int order, int numberOfLines, IO io) { super(order, numberOfLines, io); } int sTriplets, scoreBase; ArrayList triplesSum; @Override public void addLine(String line) { String[] temp = line.split("" ""); sTriplets = Integer.parseInt(temp[1]); scoreBase = Integer.parseInt(temp[2]); triplesSum = new ArrayList(temp.length - 3); for (int i = 3; i < temp.length; i++) { triplesSum.add(Integer.parseInt(temp[i])); } } private int notSTriplesThatFit() { int qt = 0, currentIndex; for (int i = 0; i - qt < triplesSum.size(); i++) { currentIndex = i - qt; if (fitNotSurprising(triplesSum.get(currentIndex))) { triplesSum.remove(currentIndex); qt++; } } return qt; } private int surprisingTriplesThatFit() { if (sTriplets <= 0) { return 0; } int qt = 0; for (Integer num : triplesSum) { if (fitSurprising(num)) { qt++; if (qt >= sTriplets) { break; } } } return qt; } public static int getMaxScoreNotSurprising(int num) { return num % 3 == 0 ? num / 3 : num / 3 + 1; } private boolean fitNotSurprising(int num) { return getMaxScoreNotSurprising(num) >= scoreBase; } public static int getMaxScoreSurprising(int num) { int maxScore = 0; if (num > 0) { maxScore = num % 3 == 0 ? num / 3 + 1 : num / 3 + num % 3; } return maxScore; } private boolean fitSurprising(int num) { return getMaxScoreSurprising(num) >= scoreBase; } @Override public void printSolution() { System.err.println(""Case #"" + getOrder() + "": "" + result); } int result; @Override public CaseSolver process() { result = notSTriplesThatFit() + surprisingTriplesThatFit(); return this; } @Override public void initializeVars() { // TODO Auto-generated method stub } } " B10095,"import java.util.Scanner; import java.util.LinkedList; public class ProblemC { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int T = scan.nextInt(); //number of cases scan.nextLine(); for (int k = 1; k <= T; k++) { int A = scan.nextInt(); int B = scan.nextInt(); int count = 0; for (int i = A; i <= B; i++) { String original = """"+i; LinkedList recycleList = new LinkedList(); for (int j = 1; j< original.length(); j++) { //where to rotate from if (original.charAt(j) < original.charAt(0)) //eliminate some obvious ""decreasing"" cases continue; //since they'll be duplicated anyway. String newstr = original.substring(j) + original.substring(0,j); int newint = Integer.parseInt(newstr); if (newint > i && newint <= B) {//don't count duplicates or pairs out of range if (!recycleList.contains(newint)) {//no duplicate recycles count++; recycleList.add(newint); } } } } //System.err.println(""count: "" + count); int solution = count; System.out.println(""Case #"" + k + "": "" + solution); } } } " B12182,"import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Problem3_C { public static void main(String[] args) throws FileNotFoundException { Scanner scanner = new Scanner(new File(""C-small-attempt0.in"")); int num = scanner.nextInt(); for(int count = 1 ; count <= num ; count++){ // Set set = new HashSet(); // Set alreadyDone = new HashSet(); int ii = scanner.nextInt(); int jj = scanner.nextInt(); int counter = 0; for(int i = ii; i <= jj ; i++) { for(int j = i ; j <= jj ; j++) { String s1 = """"+i ; String s2 = """"+j ; for(int k = 0 ; k <= s2.length() ; k++) { if(i != j){ String a = s2.substring(0, k); String b = s2.substring(k, s2.length()); if((b+a).equals(s1) /*&& !alreadyDone.contains(alreadyDone.add(s1+""_""+s2)) && !alreadyDone.contains(alreadyDone.add(s2+""_""+s1))*/) { counter++; // alreadyDone.add(s1+""_""+s2); // alreadyDone.add(s2+""_""+s1); // System.out.println(s1 + "" -- ""+ s2+ "" -- "" + (b+a)); } } } } } System.out.println(""Case #""+count+"": ""+counter); } } } " B11412,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class RecycledNumbers { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int cases = Integer.parseInt(br.readLine()); int a, b, q; String[] tok; for(int i = 1; i <= cases; i++){ tok = br.readLine().split("" ""); a = Integer.parseInt(tok[0]); b = Integer.parseInt(tok[1]); q = 0; for(int j = a; j < b; j++){ for(int k = j+1; k <= b; k++){ if(isRecycled(j,k)) q++; } } System.out.println(""Case #""+i+"": ""+q); } } static boolean isRecycled(int n1, int n2){ String a = Integer.toString(n1); String b = Integer.toString(n2); StringBuilder sb; String x; for(int i = a.length()-1; i >= 0; i--){ sb = new StringBuilder(a.substring(i) + a.substring(0, i)); x = sb.toString(); if(x.equals(b)){ return true; } } return false; } } " B11389,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.regex.Pattern; public class Solver { private static final String SMALL_FILE = ""C-small-attempt0""; // private static final String SMALL_FILE = ""C-practice""; public static void main(String[] args) { long start = System.currentTimeMillis(); String inFileName = SMALL_FILE + "".in""; String outFileName = SMALL_FILE + "".out""; String path = new File(""."").getAbsoluteFile().getParent(); if (!path.endsWith(File.separator)) { path = path + File.separator; } path = path + ""res""; path = path + File.separator; int dataCount = 0; FileReader fileReader = null; BufferedReader buffer = null; try { fileReader = new FileReader(path + inFileName); buffer = new BufferedReader(fileReader); String count = buffer.readLine(); if (count == null || !Pattern.matches(""^[0-9]+$"", count)) { buffer.close(); fileReader.close(); System.out.println(""file invalid1""); return; } dataCount = Integer.valueOf(count); } catch (IOException ex) { System.out.println(""file read error1""); return; } File file = new File(path + outFileName); PrintWriter writer = null; FileWriter fileWriter = null; BufferedWriter bw = null; try { fileWriter = new FileWriter(file); bw = new BufferedWriter(fileWriter); writer = new PrintWriter(bw); } catch (IOException ex) { System.out.println(""file writer error""); return; } for (int i = 1; i <= dataCount; i++) { try { String[] inputs = buffer.readLine().split("" ""); int result = solve(Integer.valueOf(inputs[0]), Integer.valueOf(inputs[1])); writer.println(String.format(""Case #%d: %d"", i, result)); System.out.println(String.format(""%d"", result)); } catch (IOException ex) { System.out.println(""file read error""); return; } } try { buffer.close(); writer.close(); bw.close(); fileWriter.close(); } catch (IOException ex) { } long stop = System.currentTimeMillis(); System.out.println(String.format(""End %dms"", stop - start)); } private static int solve(int inputA, int inputB) { int count = 0; for (int i = inputA; i <= inputB; i++) { final String checkStr = String.valueOf(i); final int length = checkStr.length(); ArrayList contain = new ArrayList(); contain.add(checkStr); for (int j = 1; j < length; j++) { String reverse = checkStr.substring(length - j) + checkStr.substring(0, length - j); if (contain.contains(reverse)) continue; contain.add(reverse); int reverseInt = Integer.valueOf(reverse); if (reverseInt >= i && reverseInt <= inputB) { System.out.println(reverseInt); count++; } } } return count; } } " B13181,"/** * @(#)Googlerese.java * * * @author Evan Forbes * @version 1.00 2012/4/13 */ import java.util.Scanner; import java.io.FileReader; import java.io.IOException; public class Recycle { static int caseNum=0; static int numCases; public static void main(String[] args) { try{ Scanner in=new Scanner(new FileReader(""C-small-attempt3.in"")); //Scanner in=new Scanner(new FileReader(""sample_recycled.txt"")); while (in.hasNextLine()) //go through all lines of file { String current=in.nextLine(); String output=""""; if (caseNum==0) { numCases=Integer.parseInt(current); } else { output=""Case #""+caseNum+"": ""; int mode=0; String As=""""; //number of scores int A=0; String Bs=""""; //num of suprising scores int B=0; for (int i=0;i0;i--) { String cut=n.substring(i); String compare=cut+n.substring(0,i); //System.out.println(""cut: ""+cut+"" compare: ""+compare); if (compare.equals(m)) found=true; } return found; } }" B12482,"import java.io.IOException; import java.io.InputStreamReader; import java.io.LineNumberReader; public class Recycled { static int n = 1; static void solve(int A, int B) { int len = ("""" + A).length(); int min = 1; for (int a = 1; a < len; a++) min *= 10; int res = 0; int[] seen = new int[len]; int nseen; for (int n = A; n < B; n++) { int m = n; nseen = 0; for (int a = 1; a < len; a++) { m = (m / 10) + (m % 10) * min; if (m >= min && n < m && m <= B) { boolean already = false; for (int b = 0; b < nseen; b++) if (seen[b] == m) already = true; if (!already) { res++; seen[nseen++] = m; } } } } System.out.println(""Case #"" + (n++) + "": "" + res); } public static void main(String[] args) throws IOException { LineNumberReader in = new LineNumberReader(new InputStreamReader(System.in)); int n = Integer.parseInt(in.readLine().trim()); for (int a = 0; a < n; a++) { String[] l = in.readLine().trim().split("" ""); solve(Integer.parseInt(l[0]), Integer.parseInt(l[1])); } } } " B13137,"import java.io.*; import java.util.*; import java.math.*; public class Qual22C { public static void main(String[] args) throws IOException { BufferedReader ips=new BufferedReader(new FileReader(""C-small-attempt0.in"")); PrintWriter ops=new PrintWriter(new FileWriter(""recno.in"")); int T=Integer.parseInt(ips.readLine()); for(int i=0;i=0; j--) { t=ca[j]-'0'; A=A+(int)(Math.pow(10,count)*t); count++; } //System.out.println(""A: ""+A+"" B: ""+B+"" nog: ""+count); n=A; int pw=0; for(int k=0; k<=(B-A); k++) { //n++; m=n; temp=m; rev=0; pw=0; while(temp!=0) { t=temp%10; rev=(rev*10)+t; temp=temp/10; pw++; } //System.out.println(rev); t=rev%10; tryy=(t*(int)(Math.pow(10,(count-1)))); m=((m-tryy)*10)+t; //System.out.println(n+"" : ""+m); while(m!=n) { if(n=A && m<=B) rnc++; temp=m; rev=0; pw=0; while(temp!=0) { t=temp%10; rev=(rev*10)+t; temp=temp/10; } //System.out.println(rev); t=rev%10; tryy=(t*(int)(Math.pow(10,(count-1)))); //System.out.println(t); //System.out.println(tryy); if((m-tryy)<0) m=(m*10); else m=((m-tryy)*10)+t; //System.out.println(""1. ""+n+"" : ""+m); } n++; } ops.println(""Case #""+(i+1)+"": ""+rnc); } ips.close(); ops.close(); } }" B10334,"import java.util.HashSet; public class CSolver extends SolverModule { @Override String processLine(String line) { int[] lines = toIntegers(line.split("" "")); int A = lines[0]; int B = lines[1]; HashSet hashSet = new HashSet(); for (int i = A; i < B; i++) { int length = String.valueOf(A).length(); for (int j = 1; j < length; j++) { int a = rightMove(i, length - j); int b = leftMove(i, j) - leftMove(rightMove(i, (length - j)), length); int total = a + b; if (total >= A && total <= B && total > i) { hashSet.add(i + "","" + total); } } } return String.valueOf(hashSet.size()); } private int leftMove(int number, int count) { number = number * (int) (Math.pow(10, count)); return number; } private int rightMove(int number, int count) { if (count == 0) { return number; } number = (number / (int) (Math.pow(10, count))); return number; } } " B11255,"/* * Copyright 2012 Bill Bejeck * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package comp; import java.io.*; /** * User: Bill Bejeck * Date: 4/13/12 * Time: 9:36 PM */ public class Recycled { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(args[0]))); PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(new File(args[1])))); int numCases = Integer.parseInt(reader.readLine()); for (int i = 0; i < numCases; i++) { String[] pair = reader.readLine().split("" ""); int numberOne = Integer.parseInt(pair[0]); int numberTwo = Integer.parseInt(pair[1]); int count = getRecycled(numberOne, numberTwo); String result = String.format(""Case #%d: %d"", (i + 1), count); System.out.println(result); writer.println(result); } writer.flush(); writer.close(); reader.close(); } private static int getRecycled(int n, int max) { int recycleCount = 0; for (int i = 0; i < max; i++) { String nSt = Integer.toString(n); int newMax = (n + 1); for (int k = 0; k < max && newMax <= max; k++) { String maxString = Integer.toString(newMax); for (int j = nSt.length() - 1; j >= 0; j--) { String end = nSt.substring(j); String start = nSt.substring(0, nSt.indexOf(end, j)); if (maxString.startsWith(end) && maxString.endsWith(start)) { if (maxString.equals(end + start)) { recycleCount++; } } } newMax++; } n++; } return recycleCount; } } " B13074,"import sun.rmi.runtime.NewThreadAction; import java.io.*; import java.util.*; /** * Created by IntelliJ IDEA. * User: Veniversum * Date: 4/15/12 * Time: 2:26 AM */ public class Q3 { public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(""in.txt""))); Scanner scanner = new Scanner(new FileInputStream(""in.txt"")); int cases = scanner.nextInt(); scanner.nextLine(); String output=""""; for (int i= 0;i results = new HashSet(); Scanner sc = new Scanner(scanner.nextLine()); int A = sc.nextInt(); int B = sc.nextInt(); int n; int m; for (int j = A; j <= B;j++) { n = j; m = j; String str = ("""" + m); for (int k = 0; k < ("""" + m).length();k++) { if (A <= n && n < m && m <= B) { results.add(m + "","" + n); } str = str.concat("""" + str.charAt(0)); //adds first digit to end str = str.substring(1); //remove first digit m = Integer.parseInt(str); } } output += ""Case #"" + (i+1) + "": "" + results.size() + ""\n""; PrintWriter outp = new PrintWriter(new FileOutputStream(""out.txt"")); outp.print(output); outp.close(); } System.out.print(output); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } " B11861,"package com.google.code.jam2012.problemC; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; /** * Created with IntelliJ IDEA. * User: Vahid * Date: 4/14/12 * Time: 6:54 PM * To change this template use File | Settings | File Templates. */ public class ProblemC1 { public static void main(String[] args) throws IOException { Scanner scanner = new Scanner(new FileInputStream(""data.in"")); FileOutputStream out = new FileOutputStream(""C1.out""); long a, b, m,n; int lines = scanner.nextInt(); scanner.nextLine(); for (int i = 1; i<=lines; i++){ a = scanner.nextLong(); b = scanner.nextLong(); out.write((""Case #""+i+"": ""+ calculate(a, b)).getBytes()); out.write('\r'); out.write('\n'); if (scanner.hasNextLine()) scanner.nextLine(); } scanner.close(); out.close(); } private static long calculate(long a, long b) { long logarithm = 1; long counter = 0; int len = 1; while (logarithm * 10 <= b) { logarithm *= 10; len++; } HashSet list; for (long n = a; n(100); long m = n; for (int i=1; i= line.charAt(0)){ x = s.substring(k); m = x + s.substring(0,k); temp[k-1] = m; for(int y=0;yj && Long.parseLong(m)>=a && oops == false) { System.out.println(s + "" ""+m); ans++; } } } } System.out.println(""ans = ""+ans); String res = ""Case #""+i+"": ""+ans; bw.write(res,0,res.length()); bw.flush(); bw.newLine(); } } catch(Exception e){} } } " B12592,"package googlers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; public class Mainclass { String line[]; int bv=1; Mainclass(){ line=new String[50]; FileInputStream fstream; DataInputStream in; BufferedReader br; try{ fstream = new FileInputStream(""in.txt""); in = new DataInputStream(fstream); br = new BufferedReader(new InputStreamReader(in)); int x=Integer.parseInt(br.readLine()); for(int z=0;zb) continue; z++; } } System.out.println(z/2); String output=new String(z/2+""""); try{ File file = new File(""out.txt""); FileWriter fileWritter = new FileWriter(file.getName(),true); BufferedWriter bufferWritter = new BufferedWriter(fileWritter); bufferWritter.write(new String(""Case #""+bv+"": ""+output+""\n"")); System.out.println(""Case #""+bv+"": ""+output+""\n""); bv++; bufferWritter.close(); }catch(Exception e){ e.printStackTrace(); } } public static void main(String args[]){ new Mainclass(); } } " B10207,"import java.util.*; import java.io.*; public class Mirror { public static void main(String[] args) throws IOException { Scanner scan = new Scanner(new File(""C-small-attempt0.in"")); FileWriter fstream = new FileWriter(""out.txt""); BufferedWriter out = new BufferedWriter(fstream); int numCases = scan.nextInt(); for (int z = 0; z < numCases; z++) { int low = scan.nextInt(); int high = scan.nextInt(); int count = 0; for (int i = low; i < high; i++) { String lows = """" + i; String[] arr = new String[lows.length() - 1]; for (int k = 0; k < arr.length; k++) { lows = lows.charAt(lows.length()-1) + lows.substring(0, lows.length()-1); arr[k] = lows; } for ( int j = i + 1; j <= high; j++) { String highs = """" + j; for (int k = 0; k < arr.length; k++) { if (arr[k].equals(highs)) { count++; break; } } } } out.write(""Case #"" + (z+1) + "": "" + count); if ( z != numCases - 1) out.newLine(); } out.close(); } }" B13108,"import java.util.*; public class RCTest{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); int numberOfCases = Integer.parseInt(scan.nextLine()); for(int i = 1; i <= numberOfCases; ++i){ String line = scan.nextLine(); String[] inputs = line.split("" ""); int lower = Integer.parseInt(inputs[0]); int upper = Integer.parseInt(inputs[1]); RCTest r = new RCTest(); System.out.println(""Case #"" + i + "": "" + r.getRecycleNumbers(lower, upper)); } } public int getRecycleNumbers(int a, int b){ this.lower = a; this.upper = b; int counter = 0; for(int i = a; i<=b; ++i){ int originalNumber = i; int index = getIndex(originalNumber); int recycledNumber = getRecycledNumber(i,index); while(originalNumber!=recycledNumber){ if(originalNumber < recycledNumber && recycledNumber <= upper)++counter; recycledNumber = getRecycledNumber(recycledNumber,index); } } return counter; } public int getRecycledNumber(int number, int index){ int remainder = number % 10; int quotient = number/10; int recycledNumber = ((int)Math.pow(10,index) * remainder) + quotient; return recycledNumber; } private int getIndex(int number){ int index = 0; while(number!=0){ number/=10; ++index; } return index-1; } private int lower; private int upper; }" B10761,"import java.util.Scanner; import java.io.*; public class Displayer { public static void main(String[] args) throws IOException { Scanner kb = new Scanner(new File(""/Users/mbp13/Documents/Google Code Jam/GCJ_Q3/src/input"")); PrintStream out = new PrintStream(new File(""/Users/mbp13/Documents/Google Code Jam/GCJ_Q3/src/output_q3"")); int testNum,A,B; String tmpStr,tmpStr2,cut1,cut2; int cnt,x; testNum = kb.nextInt(); for(int i=0;i j && x >= A && x <= B) { cnt++; System.out.println(j + "" "" + tmpStr2); } } } out.println(""Case #""+(i+1)+"": ""+cnt); } } } " B11451,"import java.util.*; import java.lang.Math; public class RecycledNumbers { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int numCases, currentCase, A, B, n, m, answer, currentNum; ArrayList recycles; numCases = scan.nextInt(); currentCase = 0; while (currentCase < numCases) { currentCase++; A = scan.nextInt(); B = scan.nextInt(); answer = 0; for (int j = A; j <= B; j++) { recycles = new ArrayList(); n = currentNum = j; while (currentNum > 0) { recycles.add(0, currentNum % 10); currentNum = currentNum / 10; } for (int k = 1; k < recycles.size(); k++) { m = 0; for (int l = 0; l < recycles.size(); l++) { m += (recycles.get((k + l) % recycles.size()) * Math.pow(10, recycles.size() - l - 1)); } if (m > n && m <= B) { answer++; } } } System.out.printf(""Case #%d: %d\n"", currentCase, answer); } } } " B12769,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; public abstract class FileWrapper { protected static final String CASE = ""Case #""; protected static final String OUTPUT = ""result.out""; protected int caseNum = 0; protected String output[] = null; private FileReader fr = null; private BufferedReader br = null; private FileWriter fw = null; private BufferedWriter bw = null; protected void openReadFile(String fileName) throws Exception { this.fr = new FileReader(fileName); this.br = new BufferedReader(this.fr); } protected void closeReadFile() throws Exception { this.br.close(); this.fr.close(); } protected String readLine() throws Exception { return this.br.readLine(); } protected boolean isFileReady() throws Exception { return this.br.ready(); } protected abstract void processInput(String fileName); private void openWriteFile(String fileName) throws Exception { this.fw = new FileWriter(fileName); this.bw = new BufferedWriter(this.fw); } private void closeWriteFile() throws Exception { this.bw.close(); this.fw.close(); } private void writeLine(String line) throws Exception { this.bw.write(line); this.bw.newLine(); } protected void processOutput(String fileName) { try{ this.openWriteFile(fileName); for (int i=0; i track=new ArrayList(); if (B.toString().length()<2){ System.out.println(""Case #""+counter+"": ""+0); }else{ for (Integer i=A;i<=B;i++){ Integer original=i; String marker=shift(original.toString()); while (!(marker.equals(original.toString()))){ //System.out.println(marker+ "" "" +original); if (Integer.parseInt(marker)>original && Integer.parseInt(marker)<=B ){//&& !(track.contains(marker)) track.add(Integer.parseInt(marker)); track.add(original); // marker=original.toString(); marker=shift(marker); }else{ marker=shift(marker); } //System.out.println(marker==original); } } System.out.println(""Case #""+counter+"": ""+track.size()/2); } counter++; } }catch (FileNotFoundException e){ }catch (IOException e){ } } }" B10939,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; public class RecycledNumbers { public static int rotate(int x) { if (x < 10) return x; String s = String.valueOf(x); s = s.substring(1) + s.charAt(0); return Integer.parseInt(s); } public static String rotate(String s) { if (s.length() < 2) return s; return s.substring(1) + s.charAt(0); } public static void solve(String file) throws Exception { BufferedReader f = new BufferedReader(new FileReader(file + "".in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file + "".out""))); int T = Integer.parseInt(f.readLine()); for (int i = 0; i < T; i++) { String[] s = f.readLine().split("" ""); int A = Integer.parseInt(s[0]); int B = Integer.parseInt(s[1]); int n = 0; for (int j = A; j <= B; j++) { String x = String.valueOf(j); String y = x; while (!(y = rotate(y)).equals(x)) { int r = Integer.parseInt(y); if (r > j && r <= B) n++; } } System.out.println(""Case #"" + (i+1) +"": "" + n); out.println(""Case #"" + (i+1) +"": "" + n); } out.close(); } public static void main(String[] args) throws Exception { //String file = ""C-test""; String file = ""C-small-attempt0""; solve(file); } } " B12565,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam2012; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashMap; import java.util.Scanner; import java.util.StringTokenizer; import java.util.TreeSet; /** * * @author Rumal */ public class QB { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { Scanner s = new Scanner(System.in); // int R = 100; // int[] cache = new int[R + 1]; // for (int i = 1; i <= R; i++) { // if (i < 10) { // cache[i] = 0; // continue; // } // cache[i] = cache[i-1]; // String h = (i + """"); // int N = h.length(); // System.out.println(i); // for (int j = 1; j < N; j++) { // int y = shift(i, j, N); // System.out.print(y+"", ""); // if (y <= R && i < y) { // cache[i]++; // } // } // System.out.println(cache[i]); // // } // System.out.println(Arrays.toString(cache)); // System.out.println(cache[R]); // System.out.println(cache[40]); // System.exit(0); // // // // // int T = s.nextInt(); for (int t = 1; t <= T; t++) { int A = s.nextInt(); int B = s.nextInt(); long count = 0; p: for (int i = A; i <= B; i++) { if (i < 10) { continue; } String h = (i + """"); int N = h.length(); // for (int j = 1; j < N; j++) { // if (h.charAt(j) < h.charAt(j - 1)) { // continue p; // } // } int c = 0; //System.out.println(i); TreeSet st = new TreeSet(); for (int j = 1; j < N; j++) { int y = shift(i, j, N); st.add(y); // System.out.print(y+"",""); } for (int y : st) { if (y <= B && i < y) { count++; } } } //System.out.println(chk); System.out.println(""Case #"" + t + "": "" + count); } } private static int shift(int i, int j, int n) { String s = i + """"; int N = s.length(); if (n != N) { return -1; } int y = Integer.parseInt(s.substring(N - j) + s.substring(0, N - j)); if ((y + """").length() != N) { return -1; } return y; } } " B10319,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author vhd */ import java.io.*; import java.util.*; import java.math.*; public class NewClass { public static void main(String vhd[]) throws Exception { // FileInputStream fis = new FileInputStream (""jam.txt""); // FileOutputStream out=new FileOutputStream(""outt.txt""); RandomAccessFile file = new RandomAccessFile(""jam.txt"", ""rw""); RandomAccessFile file1 = new RandomAccessFile(""outt.txt"", ""rw""); String t = file.readLine(); int times= Integer.parseInt(t); for( int r= 1 ; r<= times ; r++) { StringTokenizer st= new StringTokenizer(file.readLine()); int num1 = Integer.parseInt(st.nextToken()); int num2= Integer.parseInt(st.nextToken()); char ch ; int count =0; //fis.read(); Scanner sc = new Scanner (System.in); int main1 = num1; int main2= num2; int mid = (num1 + num2 )/2; int n,m; String s1 = (Integer.valueOf(num1)).toString(); String s2 = (Integer.valueOf(num2)).toString(); int temp; int len1 = s1.length(); int len2 = s2.length(); int k =0,l =0; int arr[] = new int[100]; for( int i = num1 ; i< num2 ; i++) { while(ki && arr[k]<=num2 ) { count++; } k++; } k=0; } file1.write((""Case #""+r+"": "" +count+ ""\n"").getBytes()); } } }" B11572,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package gcj_c; /** * * @author kay */ public class Gcj_C { /** * @param args the command line arguments */ public static void main(String[] args) { Arrange app = new Arrange(); app.do_processing(""G:/c_input.txt""); //app.do_arrange(""1111 2222""); // TODO code application logic here } } " B10728,"import java.io.*; import java.util.StringTokenizer; public class C { static boolean isrecycle (long n, long m){ String a,b; char ac[],c; int k; boolean t=false; a=String.valueOf(n); b=String.valueOf(m); for(int j=1;jn; // same length; // distinct. String m; String n = nn + """"; long mm; int mP; int nP; int result = 0; long[] cmm = new long[7]; int cmmMAX = 0; for (int i = 1; i < n.length(); i++) { m = shift(n, i); mm = Long.parseLong(m); mP = getBits(mm); nP = getBits(nn); // System.out.println(nn + "","" + mm); if (mP == nP && nn < mm && mm <= B) { if (notInclude(cmm, cmmMAX, mm)) { System.out.println(nn + "","" + mm); cmm[cmmMAX++] = mm; result++; } } } return result; } private boolean notInclude(long[] cmm, int cmmMAX, long mm) { // TODO Auto-generated method stub for (int i = 0; i < cmmMAX; i++) { if (cmm[i] == mm) return false; } return true; } private int getBits(long mm) { // TODO Auto-generated method stub int result = 1; while (mm / 10 > 0) { result++; mm = mm / 10; } return result; } private String shift(String n, int i) { // TODO Auto-generated method stub return n.substring(i) + n.substring(0, i); } public static void main(String args[]) { new RecycledNumbers(); } } " B13096,"import java.io.File; import java.io.PrintWriter; import java.util.Scanner; public class Recycled { /** * @param args */ public static void main(String[] args) { try { Scanner scanner = new Scanner(new File(""./data/inRecycled"")); PrintWriter writer = new PrintWriter(new File(""./data/outRecycled"")); int t = scanner.nextInt(); scanner.nextLine(); for(int i = 0; i < t; i++) { int a = scanner.nextInt(); int b = scanner.nextInt(); int res = 0; String check = """" + a; if(check.length() != 1) { for(int j = a; j <= b; j++){ if(check.length() == 2) { String temp = """" + j; String other1 = temp.charAt(1) + """" + temp.charAt(0); int ot = Integer.valueOf(other1); if( ot <= b && j < ot){ res++; } } else if(check.length() == 3) { String temp = """" + j; String other1 = """" + temp.charAt(2) + temp.charAt(0) + temp.charAt(1); String other2 = """" + temp.charAt(1) + temp.charAt(2) + temp.charAt(0); int ot1 = Integer.valueOf(other1); int ot2 = Integer.valueOf(other2); if ( ot1 <= b && j < ot1) { res++; } if ( ot2 <= b && j < ot2) { res++; } } } } writer.println(""Case #"" + (i+1) + "": "" + res); } writer.close(); scanner.close(); }catch(Exception e) {e.printStackTrace();} } } " B12538,"package qualification.p3; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.HashSet; public class RecycledNumbers { private static void calculate( String testCase, BufferedWriter bw, int n ) throws Exception { String[] tcData = testCase.split( "" "" ); int A = Integer.parseInt( tcData[0] ); int B = Integer.parseInt( tcData[1] ); int c = 0; HashSet was = new HashSet(); for ( int i = A; i <= B; i++ ) { int l = Integer.toString( i ).length(); int p = (int)Math.pow( 10, l-1 ); int ii = i; for ( int d = 1; d < l; d++ ) { ii = p*( ii % 10 ) + ( ii / 10 ); if ( ( ii > i && ii >= A && ii <= B ) && was.add( 1000000000l*i + ii ) ) c++; } } bw.append( ""Case #""+n+"": ""+c+""\n"" ); } public static void main( String[] args ) throws Exception { File inputFile = new File( ""inputfiles/qualification/p3/input.txt"" ); FileReader fr = new FileReader( inputFile ); BufferedReader br = new BufferedReader( fr ); int numOfTestCases = Integer.parseInt( br.readLine() ); File outputFile = new File( ""inputfiles/qualification/p3/output.txt"" ); outputFile.delete(); outputFile.createNewFile(); FileWriter fw = new FileWriter( outputFile ); BufferedWriter bw = new BufferedWriter( fw ); for ( int i = 0; i < numOfTestCases; i++ ) { String testCase = br.readLine(); calculate( testCase, bw, i+1 ); } bw.flush(); fw.flush(); bw.close(); fw.close(); } } " B10033,"package com.google.cj; public class Entry { public String n; public String m; public Entry() { // TODO Auto-generated constructor stub } public Entry(String n, String m) { super(); this.n = n; this.m = m; } @Override public String toString() { return ""Entry [n="" + n + "", m="" + m + ""]""; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((m == null) ? 0 : m.hashCode()); result = prime * result + ((n == null) ? 0 : n.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Entry other = (Entry) obj; if (m == null) { if (other.m != null) return false; } else if (!m.equals(other.m)) return false; if (n == null) { if (other.n != null) return false; } else if (!n.equals(other.n)) return false; return true; } } " B10133,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class Main { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub int numCase = 0; BufferedReader br = null; PrintWriter pr = null; try { br = new BufferedReader(new FileReader(args[0])); pr = new PrintWriter(new FileWriter(""a.out"")); numCase = Integer.parseInt(br.readLine()); String line; String[] arr; for (int i = 0 ; i < numCase ; i++){ line = br.readLine(); arr = line.split("" ""); String A = arr[0]; String B = arr[1]; long Along = Long.parseLong(A); long Blong = Long.parseLong(B); long count = 0; if (A.length() == 1) count = 0; else { for (long Nlong = Along; Nlong < Blong ; Nlong++){ String N = """" + Nlong; long LastM = -1; for (int j = 1 ; j < N.length(); j++){ String M = N.substring(j, N.length())+N.substring(0, j); long Mlong = Integer.parseInt(M); if (Mlong > Nlong && Mlong <= Blong && LastM != Mlong){ count++; LastM = Mlong; } } } } pr.println(""Case #"" + (i+1) + "": "" + count); } pr.flush(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (pr != null) pr.close(); if (br != null) br.close(); } } }" B11438,"package codejam; import java.util.HashSet; public class RecycledNumbers extends Solver { public static void main(String...args) { RecycledNumbers solver = new RecycledNumbers(); // System.out.println(solver.solve(""1 9"")); // System.out.println(solver.solve(""10 40"")); // System.out.println(solver.solve(""100 500"")); // System.out.println(solver.solve(""1111 2222"")); // System.out.println(solver.solve(""1000000 2000000"")); solver.solveSmallOf('C', 0); // solver.solveLargeOf('C'); } int a, b; @Override public String evaluate() { a = in.nextInt(); b = in.nextInt(); if(a<10) return ""0""; HashSet set = new HashSet(); for(int i=a; i<=b; i++) { if(set.add(new Signed(i))) { // System.out.println(i + "" added.""); } } int c = 0; for(Signed s: set) { c+=s.getAvailablePairsCount(); } return String.valueOf(c); } class Signed { final char[] ns; final int sign; Signed(int n) { ns = String.valueOf(n).toCharArray(); int min = Integer.MAX_VALUE; for(int i=0; i cases = new HashSet(); for(int i=0; i=a && value.intValue()<=b) cases.add(value); } shift(); } return cases.size(); } @Override public boolean equals(Object obj) { if(obj instanceof Signed) { return ((Signed) obj).sign==sign; } return super.equals(obj); } @Override public int hashCode() { return sign; } } class Pair { final int n, m; Pair(int n, int m) { if(n>m) { this.n = m; this.m = n; } else { this.n = n; this.m = m; } } @Override public boolean equals(Object obj) { if(obj instanceof Pair) { Pair p = (Pair) obj; return p.n == this.n && p.m == this.m; } else { return false; } } @Override public int hashCode() { return n*m+m; } } } " B10241,"package recyclednumbers; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ //package recyclednumbers; /** * * @author sony */ public class RecycledNumbers { /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException, IOException, InterruptedException { BufferedReader br=new BufferedReader(new FileReader(args[0])); int Testcases=Integer.parseInt(br.readLine()); for(int i=0;in&&mvalue<=second) TotalCount++; } } System.out.print(""Case #""+(i+1)+"":""+"" ""+TotalCount+""\n""); } } } " B13182,"import java.io.*; import java.util.*; import java.util.ArrayList; public class CodeJamProblem implements Runnable { //Problem C public boolean InRisultati(ArrayList array, String controllo) { for(int i =0; i risultati = new ArrayList(); if(caso==3) System.out.println("" ""); for (int i = 0; i < range.length; i++) { current_n = range[i]; current_m = range[i]; String rot_m = """"+current_m; if(caso==3) System.out.println(""Numero: "" +current_m); int len = (range[i]+"""").length(); for (int j = 0; j < len; j++) { if(caso==3) System.out.print("" "" + rot_m.substring(rot_m.length()-1) + rot_m.substring(0,len-1)); rot_m = ( rot_m.substring(rot_m.length()-1) + rot_m.substring(0,len-1) ); // A ² n < m ² B if (Integer.parseInt(rot_m) <= B && Integer.parseInt(rot_m) > current_n && Integer.parseInt(rot_m) >= A) { if(InRisultati(risultati,current_n+rot_m)==false) { risultati.add(current_n+rot_m); vincitori++; if(caso==3) System.out.println(""Inversione Vincente: "" + Integer.parseInt(rot_m)); } } } if(caso==3) System.out.println("" ""); } if(caso==3) System.out.println(""Winner :""+ vincitori); return vincitori; } public void solve() throws IOException { String test = ""small""; //String test = ""large""; Scanner in = new Scanner(new File(""C-small-attempt0.in"")).useDelimiter(System.getProperty(""line.separator"")); PrintWriter out = new PrintWriter(new File(""C-small-attempt0.out"")); int lineNum = 0; int testNum = 0; int totalTests = 0; int[] points = new int[1]; while (in.hasNext()) { String currentLine = in.next(); if(lineNum ==0 ) { //Do Nothing! totalTests = Integer.parseInt(currentLine); lineNum++; continue; } if(lineNum>0) { String[] x = currentLine.split("" ""); points = new int[x.length]; for(int i = 0;it) ans++; } t++; } fout.write(""Case #""+no+"": ""+ans+""\n""); } fout.close(); } }" B10824,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main_Recycled { static int a,b; public static void main(String[] args)throws Exception { File _=new File(""recycled.in""); BufferedReader br=_.exists()? new BufferedReader(new FileReader(_)):new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine().trim()); StringTokenizer st; boolean visited[]; int size,total; int temp; for (int i = 1; i <= t; i++) { total=0; st=new StringTokenizer(br.readLine()); a=Integer.parseInt(st.nextToken()); b=Integer.parseInt(st.nextToken()); visited=new boolean[b+1]; for (int j = a; j <= b; j++) { size=0; temp=j; while(!visited[temp]){ visited[temp]=true; size++; temp=next(temp); } total+=size*(size-1)/2; } System.out.println(""Case #""+i+"": ""+total); } } private static int next(int temp) { String str=""""+temp; do{ str=str.substring(1,str.length())+str.charAt(0); } while(Integer.parseInt(str)b); return Integer.parseInt(str); } } " B11663,"package recycled; import java.io.*; import java.util.StringTokenizer; import java.util.HashSet; class Solucionar{ int buscar(String base, String techo){ int ret = 0; HashSet cjto = new HashSet(); if ((base.length() == techo.length())||(base.length()==1)){ int tam = (int) Math.pow(10 , base.length() - 1); int veces = base.length() - 1; int inicio = Integer.parseInt(base); int fin = Integer.parseInt(techo); for (int i=inicio;i= inicio) && ( numero > original) && ( fin >= numero) ) { int ingresar = 10000 * original + numero; if (! cjto.contains(ingresar)) { //System.err.println(original + "" + "" + numero); ret++; cjto.add(ingresar); } } } } //System.err.print(tam); } return ret; } } public class Recycled{ public static void main(String[] args) throws Exception{ Solucionar s = new Solucionar(); s.buscar(""1111"", ""2222""); InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader (isr); String linea; linea = br.readLine(); int casos = Integer.parseInt(linea); for (int i=0;i { private HashMap map = new HashMap(); private ArrayList orderedKeys = new ArrayList(); public UniqueIndexAllocator() { } /** Allocate unique indices for each item in the given collection. Read back the indices using the other methods. */ public UniqueIndexAllocator(Iterable collection) { for (T it : collection) getOrAllocateIndex(it); } /** Get the assigned index for a key, or assign it a new unique index if this key has not previously been assigned an index */ public int getOrAllocateIndex(T key) { Integer currIdx = map.get(key); if (currIdx == null) { map.put(key, currIdx = orderedKeys.size()); orderedKeys.add(key); } return currIdx; } /** Get all the keys as a list in their index order */ public ArrayList getOrderedKeys() { return orderedKeys; } /** Get all the keys as an array in their index order */ @SuppressWarnings(""unchecked"") public T[] getOrderedKeysAsArray() { return (T[]) orderedKeys.toArray(); } /** Get the mapping from key to index */ public HashMap getKeyToIndexMap() { return map; } /** Return the number of allocated indices, i.e. the number of unique keys */ public int numIndices() { return orderedKeys.size(); } } " B12862,"package google.codejam; public interface GoogleSolver { String solve(String str); } " B12519,"import java.util.*; import java.io.*; public class Rec{ public static void rotateArray(char[] array, int amount) { for( int j=0; j=a); } public static boolean sameElem(char[] c){ for(int i=0;i set = new LinkedHashSet(); char[] arr = cmp.toCharArray(); int range=0; int equal=0; for(int j=0;j set; for (k = 0; k < N; k++) { String[] line = br.readLine().split("" ""); int A = Integer.parseInt(line[0]); int B = Integer.parseInt(line[1]); int counter = 0; for (i = A; i < B; i++) { set = new HashSet(); updateSet(set, i); for (j = i + 1; j <= B; j++) { if (set.contains(j)) { counter++; } } } bw.write(""Case #"" + (k+1) + "": "" + counter); bw.newLine(); // showSet(set); } br.close(); bw.close(); } catch (IOException io) { } } private static void updateSet(HashSet set, int num) { String numStr = num + """"; char[] numChar = numStr.toCharArray(); int i, j; for (i = numChar.length - 1; i >= 1; i--) { if (numChar[i] != '0') { char[] newNum = new char[numChar.length]; j = i; int counter = 0; newNum[counter] = numChar[j]; counter++; while (counter < numChar.length) { if (j < numChar.length - 1) { j++; } else { j = 0; } newNum[counter] = numChar[j]; counter++; } set.add(Integer.parseInt(new String(newNum))); } //set.add(num); } set.add(num); } /* private static void showSet(HashSet set) { for (Integer s : set) { System.out.println(s); } } */ } " B11872,"import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; public class Main { public static void main(String[] args) throws IOException { Scanner scanner = new Scanner(new File(""c:\\eclipse\\3\\C-small-attempt0.in"")); int numTc = scanner.nextInt(); for (int index = 0; index < numTc; index++) { int result = 0; int a = scanner.nextInt(); int b = scanner.nextInt(); for (int i = a; i <= b; i++) { if (i < 10) continue; int num = findNumPairs(i, a, b); result += num; } System.out.println(""Case #"" + (index + 1) + "": "" + result/2); } } private static int findNumPairs(int num, int a, int b) { char[] origStr = String.valueOf(num).toCharArray(); int len = origStr.length; char[] newStr = new char[len]; int result = 0; int startIndex = 1; HashSet consumedSet = new HashSet(); do { if (startIndex == len) { break; } int idx = 0; for (int i = startIndex; i < len; i++) { newStr[idx++] = origStr[i]; } for (int i = 0; i < startIndex; i++) { newStr[idx++] = origStr[i]; } startIndex++; int newNum = Integer.parseInt(String.valueOf(newStr)); if (newNum < a || newNum > b || newNum == num || consumedSet.contains(newNum)) { continue; } result++; consumedSet.add(newNum); } while(true); return result; } }" B11724,"import java.awt.datatransfer.*; import java.awt.Toolkit; public class Repeat { private static String inp; public Repeat() { } public static void main(String[] args) { Transferable temp = (Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null)); try { inp = (String) temp.getTransferData(DataFlavor.stringFlavor); } catch (Exception e) { System.out.println(e); } System.out.println(inp); System.out.println(""Breakdown >"" + inp.substring(inp.indexOf(""\n""))); //int iterations = Integer.parseInt(inp.substring(inp.indexOf(""\n""))); String[] newlineSplit = inp.split(""\n""); int iterations = Integer.parseInt(newlineSplit[0]); System.out.println(iterations); System.out.println(""Solutions:\n\n\n\n""); //String cases = inp.substring(inp.indexOf(""\n"")); for(int i = 1; i < newlineSplit.length;i++) { String[] nums = newlineSplit[i].split("" ""); getCount(Integer.parseInt(nums[0]) ,Integer.parseInt(nums[1]), i); } } public static void getCount(int a, int b, int caseNum) { int count = 0; while(a <= b) { String sA = """" + a; String sB = """" + b; //System.out.println(sA + "" "" + sB); for(int i = 0; i < sA.length();i++) { String temp = sA.substring(sA.length() - i-1) + sA.substring(0,sA.length() - i - 1); int iT = Integer.parseInt(temp); int iA = Integer.parseInt(sA); //System.out.println("">>["" + temp + ""] "" + (iT - iA) ); if(iT - iA > 0 && iT <= b) { count++; //System.out.println("">>>>>>> "" + sA + "" "" + temp + "" "" + (iT - iA)); } //else //System.out.println("">>["" + temp + ""] "" + (iT - iA) ); } a++; } System.out.println(""Case #"" + caseNum + "": "" + count); } } " B10646,"import java.util.*; import java.io.*; class C1small { public static void main(String[] args) throws Exception { FileInputStream fis = new FileInputStream(""C-small-attempt0.in""); Scanner scan = new Scanner(fis); FileWriter fw = new FileWriter(""output.txt""); int T = scan.nextInt(); for(int c = 1; c<=T;c++) { int A = scan.nextInt(); int B = scan.nextInt(); int digit = String.valueOf(A).length(); int count=0; for(int i=A;i<=B;i++) { String mut = String.valueOf(i); int tmp =0; int[] mem = new int[4]; boolean counted = false; for(int j=1;j Integer.parseInt(mut) && tmp >=A && tmp <=B) { for(int k=0;k 1 ) fw.write(""Case #"" +c +"": ""+ count +""\n""); else fw.write(""Case #"" +c +"": ""+ 0 +""\n""); } fw.close(); } }" B12356," import java.util.HashSet; import java.util.Scanner; /** * @author Anil Kishore, India */ public class Qual_C { static int get(int x, int A, int B) { int r = 0; String s =""""+x; HashSet set = new HashSet(); for(int i=1;i> resSet2 = new HashSet>(); int res = 0; for(int i=a; i<=b; i++){ if(i<10) continue; String numStr = i+""""; for(int j=1; j resSet1 = new HashSet(); String moved = numStr.substring(j)+numStr.substring(0, j); if(moved.charAt(0) == '0') continue; if(moved.equals(numStr)) continue; if(Integer.parseInt(moved) < a || Integer.parseInt(moved) > b) continue; resSet1.add(numStr); resSet1.add(moved); if(resSet2.contains(resSet1)) continue; else resSet2.add(resSet1); //res += moved+"" ""; res++; } } contents.append(""Case #""+row+"": ""+res). append(System.getProperty(""line.separator"")); } row++; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { e.printStackTrace(); } } System.out.println(contents.toString()); try{ FileWriter fstream = new FileWriter(""D:/CodeJam/C-small-attempt0.out""); BufferedWriter out = new BufferedWriter(fstream); out.write(contents.toString()); out.close(); }catch (Exception e){ System.err.println(""Error: "" + e.getMessage()); } } } " B11692,"import java.util.*; import java.io.*; public class Recycled { public static void main(String[] args) { Recycled d = new Recycled(); d.run(); } public Recycled() {} public boolean isRecyclable(int n, int m) { boolean result = false; String mStr = m + """"; String nStr = n + """"; if (mStr.length() == 1) { return result; } for (int i = 1; i < mStr.length(); i++) { String newM = mStr.substring(i) + mStr.substring(0, i); if (newM.equals(nStr)) { result = true; break; } } return result; } public void run() { Scanner sc = new Scanner(System.in); int testCases = sc.nextInt(); for (int i = 0; i < testCases; i++) { int a = sc.nextInt(); int b = sc.nextInt(); int n = 0; int m = 0; int recyclable = 0; for (n = a; n < b; n++) { for (m = n+1; m <= b; m++) { if (isRecyclable(n, m)) { recyclable++; } } } System.out.println(""Case #"" + (i+1) + "": "" + recyclable); } } } " B11575,"package recyclednumbers; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; public class SimpleReader { private BufferedReader br; private int line = 0; public SimpleReader() { String filename = prompt(); setReader(filename); } public SimpleReader(String filename) { setReader(filename); } private String prompt() { System.out.println(""Input file: ""); BufferedReader bufr = new BufferedReader( new InputStreamReader(System.in)); String filename = null; try { filename = bufr.readLine(); } catch (IOException e) { System.err.println(""At prompt: "" + e.getMessage()); } return filename; } private void setReader(String filename) { try { br = new BufferedReader(new FileReader(filename)); } catch (IOException e) { System.err.println(e.getMessage()); } } public String readLine() { try { line++; return br.readLine(); } catch (IOException e) { System.err.println(""Line "" + (line - 1) + "": "" + e.getMessage()); return null; } } public int readInt() { return Integer.parseInt(readLine()); } public int[] readIntArray() { String[] tokens = readLine().split("" ""); int[] ret = new int[tokens.length]; for (int i = 0; i < tokens.length; i++) { ret[i] = Integer.parseInt(tokens[i]); } return ret; } public String[] readStringArray() { return readLine().split("" ""); } } " B11698,"import java.io.*; import java.util.ArrayList; public class inpOutHandler { public testCase readInput(String fname, int linesInTestCase){ testCase allCases; ArrayList lineList = new ArrayList(); BufferedReader rd = null; try { rd = new BufferedReader(new FileReader(fname)); while (true) { String line = rd.readLine(); if (line == null) break; lineList.add(line); } rd.close(); } catch (IOException ex) { System.out.println(""Can't open that file.""); } //for(int i=0;i""); int N = Integer.parseInt(lineList.get(0)); //int N=100; allCases = new testCase(N); int index=1; for(int i=0;i { int a, b; IntegerPair(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(IntegerPair p) { if (a == p.a) return b - p.b; return a - p.a; } } public class Main implements Runnable { final String fileName = ""C-small-attempt0""; void solveCase(int test) throws Exception { out.print(""Case #"" + test + "": ""); int a = nextInt(); int b = nextInt(); TreeSet answer = new TreeSet(); for (int v = a; v <= b; v++) { String s = Integer.toString(v); for (int i = 1; i < s.length(); i++) { String t = s.substring(i) + s.substring(0, i); if (t.charAt(0) == '0') continue; int v2 = Integer.parseInt(t); if (v2 <= v || v2 > b) continue; answer.add(new IntegerPair(v, v2)); } } out.println(answer.size()); out.flush(); System.out.println(answer.size()); System.out.flush(); } void solution() throws Exception { int t = nextInt(); for (int i = 0; i < t; i++) solveCase(i + 1); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) { String l = in.readLine(); if (l == null) return null; st = new StringTokenizer(l); } return st.nextToken(); } public static void main(String args[]) { //Locale.setDefault(Locale.UK); new Thread(new Main()).start(); } public void run() { try { in = new BufferedReader(new FileReader(fileName + "".in"")); //out = new PrintWriter(System.out); out = new PrintWriter(fileName + "".out""); solution(); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(202); } } BufferedReader in; StringTokenizer st; PrintWriter out; }" B13114,"package com.vp.common; public class CommonUtility { public static int[] convertStringArraytoIntArray(String[] sarray) { if (sarray != null) { int intarray[] = new int[sarray.length]; for (int i = 0; i < sarray.length; i++) { intarray[i] = Integer.parseInt(sarray[i]); } return intarray; } return null; } public static float[] convertStringArraytoFloatArray(String[] sarray) { if (sarray != null) { float floatArray[] = new float[sarray.length]; for (int i = 0; i < sarray.length; i++) { floatArray[i] = Float.parseFloat(sarray[i]); } return floatArray; } return null; } public static double[] convertStringArraytoDoubleArray(String[] sarray) { if (sarray != null) { double darray[] = new double[sarray.length]; for (int i = 0; i < sarray.length; i++) { darray[i] = Double.parseDouble(sarray[i]); } return darray; } return null; } public static long[] convertStringArraytoLongArray(String[] sarray) { if (sarray != null) { long longarray[] = new long[sarray.length]; for (int i = 0; i < sarray.length; i++) { longarray[i] = Long.parseLong(sarray[i]); } return longarray; } return null; } public static void print(int a[]) { System.out.print(""[ ""); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + "", ""); } System.out.print("" ]""); System.out.println(""""); } public static void printWithoutExtrLine(int a[]) { System.out.print(""[ ""); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + "", ""); } System.out.print("" ]""); } public static void print(float a[]) { System.out.print(""[ ""); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + "", ""); } System.out.print("" ]""); System.out.println(""""); } public static void print(double a[]) { System.out.print(""[ ""); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + "", ""); } System.out.print("" ]""); System.out.println(""""); } public static void print(long a[]) { System.out.print(""[ ""); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + "", ""); } System.out.print("" ]""); System.out.println(""""); } public static void print(String a[]) { System.out.print(""[ ""); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + "", ""); } System.out.print("" ]""); System.out.println(""""); } } " B10777,"import java.util.Scanner; /* * Google Code Jam 2012 * Program by Tommy Ludwig * Problem: Recycled Numbers * Date: 2012-04-13 * Time: 02:08 AM */ public class recycle { public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int i = 1; i <= T; i++) { int A, B, n, m, y = 0; A = in.nextInt(); B = in.nextInt(); for (int j = 0; j < (B-A); j++) { m = B - j; String strM = String.valueOf(m); for (int k = 0; k < (B-A); k++) { n = A + k; //n must be less than m if (n >= m) break; String strN = String.valueOf(n); for (int l = 1; l < strN.length(); l++) { String sub = strN.substring(l); String new_strN = sub + strN.substring(0, l); if (new_strN.equalsIgnoreCase(strM)) { y++; break; } } } } System.out.printf(""Case #%d: %d\n"", i, y); } } } " B11722," import java.util.*; /** * * @author Izhari Ishak Aksa */ public class ProblemC { static boolean check(String a, String b) { int x = Integer.parseInt(a); for (int i = 1; i < b.length(); i++) { String c = b.substring(i) + b.substring(0, i); int y = Integer.parseInt(c); if (x == y) return true; } return false; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = Integer.parseInt(sc.nextLine()); for (int t = 1; t <= T; t++) { int a = sc.nextInt(); int b = sc.nextInt(); int ret = 0; for (int i = a; i <= b; i++) { for (int j = i + 1; j <= b; j++) { if (check(i + """", j + """")) { ret++; } } } System.out.println(""Case #"" + t + "": "" + ret); } } } " B11977,"/** * @author Saifuddin Merchant * */ package com.sam.googlecodejam.helper; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class InputReader { BufferedReader iFileBuffer; long iCurrentLineNumber; public InputReader(String pFileName) { try { iFileBuffer = new BufferedReader(new FileReader(pFileName)); } catch (FileNotFoundException e) { e.printStackTrace(); } iCurrentLineNumber = 0; } public String readNextLine() { try { return iFileBuffer.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } public void close() { try { iFileBuffer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B11914,"package qualificationround; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; public class ProblemCRecycledNumbers { @SuppressWarnings(""unchecked"") public ProblemCRecycledNumbers() { try { FileReader fr = new FileReader(""C-small-attempt0.in""); BufferedReader br = new BufferedReader(fr); FileWriter fw = new FileWriter(""C-small-attempt0.out""); BufferedWriter bw = new BufferedWriter(fw); int numCases = Integer.parseInt(br.readLine()); int caseNum = 1; String line = br.readLine(); while (line != null) { System.out.println(line); String[] nums = line.split("" ""); int lowNum = Integer.parseInt(nums[0]); int highNum = Integer.parseInt(nums[1]); Set possibles = new HashSet(); for (int num = lowNum; num<= highNum; num++) { Pair[] recycled = getRecycledNumbers(num); for (int i=0; i= lowNum) { possibles.add(recycled[i]); } } } System.out.println(possibles); String output = ""Case #""+ caseNum; output += "": ""+possibles.size(); System.out.println(output); bw.append(output); if (caseNum != numCases) bw.newLine(); caseNum++; line = br.readLine(); } bw.flush(); bw.close(); br.close(); } catch(Exception e) { e.printStackTrace(); } } public void printArr(Pair[] arr) { System.out.print(""[""); for(int i=0; i{ int int1, int2; public Pair(int int1, int int2) { this.int1 = int1; this.int2 = int2; } public boolean equals(Pair p) { return (p.int1 == this.int1 && p.int2 == this.int2) || (p.int2 == this.int1 && p.int1 == this.int2); } public boolean equals(Object p) { return this.equals((Pair) p); } public int hashCode() { return this.int1 * 10000000 + int2; } public String toString() { return ""(""+int1+"",""+int2+"")""; } public int compareTo(Pair p) { return this.int1 - p.int1; } } } " B10560,"package com.googlerese.file; import java.io.*; import java.util.HashMap; import java.util.Map; public class FileRead { private static FileRead instance = new FileRead(); private FileRead() { } public static FileRead getInstance() { return instance; } public Map read( final String fileName ) { FileInputStream fstream = null; DataInputStream in = null; BufferedReader br = null; Map input = null; try { // Open the file that is the first // command line parameter fstream = new FileInputStream( fileName ); // Get the object of DataInputStream in = new DataInputStream( fstream ); br = new BufferedReader( new InputStreamReader( in ) ); String strLine; //Read File Line By Line int count = 0; while ( ( strLine = br.readLine() ) != null ) { // Print the content on the console if ( count == 0 ) { input = new HashMap( Integer.parseInt( strLine ) ); } else { System.out.println( count + "" : "" + strLine ); String[] arr = strLine.split( ""\\s+"" ); input.put( count, arr ); } count++; } } catch ( Exception e ) {//Catch exception if any System.err.println( ""Error: "" + e.getMessage() ); } finally { //Close the input stream try { if ( br != null ) { br.close(); } if ( in != null ) { in.close(); } if ( fstream != null ) { fstream.close(); } } catch ( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } } return input; } } " B11573,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package gcj_c; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.StringTokenizer; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author kay */ public class Arrange { private int first; private int last; private BufferedReader reader; private StringTokenizer token; public void do_processing(String filename) { String current_line; int no_of_cases; try { reader = new BufferedReader(new FileReader(filename)); FileWriter fstream = new FileWriter(""G:/out.txt""); BufferedWriter out = new BufferedWriter(fstream); no_of_cases = Integer.parseInt(reader.readLine()); for (int i = 1; i <= no_of_cases; i++) { current_line = reader.readLine(); out.write(""Case #"" + i + "": ""); out.write(String.valueOf(do_arrange(current_line))); //out.write(String.valueOf(3)); //System.out.println(""outputttttttttttttttt "" + do_arrange(current_line)); out.newLine(); //Close the output stream } out.close(); reader.close(); } catch (Exception ex) { Logger.getLogger(Arrange.class.getName()).log(Level.SEVERE, null, ex); } } public int do_arrange(String line) { int output = 0, temp,temp2, tens = 1, no_of_digits = 0, new_num = 0, mod = 1, add_tens = 1; token = new StringTokenizer(line); first = Integer.parseInt(token.nextToken()); last = Integer.parseInt(token.nextToken()); System.out.println(first + """" +last); temp = first; while (temp > 0) { temp /= 10; no_of_digits++; } if (no_of_digits == 1) { output = 0; } else { for (int i = first; i <= last; i++){ temp = i; tens = 1; add_tens = 1; for (int j = 1; j < no_of_digits; j++){ add_tens = 1; temp = i; temp2 = i; temp2 /= (tens * 10); temp %= (tens * 10); //System.out.println(temp); for (int k=1; k<=(no_of_digits - j); k++){ add_tens *= 10; } //System.out.println(""add tens"" + add_tens); tens *=10; new_num = (temp * add_tens) + temp2; //System.out.println(""newwwwwwwww "" + new_num); //System.out.println(""iiiiiiii ""+ i); if((new_num >= first) && (new_num > i) && (new_num <= last)){ //System.out.println(""adddedd outtput""); output++; } } } } System.out.println(""output "" + output); return output; } } " B10821,"import java.math.*; import java.io.*; import java.util.*; public class Recycle { public static void main(String[] args) { Recycle r = new Recycle(); writeOutput(r.countRecycleds(readInput())); } // Count all recycleds for all the inputs public String countRecycleds(ArrayList lines) { String line; StringBuffer out = new StringBuffer(); for (int i = 1; i < lines.size(); i++) { line = lines.get(i); String[] args = line.split("" ""); out.append(""Case #"" + i + "": ""); out.append(countRecycleds(Integer.parseInt(args[0]), Integer.parseInt(args[1]))); out.append(""\n""); } return out.toString(); } // Count all recycleds between A and B public int countRecycleds(int A, int B) { int count = 0; for (int n = A; n <= B; n++) { count += countRecycledsForN(n, B); } return count; } // Count recycleds for one n (ie, number of ms) public int countRecycledsForN(int n, int B) { int digits = countDigits(n); int count = 0; Map used = new HashMap(); // For each number of digits we're swapping for(int swap = 1; swap < digits; swap++) { // The base 10 number to swap int swapper = (int)Math.pow(10, swap); // The digits being swapped int swappedDigits = n % swapper; // n without the digits being swapped int swappedN = n / swapper; int m = (swappedDigits * (int)Math.pow(10, digits - swap)) + swappedN; // If m is valid, count it if (n < m && m <= B && !used.containsKey(m)) { count++; used.put(m, true); } } return count; } // Count the number of digits in n (base 10) public int countDigits(int n) { return (int)Math.log10(n) + 1; } public static void writeOutput(String s) { try{ BufferedWriter out = new BufferedWriter(new FileWriter(""./Output.txt"")); out.write(s); out.close(); }catch (Exception e){ System.out.println(s); throw new RuntimeException(""Oops, couldn't write""); } } public static ArrayList readInput() { ArrayList lines = new ArrayList(); try { FileInputStream fstream = new FileInputStream(""./Input.txt""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String str; while ((str = br.readLine()) != null) { lines.add(str); } br.close(); return lines; } catch (Exception e) { throw new RuntimeException(""Couldn't read""); } } }" B12622,"import com.sun.org.apache.bcel.internal.generic.NEW; import java.io.IOException; import java.util.List; public class WaterSheds extends JamProblem { public static void main(String[] args) throws IOException { WaterSheds p = new WaterSheds(); p.go(); } Character[][] res; WSCase cs; char curr; @Override String solveCase(JamCase jamCase) { cs = (WSCase) jamCase; curr = 'a'; res = new Character[cs.h][cs.w]; for (int y = 0; y < cs.h; y++) { for (int x = 0; x < cs.w; x++) { res[y][x] = ' '; } } for (int y = 0; y < cs.h; y++) { for (int x = 0; x < cs.w; x++) { res[y][x] = update(y, x); } } return ""\n"" + JamUtil.printTable(res); //To change body of implemented methods use File | Settings | File Templates. } private char update(int y, int x) { if (res[y][x] != ' ') { return res[y][x]; } int min = cs.table[y][x]; int dir = -1; if (y > 0) { int curr = cs.table[y - 1][x]; if (curr < min) { min = curr; dir = 0; } } if (x > 0) { int curr = cs.table[y][x - 1]; if (curr < min) { min = curr; dir = 1; } } if (x < cs.w - 1) { int curr = cs.table[y][x + 1]; if (curr < min) { min = curr; dir = 2; } } if (y < cs.h - 1) { int curr = cs.table[y + 1][x]; if (curr < min) { min = curr; dir = 3; } } if (dir == -1) { return res[y][x] = curr++; } else { switch (dir) { case 0: return res[y][x] = update(y - 1, x); case 1: return res[y][x] = update(y, x - 1); case 2: return res[y][x] = update(y, x + 1); case 3: return res[y][x] = update(y + 1, x); default: throw new RuntimeException(); } } } @Override JamCase parseCase(List file, int line) { int i = line; String firstLine = file.get(i++); int[] pair = JamUtil.parseIntList(firstLine, 2); WSCase cas = new WSCase(); cas.h = pair[0]; cas.w = pair[1]; cas.lineCount = cas.h + 1; cas.table = new int[cas.h][]; for (int ih = 0; ih < cas.h; ih++) { cas.table[ih] = JamUtil.parseIntList(file.get(i++), cas.w); } return cas; } } class WSCase extends JamCase { int w, h; int[][] table; } " B12712,"import java.util.Scanner; public class Shift { public static void main(String[] args) { int a,b,c,d=10,e=0,x,T,j; int inf,sup,res=0; Scanner l = new Scanner(System.in); T=l.nextInt(); for(j=0;j0){ vixi=vixi/10; e++; } for(int i=0;ik)&&(c<=sup)&&(c>=inf)) res++; //System.out.println(c); x=c; } } System.out.println(""Case #""+(j+1)+"": ""+res); } } } " B10764,"import java.util.*; import java.io.*; public class ProblemC { final long MOD = 1000003; final int MAX_LEN = 500000; long pow(long x, long y) { if (y == 0) return 1; long res = pow(x, y/2); res = (res * res) % MOD; if (y % 2 == 1) res = (res * x) % MOD; return res; } long inv(long x) { return pow(x, MOD-2); } long[] fact, invfact; void precalc() { fact = new long[MAX_LEN + 1]; fact[0] = 1; for (int i=1; i<=MAX_LEN; i++) fact[i] = (i * fact[i-1]) % MOD; invfact = new long[MAX_LEN + 1]; invfact[0] = 1; for (int i=1; i<=MAX_LEN; i++) invfact[i] = (inv(i) * invfact[i-1]) % MOD; } long comb(int N, int M) { long res = fact[N]; res = (res * invfact[M]) % MOD; res = (res * invfact[N-M]) % MOD; return res; } class Testcase { long ans; public Testcase() { } public Testcase(int seed) { Random rnd = new Random(seed); } String s; int A =0; int B = 0; public void loadInput(Scanner sc) { // s = sc.next(); A = sc.nextInt(); B = sc.nextInt(); } public void solveSlow() { } String getShift(String sa) { String sb = sa.substring(sa.length() -1 ) + sa.substring(0,sa.length()-1); return sb; // return Integer.parseInt(s); } int getMaxDivide(int a) { int m = 1; while(a>=10){ a=a/10; m=m*10; } return m; } HashMap > map = new HashMap>(); public ArrayList getShifts(String sa) { ArrayList arr = null; arr = map.get(sa); if( arr == null ) { arr = new ArrayList(); arr.add(sa); String sn = getShift(sa); while(!sn.equals(sa)) { arr.add(sn); sn = getShift(sn); } for(String ai : arr) { map.put(ai, arr); } } return arr; } boolean isCycle(int a, int b) { int am = getMaxDivide(a); if(b/am!=0) { return true; } else { return false; } } public void solveFast() { for(int n =A;n arr = getShifts(sn); for(String ai : arr ) { int m = Integer.parseInt(ai) ; if(m>n && m<=B && isCycle(n,m) ) { ans++; } } } } public void printSelf(PrintWriter pw) { System.out.println(ans); pw.println(ans); } public boolean sameAnswers(Testcase other) { return false; } } final String AFTER_CASE = "" ""; public void go() throws Exception { Scanner sc = new Scanner(new FileReader(""src\\input.txt"")); PrintWriter pw = new PrintWriter(new FileWriter(""src\\output.txt"")); int caseCnt = sc.nextInt(); for (int caseNum = 0; caseNum < caseCnt; caseNum++) { System.out.println(""solving case "" + caseNum); Testcase tc = new Testcase(); tc.loadInput(sc); tc.solveFast(); pw.print(""Case #"" + (caseNum + 1) + "":""); pw.print(AFTER_CASE); tc.printSelf(pw); } pw.flush(); pw.close(); sc.close(); } public void stresstest() { int it = 0; Random rnd = new Random(); while (true) { it++; if (it % 1000 == 0) System.out.println(it + "" iterations""); int seed = rnd.nextInt(); Testcase tc1 = new Testcase(seed); tc1.solveFast(); Testcase tc2 = new Testcase(seed); tc2.solveSlow(); if (!tc1.sameAnswers(tc2)) { System.out.println(""ERROR: it failed""); System.exit(0); } } } public static void main(String[] args) throws Exception { new ProblemC().go(); } } " B12140,"package Recycled; import java.io.File; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.Scanner; public class recycled { static void print(int nbCases, int N, int S, int P, int[] T) { System.out.print(N + "" ""); System.out.print(S + "" ""); System.out.print(P); for (int j = 0; j < N; j++) { System.out.print("" "" + T[j]); } System.out.println(); } static int RecycledNumbers(int A, int B) { int res = 0; double d = Math.log10(A); int n = (int) Math.floor(Math.log10(A)) + 1; // System.out.println("" A = "" + A + ""B = "" + B); // System.out.println("" N = "" + n + "" pour d = "" + d); int flag = 0; HashSet l = new HashSet(); for (int i = A; i <= B; i++) { for (int j = 1; j < n; j++) { int p = (int) (((int) Math.pow(10, n - j)) * (i % (int) Math.pow(10, j)) + i / Math.pow(10, j)); if (i < p && p >= A && p <= B && p / Math.pow(10, n) != 0 && !l.contains(new Couple(i, p))) { flag += 1; res += 1; l.add(new Couple(i,p)); //if (flag >1) // System.out.println(""FLAG""); //System.out.println("" Couple : ("" + i + "", "" + p + "")""); } } flag = 0; } return res; } static void run(int A, int B, int turn) { System.out.println(""Case #"" + turn + "": "" + RecycledNumbers(A, B)); } /** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { Scanner f = new Scanner( new File( ""C:\\Users\\Jean-Baptiste\\Desktop\\Info2A\\GoogleJam\\src\\Recycled.in"")); int nbCases = f.nextInt(); int A = 1; int B = 1; for (int i = 0; i < nbCases; i++) { A = f.nextInt(); B = f.nextInt(); run(A, B, i + 1); } int n = 6; int i = 123456; int j = 4; int p = (int) (((int) Math.pow(10, n - j)) * (i % (int) Math.pow(10, j)) + i / Math.pow(10, j)); //System.out.println("" Pour i = 123456 et j = 3 : "" + p); f.close(); } } " B11188,"import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Recycling { public static void main(String[] args) throws FileNotFoundException { File file = new File(""C-small-attempt0.in""); Scanner in = new Scanner(file); int cases = in.nextInt(); for (int i = 0; i < cases; i++) { int A = in.nextInt(); int B = in.nextInt(); int pairs = 0; while (A < B) { String perm = A+""""; for (int j = 1; j < perm.length(); j++) { String x = perm.substring(0,j); String y = perm.substring(j,perm.length()); String out = y+x; int testCase = Integer.parseInt(out); if (A < testCase && testCase <= B ) { pairs++; } } A++; } System.out.println(""Case #""+ (i+1) + "": "" + pairs); } } } " B12609,"import java.io.IOException; import java.text.NumberFormat; import java.util.List; public class Welcome extends JamProblem { String welc = ""welcome to code jam""; public static void main(String[] args) throws IOException { Welcome p = new Welcome(); p.go(); } @Override String solveCase(JamCase jamCase) { WelcomeCase cas = (WelcomeCase) jamCase; int length = welc.length(); int strL = cas.str.length(); String str = cas.str; int[][] tab = new int[length][strL]; for (int i = length - 1; i >= 0; i--) { char c = welc.charAt(i); for (int j = strL - 1; j >= 0; j--) { if (i == length - 1) { if (j == strL - 1) { tab[i][j] = str.charAt(j) == c ? 1 : 0; } else { tab[i][j] = mod(tab[i][j + 1] + (str.charAt(j) == c ? 1 : 0)); } } else { if (j == strL - 1) { tab[i][j] = 0; } else { tab[i][j] = mod(tab[i][j + 1] + (str.charAt(j) == c ? 1 : 0) * tab[i + 1][j]); } } } } NumberFormat nf = NumberFormat.getInstance(); // Get Instance of NumberFormat nf.setMinimumIntegerDigits(4); // The minimum Digits required is 5 nf.setMaximumIntegerDigits(4); // The maximum Digits required is 5 nf.setGroupingUsed(false); return nf.format(tab[0][0]); //To change body of implemented methods use File | Settings | File Templates. } @Override JamCase parseCase(List file, int line) { WelcomeCase cas = new WelcomeCase(); cas.lineCount = 1; cas.str = file.get(line); return cas; } int mod(int i) { return i % 10000; } } class WelcomeCase extends JamCase { String str; } " B12973,"package szarfos; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class Main { private static List numbers; public static void main(String[] args) throws IOException { readFile(); BufferedWriter out = new BufferedWriter(new FileWriter(""output.txt"")); for (int i = 0; i < numbers.size(); i++) { int bound1 = Integer.parseInt(numbers.get(i)[0]); int bound2 = Integer.parseInt(numbers.get(i)[1]); int c = 0; for (int n1 = bound1; n1 <= bound2; n1++) { for (int n2 = bound1; n2 <= bound2; n2++) { if (isRecNums(Integer.toString(n1), Integer.toString(n2))) { c++; } } } System.out.println(""Number of rec nums: "" + c/2); int caseNum = i+1; out.write(""Case #"" + caseNum + "": "" + c/2); out.newLine(); } out.close(); } public static void readFile() { try { numbers = new ArrayList(); BufferedReader in = new BufferedReader(new FileReader(""input.txt"")); String str; in.readLine(); while ((str = in.readLine()) != null) { String[] n = str.split("" ""); numbers.add(n); } in.close(); } catch (IOException e) { } } public static boolean isRecNums(String n, String m) { if (n.length() != m.length()) return false; if (n.equals(m)) return false; for (int i = 0; i < n.length()-1; i++) { if (changeNumber(n, i).equals(m)) { return true; } } return false; } public static String changeNumber(String n, int k) { String tmp = n.substring(n.length()-1-k, n.length()); n = tmp + n.substring(0, n.length()-1-k); return n; } } " B13163,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class Test { public static void main(String[] args){ FileInputStream fstream = null; DataInputStream in = null; BufferedReader br = null; FileWriter fw = null; BufferedWriter out = null; try{ fstream = new FileInputStream(args[0]); in = new DataInputStream(fstream); br = new BufferedReader(new InputStreamReader(in)); fw = new FileWriter(args[1]); out = new BufferedWriter(fw); String strLine; int i = 0; int tc = 0; while ((strLine = br.readLine()) != null) { if(i == 0){ tc = Integer.parseInt(strLine); i++; continue; } if( i <= tc){ String[] arr = strLine.split("" ""); int minLimit = Integer.parseInt(arr[0]); int maxLimit = Integer.parseInt(arr[1]); int count = 0; int len = arr[0].length(); if(len <= 1){ count = 0; }else{ for(int j = minLimit; j <= maxLimit ; j++){ int num = j; List ls = new ArrayList(); for(int k = 1; k < len ; k++ ){ int dp = (int)Math.pow(10, len -k); int mp = (int)Math.pow(10, k); int first = num / dp; int last = num % dp; int number = last*mp + first; if(num != number){ if(number <= maxLimit && number >= minLimit){ if(!ls.contains(number+"""")){ ls.add(number+""""); count++; } } } } } } count = count/2; System.out.println(""Case #""+i+"": ""+count); out.write(""Case #""+i+"": ""+count); out.write(System.getProperty( ""line.separator"" )); } i++; } in.close(); out.close(); }catch (Exception e){ e.printStackTrace(); System.err.println(""Error: "" + e.getMessage()); } } } " B12676,"import java.util.Scanner; public class C { public static void main (String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int a, b; int[] list; for (int i = 1; i <= n; i++) { a = scan.nextInt(); if (a < 10) a = 10; b = scan.nextInt(); int count = 0; for (int j = a; j < b; j++) { String str = """" + j; int len = str.length(); list = new int[len]; int lp = 0; for (int k = 1; k < len; k++) { String str2 = str.substring(len-k) + str.substring(0, len-k); int res = Integer.valueOf(str2); if (str2.charAt(0) != '0' && res > j && res <= b) { if (!contains(list, lp, res)) { list[lp] = res; lp++; //System.out.println(j + "" "" + res); count++; } } } } System.out.println(""Case #"" + i + "": "" + count); } } private static boolean contains(int[] list, int lp, int res) { for (int i = 0; i < lp; i++) if (list[i] == res) return true; return false; } } " B11978,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; public class C { static int[] resu; /** * @param args */ public static void main(String[] args) { File input=new File(""D:\\Users\\xiaoguo\\Downloads\\C-small.in""); File output=new File(""D:\\Users\\xiaoguo\\Desktop\\output.txt""); readCaseFromInput(input); writeToOutput(output); System.out.println(""Programe exist!""); } static class Couple{ private int a; private int b; public Couple(int a, int b) { this.a=a; this.b=b; } public boolean equals(Object o){ return (this.a==((Couple)o).a && this.b==((Couple)o).b); } } static void readCaseFromInput(File input ) { try { FileReader reader=new FileReader(input); BufferedReader buf=new BufferedReader(reader); int numberCase=Integer.parseInt(buf.readLine()); resu=new int[numberCase]; String contentLine=null; int numerLine=0; while((contentLine=buf.readLine())!=null) { String[] line=contentLine.split(""\\s""); int a=Integer.parseInt(line[0]); int b=Integer.parseInt(line[1]); int n=0; ArrayList liste=new ArrayList(); if(a>=10 && b>=10) { for(int i=a;i<=b;i++) { String number=String.valueOf(i); for(int j=number.length()-1;j>=1;j--) { int x=Integer.parseInt(number.substring(j)+number.substring(0, j)); C.Couple couple=new C.Couple(i, x); if(x<=b && x>i && !liste.contains(couple)) { n++; liste.add(couple); } } } } resu[numerLine]=n; numerLine++; } buf.close(); reader.close(); } catch (Exception e) { e.printStackTrace(); } } static void writeToOutput(File output) { try { FileWriter out=new FileWriter(output); BufferedWriter buf=new BufferedWriter(out); String headLine=""Case #""; for(int i=0;i= A && hasil <= B){ // System.out.println(""Recycle ""+hasil+"" from ""+j); if(j < hasil){ //System.out.println(""Recycle ""+hasil+"" ""+j); if(!flag[hasil]){ flag[hasil] = true; //ada = true; count++; } } } } } //} } int kount = 0; /*for(int j=A;j<=B;j++){ if(flag[j]){ //System.out.println(""recycle ""+j); kount++; } }*/ System.out.println(""Case #""+(i+1)+"": ""+count); } } }" B10505," import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.Writer; import java.util.ArrayList; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers{ public static void main(String[] args) throws IOException{ String testCases; BufferedReader brTestCases = new BufferedReader(new InputStreamReader(System.in)); File inFile = new File(""C:/Users/AbhilashR/Downloads/C-small-attempt0.in"" ); Scanner sc = new Scanner(inFile); //testCases = (String)brTestCases.readLine(); testCases = sc.nextLine(); Integer noOfTestCases = null; try{ noOfTestCases = Integer.parseInt(testCases); }catch (NumberFormatException e){ System.out.println(""The entered value is not a Number""); } ArrayList inputData = new ArrayList(); for(int i =0;i inputDataObj = new ArrayList(); for(int i =0;i tempSet = new HashSet(); for(int j =0; j< numberOfDigits; j++){ int currentSize = Integer.toString(sampleM).length(); if(currentSize==numberOfDigits){ sampleM = Integer.parseInt(Integer.toString(sampleM%10)+Integer.toString(sampleM/10)); }else{ String formingSampleM = Integer.toString(sampleM%10); for(int k =0;k0){ return noOfRecycledNumbers; } return 0; } }" B12810,"package c; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.text.AttributedCharacterIterator; import java.util.Arrays; import java.util.HashSet; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { InputStream inputStream; try { inputStream = new FileInputStream(""input.txt""); } catch (IOException e) { throw new RuntimeException(e); } OutputStream outputStream; try { outputStream = new FileOutputStream(""output.txt""); } catch (IOException e) { throw new RuntimeException(e); } InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Numbers solver = new Numbers(); int testCases = in.nextInt(); for (int i = 1; i <= testCases; i++) solver.solve(i, in, out); out.close(); } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public boolean haveNextInCurrentLine() { return (tokenizer != null && tokenizer.hasMoreTokens()); } public int nextInt() { return Integer.parseInt(next()); } } class Numbers { public void solve(int testCase, InputReader in, PrintWriter out) { int a = in.nextInt(); int b = in.nextInt(); int count = 0; int[] contains = new int[b + 1]; System.out.println(""Case #"" + testCase + "" a: "" + a + "" b: "" + b); for(int i = a; i <= b; i++){ String s = Integer.toString(i); //System.out.println("" "" + s); for(int ii = 1, size = s.length(); ii < size; ii++){ StringBuilder sb = new StringBuilder(); String newNumber = sb.append(s.substring(ii, size)).append(s.substring(0, ii)).toString(); if(newNumber.charAt(0) == '0') continue; int newInt = Integer.valueOf(newNumber); if(newInt >= a && newInt < i && contains[newInt] != i){ contains[newInt] = i; count++; System.out.println("" "" + s + "" "" + newInt); } } } out.println(""Case #"" + testCase + "": "" + count); System.out.println(""Case #"" + testCase + "": "" + count); } }" B11348,"import java.util.StringTokenizer; public class Numbers { final static String INPUT = ""50\n"" + ""103 968\n"" + ""150 975\n"" + ""122 949\n"" + ""129 936\n"" + ""120 979\n"" + ""532 532\n"" + ""100 101\n"" + ""171 913\n"" + ""129 974\n"" + ""162 954\n"" + ""113 964\n"" + ""109 930\n"" + ""190 916\n"" + ""175 941\n"" + ""131 971\n"" + ""117 916\n"" + ""185 986\n"" + ""118 595\n"" + ""170 958\n"" + ""162 913\n"" + ""125 944\n"" + ""218 986\n"" + ""176 925\n"" + ""152 956\n"" + ""100 999\n"" + ""179 947\n"" + ""387 387\n"" + ""166 958\n"" + ""148 990\n"" + ""70 99\n"" + ""183 920\n"" + ""100 999\n"" + ""144 965\n"" + ""123 954\n"" + ""2 3\n"" + ""105 958\n"" + ""122 980\n"" + ""40 62\n"" + ""114 954\n"" + ""185 974\n"" + ""126 992\n"" + ""190 936\n"" + ""497 884\n"" + ""100 100\n"" + ""109 972\n"" + ""178 980\n"" + ""137 962\n"" + ""106 997\n"" + ""147 954\n"" + ""188 981\n""; public static void main(final String argv[]) throws NumberFormatException, Exception { StringTokenizer st = new StringTokenizer(INPUT); final int testCases = Integer.parseInt(st.nextToken()); for(int i = 0; i < testCases; i++) { System.out.println(""Case #""+(i+1)+"": "" + solve(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()))); } } private static int solve(final int A, final int B) throws Exception { if(A < 10) { return 0; } else { int result = 0; final int digits = Integer.toString(A).length(); for(int n = A; n < B; n++) { for(int shifts = 0; shifts < (digits - 1); shifts++) { byte [] numB = new byte[digits]; toByteArr(n, numB); shift(numB, shifts + 1); int m = toInt(numB); if(m > n && m <= B) { //System.out.println(i + "" "" + tmpNr); result++; if(numB[0] == 0) throw new Exception(""a""); } } } return result; } } private static void shift(byte[] numB, int positions) { byte [] tmp = new byte[positions]; for(int i = 0; i < positions; i++) { tmp[i] = numB[numB.length - (positions - i)]; } for(int i = numB.length - 1; i > (positions - 1); i--) { numB[i] = numB[i-positions]; } for(int i = 0; i < positions; i++) { numB[i] = tmp[i]; } } private static byte [] toByteArr(int nr, byte [] arr) { char [] chars = Integer.toString(nr).toCharArray(); for(int i = 0; i < arr.length; i++) { arr[i] = (byte) (chars[i] - 48); } return arr; } private static int toInt(byte [] arr) { int result = 0; for(int i = 0; i < arr.length; i++) { result += arr[i] * (int)Math.pow(10, arr.length - 1 - i); } return result; } } " B11496,"package de.hg.codejam.tasks.io; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public abstract class Writer { public static String generateOutputPath(String inputPath) { return inputPath.substring(0, inputPath.lastIndexOf('.') + 1) + ""out""; } public static void print(String[] output) { for (String s : output) System.out.println(s); } public static void write(String[] output) { for (int i = 0; i < output.length; i++) System.out.println(getCase(i + 1, output[i])); } public static void write(String[] output, String path) { try (BufferedWriter writer = new BufferedWriter(new FileWriter(path, false))) { for (int i = 0; i < output.length; i++) { writer.append(getCase(i + 1, output[i])); writer.newLine(); writer.flush(); } } catch (IOException e) { e.printStackTrace(); } } private static String getCase(int number, String caseString) { return ""Case #"" + (number) + "": "" + caseString; } } " B11931,"import java.util.*; import java.io.*; public class C { public static void main(String[] args) { int n = 0; int[] a = null; int[] b = null; try { File file = new File(args[0]); Scanner sc = new Scanner(file); n = sc.nextInt(); a = new int[n]; b = new int[n]; for (int i=0;i list = new ArrayList(); for (int k=1;kdigits[i+1]); if(!descending){ String num = """" + n; String match = """" + m; num = num.substring(len-1).concat(num.substring(0, len-1)); while(!num.equals(s)){ if(num.equals(match)) total += 1; num = num.substring(len-1).concat(num.substring(0, len-1)); } } //System.out.println(total); return total; } } " B11556," import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class C { int INF = 1 << 28; void run() { Scanner sc; FileOutputStream fw; try { sc = new Scanner(new File(""C.in"")); fw = new FileOutputStream(new File(""C.out"")); PrintWriter pw = new PrintWriter(fw); // sc.useDelimiter(""\\n""); int n = sc.nextInt(); for(int i=1;i<=n;i++) { int a = sc.nextInt(); int b = sc.nextInt(); int cnt = 0; for(int j=a;j<=b;j++) { String num = String.valueOf(j); // debug(num); HashSet visited = new HashSet(); for(int k=1;k j && a <= rot && rot <= b) visited.add(rot); } cnt += visited.size(); } // debug(cnt); pw.println(""Case #"" + i + "": "" + cnt); } pw.close(); fw.close(); } catch (FileNotFoundException e) { // TODO 自動生成された catch ブロック e.printStackTrace(); } catch (IOException e) { // TODO 自動生成された catch ブロック e.printStackTrace(); } } public static void main(String[] args) { new C().run(); } void debug(Object... os) { System.err.println(Arrays.deepToString(os)); } } " B10379," public class ValuePairs { int value1; int value2; public ValuePairs(int a,int b){ value1 = a; value2 = b; } @Override public boolean equals(Object vp){ if(!(vp instanceof ValuePairs)) return false; return value1 == ((ValuePairs)vp).value1 && value2 == ((ValuePairs)vp).value2; } @Override public int hashCode(){ return Integer.parseInt(""""+value1+value2); } } " B10671,"package ch.googlecodejam.qualround; import java.util.ArrayList; import java.util.List; public class RecycledNumbers { public static String solve(List> values) { StringBuilder result = new StringBuilder(); int numberOfLine = 1; for (List line : values) { int minValue = Integer.parseInt(line.get(0)); int maxValue = Integer.parseInt(line.get(1)); int numberOfRecycledNumbers = getNumberOfRecycledNumbers(minValue, maxValue); result.append(""Case #"" + numberOfLine + "": "" + numberOfRecycledNumbers + ""\n""); numberOfLine++; } return result.toString(); } private static int getNumberOfRecycledNumbers(int minValue, int maxValue) { int numberOfRececlyedNumbers = 0; for (int numberToTest = minValue; numberToTest < maxValue; numberToTest++) { numberOfRececlyedNumbers += hasRecycledNumber(numberToTest, maxValue); } return numberOfRececlyedNumbers; } private static int hasRecycledNumber(int number, int maxValue) { String originalNumber = String.valueOf(number); int numberOfRecycledNumber = 0; List alreadyRecycled = new ArrayList(); for (int i = originalNumber.length() - 1; i > 0; i--) { String recycledNumber = getSwapedNumber(i, originalNumber); if (recycledNumber.charAt(0) != '0') { int valueRecycledNumber = Integer.parseInt(recycledNumber); if (valueRecycledNumber > number && valueRecycledNumber <= maxValue && !alreadyRecycled.contains(recycledNumber)) { numberOfRecycledNumber++; alreadyRecycled.add(recycledNumber); } } } return numberOfRecycledNumber; } public static String getSwapedNumber(int startIndex, String original) { StringBuilder swaped = new StringBuilder(); swaped.append(original.substring(startIndex)); swaped.append(original.substring(0, startIndex)); return swaped.toString(); } } " B13263,"import java.util.*; import java.io.*; public class C { int numLen(int n) { int ans = 0; while(n>0) { ans++; n/=10; } return ans; } int shift(int n, int pow) { int tmp = n%10; return n/10 + tmp*pow; } public C(Scanner in, PrintWriter out) { int T = in.nextInt(); in.nextLine(); for (int t=0; t seen = new HashSet(); for (int j=0; j=A && x<=B && numLen(x) == len && !seen.contains(x)) { seen.add(x); ans++; } x = shift(x,pow); } } out.printf(""Case #%d: %d\n"",t+1,ans); } out.close(); } public static void main(String[] args) throws FileNotFoundException { new C(new Scanner(new File(""c.in"")),new PrintWriter(new File(""c.out""))); } } " B11741,"import java.util.Scanner; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; /** *Recycled Numbers */ /** * @author Avengee */ public class Demo { public static void main(String[] args) throws IOException { //Reading and Writing Files Scanner scan = new Scanner(new File(""C-small-attempt0.in"")); FileWriter writer = new FileWriter(""C-small-output.txt""); PrintWriter pw = new PrintWriter(writer); //variable declaration int T,A,B; //code T = scan.nextInt(); for (int i=1;i<=T;i++) { A = scan.nextInt(); B = scan.nextInt(); int y=0; int num=String.valueOf(A).length();//number of digits int nl=A; while(nl<=B) { int n=nl; for(int j=1;jnl && m<=B) {y++; //System.out.println(nl+"" ""+m); } n=m; } nl++; } System.out.println(""Case #""+i+"": ""+y); pw.println(""Case #""+i+"": ""+y); } scan.close(); writer.close(); } } " B11633,"import java.util.*; import static java.lang.Math.*; public class C { public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for(int zz = 1; zz <= T; zz++) { int A = in.nextInt(); int B = in.nextInt(); long ans = 0; for (int n = A; n <= B; n++) { String s = n+""""; HashSet used = new HashSet(); for (int r = 0; r <= s.length(); r++) { String t = s.substring(r) + s.substring(0, r); int m = Integer.valueOf(t); if (A <= m && m <= B && n < m && t.charAt(0) != '0' && s.charAt(0) != '0' && !used.contains(t)) { used.add(t); ans++; } } } System.out.format(""Case #%d: %d\n"", zz, ans); } } } " B11628,"package gcj2012.qual; import java.io.*; import java.util.*; import java.math.*; import static java.lang.Math.*; import static java.lang.Character.*; import static java.util.Arrays.*; import static java.util.Collections.*; import static java.math.BigInteger.*; public class C { static final char PROB = C.class.getSimpleName().charAt(0); static final boolean PRAC = false; static final double EPS = 1e-12; static final int INF = 1 << 20; static final int[] di = { -1, 0, 0, 1 }; static final int[] dj = { 0, -1, 1, 0 }; static Scanner sc = new Scanner(System.in); final int A, B; public C() { A = sc.nextInt(); B = sc.nextInt(); } public String solve() { final boolean[] f = new boolean[2000001]; int num = 0; for (int i = A; i > 0; i /= 10) num++; int d = 1; for (int i = 1; i < num; i++) d *= 10; int ans = 0; for (int X = A; X <= B; X++) { for (int i = 0, Y = X; i < num; i++, Y = Y % 10 * d + Y / 10) if (A <= Y && Y < X && !f[Y]) { ans++; f[Y] = true; } for (int i = 0, Y = X; i < num; i++, Y = Y % 10 * d + Y / 10) if (Y < X) f[Y] = false; } return """" + ans; } public static void main(String... args) { small(); int T = Integer.parseInt(sc.nextLine()); for (int t = 1; t <= T; t++) { System.err.printf(""Case #%s%n"", t); System.out.printf(""Case #%s: %s%n"", t, new C().solve()); } System.err.println(""done.""); } public static void small() { String in = PROB + ""-small"" + (PRAC ? ""-practice"" : ""-attempt"" + 0) + "".in""; String out = PROB + ""-small.out""; if (!PRAC) for (int i = 1; new File(PROB + ""-small"" + ""-attempt"" + i + "".in"").exists(); i++) in = PROB + ""-small"" + ""-attempt"" + i + "".in""; try { System.setIn(new BufferedInputStream(new FileInputStream(in))); System.setOut(new PrintStream(out)); } catch (Exception e) { e.printStackTrace(); System.exit(0); } sc = new Scanner(System.in); } public static void large() { String in = PROB + ""-large"" + (PRAC ? ""-practice"" : """") + "".in""; String out = PROB + ""-large.out""; try { System.setIn(new BufferedInputStream(new FileInputStream(in))); System.setOut(new PrintStream(out)); } catch (Exception e) { e.printStackTrace(); System.exit(0); } sc = new Scanner(System.in); } private static void debug(Object... os) { System.err.println(deepToString(os)); } }" B11904,"package googleJam; import java.io.File; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) { Scanner scan = null; try { scan = new Scanner(new File(args[0])); } catch (FileNotFoundException e) { System.err.println(""File not found!""); return; } if (!scan.hasNext()) { System.err.println(""Nothing in File!""); return; } int testCases = Integer.parseInt(scan.nextLine()); int lower; int upper; int move; int d; int total; int zeroes; int num = 1; int first; HashSet set; while(scan.hasNext()) { System.out.print(""Case #"" + num + "": ""); total = 0; lower = scan.nextInt(); upper = scan.nextInt(); for (int x = lower; x <= (upper); x++) { set = new HashSet(); zeroes = 1; move = x; while (move > 9) { move = move/10; zeroes = zeroes * 10; } int limit = zeroes; for(int n = 10; n < (limit*10); n = n * 10) { move = x/n; d = x % n; d = d * zeroes; d = d + move; zeroes = zeroes / 10; if (d < x && d >= lower && !set.contains(d) && d > 9) { total++; //System.out.println(d + "" , "" + x); set.add(d); } } } num++; System.out.print(total); if (scan.hasNext()) { System.out.println(); } } } } " B11748,"public class CodeJamUtils { /** * Makes sure that the line separator written by BufferedWriter is a single * newline character */ public static void initLineEndings() { System.setProperty(""line.separator"", ""\n""); } } " B12686,"package org.digiharbor.gene; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.Console; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class CJ2012 { public static void main(String[] args) throws FileNotFoundException, IOException { new CJ2012(); } public CJ2012() throws FileNotFoundException, IOException { BufferedReader sysin = new BufferedReader(new InputStreamReader(System.in)); String stage = ""Qual""; System.out.printf(""Stage %s Problem to run: (ae, a0, a1, al, be...): "", stage); String cmd = sysin.readLine().toUpperCase().trim(); char problem = cmd.charAt(0); String fname = """"; if (cmd.charAt(1) == 'E') fname = stage + ""/"" + problem + ""-example""; else if (cmd.charAt(1) == 'L') fname = stage + ""/"" + problem + ""-large""; else fname = stage + ""/"" + problem + ""-small-attempt"" + cmd.charAt(1); String inf = fname + "".in""; String outf = fname + "".out""; BufferedReader f = new BufferedReader(new FileReader(inf)); BufferedWriter out = new BufferedWriter(new FileWriter(outf)); int cnt = Integer.parseInt(f.readLine()); long start = System.currentTimeMillis(); System.out.printf(""Running %s => %s ..."", inf, outf); switch (problem) { case 'A': new A_SpeakingInTongues(cnt, f, out); break; case 'B': new B_DancingWithTheGooglers(cnt, f, out); break; case 'C': new C_RecycledNumbers(cnt, f, out); break; case 'D': new D_HallOfMirrors(cnt, f, out); break; } long finish = System.currentTimeMillis(); System.out.printf("" %dmsec"", finish - start); f.close(); out.close(); } class A_SpeakingInTongues { public A_SpeakingInTongues(int cnt, BufferedReader infile, BufferedWriter outfile) throws IOException { String key = ""yhesocvxduiglbkrztnwjpfmaq""; for (int i = 0; i < cnt; i++) { String ln = infile.readLine(); String res = """"; for (int p = 0; p < ln.length(); p++) { if (ln.charAt(p) == ' ') res += ' '; else res += key.charAt(ln.charAt(p) - 'a'); } outfile.write(String.format(""Case #%d: %s\r\n"", i + 1, res)); } } } class B_DancingWithTheGooglers { public B_DancingWithTheGooglers(int cnt, BufferedReader infile, BufferedWriter outfile) throws IOException { Scanner in = new Scanner(infile); for (int i = 0; i < cnt; i++) { int nGoog = in.nextInt(); int nSurprise = in.nextInt(); int best = in.nextInt(); int bestcnt = 0; int surprises = 0; int surescore = best * 3 - 2; // i.e. >=22 ensures a best of 8 (8,7,7) if (surescore < 0) surescore = 0; int surprisescore = surescore - 2; // i.e. 20,21 could get an 8 with a surprise (8,7,6) (8,6,6) if (surprisescore < 0) surprisescore = 0; for (int j = 0; j < nGoog; j++) { int total = in.nextInt(); if (total >= best && total >= surescore) bestcnt++; else if (total >= best && total >= surprisescore) surprises++; } int res = bestcnt + (nSurprise >= surprises ? surprises : nSurprise); outfile.write(String.format(""Case #%d: %d\r\n"", i + 1, res)); } } } class C_RecycledNumbers { public C_RecycledNumbers(int cnt, BufferedReader infile, BufferedWriter outfile) throws IOException { for (int i = 0; i < cnt; i++) { String[] ln = infile.readLine().trim().split("" ""); int a = Integer.parseInt(ln[0]); int b = Integer.parseInt(ln[1]); int len = ln[0].length(); int rescnt = 0; String[] rvals = new String[len]; int rvc; for (int v = a; v <= b; v++) { String val = Integer.toString(v); if (val.length() < len) val = ""0000000000"".substring(0, len - val.length()) + val; rvc = 0; for (int r = 1; r < len; r++) { String rval = val.substring(len - r) + val.substring(0, len - r); int rv = Integer.parseInt(rval); if (rv > v && rv <= b) { boolean isnew = true; for (int k = 0; k < rvc; k++) if (rvals[k].equals(rval)) isnew = false; if (isnew) { rvals[rvc++] = rval; rescnt++; } // else // for (int k = 0; k < rvc; k++) { // outfile.write(String.format(""%s <= %s < %s <= %s\r\n"", ln[0], val, rval, ln[1])); // } } } } outfile.write(String.format(""Case #%d: %d\r\n"", i + 1, rescnt)); } } } class D_HallOfMirrors { public D_HallOfMirrors(int cnt, BufferedReader infile, BufferedWriter outfile) throws IOException { } } } " B12303,"package com.mohit.codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; public class RecycledNumbers { public static void main(String[] args) { try { int noOfTests = 0; FileInputStream fis = new FileInputStream(""C-small-attempt2.txt""); DataInputStream din = new DataInputStream(fis); BufferedReader br = new BufferedReader(new InputStreamReader(din)); FileWriter fstream = new FileWriter(""output.txt""); BufferedWriter out = new BufferedWriter(fstream); String strLine; strLine = br.readLine(); if (strLine == null || strLine == """") return; strLine = strLine.trim(); noOfTests = Integer.parseInt(strLine); int testNumber = 1; while (noOfTests > 0) { strLine = br.readLine(); if (strLine == null || strLine == """" || strLine == ""\n"") break; strLine = strLine.trim().toLowerCase(); String[] nums = strLine.split("" ""); int A = Integer.parseInt(nums[0].trim()); int B = Integer.parseInt(nums[1].trim()); int firstCharB = Integer.parseInt(String.valueOf(B).charAt(0) +""""); int recycledNum = 0; for (int i = A; i <= B; i++) { String n = String.valueOf(i); if (Integer.parseInt(n.substring(n.length() - 1)) > firstCharB) { int check = i; while(check>0) { int nexti = check % 10; if(nexti < firstCharB) break; else check = check/10; } if(check == 0) { i = i + (10 - i%10); continue; } } { int condition = 0; if (n.length() % 2 == 0 && n.substring(0, n.length() / 2).equals( n.substring(n.length() / 2))) { condition = n.length() / 2; } else { condition = n.length(); } for (int j = 1; j < condition; j++) { String m = n.substring(j) + n.substring(0, j); int mi = Integer.parseInt(m); if (mi <= i || mi > B) continue; recycledNum++; } } } out.write(""Case #"" + testNumber + "": "" + recycledNum + ""\n""); testNumber ++; } br.close(); out.close(); } catch (Exception e) { System.out.print(e.getMessage()); } } } " B12319,"import java.util.*; class QC{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int kase = sc.nextInt(); for(int k = 1; k<=kase; k++){ int A = sc.nextInt(); int B = sc.nextInt(); int count = 0; for(int x= A; xx && cyc[i] <=B && (i==0 || cyc[i]!=cyc[i-1])) count++; } } System.out.println(""Case #""+k+"": ""+count); } } } " B12643,"package QR_2012; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; import java.util.TreeSet; public class C { static BufferedWriter writer; public static void main(String[] args) throws IOException { writer = new BufferedWriter(new FileWriter(""output.out"")); Scanner reader = new Scanner(new FileReader(""input.in"")); int nt = reader.nextInt(); reader.nextLine(); for(int tc = 1; tc <= nt; tc++) { writer.write(""Case #"" + tc + "": ""); int a = reader.nextInt(); int b = reader.nextInt(); int total = 0; for(int n = a; n < b; n++) { int count = count(n, b); total += count; } writer.write(Integer.toString(total)); writer.newLine(); } writer.close(); } static int count(int n, int b) { int count = 0; String s = Integer.toString(n); int l = s.length(); TreeSet T = new TreeSet(); for(int i = 1; i < l; i++) { s = s.substring(1) + s.charAt(0); if(!T.contains(s)) { T.add(s); int m = Integer.parseInt(s); if(n < m && m <= b) { count++; } } } return count; } } " B11353,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class ProblemC { public static void main(String[] args) { try (BufferedReader reader = new BufferedReader(new FileReader(""C-small.in""))) { try (BufferedWriter writer = new BufferedWriter(new FileWriter(""C-small.out""))) { String line = reader.readLine(); int numCases = Integer.parseInt(line); Scanner scanner; for(int caseIdx = 0; caseIdx < numCases; caseIdx++) { scanner = new Scanner(reader.readLine()); int A = scanner.nextInt(); int B = scanner.nextInt(); int result = 0; String sA = String.valueOf(A); String sB = String.valueOf(B); Set vs = new HashSet<>(); for(int t = A; t <= B; t++) { String st = String.valueOf(t); for(int s = 1; s < st.length(); s++) { if(st.charAt(s) == '0') continue; // no leading zeroes String ost = st.substring(s) + st.substring(0, s); if(st.compareTo(ost) > -1) continue; if(ost.compareTo(sB) > 0) continue; if(ost.compareTo(sA) < 0) continue; vs.add( st + ""_"" + ost); vs.add(ost + ""_"" + st); } } result = vs.size() / 2; String caseOutput = String.format(""Case #%d: %d"", caseIdx + 1, result); System.out.println(caseOutput); writer.append(caseOutput); writer.newLine(); } } } catch(IOException ioEx) { ioEx.printStackTrace(); } } } " B12155,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.File; import java.util.Map; import java.util.HashMap; public class GCJ_qr_c { /** * @param args */ public static void main(String[] args) { GCJReader in = new GCJReader(args[0]); GCJWriter out = new GCJWriter(args[1]); int numTestCases = Integer.parseInt(in.readLine()); HashMap map = new HashMap(); for(int i = 1; i <= numTestCases; i+=1) { String[] inLine = in.readLine().split("" ""); final int A = Integer.parseInt(inLine[0]); final int B = Integer.parseInt(inLine[1]); final int numDigits = inLine[0].length(); int count = 0; for(int j = A; j <= B; j += 1 ) { //start running through the numbers from A to B, looking for recycled numbers String n = Integer.toString(j); //start rearranging blocks of digits for(int k = 1; k < numDigits; k+=1) { //Get our n, as a String for rearranging //Get the block of digits to move to the front of n from String nBlock = n.substring(n.length() - k); //Get the ""remainder"" digits, the digits not being moved to the front String nFront = n.substring(0, n.length() - k); //Build m String m = nBlock + nFront; //check if the (n, m) pair is recycled int mVal = Integer.parseInt(m); int nVal = Integer.parseInt(n); if(!(mVal < A || mVal > B || mVal <= nVal || map.containsKey(mVal))) { map.put(mVal, nVal); count++; } } map.clear(); } String outLine = """" + count; out.writeLine(String.format(""Case #%d: %s"", i, outLine)); } } private static class GCJWriter { private String outFile = null; private BufferedWriter out = null; public GCJWriter(String outFile) { this.outFile = outFile; try { out = new BufferedWriter(new FileWriter(outFile)); } catch (Exception e) { throw new RuntimeException(e); } } public void writeLine(String output) { try { out.write(output + ""\n""); out.flush(); } catch (Exception e) { throw new RuntimeException(e); } } } private static class GCJReader { private String inFile = null; private BufferedReader in = null; public GCJReader(String inFile) { this.inFile = inFile; try { in = new BufferedReader(new FileReader(inFile)); } catch (Exception e) { throw new RuntimeException(e); } } public String readLine() { try { return in.readLine(); } catch (Exception e) { throw new RuntimeException(e); } } } }" B13132,"package y2012.quals; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; public class C { public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new File(""C.in"")); PrintWriter out = new PrintWriter(new File(""C.out"")); int nTestCase = Integer.parseInt(in.nextLine()); int[] stepeni = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000 }; for (int testCase = 0; testCase < nTestCase; testCase++) { int a = in.nextInt(); int b = in.nextInt(); int res = a - 1; int brCif = 0; while (res > 0) { brCif++; res /= 10; } HashSet hs = new HashSet(); for (int i = a; i <= b; i++) { if (i == stepeni[brCif]) brCif++; int tmp = i; for (int j = 1; j < brCif; j++) { tmp = (tmp % 10) * stepeni[brCif - 1] + tmp / 10; if (i < tmp && tmp <= b && !hs.contains(tmp)) { res++; hs.add(tmp); } } hs.clear(); } out.println(""Case #"" + (testCase + 1) + "": "" + res); } in.close(); out.close(); } } " B12167,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { public static void main(String[] args) throws IOException { FileReader fReader = new FileReader(""input/C-small-attempt0.in""); BufferedReader br = new BufferedReader(fReader); int T = Integer.valueOf(br.readLine()); int c = 1; while (T-- > 0) { String[] line = br.readLine().split(""\\s""); Integer first = Integer.valueOf(line[0]); Integer second = Integer.valueOf(line[1]); Set set = new HashSet(); int totalCount = 0; for (int i = first; i <= second; ++i) { String ll = String.valueOf(i); for (int j = 1; j < ll.length(); ++j) { String tempLine = ll.substring(ll.length() - j); tempLine += ll.substring(0, ll.length() - j); if (tempLine.startsWith(""0"")) { continue; } int secondNum = Integer.valueOf(tempLine); if (i >= secondNum || secondNum > second) { continue; } String ss = i + ""|"" + secondNum; if (set.contains(ss)) { continue; } set.add(ss); totalCount++; // System.out.println(ss); } } System.out.println(""Case #"" + c + "": "" + totalCount); c++; } fReader.close(); } } " B11711,"package com.google.codejam._2012; import java.io.File; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { private void setup() { } public void solveCases() throws Exception { setup(); Scanner s = new Scanner(new File(""./input/C-small-attempt0.in"")); int t = s.nextInt(); for(int i = 0; i < t; i++) solveProblem(s, i + 1); } private void solveProblem(Scanner s, int num) { System.out.print(""Case #"" + num + "": ""); int a = s.nextInt(); int b = s.nextInt(); int count = 0; HashSet used = new HashSet(); for(int n = a; n < b; n++) { used.clear(); String ns = Integer.toString(n); for(int split = 1; split < ns.length(); split++) { String ms = ns.substring(split) + ns.substring(0, split); if (ms.startsWith(""0"")) continue; if (used.contains(ms)) continue; int m = Integer.parseInt(ms); if (m > n && m <= b) { used.add(ms); count++; } } } System.out.println(count); } public static void main(String[] args) { RecycledNumbers rn = new RecycledNumbers(); try { rn.solveCases(); } catch (Exception e) { e.printStackTrace(); } } } " B10941,"package gcj2012.qual; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { final boolean DEBUG = false; final String PACKAGE = ""gcj2012/qual""; final String PROBLEM = ""C""; @SuppressWarnings(""unchecked"") void run(){ if(!DEBUG){ try { System.setIn(new FileInputStream(new File(""./src/""+PACKAGE+""/""+PROBLEM+""-small.in""))); // System.setIn(new FileInputStream(new File(""./src/""+PACKAGE+""/""+PROBLEM+""-large.in""))); System.setOut(new PrintStream(new File(""./src/""+PACKAGE+""/""+PROBLEM+""-small_out.txt""))); // System.setOut(new PrintStream(new File(""./src/""+PACKAGE+""/""+PROBLEM+""-large_out.txt""))); } catch (FileNotFoundException e) { e.printStackTrace(); } } Scanner sc = new Scanner(System.in); int T = sc.nextInt(); int N = 2000000; Set[] s = new Set[N+1]; for(int x=1;x<=N;x++){ s[x] = new HashSet(); String t = x+""""; int n = t.length(); for(int i=0;i findAllPermutationsWithDigits(Integer nb, Integer nbDigitsToMove, Integer min, Integer max) { List resListTmp = new ArrayList(); Integer tmpRes = this.moveNDigits(nb, nbDigitsToMove); if (tmpRes > nb && tmpRes >= min && tmpRes <= max) { resListTmp.add(tmpRes); } Set set = new HashSet(); set.addAll(resListTmp); ArrayList resList = new ArrayList(set); return resList; } public List findAllPermutations(Integer nb, Integer min, Integer max) { String strNb = nb.toString(); List resListTmp = new ArrayList(); for (int i = 1; i < strNb.length(); i++) { List resListTmp2 = this.findAllPermutationsWithDigits(nb, i, min, max); resListTmp.addAll(resListTmp2); } Set set = new HashSet(); set.addAll(resListTmp); ArrayList resList = new ArrayList(set); return resList; } public Integer findRes(int min, int max) { Integer res = 0; for (int i = min; i < max + 1; i++) { List tmpList = this.findAllPermutations(i, min, max); res += tmpList.size(); } return res; } //lecture pour le fichier de recherche public List readFile(String nFichier) { List res = new ArrayList(); String nomFichier = chemin + nFichier; try { BufferedReader in = new BufferedReader(new FileReader(nomFichier)); String line =in.readLine(); while ((line = in.readLine()) != null) { res.add(line); } in.close(); } catch (Exception e) { e.printStackTrace(); } return res; } //écrit le résultat des trie public void writeFile(List content, String nFichier) { String nomFichier = chemin + nFichier; try { PrintWriter out = new PrintWriter(new FileWriter(nomFichier)); Iterator it = content.iterator(); int cpt = 1; while (it.hasNext()) { String str = (String) it.next(); out.println(""Case #"" + cpt + "": "" +str); cpt++; } out.close(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String args[]) { Permutation pm = new Permutation(); List inputList = pm.readFile(""C-small-attempt0.in""); Iterator it = inputList.iterator(); List resList = new ArrayList(); while (it.hasNext()) { String resTmp = (String)it.next(); String str[] = resTmp.split("" ""); Integer res = pm.findRes(Integer.parseInt(str[0]), Integer.parseInt(str[1])); resList.add(Integer.toString(res)); } pm.writeFile(resList, ""toto.txt""); } } " B11256,"package com.gzroger.codejam2012; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class QC { /** * @param args */ public static void main(String[] args) { try { BufferedReader reader = new BufferedReader(new FileReader(args[0])); int nCases = Integer.parseInt( reader.readLine() ); for (int iCases=0; iCases=1) { Z = Z/10; N++; } for (int n=A; n<=B; n++) { Set hmInt = new HashSet(); for (int j=1; j (); String s = Integer.toString(n); //System.out.println(s); for(int i = 0; i < l; i++) { if( Integer.valueOf(s) >= a && Integer.valueOf(s) <= b ) { list.add(new Integer(s)); } s = s.substring(1)+s.charAt(0); System.out.println(s); } //System.out.println(list.size()); } public int n; public int l; public int a; public int b; public Set list; public int[] getList() { Integer[] ans1 = new Integer[list.size()]; int[] ans = new int[list.size()]; ans1 = list.toArray(ans1); //System.out.println(ans1.length); for(int i = 0; i < ans.length; i++) { ans[i] = ans1[i].intValue(); //System.out.println(ans[i]); } return ans; } } public static void main(String args[]) throws IOException { BufferedReader in = new BufferedReader(new FileReader(""C-small-attempt0.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""rnum2.out""))); StringTokenizer st; int n = Integer.parseInt(in.readLine()); for(int i = 0; i < n;i++) { st= new StringTokenizer(in.readLine()); out.println(""Case #"" +(1+i)+"": "" +Recycle(Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()) ) ); } in.close(); out.close(); } public static int Recycle(int p1, int p2) { int len = Integer.toString(p1).length(); int ans = 0; System.out.println(""New case p1 = "" + p1 +"" New case p2 = "" + p2); if(len <= 1) { ans = 0; } else { int j = p2-p1+1; boolean[] y = new boolean[j]; ArrayList a = new ArrayList(); java.util.Arrays.fill(y, true); int[] q; for(int i = p1; i <= p2 ; i++) { if(y[i-p1] ) { a.add(new permNum( i, len,p1,p2)); q = a.get(a.size()-1).getList(); System.out.println((i)+"" ""+q.length); if(q.length>1) { ans += (q.length-1)*(q.length)/2; for(int k = 0; k < q.length;k++) { if(q[k] >= p1 && q[k] <= p2&& q.length>1) { //System.out.println(q[k]); y[q[k]-p1] = false; } } } } } } return ans; } } " B10596,"import java.io.*; import java.util.*; /** * * @author posv */ public class Recycle{ public static void main(String[] args){ int cs = 0; int a,b,n,m; int temp1, temp2,total,len; double temp; total = 0; try{ File file = new File(""lines2.txt""); BufferedReader reader = new BufferedReader(new FileReader(file)); String line = null; while ((line = reader.readLine()) != null){ String[] tokens = line.split("" ""); Set ints = new HashSet(); if(cs==0){ cs++; continue; } else { a = Integer.parseInt(tokens[0]); b = Integer.parseInt(tokens[1]); len = tokens[0].length(); if(len == 1){ System.out.println(""Case #"" +cs+"": "" + 0); }else{ for(int i=a;i<=b;i++){ int k = len; int j=10; temp1 = i; while(j<=(Math.pow(10,len-1))){ temp2 = (int)(temp1%(j)*(Math.pow(10,k-1))) + (int)(temp1/j); if(temp1>= i && temp1 <= b && temp2<=b && temp1 < temp2){ total++; temp = temp1*(Math.pow(10,len)) + temp2; ints.add(temp); } k--; j=j*10; } } System.out.println(""Case #"" +cs+"": "" + ints.size()); } } cs++; } } catch(Exception ex){ ex.printStackTrace(); } } } " B12651,"import java.util.*; import java.io.*; public class Recycle { public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new FileReader(""C-small-attempt0.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""Recycle.out""))); StringTokenizer st; st = new StringTokenizer(f.readLine()); int T = Integer.parseInt(st.nextToken()); int A, B; int numDigit; int temp, temp1, temp2, tempPow; int countRecycle; int[] result = new int[T]; boolean[] set = new boolean[3000]; for(int i = 0; i < T; i++) { for(int j = 0; j < 1000; j++) set[j] = false; st = new StringTokenizer(f.readLine()); A = Integer.parseInt(st.nextToken()); B = Integer.parseInt(st.nextToken()); for(int j = A; j <= B; j++) { countRecycle = 1; if(set[j]) continue; else { set[j] = true; numDigit = 1; while(j/(int)Math.pow(10, numDigit) != 0) numDigit++; for(int k = 1; k < numDigit; k++) { tempPow = (int) Math.pow(10, k); temp1 = j/tempPow; temp2 = j - temp1 * tempPow; // System.out.println(""j: "" + j + ""\ntemp1: "" + temp1 + ""\ntemp2: "" + temp2 + ""\ntempPow: "" + tempPow); if(temp2*10 / tempPow == 0) continue; temp = temp2 * (int) Math.pow(10, numDigit - k) + temp1; // System.out.println(""j: "" + j + ""\ntemp1: "" + temp1 + ""\ntemp2: "" + temp2 + ""\ntemp:"" + temp); if( (A <= temp) && ( temp <= B) && (!set[temp]) ) { set[temp] = true; countRecycle++; } } } result[i] += countRecycle * (countRecycle - 1) / 2; } } for(int i = 0; i < T; i++) { out.println(""Case #"" + (i + 1) + "": "" + result[i]); } out.close(); } } " B10916,"import java.util.Scanner; public class C { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int nCases = sc.nextInt(); for (int i = 1; i <= nCases; i++) { int zzz = 0; int a = sc.nextInt(); int b = sc.nextInt(); for (int aa = a; aa <= b; aa++) { for (int bb = aa + 1; bb <= b; bb++) { if (isRecycled(aa, bb)) { zzz++; } } } System.out.println(""Case #"" + i + "": "" + zzz); } } private static boolean isRecycled(int aa, int bb) { int nDigits = 0; int temp = aa; while (temp > 0) { nDigits++; temp = temp / 10; } for (int zxc = 1; zxc < nDigits; zxc++) { int tempa = aa; tempa = (tempa % (int) Math.pow(10, zxc)) * (int) Math.pow(10,(nDigits - zxc)) + tempa / (int) Math.pow(10, zxc); if (tempa == bb) return true; } return false; } } " B11272,"import java.util.*; import java.io.*; public class Recycle { public static void main(String[] args) { Scanner in = new Scanner(new BufferedInputStream(System.in)); int T = in.nextInt(); for(int i=0; i =10) { x = x/10; digits++; } //System.out.println(""digits: "" + digits); int sum = 0; int[] m = new int[digits-1]; for(int k = 0; k < m.length; k++) m[k] = (k+1)*-1; for(int j = A; j < B; j++) { //reset m for(int k = 0; k < m.length; k++) m[k] = (k+1)*-1; //try every possible combination //count it if j < combo < B for(int k = 1; k < digits; k++) { int divisor = (int) Math.pow(10,k); int multiplier = (int)Math.pow(10,digits-k); int temp = (j%divisor)*multiplier + j/divisor; //if all digits the same skip String number = Integer.toString(temp); if(number.matches(""^([0-9])\\1*$"")) continue; if(temp > j && temp <= B) { m[k-1] = temp; sum++; } } //if redundancy subtract Arrays.sort(m); for(int k = 1; k < m.length; k++) if(m[k] == m[k-1]) sum--; } System.out.printf(""Case #%d: %d\n"",i+1,sum); } } }" B12989,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.ArrayList; public class RecycledNumbers { public static void main(String args[]) { FileInputStream fstream; FileOutputStream out; try { fstream = new FileInputStream( ""C:\\Users\\inkrabh\\Downloads\\C-small-attempt0.in""); out = new FileOutputStream( ""C:\\Users\\inkrabh\\Downloads\\C-small-attempt0.out""); DataInputStream in = new DataInputStream(fstream); PrintStream p = new PrintStream(out); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; strLine = br.readLine(); int noOfTestCases = Integer.parseInt(strLine); for (int i = 1; i <= noOfTestCases; i++) { strLine = br.readLine(); int result = findNoOfPairs(strLine.split("" "")[0], strLine.split("" "")[1]); p.println(""Case #"" + i + "": "" + result); } in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static int findNoOfPairs(String start, String end) { int count = 0; ArrayList existingList = new ArrayList(); int begin = Integer.parseInt(start); int last = Integer.parseInt(end); for (int i = begin; i <= last; i++) { String sNum = new String((new Integer(i)).toString()); existingList.add(sNum); String recycles[] = getRecycledNums(sNum); ArrayList matchList = new ArrayList(); for (int j = 0; j < recycles.length; j++) { String temp = recycles[j]; if (!matchList.contains(temp) && !existingList.contains(temp) && temp.charAt(0) != '0' && temp.compareTo(end) <= 0 && temp.compareTo(start) >= 0 && !temp.equals(sNum)) { matchList.add(temp); count++; } } } return count; } static String[] getRecycledNums(String sNum) { String s[] = new String[sNum.length() - 1]; for (int i = 1; i < sNum.length(); i++) { String temp = sNum.substring(i) + sNum.substring(0, i); s[i - 1] = temp; } return s; } } " B10201,"package cj.sample; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class C2012 { BufferedReader br; PrintWriter pw; /** * @param args */ public static void main(String[] args) { C2012 c2012 = new C2012(); c2012.processInput(); } public void processInput(){ initInFile(""/home/Vijitha/GCJ/Testdata/C-small-attempt0.in""); initOutFile(""/home/Vijitha/GCJ/Testdata/C-small-attempt0.out""); try{ String l = """"; // First line l = br.readLine(); int indx = 1; while((l = br.readLine()) != null){ String[] ary = l.split("" ""); int firstNumber = Integer.parseInt(ary[0]); int secondNumber = Integer.parseInt(ary[1]); int count = getCount(firstNumber, secondNumber); pw.println(""Case #"" + indx + "": "" + count); indx++; } br.close(); pw.close(); }catch(IOException ex){ ex.printStackTrace(); } } private int getCount(int firstN, int secondN){ int count = 0; String firstString = String.valueOf(firstN); String secondString = String.valueOf(secondN); if(firstString.length() != secondString.length()) return 0; String fDigit = Character.toString(firstString.charAt(0)); if(firstString.length() == 1) return 0; if(firstString.length() == 2){ String sDigit = Character.toString(firstString.charAt(1)); while(firstN < secondN){ firstString = String.valueOf(firstN); fDigit = Character.toString(firstString.charAt(0)); sDigit = Character.toString(firstString.charAt(1)); int swapN = Integer.parseInt(sDigit + fDigit); if(swapN > firstN && swapN <= secondN){ count++; } firstN++; } } if(firstString.length() == 3){ String sDigit = Character.toString(firstString.charAt(1)); String tDigit = Character.toString(firstString.charAt(2)); while(firstN < secondN){ firstString = String.valueOf(firstN); fDigit = Character.toString(firstString.charAt(0)); sDigit = Character.toString(firstString.charAt(1)); tDigit = Character.toString(firstString.charAt(2)); int swapl = Integer.parseInt(tDigit + fDigit + sDigit); if(swapl > firstN && swapl <= secondN) count++; int swapBoth = Integer.parseInt(sDigit + tDigit + fDigit); if(swapBoth > firstN && swapBoth <= secondN) count++; firstN++; } } return count; } public void initInFile(String name){ try{ br = new BufferedReader(new FileReader(name)); }catch(FileNotFoundException fnfe){ fnfe.printStackTrace(); } } public void initOutFile(String name){ try{ pw = new PrintWriter(new FileWriter(name)); }catch(IOException ex){ ex.printStackTrace(); } } } " B12248,"import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Scanner; public class RecycledNumber { // static HashMap> cache; public static void main(String[] args) throws IOException{ String path = ""C:\\Users\\Rapol Tongchenchitt\\Documents\\CodeJam\\""; String year = ""Qual2012\\""; String test = ""input.txt""; String outPath = ""output.txt""; String a = """"; String A = """"; String b = """"; String B = """"; String c = ""C-small-attempt0.in""; String C = ""C-small-attempt0.out""; String d = """"; String D = """"; String inName = path+year+c; String outName = path+year+C; Scanner in = new Scanner(new FileInputStream(inName)); BufferedWriter out = new BufferedWriter(new FileWriter(outName)); int caseCount = in.nextInt(); int currentCase = 0; while(currentCase++ < caseCount){ int minNum = in.nextInt(); int maxNum = in.nextInt(); int ans = 0; for( int i = minNum; i <= maxNum; i++){ ans += perform(i, minNum, maxNum); } out.write(""Case #"" + currentCase + "": "" + ans); out.newLine(); } out.close(); } private static int perform(int in, int left, int right) throws IOException{ if(in < 10){ return 0; } HashSet set = new HashSet(); int ans = 0; String now = in + """"; for(int i = 1; i < now.length(); i++){ if(now.charAt(i) >= now.charAt(0)){ int shift = Integer.parseInt(now.substring(i) + now.substring(0,i)); if(shift > in && shift <= right && shift >= left && !set.contains(shift)){ ans++; set.add(shift); } } } return ans; } } " B10320,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; public class C_RecycledNumbers { static int a; static int b; static HashSet set; public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(new File(""Cin.txt"")); PrintWriter writer = new PrintWriter(new File(""Cout.txt"")); int t = sc.nextInt(); for (int i = 1; i <= t; i++) { a = sc.nextInt(); b = sc.nextInt(); int count = 0; set = new HashSet(); for (int j = a; j <= b; j++) { count += get(j); } writer.println(""Case #"" + i + "": "" + count / 2); } writer.close(); } private static int get(int j) { String s = j + """"; int n = s.length(); int count = 0; HashSet set1 = new HashSet(); for (int i = 0; i < n - 1; i++) { String ss = s.substring(1) + s.charAt(0) + """"; s = ss; int x = Integer.parseInt(ss); if (x >= a && x <= b && s.charAt(0) != '0' && !set1.contains(x)) { if (j != x) { set1.add(x); count++; } } } return count; } } " B12942,"package com.menzus.gcj._2012.qualification.c; import java.util.Iterator; import com.menzus.gcj.common.InputBlockParser; public class CInputBlockParser implements InputBlockParser { @Override public CInput parseLineIterator(Iterator lineIterator) { String[] lineParts = lineIterator.next().split("" ""); CInput input = new CInput(); input.setLowerLimit(Integer.parseInt(lineParts[0])); input.setUpperLimit(Integer.parseInt(lineParts[1])); return input; } } " B10336,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class CodeJam { private static final String FILE_NAME = ""E:/workspace/codejam_module/C-small-attempt0.in""; public static void main(String[] args) throws IOException { File file = new File(FILE_NAME); BufferedReader in = new BufferedReader(new FileReader(file)); StringBuilder builder = new StringBuilder(); SolverModule solver = new CSolver(); builder = solver.process(in, builder); System.out.println(builder); file = new File(FILE_NAME.concat("".result"")); FileWriter fileWriter = new FileWriter(file); fileWriter.append(builder); fileWriter.flush(); fileWriter.close(); } } " B11812,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Competitiopn; import java.util.Scanner; /** * * @author vidz */ public class RecycledNumbers { public void solve() { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); int i = 0, j = 0, k = 0; int count = 0; int A = 0, B = 0, n = 0, m = 0, a = 0, b = 0;//A ≤ n < m ≤ B String nn = """"; String mm = """"; while (i < T) { // System.out.println(""a""); n = A = sc.nextInt(); m = B = sc.nextInt(); count = 0; while (n <= B) { // System.out.println(""a""); while (m >= A && m > n) { // System.out.println(""b""); nn = String.valueOf(n); mm = ""["" + String.valueOf(m) + ""]""; // System.out.println(""nn == : "" + nn + "" mm == : "" + mm); if (nn.length()==(mm.length()-2) && nn.replaceAll(mm, """").equals("""") ) { // System.out.println(""ccc""); if (isCorrect(n, m)) { count++; } } --m; } m = B; ++n; } System.out.println(""Case #""+(i+1)+"": "" + count); ++i; } } // length n == lengt m public boolean isCorrect(int n, int m) { String nn = String.valueOf(n); String mm = String.valueOf(m); int len = nn.length(); int i = 0; if (nn.equals(mm) && len > 1) { return true; } else { i = 1; while (i < len) { if (nn.charAt(i) == mm.charAt(0) && nn.charAt(i - 1) == mm.charAt(len - 1)) { String tem = nn.substring(i, len) + nn.substring(0, i); if (tem.equals(mm)) { return true; } } ++i; } } return false; } public static void main(String[] args) { new RecycledNumbers().solve(); /* * String s = ""12345""; String tem = s.substring(2, s.length()) + * s.substring(0, 2); System.out.println(tem); String a = ""21345""; * String ss = ""["" + a + ""]""; //String e = s.replaceAll(ss, """"); * //System.out.println(""e is = "" + e); * * if(s.replaceAll(ss, """").equals("""")){ * System.out.println(""aaaaaaaaaaaaaa""); }else{ * System.out.println(""bbbbbbbbbbbbb""); } */ } } " B10286,"package Qualification; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.LinkedList; import java.util.Scanner; public class ProblemC { // brute force approach public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); String output = ""./result.txt""; BufferedWriter writer = new BufferedWriter(new FileWriter(output)); int T = in.nextInt(); for (int caseNum = 1; caseNum <= T; caseNum++) { int A = in.nextInt(); int B = in.nextInt(); int count = 0; for (int m = A + 1; m <= B; m++) { for (int n = A; n < m; n++) { if (isRecycledPair(n + """", m + """")) count++; } } String toPrint = ""Case #"" + caseNum + "": "" + count; System.out.println(toPrint); writer.write(toPrint + ""\r\n""); } writer.flush(); writer.close(); } private static boolean isRecycledPair(String n, String m) { int sizeDiff = Math.abs(n.length() - m.length()); for (int i = 0; i < sizeDiff; i++) { n = ""0"" + n; } int size = n.length(); if (n.equals(m)) return true; for (int i = 1; i < size; i++) { n = n.substring(1, size) + n.charAt(0); if (n.equals(m)) return true; } return false; } } " B11813,"/** * Google CodeJam 2012 * Qualification round - Problem C * Recycled Numbers * * Solved by Üllar Soon */ package eu.positivew.codejam.recycled; /** * Recycled Numbers integer pair (m, n). * * @author Üllar Soon */ public class IntPair { private int n, m; public IntPair(int n, int m) { this.n = n; this.m = m; } public int getN() { return n; } public void setN(int n) { this.n = n; } public int getM() { return m; } public void setM(int m) { this.m = m; } @Override public boolean equals(Object o) { IntPair compTo = (IntPair)o; if(n == compTo.getN() && m == compTo.getM()) return true; else return false; } } " B10860,"package be.mokarea.gcj.recyclednumbers; import java.io.PrintWriter; import java.util.HashSet; import be.mokarea.gcj.common.TestCaseReader; import be.mokarea.gcj.common.Transformation; public class RecycledNumbersTransformation extends Transformation { public RecycledNumbersTransformation( TestCaseReader caseReader, PrintWriter outputWriter) { super(caseReader, outputWriter); } @Override protected String transform(RecycledNumbersTestCase testCase) { HashSet setOfN_M = new HashSet(); final int a = testCase.getA(); final int b = testCase.getB(); for (int n = a; n <= b; n++) { for (int m : recycledNumberOf(n)) { if ( a <= n && n < m && m <= b) { setOfN_M.add(new PairOfInteger(n,m)); } } } return formatOutput(testCase.getCaseNumber(), setOfN_M.size()); } private String formatOutput(int caseNumber, int nbMatches) { StringBuffer buf = new StringBuffer(); buf.append(""Case #""); buf.append(caseNumber); buf.append("": ""); buf.append(nbMatches); return buf.toString(); } private HashSet recycledNumberOf(int n) { HashSet recycledNumbers = new HashSet(); String nAsString = String.valueOf(n); for (int nbDigit = 1 ; nbDigit < nAsString.length(); nbDigit++) { final String end = nAsString.substring(nbDigit, nAsString.length()); final String front = nAsString.substring(0, nbDigit); final String n2 = end + front; recycledNumbers.add(Integer.parseInt(n2)); } return recycledNumbers; } class PairOfInteger { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + m; result = prime * result + n; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PairOfInteger other = (PairOfInteger) obj; if (m != other.m) return false; if (n != other.n) return false; return true; } private final int n; private final int m; PairOfInteger(int n, int m) { this.n = n; this.m = m; } } } " B12265," import java.io.File; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; public class C { public static void main(String args[]) throws Exception { final String PATH = ""/home/goalboy/software installation/codejam-commandline-1.0-beta4/source/""; final String FILE = ""C-small-0""; Scanner in = new Scanner(new File(PATH + FILE + "".in"")); PrintWriter out = new PrintWriter(PATH + FILE + "".out""); int test = in.nextInt(); for (int t = 1; t <= test; t++) { String strA = in.next(); int A = Integer.parseInt(strA); int B = in.nextInt(); int length = strA.length(); int result = 0; for (int n = A; n < B; n++) { String rotated = n + """"; HashSet setM = new HashSet(); for (int i = 0; i < length - 1; i++) { rotated = rotated.substring(1) + rotated.charAt(0); if (rotated.charAt(0) == '0') { continue; } int m = Integer.parseInt(rotated); if (m > n && m <= B) { setM.add(m); } } result += setM.size(); } out.println(""Case #"" + t + "": "" + result); } out.close(); } } " B11126,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; public class rec1 { public static void main(String args[]) throws Exception{ FileInputStream fs = new FileInputStream(""input2.txt""); DataInputStream in = new DataInputStream(fs); BufferedReader br=new BufferedReader(new InputStreamReader(in)); FileWriter fstream = new FileWriter(""output2.txt""); BufferedWriter out = new BufferedWriter(fstream); int T=Integer.parseInt(br.readLine()); for(int i=0;i0) { goo=0; A = sc.nextInt(); B = sc.nextInt(); temp = A; len=1; while(temp>=10) { temp = temp/10; len++; } System.out.println(A+ "" "" +B+ "" "" +len); for(int i=A; iA && no<=B && no>i){ //pw.println(i+"",""+no+"",""+j); goo++; } } } System.out.println(goo); pw.println(""Case #""+ ++count +"": ""+ goo); pw.flush(); T--; } pw.close(); }catch(Exception e){} } } " B11942,"import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.util.ArrayList; import java.util.HashMap; public class Main { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub FileInputStream fstream = null; try { fstream = new FileInputStream(""input.txt""); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; ArrayList plik = new ArrayList(); try { while ((strLine = br.readLine()) != null) { // Print the content on the console System.out.println(strLine); plik.add(strLine); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } plik.remove(0); // counter nie jest potrzebny int count = 1; FileWriter writer = null; try { writer = new FileWriter(""output.txt""); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } for (String s : plik) { StringBuilder outputString = new StringBuilder(""Case #"" + count++ + "": ""); int recycledPairsCount = 0; String[] splitted = s.split("" ""); Integer A = Integer.parseInt(splitted[0]); Integer B = Integer.parseInt(splitted[1]); int a = A; int b = B; for (int n = a; n < b; n++) { for (int m = n + 1; m <= B; m++) { if (Integer.toString(m).length() != Integer.toString(n) .length()) { continue; } if (isRecycledPair(n, m)) { recycledPairsCount += 1; } } } outputString.append(recycledPairsCount); System.out.println(outputString); try { writer.write(outputString.toString()); writer.write(""\r\n""); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static boolean isRecycledPair(int n, int m) { String N = Integer.toString(n); String M = Integer.toString(m); int digitNumber = N.length(); if (digitNumber == 1) { return false; } for (int i = 1; i <= digitNumber; i++) { String temp = N.substring(i, digitNumber); temp += N.substring(0, i); if (temp.equals(M)) { return true; } } return false; } } " B11832,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.Set; public class CopyOfCopyOfMain { static int ndigits(int n) { return (int) (Math.log10(n) + 1); } static int rot(int n, int dig) { return (int) ((n % 10) * Math.pow(10, dig - 1)) + (int) (n / 10); } public static void main(String[] args) throws FileNotFoundException { String file = ""C-small-attempt0""; Scanner in = new Scanner(new File(file + "".in"")); PrintWriter out = new PrintWriter(new File(file + "".out"")); int T = in.nextInt(); for (int t = 1; t <= T; t++) { int A = in.nextInt(); int B = in.nextInt(); int c = 0; int[] list = new int[ndigits(B)]; numbers: for (int i = A; i <= B; i++) { int digs = ndigits(i); int rot = i; int pairs = 0; Arrays.fill(list, -1); list[0] = i; digits: for (int j = 1; j <= digs + 1; j++) { rot = rot(rot, digs); if(rot < i) continue; if (A <= rot && rot <= B) { for (int k = 0; k < j; k++) { if (list[k] == rot) { continue digits; } } pairs++; list[j] = rot; } } //c += pairs * (pairs + 1) / 2; c += pairs ; // c+=digs; } out.println(""Case #"" + t + "": "" + c); } in.close(); out.close(); } } " B12100,"package codejam2012.qualification; import java.io.*; import java.math.BigInteger; import java.util.*; public class RecycledNumbers { // general part private static final String INPUT = ""src/main/resources""; private static final String OUTPUT = ""target/output""; private static final String ROUND = ""codejam2012/qualification""; private static final String SAMPLE = ""C-sample.in""; private static final String SMALL = ""C-small-attempt0.in""; private static final String LARGE = ""C-large.in""; private Scanner scanner; private PrintWriter writer; public RecycledNumbers(InputStream is, OutputStream os) { scanner = new Scanner(is); writer = new PrintWriter(os); } public void close() { scanner.close(); writer.flush(); } private static void runTest(String fileName, boolean isConsole) throws Exception { InputStream is = initInputStream(fileName); OutputStream os = initOutputStream(fileName, isConsole); RecycledNumbers problem = new RecycledNumbers(is, os); problem.solve(); problem.close(); doneStreams(isConsole, is, os); } private static InputStream initInputStream(String fileName) throws FileNotFoundException { File inputDir = new File(INPUT + File.separator + ROUND); File inputFile = new File(inputDir, fileName); InputStream is = new FileInputStream(inputFile); return is; } private static OutputStream initOutputStream(String fileName, boolean isConsole) throws FileNotFoundException { OutputStream os = System.out; if (isConsole) { System.out.println(fileName); System.out.println("" ---] cut [---""); } else { File outputDir = new File(OUTPUT + File.separator + ROUND); outputDir.mkdirs(); File outputFile = new File(outputDir, fileName.replace("".in"", "".out"")); os = new PrintStream(new FileOutputStream(outputFile)); } return os; } private static void doneStreams(boolean isConsole, InputStream is, OutputStream os) throws IOException { is.close(); if (isConsole) { System.out.println("" ---] cut [---""); System.out.println(""""); } else { os.close(); } } public static void main(String[] args) { try { runTest(SAMPLE, true); runTest(SMALL, false); // runTest(LARGE, false); } catch (Exception e) { e.printStackTrace(); } } // problem part /** * Solve the problem */ public void solve() { int t = scanner.nextInt(); for (int i = 1; i <= t; i++) { writer.print(""Case #""); writer.print(i + "": ""); int a = scanner.nextInt(); int b = scanner.nextInt(); writer.println(solve(a, b)); } } private long solve(int a, int b) { Set pairs = new HashSet(); for (int i=a; i<=b; i++) { char[] digits = getDigits(i); for (int j=0; j b)) { continue; } if (number <= i) { continue; } pairs.add(new Pair(i, number)); } } return pairs.size(); } private char[] getDigits(int i) { String string = ((Integer)i).toString(); return string.toCharArray(); } private int getNumber(char[] digits) { String string = new String(digits); return Integer.parseInt(string); } private void shift(char digits[]) { char first = digits[0]; for (int i=1; i compList = new ArrayList(); for(int test=1; test<=testcases; test++) { a = in.nextInt(); b = in.nextInt(); count = 0; while(a(); aString = String.valueOf(a); for(int i=1; i pairs = new HashSet(); pairs.add(nn); mark[nn - a] = true; for (int i = 0; i < len; i++) { nn = (nn % 10) * factor + nn / 10; if (nn >= a && nn <= b) { pairs.add(nn); mark[nn - a] = true; } } count += cn2(pairs.size()); } return count; } private static long cn2(int size) { long s = (long) size; return s * (s - 1) / 2L; } } " B10721,"public class recycled { public static void main(String args[]) { java.util.Scanner s = new java.util.Scanner(System.in); int T = s.nextInt(); for (int n = 1; n <= T; n++) System.out.println(""Case #"" + n + "": "" + f(s.nextInt(), s.nextInt())); } public static int f(int a, int b) { String A = """" + a; String B = """" + b; java.util.HashSet s = new java.util.HashSet(); for (int i = a; i <= b; i++) { String I = """" + i; for (int j = 1; j < I.length(); j++) { String x = I.substring(j) + I.substring(0, j); if (A.compareTo(x) <= 0 && B.compareTo(x) >= 0 && !I.equals(x)) if (x.compareTo(I) > 0) s.add(x+"":""+I); else s.add(I+"":""+x); } } return s.size(); } }" B12644," import java.util.*; import java.io.*; public class RecycledNum{ public static LinkedList routeList; public static LinkedList routeForOList; public static LinkedList routeForBList; public static List processed=new ArrayList(); public static void main(String[] args){ String fn = ""C:\\Users\\Ashu\\Desktop\\C-small-attempt0.in""; String fnOut = toFnOut(fn); String out=null; try{ //BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedReader br = new BufferedReader(new FileReader(fn)); BufferedWriter bw = new BufferedWriter(new FileWriter(fnOut)); String line = null; int NCase = Integer.valueOf(br.readLine()); int start=0; int end=0; for(int icase=0;icase10?start:12; for(int i=start;i<=end;i++){ List digits=getDigits(i); for(int j=1;j=start && i digits, int digitsMoved){ int result=0; int size=digits.size(); int num1=0,num2=0; for(int i=digitsMoved,j=1;i>0;i--,j++){ num1=num1+ digits.get(i-1)*(int)Math.pow(new Double(10), new Double(digits.size()-j)); } for(int i=size-1;i>=digitsMoved;i--){ num2=num2+ digits.get(i)*(int)Math.pow(new Double(10), new Double(i-digitsMoved)); } result=num1+num2; return result; } /** * * @param noOfDigits no of digits to be moved * @param num - total no of digits * @param digits - list of digits * @return */ static int moveDigits(int moveDigits, int totalDigits,List digits){ int result = 0; if(moveDigits==1){ if(totalDigits==2){ result = digits.get(0)*10+digits.get(1); } }else if(moveDigits==2){ }else if(moveDigits==3){ } return result; } static List getDigits(int num){ List digits = new ArrayList(); int t; while(num>0) { t=num%10; digits.add(t); num=num/10; } return digits; } static int countNoOfNonZeroDigits(int num){ int t; int count =0; while(num>0) { t=num%10; if(t!=0){ count=0; }else{ count++; } num=num/10; } return count; } static String toFnOut(String fn){ if(fn.lastIndexOf('.')!=-1){ return fn.substring(0,fn.lastIndexOf('.'))+"".out""; }else return fn + "".out""; } } " B11648,"package com.jp.common; public interface Puzzle { public String[] solve(String[] dataSet ); } " B11119,"package gcj2012; import java.io.FileInputStream; import java.io.PrintStream; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class C { public static void main(String[] args) throws Exception { new C().run(); } void run() throws Exception { Scanner in = new Scanner(System.in); in = new Scanner(new FileInputStream(""C-small-attempt0.in"")); // in = new Scanner(new FileInputStream(""C-large.in"")); PrintStream out = System.out; out = new PrintStream(""C-small-attempt0.out""); // out = new PrintStream(""C-large.out""); int T = in.nextInt(); for (int x = 1; x <= T; x++) { int A = in.nextInt(); int B = in.nextInt(); out.printf(""Case #%d: %d\n"", x, countRecycled(A, B)); } } private int countRecycled(int a, int b) { int res = 0; int p0 = 1; while (p0 < b) p0 *= 10; for (int s = a; s <= b; s++) res += countRecycledStartingBy(a, b, s, p0); return res; } private int countRecycledStartingBy(int a, int b, int s, int p0) { int p = 1; Set recs = new TreeSet(); while (p < 1000000) { int end = s % p; int beg = s / p; int rec = end * p0 + beg; if (rec >= a && rec <= b && rec != s && s < rec) recs.add(rec); p *= 10; p0 /= 10; } return recs.size(); } } " B10408,"import java.io.*; import java.util.*; public class Main { Scanner in; PrintWriter out; static final String problemName = ""C""; static void asserT(boolean e) { if (!e) { throw new Error(); } } int solveOne(int a, int b) { int count = 0; int nDigits = ("""" + a).length(); int maxDivisor = 1; for (int i = 1; i < nDigits; i++) { maxDivisor *= 10; } for (int i = a; i <= b; i++) { int maxD = maxDivisor; int divisor = 10; ArrayList list = new ArrayList(); for (int j = 1; j < nDigits; j++) { if (i % divisor >= divisor / 10) { int rem = i % divisor; int top = i / divisor; int value = rem * maxD + top; if (!list.contains(value ) && i < value && value <= b) { //out.println(i + "": "" + value); list.add(value); count++; } } divisor *= 10; maxD /= 10; } } return count; } void solve() { int nTests = in.nextInt(); in.nextLine(); for (int i = 0; i < nTests; i++) { out.println(""Case #"" + (i+1) + "": "" + solveOne(in.nextInt(), in.nextInt())); } } void run() { try { in = new Scanner(new FileReader(""C:/GCJ/"" + problemName + "".in"")); out = new PrintWriter(new FileWriter(""C:/GCJ/"" + problemName + "".out"")); } catch (IOException e) { in = new Scanner(System.in); out = new PrintWriter(System.out); // throw new Error(); } try { solve(); } finally { out.close(); } } public static void main(String[] args) { new Main().run(); } }" B10328," import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Scanner; import java.util.Set; public class Recycle { public static void main (String[] args){ String output = """"; try { System.out.println(""start : "" + new java.util.Date().toString()); FileOutputStream fo = null; FileInputStream fi = null; fi = new FileInputStream(""F:\\adarsh\\codejam10\\codejam12\\src\\C-small-attempt0.in""); BufferedReader reader = new BufferedReader(new InputStreamReader(fi)); Scanner sc = new Scanner(reader); int testCases = sc.nextInt(); System.out.println(""test cases : "" + testCases); fo = new FileOutputStream(""F:\\adarsh\\codejam10\\codejam12\\src\\C-small.out""); PrintStream ps = new PrintStream(fo); sc.nextLine(); for (int i = 1; i <= testCases; i++) { output = """"; int j = 0; String data = sc.nextLine(); System.out.println(""data : "" + data); String[] dataarray = data.split("" ""); int lowerlimit = Integer.parseInt(dataarray[j++]); int upperlimit = Integer.parseInt(dataarray[j++]); sout(""lowerlimit"" , """"+lowerlimit); sout(""upperlimit"" , """"+upperlimit); int out = performWork(lowerlimit , upperlimit); sout(""out"" , """"+out); ps.println(""Case #""+i+"": "" + out); } ps.close(); fo.close(); System.out.println(""end : "" + new java.util.Date().toString()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static int performWork(int lowerlimit , int upperlimit) { int output = 0; java.util.ArrayList pairs = new ArrayList(); int templow = lowerlimit; for(; templow<= upperlimit ; templow++) { String temp = """"+templow; sout(""temp"" , temp); for(int i = 1 ; i < temp.length() ; i++) { int newnumber = Integer.parseInt(temp.substring(i) + temp.substring(0, i)); sout(""newnumber"" , """"+newnumber); if(newnumber >= lowerlimit && newnumber <= upperlimit && !((""""+newnumber).equals(temp))) { if(!pairexists(pairs , temp , """"+newnumber)) { String[] t = new String[2]; t[0] = temp; t[1] = """"+newnumber; pairs.add(t); output++; } } } } sout(""output"" , """"+output); return output; } private static boolean pairexists(java.util.ArrayList pairs , String temp , String newnumber) { for(int i = 0 ; i < pairs.size(); i++) { String[] t = (String[]) pairs.get(i); if((t[0].equals(temp) && t[1].equals(newnumber)) || (t[1].equals(temp) && t[0].equals(newnumber))) { sout(""pair exists"" , ""true""); return true; } } sout(""pair exists"" , ""false""); return false; } private static void sout(String str1 , String str2) { System.out.println(str1 + "" : "" + str2); } } " B10234,"import java.util.Scanner; public class C2 { /** * @param args */ public static void main(String[] args) { new C2(); } int a, b, nbrDigits; // All numbers that we have already seen boolean[] seen; C2() { Scanner sc = new Scanner(System.in); int nbrCases = sc.nextInt(); for (int i = 1; i <= nbrCases; ++i) { sc.nextLine(); System.out.print(""Case #"" + i + "": ""); a = sc.nextInt(); b = sc.nextInt(); nbrDigits = nbrDigits(a); seen = new boolean[b + 1]; for (int j = 0; j <= b; ++j) { seen[j] = false; } int result = 0; for (int j = a; j <= b; ++j) { result += nbrRecycledLocal(j); } System.out.println(result); } } /** * Get the number of recycled pairs starting from the given number * * @param start * the number to start from * @return the number of recycled pairs between a and b */ int nbrRecycledLocal(int start) { if (seen[start]) { return 0; } seen[start] = true; byte[] parts = separate(start); int hits = 0; for (int i = 1; i < nbrDigits; ++i) { int recycled = getRecycled(parts, i); if (recycled != start && recycled >= a && recycled <= b && !seen[recycled]) { ++hits; seen[recycled] = true; } } if (hits <= 1) { return hits; } int res = 1; for (int i = 2; i <= hits; ++i) { res += i; } return res; } /** * Get the number of digits in the given number * * @param number * the number * @return the number of digits in the number */ int nbrDigits(int number) { int digits = 0; while (number != 0) { number /= 10; digits++; } return digits; } /** * Separate the given number into its digits * * @param start * the number * @return an array with the digits of the number */ byte[] separate(int start) { byte[] res = new byte[nbrDigits]; for (int i = 0; i < nbrDigits; ++i) { res[nbrDigits - 1 - i] = (byte) (start % 10); start = start / 10; } return res; } /** * Get the recycled number given the start number and the number of steps to * move the digits * * @param start * the original number in digits * @param steps * the steps to take * @return the recycled number */ int getRecycled(byte[] start, int steps) { int res = 0; int factor = 1; int size = start.length; for (int i = 0; i < size; ++i) { int pos = (size - 1 - i + steps) % size; res += factor * start[pos]; factor *= 10; } return res; } } " B10340," import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Scanner; /** * * @author dafferianto */ public class RecycledNumbers { private static Scanner inputStream; private static PrintWriter outputStream; private static int T, lower, upper, counter, tempNumber, result; private static String numberString, tempNumberString; private static HashMap aHashMap; public static void main(String[] args) throws FileNotFoundException, IOException { try { inputStream = new Scanner(new FileReader(args[0])); outputStream = new PrintWriter(new FileWriter(""RecycledNumbersOutput.txt"")); T = inputStream.nextInt(); //T = Integer.parseInt(inputStream.nextLine()); for (int i = 0; i < T; i++) { // For each test case lower = inputStream.nextInt(); upper = inputStream.nextInt(); aHashMap = new HashMap(); //result = solve(lower, upper); //outputStream.println(""Case #"" + (i+1) + "": "" + result); outputStream.println(""Case #"" + (i+1) + "": "" + solve(lower, upper)); //System.out.println(""Case #"" + (i+1) + "": "" + result); } } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } } private static int solve(int lower, int upper) { counter = 0; for (int currentNumber = lower; currentNumber <= upper; currentNumber++) { if (aHashMap.containsKey(currentNumber)) { continue; } counter += process(currentNumber); } return counter; } private static int process(int aNumber) { int localCounter = 0; numberString = Integer.toString(aNumber); for (int i = numberString.length()-1; i > 0; i--) { if (Character.getNumericValue(numberString.charAt(i)) == 0) { continue; } tempNumberString = numberString.substring(i) + numberString.substring(0, i); tempNumber = Integer.parseInt(tempNumberString); if (tempNumber == aNumber) { continue; } if (aHashMap.containsKey(tempNumber)) { continue; } if ((tempNumber >= lower) && (tempNumber <= upper)) { localCounter++; aHashMap.put(tempNumber, tempNumber); //System.out.println(tempNumber); } } if (localCounter != 0) { aHashMap.put(aNumber, aNumber); //System.out.println(aNumber); } if (localCounter > 1) { return sumOfSequence(localCounter); } return localCounter; } private static int sumOfSequence(int aCounter) { int tempSum = 0; for (int i = 1; i <= aCounter; i++) { tempSum += i; } return tempSum; } } " B10195,"// usage: java c infile > outfile import java.io.BufferedReader; import java.io.FileReader; import java.util.Set; import java.util.HashSet; public class c { public static void main(String[] args) throws Exception { String infile = args[0]; BufferedReader reader = new BufferedReader(new FileReader(infile)); int T = Integer.parseInt(reader.readLine()); for (int t = 1; t <= T; t++) { Set pairs = new HashSet(); String[] inputs = reader.readLine().split("" ""); int A = Integer.parseInt(inputs[0]); int B = Integer.parseInt(inputs[1]); int length = inputs[0].length(); //System.out.println(""test = "" + A + "", "" + B + "", "" + length); int total = 0; for (int i = A; i <= B; i++) { String trial = """" + i; //System.out.println(""i = "" + i); for (int n = 1; n < length; n++) { int j = Integer.parseInt(trial.substring(n) + trial.substring(0, n)); //System.out.println(trial.substring(n) + "":"" + trial.substring(0, n)); if (trial.charAt(n) == '0') { continue; } String pair = i + "" "" + j; if (i < j && j <= B && !pairs.contains(pair)) { total++; pairs.add(pair); } } } System.out.println(""Case #"" + t + "": "" + total); } reader.close(); } } " B10168,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.util.HashSet; import java.util.Map; import java.util.Set; public class RecycledNumbers { public static void main(String[] args) { if (args.length != 2) { System.out.println(""Usage: java RecycledNumbers ""); System.exit(0); } try { RecycledCounter counter = new RecycledCounter(new FileReader(args[0]), new FileWriter(args[1])); counter.count(); } catch (Exception e) { System.out.println(""Sorry, there was a fatal error:""); e.printStackTrace(); System.exit(0); } } } class RecycledCounter { private final BufferedReader reader; private final PrintWriter writer; public RecycledCounter(Reader in, Writer out) throws IOException { reader = new BufferedReader(in); writer = new PrintWriter(out); } public void count() throws IOException { String line = reader.readLine(); int numTests = Integer.parseInt(line); for (int i = 0; i < numTests; i++) { line = reader.readLine(); writer.printf(""Case #%d: %s"", i + 1, countNumberOfRecycledPairs(line)); writer.println(); } writer.flush(); writer.close(); reader.close(); } public int countNumberOfRecycledPairs(String line) { String[] tokens = line.split("" ""); int a = Integer.parseInt(tokens[0]); int b = Integer.parseInt(tokens[1]); int y = 0; Set distinct = new HashSet(); for (; a <= b; a++) { if (a < 10) { continue; } String num = String.valueOf(a); for (int i = num.length() - 1; i > 0; i--) { String recycledNum = num.substring(i) + num.substring(0, i); if (recycledNum.startsWith(""0"")) { continue; } int recycled = Integer.valueOf(recycledNum); if (recycled >= a && recycled <= b && a < recycled && !distinct.contains(num + recycledNum)) { distinct.add(num + recycledNum); y++; } } } return y; } } " B11549,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package googlejam3; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; /** * * @author Nomeir */ public class GoogleJam3 { private String inputFile = // ""C-large.in""; "".\\C-small-attempt0.in""; // "".\\test3.in""; private String outputFile = "".\\out.txt""; private String line = ""start""; private FileReader reader; private BufferedReader buffer; private FileWriter writer; private BufferedWriter printer; public GoogleJam3() { try { new File(outputFile).createNewFile(); reader = new FileReader(inputFile); buffer = new BufferedReader(reader); new File(outputFile).createNewFile(); writer = new FileWriter(outputFile); printer = new BufferedWriter(writer); } catch (IOException ex) { System.out.println(""The file couldn't be created ...""); } } public void endOperations() { try { if (reader != null) { reader.close(); } if (buffer != null) { buffer.close(); } if (printer != null) { printer.flush(); printer.close(); } if (writer != null) { writer.close(); } } catch (IOException ex) { ex.printStackTrace(); } } int lines; public void readInfo() { try { line = buffer.readLine(); if (line != null) { lines = Integer.valueOf(line); // int i = 0, j = 0; // L = Integer.valueOf(line.substring(0, i = line.indexOf("" ""))); // D = Integer.valueOf(line.substring(++i, j = line.indexOf("" "", i))); // N = Integer.valueOf(line.substring(++j, line.length())); } } catch (FileNotFoundException ex) { System.err.println(""Source file not found .. !""); } catch (IOException e) { e.printStackTrace(); } catch (StringIndexOutOfBoundsException e) { e.printStackTrace(); } } int aMinValue, bMaxValue, aMovingValue; int nMinValue, mMaxValue; String aStr, bStr; int t1, t2, searchIndex; ArrayList keys, values; ArrayList ab; private void readInfoLines() { try { for (int i = 0; i < lines;) { line = buffer.readLine(); ab = new ArrayList(); recurser(line, ab); aMinValue = ab.get(0); aMovingValue = aMinValue; bMaxValue = ab.get(1); bStr = bMaxValue + """"; keys = new ArrayList(); values = new ArrayList(); if (bStr.length() > 1 && aMinValue < bMaxValue) { for (; aMovingValue <= bMaxValue; aMovingValue++) { aStr = aMovingValue + """"; if (aStr.length() > 1) { for (int j = 1; j < aStr.length(); j++) { nMinValue = aMovingValue; mMaxValue = Integer.parseInt(aStr.substring(j, aStr.length()) + aStr.substring(0, j)); if (mMaxValue > bMaxValue || mMaxValue < aMinValue) { continue; } if (nMinValue < mMaxValue) { searchIndex = Collections.binarySearch(keys, nMinValue); if (searchIndex >= 0 && values.get(searchIndex) == mMaxValue) { } else { keys.add(nMinValue); values.add(mMaxValue); } } } } } } printer.write(""Case #"" + ++i + "": "" + keys.size()); printer.newLine(); } } catch (IOException ex) { ex.printStackTrace(); } } public void recurser(String s, ArrayList links) { int i = 0, k = 0; if (s != null) { if ((i = s.indexOf("" "")) >= 0) { if (links.size() == 0) { links.add(Integer.valueOf("""" + s.substring(0, i))); } if ((k = s.indexOf("" "", ++i)) >= 0) { links.add(Integer.valueOf("""" + s.substring(i, k))); s = s.substring(k); recurser(s, links); } else { links.add(Integer.valueOf(s.substring(i, s.length()))); } } } } /** * @param args the command line arguments */ public static void main(String[] args) { long t = System.currentTimeMillis(); GoogleJam3 obj = new GoogleJam3(); obj.readInfo(); obj.readInfoLines(); // obj.printTestCases(); obj.endOperations(); t = System.currentTimeMillis() - t; System.out.println(""Time elapsed "" + t); } } " B11519,"import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; public class RecycledNumbers { static int t, a, b; public static void main(String[] args) throws FileNotFoundException { Scanner reader = new Scanner(new File(""numbers.in"")); t = reader.nextInt(); for (int c = 1; c <= t; c++) { a = reader.nextInt(); b = reader.nextInt(); int cuenta = 0; for (int n = a; n < b; n++) { cuenta += eval(n); } System.out.println(""Case #""+c+"": ""+cuenta); } } static int eval(int n){ String s = """"+n; int l = s.length(); int cuenta = 0; int nn; ArrayList nns = new ArrayList(); for (int i = 1; i < l; i++) { s = rotar(s); if (s.charAt(0)=='0') continue; nn = Integer.parseInt(s); if (nn>n && nn<=b && !nns.contains(nn)){ cuenta++; nns.add(nn); } } return cuenta; } static String rotar(String s){ return s.substring(1) + s.charAt(0); } } " B11679,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package uk.co.epii.codejam.common; /** * * @author jim */ public interface Processor { public String processLine(String line); } " B13089," import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author viswas */ public class Recycled { public static void main(String [] args)throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = 1; int T = Integer.parseInt(br.readLine()); while(T-- > 0){ long count = 0; StringTokenizer str = new StringTokenizer(br.readLine(), "" ""); int A = Integer.parseInt(str.nextToken()); int B = Integer.parseInt(str.nextToken()); ArrayList Alist = new ArrayList(); for(int i = A; i <= B; i++){ String s = i + """"; String aa = s; int len = s.length(); s += s; Alist.clear(); for(int j = 0; j < len; j++){ String s1 = s.substring(j, j + len); int s2 = Integer.parseInt(s1); if(!Alist.contains(s2)){ s1 = s2 + """"; if(i < s2 && aa.length() == s1.length() && B >= s2){ count++; //System.out.println(n.substring(0, len) + "" "" + m); } Alist.add(s2); } } } System.out.printf(""Case #%d: %d"", t, count); System.out.println(); t++; } } } " B12440,"package com.jam.google; import java.util.List; public class RecycledNumbers { public int count(int a, int b) { int pairCount = 0; for (int i = a; i <= b; i++) { int candidate = i; int j = 1; while( (candidate = recycle(i,j++) ) != i) { if (candidate > i && candidate <=b) pairCount++; } } return pairCount; } public int recycle(int i, int offset) { String string = String.valueOf(i); int answer = i; if (string.length()>1) { String recycledString = string.substring(string.length()-offset) + string.substring(0, string.length()-offset); answer = Integer.parseInt(recycledString); } return answer; } public void test() { InputUtil util = new InputUtil(); // List lines = util.readFile(""test1.txt""); List lines = util.readFile(""C-small-attempt2.in""); // int N = Integer.parseInt(lines.remove(0)); int i = 1; for (String string : lines) { String[] split = string.split("" ""); int count = count(Integer.parseInt(split[0]), Integer.parseInt(split[1])); System.out.println(""Case #""+(i++)+"": ""+count); } } } " B11133,"import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class ProblemC { /** * @param args */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); List[] l = genRecycled(); for(int i = 0; i < T; i++){ int c = processCase(sc, l); System.out.println(""Case #"" + (i+1) + "": "" + c); } } public static List[] genRecycled(){ // gen all the possible ms for a given n List[] rec = new List[1001]; int cmp; // generate a load of blank lists for(int i = 0; i < rec.length; i++){ // if(i % 10000 == 0) System.out.println(""hi "" + i); rec[i] = new ArrayList(); String n = Integer.toString(i); String m = rotate(n); // detect when back to the first while(!m.equals(n)){ // no leading zeros if(m.charAt(0) != '0'){ // find the numeric value cmp = Integer.parseInt(m); // number can't be greater than the max // and also has to be greater than n if(cmp < rec.length && cmp > i){ // add it to the list of possibles rec[i].add(cmp); } } m = rotate(m); } } return rec; } public static String rotate(String s){ return s.substring(1) + s.charAt(0); } public static int processCase(Scanner sc, List[] l){ int a = sc.nextInt(); int b = sc.nextInt(); int count = 0; // loop through the range for(int i = a; i < b; i++){ List li = l[i]; // find the pre-calculated things for(Integer el : li){ // if m is less than or equal to B, count it if(el <= b) count++; } } return count; } } " B11533,"package com.google.jam.eaque.stub; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class InputFileManager { private BufferedReader br; public InputFileManager(String filePath) throws NumberFormatException, IOException { br = new BufferedReader(new FileReader(filePath)); } public void close() throws IOException { br.close(); } public String readLine() throws IOException { return br.readLine(); } public long readLong() throws NumberFormatException, IOException { return Long.parseLong(br.readLine()); } public String[] readAndSplit() throws IOException { return br.readLine().split("" ""); } } " B13229,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.HashMap; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub try { BufferedReader br = new BufferedReader(new FileReader(""/Users/William/Desktop/C-small-attempt0.in"")); String strLine; FileWriter fostream = new FileWriter(""/Users/William/Desktop/output.txt""); BufferedWriter out = new BufferedWriter(fostream); strLine = br.readLine(); int numOfLine = Integer.parseInt(strLine); for (int i=1;i> map = new HashMap>(); for (int j=1;j list; if (map.get(k)==null) { list = new ArrayList(); } else { list = map.get(k); } boolean contains = false; for (Integer m : list) { if (m.intValue()==newNum) { contains = true; break; } } if (contains) { continue; } list.add(newNum); map.put(k, list); if ((newNum>k) && (newNum<=secondNum)) { // System.out.println(""("" + k + "" , "" + newNum + "")""); count ++; } } } System.out.println(""Case #"" + i + "": "" + count); out.write(""Case #"" + i + "": "" + count + ""\n""); } out.close(); br.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } } " B10527,"import java.io.*; import java.util.HashSet; import java.util.Set; /** * Created by IntelliJ IDEA. * User: YC14RP1 * Date: 4/14/12 * Time: 12:57 AM * To change this template use File | Settings | File Templates. */ public class Test3 { public static void main(String[] args) throws FileNotFoundException { String path = ""C:\\Users\\YC14rp1\\Downloads\\C-small-attempt0.in""; try{ // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(path); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; //Read File Line By Line strLine = br.readLine(); int n = Integer.valueOf(strLine); for (int i=1;i<=n;i++) { strLine = br.readLine(); String[] split = strLine.split("" ""); String s1 = split[0]; long d1 = Long.valueOf(s1); String s2 = split[1]; long d2 = Long.valueOf(s2); int res = 0; for (long j=d1;j<=d2;j++) { Set cSet = new HashSet(); String ss = String.valueOf(j); for (int k=0;kj) && (r>=d1) && (r<=d2)) { if (!cSet.contains(r)) { //System.out.println(j+""/""+r); res++; } cSet.add(r); //res++; } } } // Print the content on the console System.out.println(""Case #"" + i + "": "" + res); } //Close the input stream in.close(); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } } " B11307,"/** * Copyright 2012 Christopher Schmitz. All Rights Reserved. */ package com.isotopeent.codejam.lib.converters; import com.isotopeent.codejam.lib.InputConverter; public class StringLine implements InputConverter { private String input; @Override public boolean readLine(String data) { input = data; return false; } @Override public String generateObject() { return input; } } " B10323,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.StringTokenizer; /** * */ /** * @author Bageshwar * */ public class Recycle { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { long[] p = new long[] { 10, 100, 1000, 10000, 100000, 1000000, 10000000 }; // HashSet set=new HashSet(); // HashSet set1=new HashSet(); BufferedReader fr = new BufferedReader(new FileReader(new File(args[0]))); String str = fr.readLine(); //System.out.println(str); int lines = Integer.parseInt(str); FileWriter writer = new FileWriter(new File(args[1])); StringTokenizer stk; for (int l = 0; l < lines; l++) { writer.write(""Case #""+(l+1)+"": ""); str = fr.readLine(); stk = new StringTokenizer(str,"" ""); long a = Integer.parseInt(stk.nextElement().toString()); long b = Integer.parseInt(stk.nextElement().toString()); int total = 0; long t = 0; int k = 0; int c = ("""" + b).length() - 1; for (long i = a; i <= b; i++) { for (int j = 0; j < c; j++) { // rotate by j // j=j-1; k = c - j - 1; t = (i % p[j]) * p[k] + (i / p[j]); System.out.print("" ""+i+"":""+t); if (t <= b && t >= a && i != t) { System.out.print(""!""); // set.add(i); total++; //System.out.println(""##########"" + i + "">>"" + t); // set1.add(e) } } System.out.println(""""); } System.out.println(total); System.out.println(total / 2); writer.write(total/2+""\r\n""); } writer.close(); fr.close(); } } " B12464,"package codejam2012; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import reusable.CodeJamBase; public class RecycledNumbers { public static void main(String[] args) { new CodeJamBase(""C-small-attempt0"") { private int rotate(int value, int rotations, int totalRotations) { int tens = (int) Math.pow(10, rotations); int left = (int) Math.pow(10, totalRotations - rotations); return left * (value % tens) + (value / tens); } @Override protected String solution() { int[] input = nextIntArray(); int lowerBound = input[0]; int upperBound = input[1]; Map> distinctPairs = new HashMap<>(); int result = 0; for (int n = lowerBound; n <= upperBound; n++) { int totalRotations = String.valueOf(lowerBound).length(); for (int rotations = 1; rotations < totalRotations; rotations++) { int m = rotate(n, rotations, totalRotations); if (String.valueOf(m).length() != totalRotations) { continue; } if (distinctPairs.get(n) == null) { distinctPairs.put(n, new ArrayList()); } if (distinctPairs.get(n).contains(m)) { continue; } if ((lowerBound <= n) && (n < m) && (m <= upperBound)) { distinctPairs.get(n).add(m); result++; } } } return String.valueOf(result); } }.run(); } } " B12036,"import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; /** * @author Nikita Beloglazov * Date: May 22, 2010 */ public class Solution { private Map root; private int res; private void createDirectory(String[] dirs) { Map cur = root; for (String dir : dirs) { if (cur.get(dir) == null) { res++; cur.put(dir, new HashMap()); } cur = (Map)cur.get(dir); } } private void solve() throws IOException { Scanner sc = new Scanner(new File(""input.txt"")); PrintWriter pw = new PrintWriter(new FileWriter(""output.txt"")); int tt = sc.nextInt(); for (int t = 1; t <= tt; t++) { int n = sc.nextInt(), m = sc.nextInt(); root = new HashMap(); root.put("""",new HashMap()); for (int i = 0; i < n; i++) { createDirectory(sc.next().split(""/"")); } res = 0; for (int i = 0; i < m; i++) { createDirectory(sc.next().split(""/"")); } pw.printf(""Case #%d: %d\n"", t, res); } pw.close(); } public static void main(String[] args) throws IOException { new Solution().solve(); } } " B10106," import java.awt.Point; import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class Start { final boolean ONLINE_JUDGE = System.getProperty(""ONLINE_JUDGE"") != null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""""); void init() throws FileNotFoundException { if (ONLINE_JUDGE) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader(""input.txt"")); out = new PrintWriter(""output.txt""); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } public static void main(String[] args) { new Start().run(); } public static void mergeSort(int[] a) { mergeSort(a, 0, a.length - 1); } private static void mergeSort(int[] a, int levtIndex, int rightIndex) { final int MAGIC_VALUE = 50; if (levtIndex < rightIndex) { if (rightIndex - levtIndex <= MAGIC_VALUE) { insertionSort(a, levtIndex, rightIndex); } else { int middleIndex = (levtIndex + rightIndex) / 2; mergeSort(a, levtIndex, middleIndex); mergeSort(a, middleIndex + 1, rightIndex); merge(a, levtIndex, middleIndex, rightIndex); } } } private static void merge(int[] a, int levtIndex, int middleIndex, int rightIndex) { int length1 = middleIndex - levtIndex + 1; int length2 = rightIndex - middleIndex; int[] levtArray = new int[length1]; int[] rightArray = new int[length2]; System.arraycopy(a, levtIndex, levtArray, 0, length1); System.arraycopy(a, middleIndex + 1, rightArray, 0, length2); for (int k = levtIndex, i = 0, j = 0; k <= rightIndex; k++) { if (i == length1) { a[k] = rightArray[j++]; } else if (j == length2) { a[k] = levtArray[i++]; } else { a[k] = levtArray[i] <= rightArray[j] ? levtArray[i++] : rightArray[j++]; } } } private static void insertionSort(int[] a, int levtIndex, int rightIndex) { for (int i = levtIndex + 1; i <= rightIndex; i++) { int current = a[i]; int j = i - 1; while (j >= levtIndex && a[j] > current) { a[j + 1] = a[j]; j--; } a[j + 1] = current; } } public void run() { try { long t1 = System.currentTimeMillis(); init(); solve(); out.close(); long t2 = System.currentTimeMillis(); System.err.println(""Time = "" + (t2 - t1)); } catch (Exception e) { e.printStackTrace(System.err); System.exit(-1); } } class LOL { int x; int y; public LOL(int x, int k){ this.x = x; y = k; } } ArrayList list; int a,b; void PROC (int x){ String s = Integer.toString(x); for (int i = 0; i=a && k<=b && x < k ) { boolean b = false; for (int z = 0; z (); int ans = 0; for (int i = a; i<=b; i++){ PROC(i); } out.print(""Case #""+t+"": ""); out.print(list.size()); if (t!=n) out.println(); list.clear(); } } } " B12087,"package qualC; import java.util.*; public class RecycledNumbers { private static int cases; public static void main(String[] args) { Scanner input = new Scanner(System.in); if (input.hasNextInt()) { cases = input.nextInt(); } for (int i = 0; i < cases; i++) { System.out.println(""Case #"" + (i+1) + "": "" + findRecycled(input)); } } public static int findRecycled(Scanner input) { int startingPoint = 0; int endingPoint = 0; int counter = 0; if (input.hasNextInt()) { startingPoint = input.nextInt(); } if (input.hasNextInt()) { endingPoint = input.nextInt(); } //for each item from start->end.. for (Integer i = startingPoint; i < endingPoint; i++) { //cast that item to a string.. String value = i.toString(); ArrayList thisItem = new ArrayList(); //for each character in the string.. for (int z = 0; z < value.length(); z++) { //shuffle the characters along one String rotate = value.substring(z); rotate += value.substring(0, z); //cast to an int int shuffledInt = Integer.parseInt(rotate); //make sure it is within the boundaries.. if (shuffledInt <= endingPoint && shuffledInt >= startingPoint) { //if it is greater than the original then it is a duplicate if (Integer.parseInt(value) < shuffledInt) { //make sure if we've looked at this item before that it's not a duplicate.. if (!thisItem.contains(shuffledInt)) { counter++; thisItem.add(shuffledInt); } } } } } return counter; } }" B12212,"package hk.polyu.cslhu.codejam.lib; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; public class ResultCollector { public static Logger logger = Logger.getLogger(ResultCollector.class); public static String IndexPartInRow = ""%i""; public static String ResultPartInRow = ""%r""; private Map> resultMap; private String resultFile, resultPattern; private int amountOfTestCases, numOfProcessedTestCases; /** * Constructs a instance of result collector * * @param amountOfTestCases int The amount of test cases * @param resultFile String The location of result file */ public ResultCollector(int amountOfTestCases, String resultFile, String resultPattern) { this.resultMap = new HashMap> (); this.resultFile = resultFile; this.resultPattern = resultPattern; this.amountOfTestCases = amountOfTestCases; this.numOfProcessedTestCases = 0; } /** * update the result stored in the object * * @param partIndex int The part index of result * @param partOfResult List The part of result */ public synchronized void updateResult(int partIndex, List partOfResult) { // add the part of result if (this.resultMap.containsKey(partIndex)) { logger.error(""Failure to add the part of result with part index "" + partIndex); } else { this.resultMap.put(partIndex, partOfResult); this.numOfProcessedTestCases += partOfResult.size(); logger.info(""The #"" + partIndex + "" is completed!""); } // trigger the save method when all test cases are processed if (this.numOfProcessedTestCases == this.amountOfTestCases) this.save(); else if (this.numOfProcessedTestCases > this.amountOfTestCases) logger.error( ""The number of processed test cases is more than the amount of test cases ("" + this.numOfProcessedTestCases + "" > "" + this.amountOfTestCases + "")""); } /** * Save the result in the given file * * @param filePath String The location of file to be saved */ private void save() { // constructs the content String content = this.constructTheContent(); FileStream.save(this.resultFile, content); logger.info(""The result of all test cases is saved with the path "" + this.resultFile); } /** * Construct the content to be saved * * @return String The content of file */ private String constructTheContent() { // TODO Auto-generated method stub String content = """"; int rowIndex = 1; // sort the key of result map List keySet = new LinkedList(this.resultMap.keySet()); Collections.sort(keySet); for (Integer key : keySet) { List resultList = this.resultMap.get(key); for (String result : resultList) { String rowContent = this.resultPattern.replaceAll(IndexPartInRow, String.valueOf(rowIndex)).replaceAll(ResultPartInRow, result); content += rowContent; rowIndex++; } } return content; } } " B11047,"package midnighter.googlejam.y2012; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class QualificationC { static final String inFileName = ""inputs/C-small-attempt0.in""; static final String outFileName = ""outputs/C-small.out""; Scanner in; PrintWriter out; public int oneCase() { int A = in.nextInt(); int B = in.nextInt(); int res = 0; for (int i = A; i <= B; i++) { int d = 1, c = i; while ((c /= 10) > 0) d++; int v = i; for (int k = 0; k < d - 1; k++) { int nw = v % 10; for (int j = 0; j < d - 1; j++) nw *= 10; v = v / 10 + nw; if (v == i) break; if (nw != 0 && v <= B && v > i) res++; } } return res; } public void run() throws Exception { in = new Scanner(new FileReader(inFileName)); out = new PrintWriter(new FileWriter(outFileName)); int nCases = in.nextInt(); in.nextLine(); for (int c = 1; c <= nCases; c++) out.println(""Case #"" + c + "": "" + oneCase()); out.flush(); out.close(); in.close(); } public static void main(String[] args) throws Exception { new QualificationC().run(); } } " B11177,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; public class RecycleNumber { public static void solution(String fileName) throws IOException { FileReader fileReader = new FileReader(new File(fileName)); BufferedReader bufferedReader = new BufferedReader(fileReader); String textLine = bufferedReader.readLine(); int lines = Integer.parseInt(textLine); int[] ret = new int[lines]; for (int i = 0; i < lines; i++) { textLine = bufferedReader.readLine(); String[] t = textLine.split("" ""); if (t.length < 2) { ret[i] = 0; continue; } long start = Long.parseLong(t[0]); long end = Long.parseLong(t[1]); int c = 0; for (long j = start; j < end; j++) { if (start < 10) break; c += getNumber(Long.toString(j), start, end); } ret[i] = c; } for (int i = 0; i < ret.length; i++) { System.out.println(""Case #"" + (i + 1) + "": "" + ret[i]); } } public static int getNumber(String n, long s, long e) { int ret = 0; String t = n; long lo = Long.parseLong(n); HashSet map = new HashSet(); for (int i = 1; i < n.length(); i++) { t = n.substring(i) + n.substring(0, i); String ts = n+"";""+t; if (map.contains(ts)) continue; else map.add(ts); long l = Long.parseLong(t); if (l <= e && l >= s && lo < l) ret++; } return ret; } public static void main(String[] args) throws Exception { solution(""c:\\sql\\C-small-attempt0.in""); } } " B11178,"import java.io.*; import java.util.*; import java.lang.*; class Source2 { public static void main(String[] args) throws IOException { String s,word,buffer; FileReader input = new FileReader(""C-small.in""); BufferedReader in = new BufferedReader(input); File file = new File(""C-small.out""); BufferedWriter out = new BufferedWriter(new FileWriter(file)); s = in.readLine(); int count= Integer.parseInt(s); int i=1; while ((s = in.readLine()) != null && s.length() != 0) { out.write(""Case #""+(i++)+"": ""); Scanner scan =new Scanner(s); buffer=""""; long A =Integer.parseInt(scan.next()); long B = Integer.parseInt(scan.next()); long ans = calculatemn(A,B); out.write(ans+""\n""); } out.close(); } public static long calculatemn(long A,long B) { long[][] recyclepair =new long[2000000][2]; long count=0; boolean check=false; int re_i=0; for(long n=A ;n<=B;n++) { check=true; String stn =n+""""; String stm =n+""""; int length =stn.length(); for(int i=1;iN&&M<=B) { boolean pass =true; for(int j=0;j recyclePairSet = new HashSet(); for(int i=min; i<=max; i++) { String input = String.valueOf(i) + String.valueOf(i); for(int index=1; index < digits; index++) { String num = input.substring(index, index+digits); int numVal = Integer.valueOf(num); if(!(numVal > min && numVal < max)) continue; if(num.startsWith(""0"") || i == numVal) continue; if(i < Integer.valueOf(num)) { recyclePairSet.add(String.valueOf(i) + String.valueOf(num)); } else { recyclePairSet.add(String.valueOf(num) + String.valueOf(i)); } } } return recyclePairSet.size(); } public static void main(String[] args) throws IOException { Recycle recycle = new Recycle(); recycle.processInput(""C:/downloads/C-small-attempt0.in""); } } " B10783," import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.ObjectInputStream.GetField; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; import java.math.BigInteger; public class C { private static char[] alph; private static String fileIN = ""./A.in""; //archivo de entrada (en el dir local del programita) private static String fileOUT = ""./out.txt""; //salida public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new File(fileIN)); PrintWriter out = new PrintWriter(new File(fileOUT)); int T = in.nextInt(); for (int i = 0; i < T; i++) { String s = ""Case #"" + (i + 1) + "": "" + new C().solve(in); out.println(s); System.out.println(s); } out.close(); //getCombinaciones(1234); } /** * Retorna la solucion a un caso **/ private String solve(Scanner in) { int min, max = 0; min= in.nextInt(); max= in.nextInt(); int tot = 0; int tot_[] = new int[6]; int prov = 0; for(int i = min; i< max; i++){ for(Integer j: getCombinaciones(i)){ //System.out.println(j); if(j>i) if(isValid(j, min, max)) prov++; } tot_[prov]++; tot+= prov; prov =0; } /* for(int i = 0; i < tot_.length; i++){ tot-= }*/ return String.valueOf(tot); } private boolean isValid(Integer j, int min, int max) { return j<=max && j>=min; } private static List getCombinaciones(int i) { ArrayList l = new ArrayList(); String is = String.valueOf(i); String aux = String.valueOf(i); if(symetric(is)) return l; do{ aux = aux.charAt(aux.length()-1)+ aux.substring(0, aux.length()-1); if(aux.charAt(0)!='0') l.add(Integer.valueOf(aux)); } while(!is.equals(aux)); l.remove(l.size()-1); return l; } private static boolean symetric(String is) { if(is.length() % 2 ==1) return false; else return is.substring(0, is.length()/2).equals(is.substring(is.length()/2 + 1, is.length())); } } " B10275," package recyclednumbers; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; public class RecycledNumbers { public static void main(String[] args) { int result= 0 ,x,y,counter,num,count; String SoX,temp; int[] array = new int[7]; int cntarray=0; boolean flag = true; PrintWriter pw = null; Scanner sc = null; try { sc = new Scanner(new FileReader(""C:\\Users\\gad\\Downloads\\C-small-attempt0.in"")); pw = new PrintWriter(new FileWriter(""D:\\mystudy\\RCoutput.out"")); int cc=Integer.parseInt(sc.nextLine()); for(int cnt=0;cnt1) { temp = temp.substring(1,counter) + temp.charAt(0); num = Integer.parseInt(temp); for (int t=0;t=x&&j tcList = TestCaseIO.loadFromFile(infile); //ArrayList tcList = TestCaseIO.mockUp(); int numThreads = 1; if (numThreads == 1) { TestCaseSolver tcSolver = new TestCaseSolver(tcList, 1); tcSolver.run(); } else { //split into separate lists ArrayList> tcSubLists = new ArrayList<>(); for (int i = 0; i < numThreads; i++) { tcSubLists.add(new ArrayList()); } int i = 0; for (TestCase tc : tcList) { tcSubLists.get(i).add(tc); i++; if (i == numThreads) { i = 0; } } //run each sublist in its own thread ArrayList threadList = new ArrayList<>(); int ref = 1; for (ArrayList tcl : tcSubLists) { TestCaseSolver tcs = new TestCaseSolver(tcl, ref); Thread h = new Thread(tcs); threadList.add(h); h.start(); ref++; } //wait for completion for (Thread h : threadList) { try { h.join(); } catch (InterruptedException ex) { Utils.die(""InterruptedException waiting for threads""); } } } TestCaseIO.writeSolutions(tcList, outfile); double totalTime = 0; for (TestCase tc : tcList) { totalTime += tc.getTime(); } double avTime = totalTime / (double)tcList.size(); Utils.sout(""Total compute time "" + String.format(""%.2f"", totalTime) + "" secs.""); Utils.sout(""Average compute time "" + String.format(""%.2f"", avTime) + "" secs.""); Utils.sout(""Done.""); } public static void test() { } } " B12832,"package com.googlecodejam.gcj2012.qualificationround; import java.io.File; import java.io.FileWriter; import java.util.HashSet; import java.util.Scanner; public class C { // public final static String INPUT_FILE_NAME = ""test.in""; public final static String INPUT_FILE_NAME = ""C-small-attempt0.in""; // public final static String INPUT_FILE_NAME = ""C-large.in""; public FileWriter outputWriter; public Scanner scanner; public String output = """"; public void run() throws Exception { // Commons variables int testCaseNumber = 0; int testCaseResult = 0; // Test start { int nbTests = Integer.parseInt(scanner.nextLine()); for (testCaseNumber = 0; testCaseNumber < nbTests; testCaseNumber++) { String[] bounds = scanner.nextLine().split("" ""); String sMinValue = bounds[0]; String sMaxValue = bounds[1]; int minValue = Integer.parseInt(sMinValue); int maxValue = Integer.parseInt(sMaxValue); int nbDigits = sMinValue.length(); testCaseResult = 0; if (nbDigits > 1) { for (int currentValue = minValue; currentValue < maxValue; currentValue++) { HashSet foundValues = new HashSet(); String sCurrentValue = Integer.toString(currentValue); char firstNumber = sCurrentValue.charAt(0); for (int i = nbDigits - 1; i > 0; i--) { char number = sCurrentValue.charAt(i); if (number >= firstNumber) { String firstPart = sCurrentValue.substring(0, i); String secondPart = sCurrentValue.substring(i); int val = Integer.parseInt(secondPart + firstPart); if (val <= maxValue && val > currentValue && !foundValues.contains(val)) { testCaseResult++; foundValues.add(val); } } } } } output += ""Case #"" + (testCaseNumber+1) + "": "" + testCaseResult + ""\n""; } } } ///////////////////////////////////////////////////////////////////////////////////////////////////// public void init() throws Exception { File temp = new File(""output/""); if (!temp.exists()) { temp.mkdir(); } // Output file outputWriter = new FileWriter(""output/output.txt"", false); // Input file scanner = new Scanner(new File(""resources/"" + INPUT_FILE_NAME)); } public void stop() throws Exception { // Closing files outputWriter.write(output, 0, output.length()); scanner.close(); outputWriter.close(); } /** * @param args */ public static void main(String[] args) throws Exception { C instance = new C(); long start = System.currentTimeMillis(); instance.init(); instance.run(); instance.stop(); System.out.println(""Finished in "" + (System.currentTimeMillis() - start) + "" ms""); } } " B12296,"/************************************************************************* * Compilation: javac In.java * Execution: java In * * Reads in data of various types from: stdin, file, URL. * * % java In * * Remarks * ------- * - isEmpty() returns true if there is no more input or * it is all whitespace. This might lead to surprising behavior * when used with readChar() * *************************************************************************/ import java.net.URLConnection; import java.net.URL; import java.net.Socket; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.BufferedInputStream; import java.util.Scanner; import java.util.Locale; /** * Input. This class provides methods for reading strings * and numbers from standard input, file input, URL, and socket. *

* The Locale used is: language = English, country = US. This is consistent * with the formatting conventions with Java floating-point literals, * command-line arguments (via Double.parseDouble()) * and standard output (via System.out.print()). It ensures that * standard input works the number formatting used in the textbook. *

* For additional documentation, see Section 3.1 of * Introduction to Programming in Java: An Interdisciplinary Approach by Robert Sedgewick and Kevin Wayne. */ public final class In { private Scanner scanner; // assume Unicode UTF-8 encoding //private String charsetName = ""UTF-8""; private String charsetName = ""ISO-8859-1""; // assume language = English, country = US for consistency with System.out. private Locale usLocale = new Locale(""en"", ""US""); /** * Create an input stream for standard input. */ public In() { scanner = new Scanner(new BufferedInputStream(System.in), charsetName); scanner.useLocale(usLocale); } /** * Create an input stream from a socket. */ public In(Socket socket) { try { InputStream is = socket.getInputStream(); scanner = new Scanner(new BufferedInputStream(is), charsetName); scanner.useLocale(usLocale); } catch (IOException ioe) { System.err.println(""Could not open "" + socket); } } /** * Create an input stream from a URL. */ public In(URL url) { try { URLConnection site = url.openConnection(); InputStream is = site.getInputStream(); scanner = new Scanner(new BufferedInputStream(is), charsetName); scanner.useLocale(usLocale); } catch (IOException ioe) { System.err.println(""Could not open "" + url); } } /** * Create an input stream from a file. */ public In(File file) { try { scanner = new Scanner(file, charsetName); scanner.useLocale(usLocale); } catch (IOException ioe) { System.err.println(""Could not open "" + file); } } /** * Create an input stream from a filename or web page name. */ public In(String s) { try { // first try to read file from local file system File file = new File(s); if (file.exists()) { scanner = new Scanner(file, charsetName); scanner.useLocale(usLocale); return; } // next try for files included in jar URL url = getClass().getResource(s); // or URL from web if (url == null) { url = new URL(s); } URLConnection site = url.openConnection(); InputStream is = site.getInputStream(); scanner = new Scanner(new BufferedInputStream(is), charsetName); scanner.useLocale(usLocale); } catch (IOException ioe) { System.err.println(""Could not open "" + s); } } /** * Does the input stream exist? */ public boolean exists() { return scanner != null; } /** * Is the input stream empty? */ public boolean isEmpty() { return !scanner.hasNext(); } /** * Does the input stream have a next line? */ public boolean hasNextLine() { return scanner.hasNextLine(); } /** * Read and return the next line. */ public String readLine() { String line = null; try { line = scanner.nextLine(); } catch (Exception e) { } return line; } /** * Read and return the next character. */ public char readChar() { // (?s) for DOTALL mode so . matches any character, including a line termination character // 1 says look only one character ahead // consider precompiling the pattern String s = scanner.findWithinHorizon(""(?s)."", 1); return s.charAt(0); } // return rest of input as string /** * Read and return the remainder of the input as a string. */ public String readAll() { if (!scanner.hasNextLine()) { return null; } // reference: http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html return scanner.useDelimiter(""\\A"").next(); } /** * Return the next string from the input stream. */ public String readString() { return scanner.next(); } /** * Return the next int from the input stream. */ public int readInt() { return scanner.nextInt(); } /** * Return the next double from the input stream. */ public double readDouble() { return scanner.nextDouble(); } /** * Return the next float from the input stream. */ public double readFloat() { return scanner.nextFloat(); } /** * Return the next long from the input stream. */ public long readLong() { return scanner.nextLong(); } /** * Return the next byte from the input stream. */ public byte readByte() { return scanner.nextByte(); } /** * Return the next boolean from the input stream, allowing ""true"" or ""1"" * for true and ""false"" or ""0"" for false. */ public boolean readBoolean() { String s = readString(); if (s.equalsIgnoreCase(""true"")) return true; if (s.equalsIgnoreCase(""false"")) return false; if (s.equals(""1"")) return true; if (s.equals(""0"")) return false; throw new java.util.InputMismatchException(); } /** * Close the input stream. */ public void close() { scanner.close(); } /** * Test client. */ public static void main(String[] args) { In in; String urlName = ""http://www.cs.princeton.edu/IntroCS/stdlib/InTest.txt""; // read from a URL System.out.println(""readAll() from URL "" + urlName); System.out.println(""---------------------------------------------------------------------------""); try { in = new In(urlName); System.out.println(in.readAll()); } catch (Exception e) { } System.out.println(); // read one line at a time from URL System.out.println(""readLine() from URL "" + urlName); System.out.println(""---------------------------------------------------------------------------""); try { in = new In(urlName); while (!in.isEmpty()) { String s = in.readLine(); System.out.println(s); } } catch (Exception e) { } System.out.println(); // read one string at a time from URL System.out.println(""readString() from URL "" + urlName); System.out.println(""---------------------------------------------------------------------------""); try { in = new In(urlName); while (!in.isEmpty()) { String s = in.readString(); System.out.println(s); } } catch (Exception e) { } System.out.println(); // read one line at a time from file in current directory System.out.println(""readLine() from current directory""); System.out.println(""---------------------------------------------------------------------------""); try { in = new In(""./InTest.txt""); while (!in.isEmpty()) { String s = in.readLine(); System.out.println(s); } } catch (Exception e) { } System.out.println(); // read one line at a time from file using relative path System.out.println(""readLine() from relative path""); System.out.println(""---------------------------------------------------------------------------""); try { in = new In(""../stdlib/InTest.txt""); while (!in.isEmpty()) { String s = in.readLine(); System.out.println(s); } } catch (Exception e) { } System.out.println(); // read one char at a time System.out.println(""readChar() from file""); System.out.println(""---------------------------------------------------------------------------""); try { in = new In(""InTest.txt""); while (!in.isEmpty()) { char c = in.readChar(); System.out.print(c); } } catch (Exception e) { } System.out.println(); System.out.println(); // read one line at a time from absolute OS X / Linux path System.out.println(""readLine() from absolute OS X / Linux path""); System.out.println(""---------------------------------------------------------------------------""); in = new In(""/n/fs/csweb/introcs/stdlib/InTest.txt""); try { while (!in.isEmpty()) { String s = in.readLine(); System.out.println(s); } } catch (Exception e) { } System.out.println(); // read one line at a time from absolute Windows path System.out.println(""readLine() from absolute Windows path""); System.out.println(""---------------------------------------------------------------------------""); try { in = new In(""G:\\www\\introcs\\stdlib\\InTest.txt""); while (!in.isEmpty()) { String s = in.readLine(); System.out.println(s); } System.out.println(); } catch (Exception e) { } System.out.println(); } } " B11616,"import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Scanner; /** * @author fedor.korotkov */ public class QualificationC { public static void main(String[] args) throws FileNotFoundException { final Scanner in = new Scanner(new FileInputStream(""in.txt"")); int t = in.nextInt(); for (int i = 1; i <= t; ++i) { int a = in.nextInt(); int b = in.nextInt(); System.out.print(""Case #"" + i + "": ""); System.out.println(solve(a, b)); } } private static int solve(int a, int b) { int result = 0; for (int i = a; i < b; ++i) { for (int j = i + 1; j <= b; ++j) { if (recycled(i, j)) ++result; } } return result; } private static boolean recycled(int i, int j) { String tmp = Integer.toString(i) + Integer.toString(i); return tmp.indexOf(Integer.toString(j)) != -1; } } " B12954,"package google.contest.A; import google.loader.Challenge; import google.problems.AbstractChallenge; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class AChallenge extends AbstractChallenge implements Challenge { private String text; private static Map map; public AChallenge(int number, String line) { super(number); text = line; initTranslationMap(); setResult(translate()); } private String translate() { String res=""""; for(int i=0;i(); String input=""ejp mysljylc kd kxveddknmc re jsicpdrysirbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcdde kr kd eoya kw aej tysr re ujdr lkgc jv""; String output=""our language is impossible to understandthere are twenty six factorial possibilitiesso it is okay if you want to just give up""; for(int i=0;i 0){ a[d] = tmp % 10; tmp /= 10; d++; } int ten = 1; for(i=0;i x && y[i] <= M && (i == 0 || y[i] != y[i-1])) ans++; return ans; } public static void main(String args[]){ int T,t,A,B,i; Scanner scan = new Scanner(System.in); T = scan.nextInt(); for(t=0;t memo = new ArrayList(); static ArrayList old = new ArrayList(); public static int solve(int s, int e){ count = 0 ; memo.clear(); old.clear(); for (int i = s; i <= e; i++) { n = i+""""; in:for (int j = 0; j < n.length(); j++) { h = n.substring(n.length()-j) + n.substring(0,n.length()-j); t = Integer.parseInt(h); if (t <= e && t>i ) { for (int k = 0; k < memo.size(); k++) { if (memo.get(k)==t && old.get(k)==i) continue in; } memo.add(t); old.add(i); count++; } } } return count; } static BitSet v1 = new BitSet(2000000); static int [] index = new int[2000000]; public static int solve2(int s, int e){ count = 0; v1.clear(); Arrays.fill(index, 0,0,e); for (int i = s; i <= e; i++) { n = i+""""; for (int j = 0; j <= n.length(); j++) { h = n.substring(n.length()-j) + n.substring(0,n.length()-j); t = Integer.parseInt(h); if (t <= e && t >i ) { if (v1.get(i) && index[i]==t) continue; count++; v1.set(i); index[i] = t ; } } } return count; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader(""c.in"")); BufferedWriter bw = new BufferedWriter(new FileWriter(""c.out"")); int n; int t = Integer.parseInt(br.readLine().trim()); String ss[]; for (int i = 1; i <= t; i++) { ss= br.readLine().split("" ""); n = solve2(Integer.parseInt(ss[0]), Integer.parseInt(ss[1])); // System.out.println(""Case #""+i+"": ""+n); bw.write(""Case #""+i+"": ""+n); bw.newLine(); } bw.close(); } } " B13240,"package com.codejam; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; public class RecycledNumbers { private static int lowRange = 0, highRange = 0; private static ArrayList list = null; private static ArrayList newList = null; public static void main(String[] args) { try { FileInputStream fstream = new FileInputStream( ""D:\\Softwares\\C-small-attempt0.in""); DataInputStream in = new DataInputStream(fstream); FileOutputStream out = new FileOutputStream(""D:\\Softwares\\C-small-attempt0.out""); PrintStream p = new PrintStream(out); int lineNo = 1; while (in.available() != 0) { if (lineNo == 1) { cases(in.readLine(), in, p); } lineNo++; } in.close(); } catch (Exception e) { e.printStackTrace(); } } private static void cases(String firstLine, DataInputStream in, PrintStream p) throws IOException { int casesNo = Integer.parseInt(firstLine); for (int i = 0; i < casesNo; i++) { p.print(""Case #"" + (i + 1) + "": ""); String line = in.readLine(); numbers(line, p); } } private static void numbers(String line, PrintStream p) { String[] range = line.split("" ""); lowRange = Integer.parseInt(range[0]); highRange = Integer.parseInt(range[1]); int[] numbers = new int[highRange - lowRange + 1]; for (int i = 0; i < numbers.length; i++) { numbers[i] = lowRange + i; } list = new ArrayList(); newList = new ArrayList(); int total = recycled(numbers); p.println(total); } private static int recycled(int[] numbers) { int total = 0; int dupliTotal = 0; for (int i = 0; i < numbers.length; i++) { int num = numbers[i]; int length = (int)(Math.log10(num)+1); int max = maxTen(length); int min = 10; while (num/min > 0){ int rem = num%min; int remNum = num/min; max /= min; int newNum = rem*max + remNum; if(newNum>num){ if (newNum <= highRange && newNum > lowRange) { if (list.contains(num)) if (newList.get(list.indexOf(num))==newNum) dupliTotal++; list.add(num); newList.add(newNum); total++; } } min*=10; max = maxTen(length); } } return total-dupliTotal; } private static int maxTen(int length){ int result = 1; int len = (int)(Math.log10(result)+1); while(len!=length){ result*= 10; len = (int)(Math.log10(result)+1); } return result*10; } } " B12535,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam3; import java.io.File; import java.io.*; import java.util.*; /** * * @author saad */ public class Codejam3 { /** * @param args the command line arguments */ static int convert(Integer min,Integer max){ int n=min.toString().length() ; int res=0 ; List l=new LinkedList() ; for(int i=min;ii&&a<=max){ if(!l.contains(a)){ res++ ; l.add(a) ; } } } } return res ; } public static void main(String[] args) throws FileNotFoundException { Scanner in=new Scanner(new File(""C-small-attempt1(1).in"")) ; PrintWriter out=new PrintWriter(""C-small-attempt1.out"") ; int n=in.nextInt() ; for(int i=0;i lines = getLines(fileIn); StringBuffer result = new StringBuffer(); if(lines!=null){ String firstLine[] = lines.get(0).split("" ""); int caseTotal = Integer.parseInt(firstLine[0]); for(int i = 0; i map = new HashMap(); for(int i=line0;i<=line1;i++){ for(int j=1; j getLines(String filePath){ ArrayList lines = null; try{ lines = new ArrayList(); String str; BufferedReader in = new BufferedReader( new FileReader(filePath)); while ((str = in.readLine()) != null) { lines.add(str); } in.close(); }catch(IOException e){ e.printStackTrace(); } return lines; } }" B12566,"package google; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Scanner; public class Recycled { public static void main(String[] args) throws FileNotFoundException, IOException { IO.changeGoogleIO('C', 0); Scanner input = new Scanner(System.in); int n = input.nextInt(); int a, b; int x, digit; int len; int result0; String s; String result; for (int i = 0; i < n; ++i) { result = ""Case #"" + (i + 1) + "": ""; a = input.nextInt(); b = input.nextInt(); result0 = 0; for (int j = a; j <= b; ++j) { s = j + """"; len = s.length(); do { s = s.charAt(len - 1) + s.substring(0, len - 1); x = Integer.parseInt(s); if ((x > j) && (x >= a) && (x <= b)) ++result0; } while (x != j); } result += result0; System.out.println(result); } } } " B11107,"import java.util.*; public class RecycledNumbers{ public static void main(String[] args){ Scanner scanner = new Scanner(System.in); int num = Integer.parseInt(scanner.nextLine()); for(int i = 1; i <= num; ++i){ String[] tokens = scanner.nextLine().split("" ""); int lower = Integer.parseInt(tokens[0]); int upper = Integer.parseInt(tokens[1]); RecycledNumbers r = new RecycledNumbers(); System.out.println(""Case #"" + i + "": "" + r.recycledNumbers(lower, upper)); } } public int recycledNumbers(int a , int b){ this.lower = a; this.upper = b; for(int i = a; i <= b; ++i){ findAllRecycleNumbers(i); } return numRecycleNumbers; } public void findAllRecycleNumbers(int i){ Set pairs = new HashSet(); int power = getPower(i); int recycleNumber = i; for(int count = 0; count <= power; ++count){ int quotient = recycleNumber / 10; int remainder = recycleNumber % 10; recycleNumber = (int)Math.pow(10, power) * remainder + quotient; if(recycleNumber >= lower && recycleNumber > i && recycleNumber <= upper){ if(!pairs.contains(recycleNumber)){ pairs.add(recycleNumber); ++numRecycleNumbers; } } } } private int getPower(int i){ int pow = 0; while(i > 9){ i /= 10; ++pow; } return pow; } public static class Pairs{ int lower; int upper; public Pairs(int lower, int upper){ this.lower = lower; this.upper = upper; } } private int numRecycleNumbers; private int lower; private int upper; }" B12575,"package problem1; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; public class Problem1 { public static void main(String[] args) throws FileNotFoundException, IOException{ try { TextIO.readFile(""L:\\Coodejam\\Input\\Input.txt""); } catch (IllegalArgumentException e) { System.out.println(""Can't open file ""); System.exit(0); } FileOutputStream fout = new FileOutputStream(""L:\\Coodejam\\Output\\output.txt""); PrintStream ps=new PrintStream(fout); int cases=TextIO.getInt(); for(int i=0;iA;i--) { result = result+howMany(i); } out.write(Integer.toString(result));// write result out.newLine(); } fstream.close(); out.close(); //log.close(); } static int howMany(int m) throws IOException { int n,no=0; int length = (Integer.toString(m)).length(); if(length==1) { return 0; } for(int i=1;io && k<=m) { rec++; recycle.tes++; //System.out.println(""(K=""+k+""> O=""+o+"" && K=""+k+"" processed = new HashSet(); for (int num = A; num <= B; num++) { if (processed.contains(num)) continue; processed.add(num); int count = 0; for (int rotated = 1; rotated < numDigits; rotated++) { int tp = tenpow(rotated); int dropped = num % tp; int stay = num / tp; int recyclednumber = dropped * tenpow(numDigits - rotated) + stay; if (processed.contains(recyclednumber)) continue; processed.add(recyclednumber); if (recyclednumber >= A && recyclednumber <= B) count++; } if (count == 0) continue; count +=1; result += ncr(count, 2); } return result; } private static int ncr(int n, int r) { return factorial(n)/(factorial(n-r) * factorial(r)); } private static int tenpow(int exp) { int res = 1; for (int i = 0; i < exp; i++) res *= 10; return res; } private static int factorial(int n) { if (n == 0) return 1; return n * factorial(n-1); } } " B11046,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package javaapplication1; import java.io.FileNotFoundException; import java.util.Scanner; import java.io.File; /** * * @author kutub */ public class rn { public static void main(String args[]) throws FileNotFoundException { File f=new File(""C:/Users/kutub/Documents/NetBeansProjects/JavaApplication1/src/javaapplication1/input2.txt""); Scanner s=new Scanner(f); int n=0,a=0,b=0,count=0; while(s.hasNext()) { n=s.nextInt(); for(int i=1;i<=n;i++) { s.nextLine(); a=s.nextInt(); b=s.nextInt(); count=0; for(int j=a;j<=b;j++) { //System.out.println(j); if(j>1000) { int k=j%10; int l=j/10; int m=l%10; int no=l/10; int ko=no%10; int lo=no/10; int mo=k*1000+l; if(mo>j && mo<=b && mo>a) { //System.out.println(""mo: ""+mo); count++; } mo=m*1000+k*100+no; if(mo>j && mo<=b && mo>a) { //System.out.println(""mo: ""+mo); count++; } mo=ko*1000+m*100+k*10+lo; if(mo>j && mo<=b && mo>a) { //System.out.println(""mo: ""+mo); count++; } } if(j<=1000 && j>100) { int k=j%10; int l=j/10; int m=l%10; int no=l/10; int mo=k*100+l; if(mo>j && mo<=b && mo>a) { //System.out.println(""j: ""+j+"" mo: ""+mo); count++; } mo=m*100+k*10+no; if(mo>j && mo<=b && mo>a) { //System.out.println(""j: ""+j+"" mo: ""+mo); count++; } } else if(j<=100 && j>=10 ) { int k=j%10; int l=j/10; int m=(k*10)+l; if(m<=b && m>a && m>j) { //System.out.println(""j: ""+j+"" mo: ""+m); count++; } } } System.out.print(""Case #""+i+"": ""); System.out.println(count); } } } } " B11208,"package c2012; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; public class RecycledPairCalculator { private ArrayList outputs ; public RecycledPairCalculator() { this.outputs = new ArrayList(); } public void perform(String path) throws NumberFormatException, IOException{ String [] inputs = readInput(path); for (int i = 0; i < inputs.length; i++) { String s = inputs[i]; String [] ab = s.split("" ""); this.outputs.add(calculatePair(Integer.parseInt(ab[0]), Integer.parseInt(ab[1]))); } writeOutput(); } private int calculatePair(int a, int b){ int pairsCount =0; for (int i = a; i <= b; i++) { int n = i; int m = n+1; while(m<=b){ if(isRecycled(n, m)) pairsCount++; m++; } } return pairsCount; } private boolean isRecycled(int n, int m){ String nn = String.valueOf(n) + String.valueOf(n); return nn.contains(String.valueOf(m)); } private String[] readInput(String path) throws NumberFormatException, IOException{ String [] inputs; FileInputStream fstream = new FileInputStream(path); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); int numberOfTestCases = Integer.parseInt(br.readLine()); inputs = new String[numberOfTestCases]; for (int i = 0; i < numberOfTestCases; i++) { inputs[i] = br.readLine(); } return inputs; } private void writeOutput() throws IOException{ FileWriter fstream = new FileWriter(""output_files/out.txt""); BufferedWriter out = new BufferedWriter(fstream); for (int i = 0; i < this.outputs.size(); i++) {; String output = ""Case #""+(i+1)+ "": "" + this.outputs.get(i)+""\n""; out.write(output); } out.close(); } public static void main(String[] args) throws NumberFormatException, IOException { RecycledPairCalculator r = new RecycledPairCalculator(); r.perform(""input_files/C-small-attempt0.in""); } } " B11097,"import java.io.*; import java.util.HashSet; import java.util.Set; public class C { private static final String FILE = ""C-small-attempt0""; private static final boolean SAVE_OUT = true; public static void main(String[] args) throws IOException { BufferedReader in = createReader(); FileWriter out; if (SAVE_OUT) { out = new FileWriter(FILE + "".out""); } int t = Integer.parseInt(in.readLine()); int c = 0; while (t-- > 0) { String row = in.readLine(); String[] split = row.split("" ""); int a = Integer.parseInt(split[0]); int b = Integer.parseInt(split[1]); int num = 0; for (int i = a; i <= b; ++i) { num += calc(i, a, b); } String res = String.format(""Case #%d: %d"", ++c, num / 2); System.out.println(res); if (SAVE_OUT) { out.append(res); out.append(""\n""); } } if (SAVE_OUT) { out.close(); } } private static int calc(int c, int a, int b) { int num = 0; String s = Integer.toString(c); Set seen = new HashSet(); for (int i = 1; i < s.length(); ++i) { int cc = flip(s, i); while (cc <= b) { if (seen.contains(cc)) { break; } if (cc >= a && c != cc) { ++num; seen.add(cc); } cc *= 10; } } return num; } private static int flip(String s, int k) { String first = s.substring(0, k); StringBuilder sb = new StringBuilder(); sb.append(s.substring(k)); sb.append(first); while (sb.charAt(0) == '0') { sb.deleteCharAt(0); } return Integer.parseInt(sb.toString()); } private static BufferedReader createReader() throws FileNotFoundException { return new BufferedReader(new FileReader(FILE + "".in"")); } } " B11132,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.Set; import java.util.StringTokenizer; public class C { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader(""C-small.in"")); PrintWriter out =new PrintWriter(new FileWriter(""C-small.out"")); int T = Integer.parseInt(br.readLine()); for(int i = 0; i 0) { int first = k/b; int second = k%b; String res = Integer.toString(second)+Integer.toString(first); int ires = Integer.parseInt(res); if(ires != j&& ires>j && ires <=m ) { count++; } if(ires==j) break; b=b*10; } } out.println(""Case #""+(i+1)+"": "" +count); } br.close(); out.close(); } } " B10061,"package qualification; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.util.BitSet; import java.util.Scanner; public class RecycledNumbers { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub Scanner in = new Scanner(new FileInputStream(""/home/meha/eclipse-android-workspace/Code Jam/Testcase/RecycledNumbers/C-small-attempt0.in"")); FileWriter out = new FileWriter(""/home/meha/eclipse-android-workspace/Code Jam/Testcase/RecycledNumbers/A-small.out""); int T = in.nextInt(); for(int i = 0; i < T; i++) { int A = in.nextInt(); int B = in.nextInt(); int count = 0; //for(int n=A, m=B; n < m; n++,m--) for(int n=A; n < B; n++) { for(int m=B; n < m; m--) { if(areRecycled(n,m)) count++; } } int tmp = i + 1; out.write(""Case #"" + tmp + "": "" + count + ""\n""); System.out.print(""Case #"" + tmp + "": "" + count + ""\n""); } out.close(); //System.out.print(areRecycled(12345, 34512)); } private static boolean areRecycled(int N, int M) { // TODO Auto-generated method stub String n = Integer.toString(N); String m = Integer.toString(M); if(n.length() != m.length()) return false; BitSet sChar = new BitSet(m.length()); for(int i = 0; i < m.length(); i++) { if(m.charAt(i) == n.charAt(0)) { sChar.set(i); } } for(int i = sChar.nextSetBit(0); i >=0; i = sChar.nextSetBit(i+1)) { String mstart = m.substring(0, i); String mend = m.substring(i, m.length()); String nstart = n.substring(0, n.length() - i); String nend = n.substring(n.length() - i, n.length()); if(nstart.equalsIgnoreCase(mend) && nend.equalsIgnoreCase(mstart)) { return true; } } return false; } } " B13201,"package tr0llhoehle.cakemix.utility.googleCodeJam; /** * Describes all Types currently supported. * * @author Cakemix * */ public enum SupportedTypes { INT, DOUBLE, BOOLEAN, STRING, LIST_INT, LIST_DOUBLE, LIST_BOOLEAN, LIST_STRING } " B10117,"import java.util.*; public class Recycle { private static Scanner s = new Scanner(System.in); public static void main(String[] args) { int T = s.nextInt(); List ms = new LinkedList(); for (int t = 0; t < T; t++) { int A = s.nextInt(); int B = s.nextInt(); int digits = String.valueOf(A).length(); int total = 0; for (int i = A; i < B; i++) { String num = String.valueOf(i); ms.clear(); for (int j = 1; j < digits; j++) { int r = Integer.parseInt(num.substring(j) + num.substring(0, j)); if (r > i && r <= B && !ms.contains(r)) { total++; ms.add(r); } } } System.out.printf(""Case #%d: %d\n"", t + 1, total); } } } " B11666,"/** * */ package google; import hack.Tool; import java.util.HashSet; import java.util.List; /** * http://code.google.com/codejam/contest/dashboard?c=1460488#s=p2 a pair of * distinct positive integers (n, m) is recycled if you can obtain m by moving * some digits from the back of n to the front without changing their order. * * @author y */ public class RotateNumbers { /** * Given integers A and B with the same number of digits and no leading * zeros, how many distinct recycled pairs (n, m) are there with A ¡Ü n < m ¡Ü * B? * * @param min * @param max */ static int pairsRotated (int min, int max){ if(max<10 || max<=min){return 0;} int ret = 0; for(int j=min; j set = new HashSet(); for(int k=1; k=s.charAt(0)){ //=212-> 221. ignore repeat, count (12, 21) once String rotateString = s.substring(k) + s.substring(0, k); int rotate = Integer.valueOf(rotateString); if((j=min if(!set.contains(rotate)){ set.add(rotate); ret ++; } //System.out.println(j + ""-> "" + rotate); } } } } return ret; } public static void main(String[] args) { Tool.createOutput(); List input = Tool.readLine(); for (int j = 0; j < input.size(); j++) { String[] line = input.get(j); int n = Integer.parseInt(line[0]); int k = Integer.parseInt(line[1]); int ret = pairsRotated(n, k); String outputLine = ""Case #"" + (j+1) + "": "" + ret; System.out.println(outputLine); Tool.writeOutput(outputLine); } } } " B12047,"import java.util.Scanner; //""c:\Program Files\Java\jdk1.6.0_25\bin\javac.exe"" a.java //""c:\Program Files\Java\jdk1.6.0_25\bin\java.exe"" a test.out public class C { public static String meth1 (String s){ String res = """"; res=res+s; return res; } //""c:\Program Files\Java\jdk1.6.0_25\bin\javac.exe"" A.java //""c:\Program Files\Java\jdk1.6.0_25\bin\java.exe"" A test.out static Scanner sc = new Scanner(System.in); public static void main(String[] args) { int cases ; int res; int m=0; String tmp; cases = Integer.parseInt(sc.nextLine()); int A,B; String buff; for(int id = 1; id <= cases; id++){ res=0; buff=""""; A = sc.nextInt(); B = sc.nextInt();sc.nextLine(); for (int i = A;i<=B;i++){ tmp = i+""""; for(int j =1;ji&&m<=B) if(!buff.contains( tmp+""#""+m)){ res++; buff+= tmp+""#""+m+"")(""; } } } System.out.printf(""Case #%d: %d%n"", id, res); } } }" B11120,"// Calculate num of recycled pairs // Anna Thalassinos // 14 April 2012 import java.io.*; import java.util.Scanner; public class RecycledPairs{ public static void main(String[] args) { Scanner input = null; PrintWriter out = null; try { input = new Scanner(new FileInputStream(""C-small-attempt0.in"")); out = new PrintWriter(new FileOutputStream (""pairs.out"")); int numLines = Integer.parseInt(input.nextLine()); String[] lines = new String[numLines]; int[][] AB = new int[numLines][2]; int[] temp = new int[2]; for(int i = 0; i < numLines; i++) { lines[i] = input.nextLine(); temp[0] = Integer.parseInt(lines[i].split("" "")[0]); temp[1] = Integer.parseInt(lines[i].split("" "")[1]); AB[i][0] = temp[0]; AB[i][1] = temp[1]; } int max; int min; int[] range; int match = 0; int size = 0; for(int j = 0; j < numLines; j++) { match = 0; max = AB[j][1]; min = AB[j][0]; range = new int[max-min+1]; for(int k = 0; k < range.length; k++) { range[k] = min; min++; } int[] sums = new int[range.length]; // calculate sums of numbers size=(""""+range[0]).length(); for(int l = 0; l used = new HashSet(); //used.add(k); int kk = k; for (int d = 1; d < digits; d++) { int r = kk % 10; kk /= 10; kk += r * m; if (kk > k && kk <= B && !used.contains(kk)) { result++; used.add(kk); } } } out.println(""Case #"" + i + "": "" + result); } out.flush(); out.close(); } private int digits(int a) { int d = 0; while (a > 0) { d++; a /= 10; } return d; } public static void main(String[] args) throws IOException { ProblemC solver = new ProblemC(); solver.solve(); } } " B12629,"import java.lang.reflect.Array; import java.util.*; public class ArrayUtil { static T[] revers (T[] t){ List list = Arrays.asList(t); Collections.reverse(list); return (T[]) list.toArray(); } static Map listToMap(List list) { HashMap map = new HashMap<>(); for (int i = 0; i < list.size(); i++) { T t = list.get(i); map.put(t,i); } return map; } static List fromIndexList(List inds, List values) { ArrayList ts = new ArrayList<>(); for (Integer ind : inds) { ts.add(values.get(ind)) ; } return ts; } } " B10138,"import java.util.Scanner; public class Recycled { /* private static boolean areTwoMirrors(int n, int m, int A, int B) { if (A > n || n >= m || m > B) return false; String mStr = Integer.toString(m); String nStr = Integer.toString(n); if (mStr.charAt(0) == '0' || nStr.charAt(0)=='0') return false; if (mStr.length() != nStr.length()) return false; for (int i=1; i < nStr.length(); i++) { nStr = nStr.substring(1) + nStr.charAt(0); if (nStr.equals(mStr)) return true; } return false; }*/ static int[] powersOfTen = new int[7]; private static int process(int A, int B) { //boolean[] hasVisited = new boolean[B+1]; int numDigits = Integer.toString(A).length(); int count = 0; for (int i = A; i < B; i++) { int num = i; for (int start = 1; start < numDigits; start++) { int firstDigit = num/powersOfTen[numDigits-1]; num -= firstDigit*powersOfTen[numDigits-1]; num *= 10; num += firstDigit; if (num <= B && num > i) { //if (!areTwoMirrors(i,num,A,B)) System.out.println(""Jlfwje""); //System.out.println(i+"" ""+num); count++; } } } return count; } public static void main(String[] args) { int currPower = 1; for (int i=0; i < powersOfTen.length; i++) { powersOfTen[i] = currPower; currPower *= 10; } Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int i=0; i < T; i++) { int A = in.nextInt(); int B = in.nextInt(); System.out.println(""Case #""+(i+1)+"": ""+process(A,B)); } //System.out.println(process(A,B)); } } " B11504,"package it.simone.google.code.jam2012; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class GoogleCodeJamManager { public static void main(String[] args) { // GoogleCodeExercise tm = new Translator(); // GoogleCodeJamManager.execute(""inputFile_Translator.in"",""outputFile_Translator.out"",tm); // GoogleCodeExercise dancer = new Dancer(); // GoogleCodeJamManager.execute(""inputFile_Dancer.in"",""outputFile_Dancer.out"",dancer); GoogleCodeExercise recycled = new RecycledNumber(); GoogleCodeJamManager.execute(""inputFile_Recycled.in"",""outputFile_Recycled.out"",recycled); } public static void execute(String inputFile,String outputFile,GoogleCodeExercise exercise) { BufferedReader br = null; BufferedWriter bw=null; int testNumber=0; try { exercise.initialize(); br = new BufferedReader(new FileReader(inputFile)); bw=new BufferedWriter(new FileWriter(outputFile)); String line = br.readLine(); testNumber=Integer.parseInt(line); line=br.readLine(); int testCounter=1; while (line != null) { System.out.println(""Test"" +testCounter +""/""+testNumber+ ""\t Line="" + line); String translatedLine=exercise.execute(line); bw.write(""Case #""+testCounter+"": ""+translatedLine+""\n""); line=br.readLine(); testCounter++; } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { if (br != null) br.close(); if(bw!=null) bw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } " B10669,"import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Recycled implements Runnable { final Scanner in; final PrintWriter out; public Recycled() throws FileNotFoundException { out = new PrintWriter(getClass().getName().toLowerCase() + "".out""); in = new Scanner(new File(getClass().getName().toLowerCase() + "".in"")); } public static void main(String[] args) { try { new Recycled().run(); } catch (FileNotFoundException e) { e.printStackTrace(); } } public void run() { int tests = in.nextInt(); for (int testcase = 1; testcase <= tests; testcase++) { out.print(""Case #"" + testcase + "": ""); int a = in.nextInt(); int b = in.nextInt(); int res = 0; HashSet met = new HashSet(); for (int i = a; i <= b; i++) { String istr = String.valueOf(i); met.clear(); for (int len = 1; len < istr.length(); len++) { String rec = istr.substring(len) + istr.substring(0, len); if (rec.startsWith(""0"")) { continue; } int x = Integer.parseInt(rec); if (x >= a && x <= b && i < x) { met.add(x); } } res += met.size(); //System.out.println(istr + ""-> "" + met); } out.println(res); } out.close(); in.close(); } } " B11827,"package main; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class main { public static void main(String[] args) throws IOException{ String text = """"; int lineCounter = 0; int totalLength = 2; int outputTotal = 0; int firstNum = 0; int secondNum = 0; long rotated = 0; String[] array = null; int copy=0; char[] Output=null; String output=null; String firstNumStr=""""; String secondNumStr = """"; String temp = """"; PrintWriter out = null; BufferedReader in = new BufferedReader(new FileReader(""C-small.in"")); text = in.readLine(); totalLength = Integer.parseInt(text); //System.out.print(totalLength); while(lineCounter < totalLength){ text = in.readLine(); System.out.println(text); if(text == null)break; array = text.split("" ""); firstNum = Integer.parseInt(array[0]); firstNumStr = array[0]; secondNum = Integer.parseInt(array[1]); secondNumStr = array[1]; copy = firstNum; //System.out.println(""firstNum = "" + firstNum); //System.out.println(""secondNum = "" + secondNum); int numOfDigits = (int) Math.log10((double) firstNum) + 1; for(int i = 0; i < (secondNum - copy); i++){ for(int j = 1; j < numOfDigits; j++){ temp = firstNumStr.substring(j); temp = temp + firstNumStr.substring(0, j); rotated = Integer.parseInt(temp); if(rotated > firstNum && rotated <= secondNum){ outputTotal++; } } firstNum++; firstNumStr = Integer.toString(firstNum); } //output = new String(outputTotal); out = new PrintWriter(new FileWriter(""outputfile.out"",true)); out.println(""Case #""+ String.valueOf(lineCounter+1)+ "": ""+ outputTotal); out.close(); System.out.println(""Case #""+ String.valueOf(lineCounter+1)+ "": ""+ outputTotal); outputTotal = 0; lineCounter++; } } } " B13131,"import java.io.*; import java.util.Arrays; import java.util.Locale; import java.util.Scanner; public class RecycledNumbers { // -ea –Xmx256M –Xss64M long A, B; private Object solve() throws Exception { long result = 0; for (long n = A; n < B; n++) { long d = 1; while (d <= n) d *= 10; d /= 10; long m = n; do { m = (m % d) * 10 + m / d; if (n < m && m <= B) { result++; } } while (m != n); } return result; } private void load() throws Exception { A = nextLong(); B = nextLong(); log.print(""A: "" + A + "", B: "" + B); } private static final String PREFIX = ""C-small-attempt0""; private static final String PATH = ""d:/gcjam12/qr/""; private static final String POSTFIX_IN = "".in""; private static final String POSTFIX_OUT = "".out""; private static final PrintStream log = System.out; public static void main(String args[]) throws Exception { Locale.setDefault(Locale.US); InputStreamReader reader = new InputStreamReader(new BufferedInputStream(new FileInputStream(PATH + PREFIX + POSTFIX_IN))); PrintStream out = new PrintStream(new FileOutputStream(PATH + PREFIX + POSTFIX_OUT)); Scanner in = new Scanner(reader); long t0 = System.nanoTime(); int testCount = in.nextInt(); in.nextLine(); for (int testIndex = 1; testIndex <= testCount; testIndex++) { log.printf(""Data #%d: "", testIndex); RecycledNumbers s = new RecycledNumbers(); s.in = in; s.load(); s.in = null; log.println(); long t1 = System.nanoTime(); String result = ""Case #"" + testIndex + "": "" + s.solve(); out.println(result); log.println(result); log.printf(""Time #%d: %.6f sec\n\n"", testIndex, (System.nanoTime() - t1) / 1e9); } log.printf(""Total time: %.6f sec"", (System.nanoTime() - t0)/1e9); reader.close(); out.close(); } private Scanner in; private int nextInt() { return in.nextInt(); } private long nextLong() { return in.nextLong(); } private double nextDouble() { return Double.parseDouble(in.next()); } private String nextLine() { return in.nextLine().trim(); } private void skipLine() { in.nextLine(); } private String next() { return in.next().trim(); } private int[] nextIntArray(int size) { int[] a = new int[size]; for (int i = 0; i < size; i++) a[i] = in.nextInt(); return a; } private long[] nextLongArray(int size) { long[] a = new long[size]; for (int i = 0; i < size; i++) a[i] = in.nextLong(); return a; } private double[] nextDoubleArray(int size) { double[] a = new double[size]; for (int i = 0; i < size; i++) a[i] = Double.parseDouble(in.next()); return a; } private String[] nextLineArray(int size) { String[] a = new String[size]; for (int i = 0; i < size; i++) a[i] = in.nextLine().trim(); return a; } private String[] nextTokenArray(int size) { String[] a = new String[size]; for (int i = 0; i < size; i++) a[i] = in.next().trim(); return a; } } " B10116,"import java.util.*; class Main { public static void main(String[] arg) { Scanner in = new Scanner(System.in); int trials = in.nextInt(); int tt = 0; while(tt < trials) { int ret = 0; int A = in.nextInt(); int B = in.nextInt(); for(int i=A; i oNums = new HashSet(); for(int j=1; j i && val <= B) { ++ret; } oNums.add(num); } } } System.out.println(""Case #"" + ++tt + "": "" + ret); } } }" B13197,"package tr0llhoehle.cakemix.utility.googleCodeJam; public interface Solver { public String solve(T p); } " B12572,"package c; import java.io.BufferedReader; import java.io.FileReader; import java.io.PrintWriter; import java.util.HashSet; public class RecycledNumbers { public static int getDistinctRecycleCount(int min, int max) { HashSet distinctCollection = new HashSet(); for(int i = min; i <= max; i++) { distinctCollection.addAll(getThePossiblePair(i, max)); } return distinctCollection.size(); } private static HashSet getThePossiblePair(int theNum, int max) { HashSet ret = new HashSet(); String theNumStr = Integer.toString(theNum); for(int n = 1; n < theNumStr.length(); n++) { //roll the number 1 time to the left char firstChar = theNumStr.charAt(0); theNumStr = theNumStr.substring(1) + firstChar; int theRolledNum = Integer.parseInt(theNumStr); //check if the rolled number is possible if((theNum < theRolledNum) && (theRolledNum <= max)) ret.add(Integer.toString(Math.min(theNum, theRolledNum)) + ""-"" + Integer.toString(Math.max(theNum, theRolledNum))); } return ret; } public static void main(String[] args) throws Exception { //initial reader by args[0] BufferedReader r = new BufferedReader(new FileReader(args[0])); int cases = Integer.parseInt(r.readLine()); //initial writer by args[1] PrintWriter w = new PrintWriter(args[1]); //do for(int i = 1; i <= cases; i++) { String[] ab = r.readLine().split("" ""); w.println(""Case #"" + i + "": "" + getDistinctRecycleCount(Integer.parseInt(ab[0]), Integer.parseInt(ab[1]))); } //close file handles w.close(); r.close(); } }" B10869,"package CodeJam2012; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.Stack; public class Q3 { public static void main(String[] args)throws IOException { FileReader buf=new FileReader(""C-small.in""); BufferedReader br=new BufferedReader(buf); int cases=Integer.parseInt(br.readLine()); String[] output=new String[cases]; for(int i=1;i<=cases;i++){ int ctr=0; String input=br.readLine(); String[] splits=input.split("" ""); int A=Integer.parseInt(splits[0]); int B=Integer.parseInt(splits[1]); for(int n=A;n<=B;n++){ String temp=n+""""+n; for(int m=n+1;m<=B;m++){ String temp2=m+""""; if(temp.contains(temp2)){ ctr++; } } } if(i!=cases) output[i-1]=""Case #""+i+"": ""+ctr+""\n""; else output[i-1]=""Case #""+i+"": ""+ctr; } br.close(); buf.close(); FileWriter buf1 = new FileWriter(new File (""C-small_Output.txt""), true); BufferedWriter bw1=new BufferedWriter(buf1); for(int i=0;i0){ String s1s1 = s1+s1; return isSubString(s2,s1s1); } return false; } public static int recycle(int a, int b){ int n; int m; int count=0; for(n=a;n pairs = new HashSet(); for (int m = start + 1; m <= end; m++) { for (int n = start; n < m; n++) { String recycle = recycle(n, m); if (recycle != null) { pairs.add(recycle); } } } return pairs.size(); } private String recycle(int n, int m) { String ns = String.valueOf(n); String ms = String.valueOf(m); if (ms.length() != ns.length()) return null; if ((ns + ns).contains(ms)) { return n + "" "" + m; } else { return null; } } } " B11012,"import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.LinkedList; import java.util.Scanner; public class ProblemC { static long[] pow = new long[12]; private static long solve(int a, int b) { HashMap> f = new HashMap>(); long res = 0; for (int i = a; i <= b; i++) { int s = (i + """").length(); for (int j = 1; j < s; j++) { int c = (int) ((i / pow[j]) + pow[s - j] * (i % pow[j])); if (c <= b && c >= a && c != i && (c + """").length() == s) { boolean k = f.containsKey(i); if (!k)f.put(i, new LinkedList()); if (f.containsKey(c))k = f.get(c).contains(i); if (!k) {f.get(i).add(c);res++; } } } } return res; } public static void main(String[] args) throws IOException { pow[1] = 10; for (int i = 2; i < 12; i++) pow[i] = pow[i - 1] * 10; Scanner input = new Scanner(new FileReader(""input"")); BufferedWriter output = new BufferedWriter(new FileWriter(""output"")); long res; int n = input.nextInt(); for (int j = 1; j <= n; j++) { res = solve(input.nextInt(), input.nextInt()); output.write(""Case #"" + j + "": "" + res); output.newLine(); } output.close(); } }" B11544,"import java.io.BufferedReader; import java.io.InputStreamReader; public class Recycler { public static void main(String[] args) { // TODO Auto-generated method stub String input; BufferedReader br; try{ br=new BufferedReader(new InputStreamReader(System.in)); int T=Integer.parseInt(br.readLine()); int A,B; String []inputs; for (int i=0;i 0) { m=Integer.parseInt(n%multiple + """" + n/multiple); if (m<=B && n= A && arr[k] <= B && arr[k] > i) ans++; } } out.println(""Case #"" + C + "": "" + ans); } public static int[] rotateString(String s){ Set list = new HashSet(); int L = s.length(); if(L == 1) return new int[]{}; for(int i = 1; i < L ; i++) { list.add(Integer.parseInt( s.substring(i) + s.substring(0, i))); } int size = list.size(); int[] arr = new int[size]; int now = 0; for(Integer num : list) arr[now++] = num; return arr; } }" B12879,"package codejam2012.qr; import codejam.common.CodeHelper; import java.util.ArrayList; import java.util.List; /** * * @author Chen Ling */ public class ProblemC { private static String SMALL_IN_FILE_NAME = ""/codejam2012/qr/C-small.in""; private static String LARGE_IN_FILE_NAME = ""/codejam2012/qr/C-large.in""; private static String SMALL_OUT_FILE_NAME = ""/codejam2012/qr/C-small.out""; private static String LARGE_OUT_FILE_NAME = ""/codejam2012/qr/C-large.out""; public static int solve(int start, int end) { int total = 0; for (int number = start; number < end + 1; number++) { String pairN = String.valueOf(number); if (pairN.length() == 1) { continue; } for (int i = 1; i < pairN.length(); i++) { String pairM = pairN.substring(i, pairN.length()) + pairN.substring(0, i); int pairMI = Integer.parseInt(pairM); if (pairMI >= start && pairMI > number && pairMI <= end) { total++; // System.out.print(""Pair("" + pairN + "", "" + pairM + "")""); // System.out.print("", Ture""); // System.out.println(""""); } } } // System.out.println(""Total: "" + total); return total; } public static void main(String[] args) { // ProblemC.solve(1111, 2222); List smallLinesIn = CodeHelper.loadInputLines(SMALL_IN_FILE_NAME); List smallOuts = new ArrayList(); for (int i = 1; i < smallLinesIn.size(); i++) { String[] numbers = smallLinesIn.get(i).split("" ""); int start = Integer.parseInt(numbers[0]); int end = Integer.parseInt(numbers[1]); smallOuts.add(""Case #"" + i + "": "" + ProblemC.solve(start, end)); } CodeHelper.writeOutputs(SMALL_OUT_FILE_NAME, smallOuts); // // List largeLinesIn = CodeHelper.loadInputLines(LARGE_IN_FILE_NAME); // List largeOuts = new ArrayList(); // for (int i = 1; i < largeLinesIn.size(); i++) { // String[] numbers = largeLinesIn.get(i).split("" ""); // int start = Integer.parseInt(numbers[0]); // int end = Integer.parseInt(numbers[1]); // largeOuts.add(""Case #"" + i + "": "" + ProblemC.solve(start, end)); // } // CodeHelper.writeOutputs(LARGE_OUT_FILE_NAME, largeOuts); } } " B12114,"package com.renoux.gael.codejam.fwk; import com.renoux.gael.codejam.utils.Input; import com.renoux.gael.codejam.utils.Output; public class Model extends Solver { public static void main(String... args) throws Exception { new Model().run(); } @Override protected void solveCase(Input in, Output out) { // TODO } @Override protected String getProblemName() { return ""hey2012/Model""; } } " B12126,"import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.FileInputStream; import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { public static int gao(int a, int b) { int r = 0; int n = ("""" + a).length(); int m = 1; for (int i = 1; i < n; ++i) m*= 10; for (int i = a; i <=b; ++i) { Set s = new HashSet(); int x = i; for (int j = 0; j < n; ++j) { int y = x % 10 * m + x / 10; if (y > i && y <=b && !s.contains(y)) { r ++; s.add(y); } x = y; } } return r; } public static void main(String[] args) throws Exception { //InputStream in = System.in; InputStream in = new FileInputStream(""c:\\C-small-attempt0.in""); Scanner scanner = new Scanner(in); //BufferedReader r = new BufferedReader(new InputStreamReader(in)); /* for (;;) { String l = r.readLine(); if (l == null) { break; } } */ int n; n = scanner.nextInt(); for (int i = 1; i <= n; ++i) { int a = scanner.nextInt(); int b = scanner.nextInt(); System.out.println(""Case #"" + i + "": "" + gao(a,b)); } } } " B11014,"import java.io.*; import java.util.LinkedList; import java.util.StringTokenizer; public class RecycledNumbers { public static void main(String[] args) { StringTokenizer st; BufferedReader br = null; try { FileWriter fstream = new FileWriter(""output.out""); BufferedWriter out = new BufferedWriter(fstream); String sCurrentLine; br = new BufferedReader(new FileReader(""C-small-attempt0.in"")); sCurrentLine = br.readLine();//no. of cases int i = 1; while ((sCurrentLine = br.readLine()) != null) { out.write(""Case #"" + i++ + "": ""); st = new StringTokenizer(sCurrentLine,"" ""); String n = st.nextToken(); int N = Integer.parseInt(n); int m = Integer.parseInt(st.nextToken()); int count = 0; for (int j = N; j < m; j++) { String recycled = Integer.toString(j); LinkedList possible_rotations = new LinkedList(); for (int k = 0; k < n.length(); k++) { recycled = recycled.substring(1)+recycled.charAt(0); if(!possible_rotations.contains(recycled) && Integer.parseInt(recycled) > j && Integer.parseInt(recycled) <= m) count++; possible_rotations.addLast(recycled); } } out.write(count + ""\n""); } out.close(); } catch (IOException e) { e.getMessage(); } finally { try { if (br != null)br.close(); } catch (IOException ex) { ex.getMessage(); } } } } " B12252,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codajam2012; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; import java.util.Vector; /** * * @author dectroo */ public class Recycled { public static Vector tabl; static long[] RotationList(String N) { long result[] = new long[N.length() - 1]; long n = Long.parseLong(N); long number = n; long start = number; int i = 0; int numdigits = (int) Math.log10((double) number); // would return numdigits - 1 int multiplier = (int) Math.pow(10.0, (double) numdigits); while (true) { long q = number / 10; long r = number % 10; number = number / 10; number = number + multiplier * r; if (number == start) { break; } else { result[i] = number; i++; } } return result; } static void ComputePair(long A, long B) { long index = A; int numbrPair = 0; tabl = new Vector(); String indexString; while (index < B) { if (index != 0) { indexString = String.valueOf(index); long result[] = RotationList(indexString); for (int i = 0; i < result.length; i++) { /* * if(tabl.contains(new Long(result[i]))){ * * } */ if (index < result[i] && result[i] <= B) { tabl.add(new Long(result[i])); //System.out.println(result[i]); } } } index++; } } public static void main(String[] args) throws IOException { // TODO Auto-generated method stub Scanner in = new Scanner(new File(""test.in"")); PrintWriter out = new PrintWriter(""recycled.out""); /* * for(int i=0;i { protected String s1; protected String s2; public MyNumberStringPair(String str1, String str2){ /* assert (str1.compareTo(str2) != 0) : ""Identical Strings cannot be paired.""; if (str1.compareTo(str2) != 0){ return; } */ if (str1.compareTo(str2) < 0 ){ s1 = new String(str1); s2 = new String(str2); } else{ s1 = new String(str2); s2 = new String(str1); } } public String getS1() { return s1; } public void setS1(String s1) { this.s1 = s1; } public String getS2() { return s2; } public void setS2(String s2) { this.s2 = s2; } @Override public int compareTo(MyNumberStringPair o) { // TODO Auto-generated method stub int c1, c2; c1 =this.s1.compareTo(o.s1); c2 = this.s2.compareTo(o.s2); if ((c1 == 0 ) && (c2 ==0)) return 0; if ( c1 != 0 ){ return c1; } return c2; } } " B10555,"import java.io.*; import java.util.Scanner; public class tknowjam3 { public static void main(String args[]) throws java.lang.Exception { int a,b,n,m, cnt=0,len=0; int t,cas=1; Scanner scan=new Scanner(new FileReader(""tknowjam3in"" + "".in"")); PrintWriter out=new PrintWriter(""tknowjam3out"" + "".out""); t=scan.nextInt(); while(t!=0) { t--; cnt=0; a=scan.nextInt(); b=scan.nextInt(); String str1,tstr1; for(int i=a;i<=b;i++) { str1=Integer.toString(i); for(int j=a;j<=b;j++) { if(i!=j && i iCanHasPair=new HashSet(); int result=0; for (int i=a; i<=b; i++){ curr=String.valueOf(i); boolean inRange; for (int k=1; kb){ inRange=false; break; } } if (currVal added = new TreeSet(); for(int j = 0; j diffNums = new HashSet(); diffNums.add(num); int ans = 0; String numString = num+""""; for(int i =0; i< numString.length(); i++){ numString = numString.substring(1)+numString.charAt(0); int numTest = Integer.parseInt(numString); if(numTest<=max&&numTest>=min&&diffNums.add(numTest)){ ans++; } } return ans; } } " B11409,"import java.io.*; import java.util.*; import static java.lang.Integer.*; import static java.lang.Math.*; public class CodeJamC { public static void main(String args[]) throws Throwable { System.setOut(new PrintStream(""C-Small.out"")); BufferedReader in = new BufferedReader(new FileReader(""C-small-attempt0.in"")); //BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); for (int t=0,T=parseInt(in.readLine().trim());t++ set=new TreeSet(new Comparator() { public int compare(int[] o1, int[] o2) { return o1[0]!=o2[0]?o1[0]-o2[0]:o1[1]-o2[1]; } }); for(int i=A;i<=B;i++){ String a=i+""""; for(int j=a.length()-1;j>0;j--){ int b=parseInt(a.substring(j)+a.substring(0,j)); if(i!=b&&b>=A&&b<=B&&(b+"""").length()==a.length()){ set.add(new int[]{min(i,b),max(i,b)}); } } } sb.append(""Case #""+t+"": ""+set.size()+""\n""); } System.out.print(new String(sb)); } }" B11605,"package recyclednumbers; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class Input { List cases = null; public List getCases() { return cases; } String path = """"; public String getPath() { return path; } public Input(String path) { this.path = path; } public void setInputData() { try { // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(this.path); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; // Read File Line By Line int lineNumber = 0; cases = new ArrayList(); while ((strLine = br.readLine()) != null) { // Print the content on the console lineNumber++; if(lineNumber == 1){continue;} cases.add(new TestCase(Integer.parseInt(strLine.split("" "")[0]), Integer.parseInt(strLine.split("" "")[1]))); } // Close the input stream in.close(); } catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } } " B10747,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { private RecycledNumbers() { } public void solveInput(final InputStream input, final OutputStream output) throws IOException { final BufferedReader reader = new BufferedReader(new InputStreamReader( input)); final BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(output)); final int numTestCase = Integer.valueOf(reader.readLine().trim()); System.out.println(""Total Test Cases: "" + numTestCase); String line = null; int caseNo = 1; while ((line = reader.readLine()) != null) { final String[] words = line.trim().split("" ""); final long A = Long.parseLong(words[0]); final long B = Long.parseLong(words[1]); final Set resultSet = new HashSet(); for (long M = B; M >= A; M--) { final String str1 = String.valueOf(M); if (str1.length() == 1) { continue; } for (int max = str1.length() - 1; max >= 1; max--) { final String first = str1.substring(0, str1.length() - max); final String last = str1.substring(str1.length() - max, str1.length()); final String str2 = last + first; final long N = Long.valueOf(str2); if (A <= N && N < M && M <= B && str1.charAt(0) != '0' && str2.charAt(0) != '0') { /* * System.out.println(A + "" <= "" + N + ""("" + str2 + * "") < "" + M + ""("" + str1 + "") <= "" + B); */ resultSet.add(str1 + str2); } } } if (caseNo > 1) { writer.write(""\n""); } final String text = ""Case #"" + (caseNo++) + "": "" + resultSet.size(); System.out.println(text); writer.write(text); writer.flush(); } writer.close(); reader.close(); } public static void main(final String[] args) throws Exception { final RecycledNumbers number = new RecycledNumbers(); final File outputFile = new File(""output/C-small-attempt0.out""); if (outputFile.exists()) { outputFile.delete(); } final FileOutputStream fos = new FileOutputStream(outputFile); number.solveInput(SpeakingInTongues.class .getResourceAsStream(""C-small-attempt0.in""), fos); } } " B10108,"import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); Integer numCases = Integer.parseInt(in.nextLine()); for (int k = 0; k < numCases; k++) { Integer num1 = Integer.parseInt(in.next()); int num2 = Integer.parseInt(in.next()); int count = 0; //ArrayList tested = new ArrayList(); for (Integer i = num1; i <= num2; i++) { String number = i.toString(); for (int j = 1; j < number.length(); j++) { String front = number.substring(j); String newNumber = front + number.substring(0, j); Integer result = Integer.parseInt(newNumber); if (result > i && result <= num2) { /*tested.add(result); tested.add(i); System.out.println(result);*/ count++; } } //tested.add(i); } System.out.println(""Case #""+(k+1)+"": ""+count); } } }" B13162,"package org.weiwei.recyclenumber; import java.util.Date; import java.util.HashSet; import java.util.Set; /** * Created with IntelliJ IDEA. * User: ding * Date: 12-4-14 * Time: 下午1:03 * To change this template use File | Settings | File Templates. */ public class RecyleBin { int lower; int higher; Set retSet = new HashSet(); int length; public RecyleBin(int lower, int higher) { this.lower = lower; this.higher = higher; this.length = String.valueOf(lower).length(); } public int exhaust(int i){ int ret = 0; retSet.clear(); if(length ==1 ) return 0; else{ for(int j = 1; j < length+1; j++){ int temp = i/(int)Math.pow(10,j)+i%(int)Math.pow(10,j)*(int)Math.pow(10,length - j); if(temp >= (10^length) && temp < i && temp >= lower && !retSet.contains(temp)){ ret++; retSet.add(temp); } } } return ret; } public int exhaust(){ int ret = 0; for(int i = higher; i >= lower; i--){ ret+=exhaust(i); } return ret; } public static void main(String[] args) { System.out.println(new Date(System.currentTimeMillis())); RecyleBin bin = new RecyleBin(1111, 2222); System.out.println(bin.exhaust()); } } " B12785,"package qualification; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Recycled { public static void main(String[] args) { Scanner s = new Scanner(System.in); int numCases = s.nextInt(); for (int i = 1; i <= numCases; i++) { int a = s.nextInt(); int b = s.nextInt(); int numRecycled = countRecycled(a, b); System.out.printf(""Case #%d: %d\n"", i, numRecycled); } } private static int countRecycled(int a, int b) { int result = 0; StringBuilder sbB = new StringBuilder(); sbB.append(b); List register = new ArrayList(); for (int i = a; i <= b; i++) { register.clear(); if (i < 10) continue; StringBuilder sb = new StringBuilder(); sb.append(i); for (int j = sb.length() - 1; j > 0; j--) { StringBuilder newCombinedSb = new StringBuilder(); newCombinedSb.append(sb.substring(j)).append(sb.substring(0, j)); if (newCombinedSb.charAt(0) == '0') continue; if (newCombinedSb.charAt(0) > sbB.charAt(0)) continue; if (newCombinedSb.charAt(0) < sb.charAt(0)) continue; int newCombinedInt = Integer.parseInt(newCombinedSb.toString()); if (newCombinedInt <= b && newCombinedInt > i) { if (!register.contains(newCombinedInt)) { register.add(newCombinedInt); } } } result += register.size(); } return result; } } " B12925,"package com.javanme.gcj.one.c; import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.Charset; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class RecycledNumbers { public static void main(String args[]) { String input = ""C-small-attempt0""; Path pathin = FileSystems.getDefault().getPath(input + "".in""); Path pathout = FileSystems.getDefault().getPath(input + "".out""); try (PrintWriter pout = new PrintWriter(Files.newOutputStream(pathout, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE))) { List lines = Files.readAllLines(pathin, Charset.forName(""UTF-8"")); int countLines = lines.size(); String str = null; int small = 0; int smallAux = 0; int big = 0; String[] split = null; String num = null; String numAux = null; StringBuffer backDigits = null; int countRecycled = 0; Map mapDistinct = null; for (int i = 1; i < countLines; i++) { countRecycled = 0; str = lines.get(i); split = str.split("" ""); small = Integer.parseInt(split[0]); big = Integer.parseInt(split[1]); for (int j = small; j < big; j++) { num = """" + j; backDigits = new StringBuffer(); mapDistinct = new HashMap<>(); for (int k = num.length() - 1; k > 0; k--) { backDigits.insert(0, num.charAt(k)); numAux = backDigits.toString() + num.substring(0, num.length() - backDigits.length()); smallAux = Integer.parseInt(numAux); if (j < smallAux && smallAux <= big) { for (int m = j + 1; m <= big; m++) { if (smallAux == m) { if (!mapDistinct.containsKey(m)) { mapDistinct.put(m,1); countRecycled++; } break; } } } } } pout.printf(""Case #%d: %d\n"", i, countRecycled); } } catch (IOException ex) { ex.printStackTrace(); } } } " B11532,"package com.google.jam.eaque.qualif.c; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import com.google.jam.eaque.stub.InputFileManager; import com.google.jam.eaque.stub.Stub; import com.google.jam.eaque.stub.Util; public class StubImpl extends Stub { @Override public String runTestCase(InputFileManager ifm) throws NumberFormatException, IOException { long[] supremum = Util.stringsToLongs(ifm.readAndSplit()); long res = 0; ArrayList rotations = null; ArrayList test = new ArrayList<>(); for (long i = supremum[0]; i <= supremum[1]; i++) { if (isUnique(i)) { continue; } rotations = getRotations(i); for (Long rot : rotations) { if (rot > i && rot <= supremum[1]) { res++; test.add(i + "" "" + rot); } } } for (int i = 0; i < test.size(); i++) { for (int j = i+1; j < test.size(); j++) { if (test.get(i).equals(test.get(j))) { System.out.println(test.get(i)); } } } return "" "" + res; } private boolean isUnique(long l) { Byte[] ba = longToByteArray(l); boolean res = true; for (int i = 0; i < ba.length - 1; i++) { if (ba[i] != ba[i+1]) { res = false; break; } } return res; } private Byte[] longToByteArray(long l) { ArrayList res = new ArrayList(); while (l != 0) { res.add((byte) (l % 10)); l /= 10; } Collections.reverse(res); return res.toArray(new Byte[0]); } private long byteArrayToLong(Byte[] b) { long res = 0; for (int k = 0; k < b.length; k++) { res += b[b.length - 1 - k] * (long)Math.pow(10, k); } return res; } private ArrayList getRotations(long l) { Byte[] ba = longToByteArray(l); Byte[] tmp = new Byte[ba.length]; ArrayList res = new ArrayList(); for (int i = 0; i < ba.length - 1; i++) { for (int j = 0; j < ba.length ; j++) { tmp[j] = ba[(ba.length - 1 + j - i) % ba.length]; } if (tmp[0] != 0 && !res.contains(byteArrayToLong(tmp))) { res.add(byteArrayToLong(tmp)); } } return res; } } " B13140,"import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Q3RecycledNumbers { public static void main(String[] args) throws FileNotFoundException, IOException { Scanner scanner = new Scanner(new File(""q3.input"")); FileWriter writer = new FileWriter(""q3.output""); int cases = scanner.nextInt(); for (int i = 1; i <= cases; i++) { int a = scanner.nextInt(); int b = scanner.nextInt(); int n = solve(a, b); writer.write(""Case #"" + i + "": "" + n + ""\n""); } writer.close(); } private static int solve(int a, int b) { int n = 0; for (int i = b; i >= a; i--) { String strI = String.valueOf(i); Set mirrorSet = new HashSet(); for (int j = 1; j <= strI.length(); j++) { String r = strI.substring(j, strI.length()) + strI.substring(0, j); int intR = Integer.valueOf(r); if (intR < i && intR >= a && !mirrorSet.contains(intR)) { mirrorSet.add(intR); n++; } } } return n; } } " B12647,"import java.util.*; import java.io.*; class gcj002{ public static String RotateNumber(String aaa) { /* int start = Integer.parseInt(aaa); int number = Integer.parseInt(aaa); int numdigits = (int) Math.log10((double)number); // would return numdigits - 1 int multiplier = (int) Math.pow(10.0, (double)numdigits); //System.out.println(numdigits); //System.out.println(multiplier); int q = number / 10; int r = number % 10; //1234 = 123; number = number / 10; number = number + multiplier * r; return number+""""; */ String ret=""""; String str,str1; // str=""""+number; str=aaa; int numdigits=str.length(); char c; c=str.charAt(numdigits-1); str1=c+str.substring(0,numdigits-1); //number=Integer.parseInt(str1); //return number; // return ret=""""+number; return str1; } public static void main (String[] args) throws IOException{ //String str="""",str1=""""; //char c; FileReader fin=new FileReader(""C-small-attempt0.in""); FileWriter fout=new FileWriter(""out.out""); Scanner scan=new Scanner(fin); Scanner scan1=new Scanner(fin); int count=scan.nextInt(); int num1=0,num2=0,temp=0,length=0,ans,rnum,j=0,k=0; String str="""",pp="""",rt=""""; for (int i=0;i>>""+j+"" K------>>>""+k); for(int z=0;z>>""+temp+"" k------>>>""+k); } } } } //System.out.println(""length ----------""+length); // System.out.println(""Count======""+i); // System.out.println(ans+""\n""); // System.out.println(""Case #""+(i+1)+"": ""+ans+""\n""); fout.write(""Case #""+(i+1)+"": ""+ans+""\n""); } fin.close(); fout.close(); } }" B10049,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package google.code.jam.recycled.numbers; import java.io.*; import java.util.ArrayList; /** * * @author Lucas */ public class Utils { public ArrayList parse(String file) { BufferedReader in = null; ArrayList list = new ArrayList(); int size; try { in = new BufferedReader(new InputStreamReader(new DataInputStream(new FileInputStream(file)))); size = Integer.parseInt(in.readLine()); for (int n = 0; n < size; n++) { String[] stringCases = in.readLine().split(""\\s+""); Integer[] cases = new Integer[2]; cases[0] = Integer.parseInt(stringCases[0]); cases[1] = Integer.parseInt(stringCases[1]); list.add(cases); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (IOException e) { e.printStackTrace(); } } return list; } public void write(ArrayList output, String file) { BufferedWriter out = null; try { out = new BufferedWriter(new FileWriter(file)); for (int n = 0; n < output.size() - 1; n++) { out.write(""Case #"" + (n + 1) + "": "" + output.get(n)); out.newLine(); } out.write(""Case #"" + output.size() + "": "" + output.get(output.size() - 1)); } catch (IOException e) { e.printStackTrace(); } finally { try { if (out != null) { out.flush(); out.close(); } } catch (IOException ex) { ex.printStackTrace(); } } } } " B10988," /** * Write a description of class solver here. * * @author (your name) * @version (a version number or a date) */ public class solver { public int aise(int a[],int k,int j) { int i; int temp=0; for(i=0;ia[j]) return true; } return false; } public boolean lesser(int a[],int b[],int k,int j,int n1) { if(jb[i]) return false; else if(a[(k+i)%j]0) { arr2[n1++]=temp1%10; temp1=temp1/10; } arr2=reverse(arr2,n1); for(i=a;i0) { arr[j++]=temp%10; temp=temp/10; } arr=reverse(arr,j); s=0; for(k=j-1;k>0;k--) { if(arr[k]!=0) { if(greater(arr,k,j) && lesser(arr,arr2,k,j,n1)) { count++; comp[s++]=aise(arr,k,j); } } } for(k=0;k set; public static void main(String[] codejam) throws Exception { BufferedReader br = new BufferedReader (new FileReader (""recycle.in"")); PrintStream ps = new PrintStream (new FileOutputStream (""recycle.out"")); int t = Integer.parseInt(br.readLine()); for(int l=1;l<=t;l++) { String[] in = br.readLine().split("" ""); int first = Integer.parseInt(in[0]); int last = Integer.parseInt(in[1]); total = 0; for(int i=first;i(); for(int i=0;i a && m > n && !set.contains(m)) { set.add(m); total++; } } number = temp; } } }" B10493,"import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.SortedSet; import java.util.TreeSet; public class Executer { protected static final String FICHERO_ENTRADA_SHORT = ""C-small-attempt0.in""; protected static final String FICHERO_SALIDA_SHORT = ""C-small-attempt0.out""; protected static final String FICHERO_ENTRADA_LARGE = ""C-large-attempt0.in""; protected static final String FICHERO_SALIDA_LARGE = ""C-large-attempt0.out""; /** * @param args */ public static void main(String[] args){ TemplateClass test; try{ //SHORT VERSION test = new Recycled(FICHERO_ENTRADA_SHORT, FICHERO_SALIDA_SHORT); //LARGE VERSION //test = new Store(FICHERO_ENTRADA_LARGE, FICHERO_SALIDA_LARGE); test.procesaTestCase(); }catch (Exception e){ System.out.println(""ERROR""); } } } " B11921,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recycle; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; /** * * @author ALEX */ public class Recycle { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here try { FileReader fin=new FileReader(""C-small-attempt0.in""); BufferedReader in = new BufferedReader(fin); FileWriter fout=new FileWriter(""result.txt""); BufferedWriter out=new BufferedWriter(fout); int nrt; nrt=Integer.valueOf(in.readLine()); String [] med; String str; for(int i=1;i<=nrt;i++) { str=in.readLine(); med=str.split("" ""); int A=Integer.valueOf(med[0]); int B=Integer.valueOf(med[1]); int nr=0; String s; for (int a=A;a<=B;a++){ int x; int mo=1; while((a/mo)%10==0){ mo=mo*10; } if(a/mo>9){ mo=mo*10; s=(a%mo+""""+a/mo); x=Integer.valueOf(s); } else continue; while(a!=x){ if(x>=A&&x<=B){ nr++; } mo=1; while((x/mo)%10==0){ mo=mo*10; } if(x/mo>9){ mo=mo*10; s=(x%mo+""""+x/mo); x=Integer.valueOf(s); } else break; } } System.out.println(nr/2); out.write(""Case #""+i+"": ""+nr/2); out.newLine(); } in.close(); fin.close(); out.close(); fout.close(); } catch(Exception e){} } } " B12702,"package cj; import java.io.IOException; import java.io.FileReader; import java.io.BufferedReader; import java.io.PrintWriter; import java.io.FileWriter; import java.util.List; import java.util.ArrayList; import java.util.Scanner; public class Utils { public static int[] toInts(String str, String sep) { String[] strs = str.split(sep); int[] ret = new int[strs.length]; for (int i=0; i lines = new ArrayList(); try { FileReader fr = new FileReader(file); BufferedReader textReader = new BufferedReader(fr); String line = null; while ((line = textReader.readLine()) != null) { lines.add(line); } fr.close(); textReader.close(); } catch (IOException ioe) { ioe.printStackTrace(); } return lines.toArray(new String[0]); } public static int[] sort(int[] a) { boolean swapped = true; while (swapped) { swapped = false; for (int i=0; ia[i+1]) { int temp = a[i]; a[i] = a[i+1]; a[i+1] = temp; swapped = true; } } } return a; } public static int[] reverse(int[] a) { int[] ret = new int[a.length]; for (int i=0; i n && m[idx] <= B ) { f[idx]=1; ans++; } } } for ( int i=0 ; i < dd ; i++ ){ if ( f[i] == 1 ) { for ( int j = i+1 ; j < dd ; j++) { if ( m[i] == m[j] ) { ans--; } } } } } pw.println(""Case #"" + (t+1) + "": "" + ans); } } public int recycle (int i, int index){ return Integer.parseInt ( this.recycle ( String.valueOf(i),index ) ) ; } public String recycle (String s, int index){ return s.substring(index, s.length()) + s.substring( 0, index ); } } " B13091,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class C { public static void main(String[] args) { try { int num; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = null; str = br.readLine(); num = Integer.parseInt(str); for (int i = 0; i < num; i++) { String s = br.readLine(); String arr[] = s.split(""\\s+""); int num1 = Integer.parseInt(arr[0]); int num2 = Integer.parseInt(arr[1]); int count = 0; for (int j = num1; j <= num2; j++) { String originalStr = """" + j; String numStr = originalStr; do { numStr = numStr.substring(1) + numStr.charAt(0); if (numStr.compareTo(originalStr) > 0) { if (Integer.parseInt(numStr) <= num2) count++; } } while (!numStr.equals(originalStr)); } System.out.println(""Case #"" + (i+1) + "": "" + count); } } catch (IOException e) { e.printStackTrace(); } } } " B12023,"import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.Math.max; import static java.lang.Math.min; import static java.util.Arrays.fill; import java.io.*; import java.math.BigInteger; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class C { static BufferedReader in; static PrintWriter out; static StringTokenizer tok; static void solveTest() throws Exception { int A = nextInt(); int B = nextInt(); int digit = Integer.toString(A).length(); int res = 0; for(int n = A;n<=B;n++){ Set set = new HashSet(); for(int i = 1;i< digit;i++){ int nshift = shift(n,i); if(nshift > n && nshift <= B) { set.add(nshift); } } res += set.size(); } out.printf(""%d\n"", res); } static int shift(int N, int idx) { String bef = Integer.toString(N); int n = bef.length(); String aft = bef.substring(idx,n) + bef.substring(0,idx); return Integer.parseInt(aft); } static void solve() throws Exception { int tests = nextInt(); for (int test = 1; test <= tests; test++) { out.print(""Case #"" + test + "": ""); solveTest(); } } public static void main(String[] args) throws Exception { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); solve(); in.close(); out.close(); } static String next() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine(),"" \r\n\t\f""); } return tok.nextToken(); } static char nextChar() throws IOException { String token = next(); if (token.length() != 1) { throw new IllegalArgumentException(""String \"""" + token + ""\"" is not a single character""); } return token.charAt(0); } static int nextInt() throws IOException { return parseInt(next()); } static long nextLong() throws IOException { return parseLong(next()); } static BigInteger nextBigInt() throws IOException { return new BigInteger(next()); } }" B11176,"import java.io.*; class RNumber { public static void main(String args[])throws Exception { String[] output; BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); FileOutputStream fo=new FileOutputStream(""probB.out""); int T=Integer.parseInt(in.readLine()); output=new String[T]; int[][] inp=new int[T][]; String temp=""""; for(int i=0;i distinctPairs = new HashSet(); for (int number = A; number <= B; number++) { List pairs = generatePairsFromNumber(number, numDigits(number)); distinctPairs.addAll(pairs); } int result = distinctPairs.size(); //System.out.println(distinctPairs); System.out.println(""Case #"" + caseNumber + "": "" + result); } private List generatePairsFromNumber(int number, int digits) { List result = new ArrayList(digits); for (int pow = 1; pow < digits; pow++) { int xnumber = (number % POW10[pow]) * POW10[digits - pow] + number / POW10[pow]; if (xnumber < A || xnumber > B || xnumber == number || xnumber < POW10[digits - 1]) { continue; } Pair pair = new Pair(number, xnumber); result.add(pair); } return result; } private int numDigits(int number) { int digits = 0; while (number >= POW10[digits]) { digits++; } return digits; } class Pair { int x, y; Pair(int x, int y) { if (x < y) { this.x = x; this.y = y; } else { this.x = y; this.y = x; } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; if (x != pair.x) return false; if (y != pair.y) return false; return true; } @Override public int hashCode() { int result = x; result = 31 * result + y; return result; } @Override public String toString() { return ""{"" + x + "", "" + y + '}'; } } } " B11429,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class C { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { BufferedReader br= new BufferedReader(new FileReader(args[0])); BufferedWriter bw= new BufferedWriter(new FileWriter(args[0]+"".out"")); String line= br.readLine(); int cases= Integer.parseInt(line); for (int i= 0; i != cases; i++) { Scanner sc= new Scanner(br.readLine()); bw.write(""Case #""+(i+1)+"": ""+recycle(sc.nextInt(), sc.nextInt())+""\n""); } br.close(); bw.close(); } public static int recycle(int a, int b) { int pairs= 0; for (int n= a; n != b; n++) { char[] num= (""""+n).toCharArray(); for (int i= 0; i != num.length-1; i++) { char[] rec= new char[num.length]; rec[0]= num[num.length-1]; // put last digit at beginning for (int j= 0; j != num.length-1; j++) rec[j+1]= num[j]; num= rec; int m= Integer.parseInt(new String(num)); if (m > n && m <= b) { pairs++; //System.out.println(q+"" ""+n); } } } return pairs; } } " B11667,"import java.io.*; public class Recycled{ public static void main(String args[]) { try{ File myFile = new File(""C-small-attempt0.in""); FileReader fileReader = new FileReader(myFile); BufferedReader reader = new BufferedReader(fileReader); FileWriter fileWriter = new FileWriter(""C-small-attempt0.out""); BufferedWriter writer = new BufferedWriter(fileWriter); String line = null; line = reader.readLine(); int numLines = Integer.parseInt(line); //writer.write(""hello""); for(int i=0;in) { recyclecount++; System.out.println(""RC "" + recyclecount); //writer.write(""RC "" + recyclecount+""\r\n""); } } } } } String out = ""Case #"" + (i+1) +"": ""+recyclecount+""\r\n""; writer.write(out); System.out.println(out); } reader.close(); writer.close(); }catch(Exception ex){ ex.printStackTrace(); } } }" B10468,"package CodeJam2012; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.StringTokenizer; public class RecycledNumbers { public static void main(String[] args) throws IOException { FileReader in = new FileReader(""C-small-attempt0.in""); BufferedReader buff = new BufferedReader(in); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter( ""C-small-attempt0.out""))); int nCases = Integer.parseInt(buff.readLine()); StringBuilder output = new StringBuilder(""""); for (int i = 0; i < nCases; i++) { String input = buff.readLine(); output.append(""Case #"" + (i + 1) + "": "" + getPairs(input) + ""\n""); } out.print(output.toString()); in.close(); out.close(); } private static long getPairs(String input) { StringTokenizer st = new StringTokenizer(input); String first = st.nextToken(); String second = st.nextToken(); int from = Integer.parseInt(first); int to = Integer.parseInt(second); long counter = 0; HashSet set = new HashSet(); for (int i = from; i <= to; i++) { String temp = i + """"; for (int j = 0; j < temp.length(); j++) { String next = temp.substring(j, temp.length()) + temp.substring(0, j); int x = Integer.parseInt(next); if (x <= to && x >= from && i < x && !set.contains(temp + ""$"" + next)) { counter++; set.add(temp + ""$"" + next); } } } return counter; } } " B10850,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.Scanner; public class C { private static boolean isRecyledPair(String n, String m) { int l = n.length(); String s = """"; for (int i = 1; i < l; i++) { for (int j = 0; j < l; j++) { s += n.charAt((j+i) % (l)); } if (s.equals(m)) { return true; } s = """"; } return false; } public static void main(String[] args) { try { Scanner file = new Scanner(new File(args[0])); int T = Integer.parseInt(file.nextLine()); BufferedWriter out = new BufferedWriter(new FileWriter(args[0].substring(0, args[0].length()-2) +""out"")); for (int i = 0; i < T; i++) { int A = file.nextInt(); int B = file.nextInt(); int ans = 0; for (int j = A; j < B; j++) { for (int k = j+1; k <= B; k++) { if (isRecyledPair(String.valueOf(j), String.valueOf(k))) { ans++; } } } out.write(new StringBuilder().append(""Case #"").append(i+1).append("": "").append(ans).append(""\n"").toString()); } out.close(); } catch (Exception ex) { ex.printStackTrace(); } } }" B10107,"import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); for (int i = 0; i < n; i++) { int a = sc.nextInt(); int b = sc.nextInt(); long output = solve(a, b); System.out.println(""Case #"" + (i + 1) + "": "" + output); } } private static long solve(int a, int b) { if (b <= 10) return 0; int start = a; if(a <= 10) start = 11; int count = 0; Set found = new HashSet(); for(int i = start; i < b; i++){ String toshift = String.valueOf(i); int len = toshift.length(); for(int j =1; ja && i < v && !found.contains(v) && !shifted.startsWith(""0"")) { found.add(v); count++; } } found.clear(); } return count; } private static String shift(String toshift, int j) { String pre = toshift.substring(0, j); String post = toshift.substring(j); return post.concat(pre); } } " B12250,"import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.util.Arrays; import java.util.Scanner; public class Read { int noOfTestCases; int []nums; public void Read(String name) { File file = new File(name); try { Scanner scanner = new Scanner(file); String line = scanner.nextLine(); noOfTestCases = Integer.parseInt(line); nums = new int[noOfTestCases*2]; int i=0; while(i set = new HashSet(); for (int i = 0; i < length; i++) { // bring to front int last = temp % 10; temp = temp / 10; temp += last * Math.pow(10, length - 1); if (temp > save && temp >= a && temp <= b && !set.contains(temp)) { pairs++; set.add(temp); } } } System.out.println(""Case #"" + (p + 1) + "": "" + (pairs - numRepeats)); } } }" B10521,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; public class C { public static void main(String[] args) { // split table int split[] = new int[10]; for (int i = 0; i < split.length; i++) { split[i] = (int)Math.pow(10, i); } // read input CaseC[] cases = read(""C-small-attempt0.in""); int front, back, size, m, a, b; // calculate each case for (CaseC c : cases) { // in each case size = c.getSize(); a = c.getA(); b = c.getB(); for (int n = a; n <= b; n++) { // for each value in range [A, B] for (int i = size - 1; i > 0; i--) { front = n / split[i]; back = n % split[i]; if (back < split[i-1]) { // ignore case with leading zero(s) in ""back"" part //System.err.printf(""Leading zero at position %d in number %d\n"", i, n); continue; } m = back * split[size - i] + front; if (m > n && m <= b) { c.increment(n, m); } } } } // write output writeFile(cases, ""C-small-attempt0.out""); print(""Complete!""); } public static void printf(String format, Object... args) { System.out.printf(format, args); } public static void print(Object o) { System.out.println(o); } public static void writeFile(CaseC[] result, String out) { PrintWriter writer = null; try { writer = new PrintWriter(out); for (int i = 0; i < result.length; i++) { writer.printf(""Case #%d: %s\n"", i+1, result[i]); } writer.flush(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (writer != null) { writer.close(); } } } public static CaseC[] read(String file) { BufferedReader reader = null; CaseC[] cases = null; try { reader = new BufferedReader(new FileReader(file)); // get test case count int caseCount = Integer.parseInt(reader.readLine()); cases = new CaseC[caseCount]; for (int i = 0; i < cases.length; i++) { String[] paramStr = reader.readLine().split("" ""); cases[i] = new CaseC(Integer.parseInt(paramStr[0]), Integer.parseInt(paramStr[1])); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return cases; } } class CaseC { private int a; private int b; private int size; //private int count; private HashSet set; public CaseC(int a, int b) { this.a = a; this.b = b; this.size = String.valueOf(b).length(); this.set = new HashSet(); //System.out.printf(""A=%d, B=%d, Size=%d\n"", a, b, size); } public int getA() { return a; } public int getB() { return b; } public int getSize() { return size; } public void increment(int n, int m) { String s = n + "":"" + m; if (set.contains(s)) { //System.err.println(""Duplicated entry: "" + s); } else { set.add(s); //count++; } } public int getCount() { //return count; return set.size(); } @Override public String toString() { return """" + set.size(); } }" B12887,"package com.techy.rajeev; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class Recycled { public static int[] toIntArray(String line){ String[] p = line.trim().split(""\\s+""); int[] out = new int[p.length]; for(int i=0;i0){ int arr[]=toIntArray(br.readLine()); int x=arr[0]; int y=arr[1]; String past=""""; for(int i=x;i<=y;i++){ String temp=i+""""; for(int j=temp.length()-1,m=1;j>0;j--,m++){ String test=temp.substring(m)+temp.substring(0,m); if(test.equals(past)){ break; } int lk=Integer.parseInt(test); if(lk>i&&lk<=y){ count++; past=test; } } } bw.write(""Case #""+k+"": ""+count); bw.newLine(); count=0; num--; k++; } br.close(); bw.close(); } } " B11494,"package de.hg.codejam.tasks.numbers.service; import java.util.HashSet; import java.util.Set; public class Calculator { private final Set overallShifts = new HashSet<>(); public int calculate(int[] pair) { int result = 0; int lowerBorder = pair[0]; int upperBorder = pair[1]; for (int i = lowerBorder; i <= upperBorder; i++) { if (!overallShifts.contains(i)) { Set shifts = getShifts(i); int numberOfValidPairs = countValidPairs(shifts, lowerBorder, upperBorder); result += numberOfValidPairs; } } return result; } public static int[] calculate(int[][] pairs) { int[] results = new int[pairs.length]; for (int i = 0; i < pairs.length; i++) results[i] = new Calculator().calculate(pairs[i]); return results; } private Set getShifts(int number) { String n = String.valueOf(number); Set result = new HashSet<>(n.length()); result.add(number); for (int i = 1; i < n.length(); i++) { n = n.substring(n.length() - 1) + n.substring(0, n.length() - 1); result.add(Integer.parseInt(n)); } overallShifts.addAll(result); return result; } private int countValidPairs(Set numbers, int lowerBorder, int upperBorder) { int counter = 0; Integer[] array = new Integer[numbers.size()]; numbers.toArray(array); for (int i = 0; i < array.length; i++) if (array[i] >= lowerBorder && array[i] <= upperBorder) for (int j = i + 1; j < array.length; j++) if (array[j] >= lowerBorder && array[j] <= upperBorder) if (array[i] != array[j] && String.valueOf(array[i]).length() == String .valueOf(array[j]).length()) counter++; return counter; } } " B12939,"package com.menzus.gcj._2012.qualification.c; import java.util.HashSet; import java.util.Set; import com.menzus.gcj.common.OutputProducer; public class COutputProducer implements OutputProducer { @Override public COutputEntry produceOutput(CInput input) { int lowerLimit = input.getLowerLimit(); int upperLimit = input.getUpperLimit(); long recycledPairNumber = 0; Set pairs = new HashSet(); for (int i = lowerLimit; i < upperLimit; i++) { pairs.clear(); int numberLength = getNumberLength(i); int numberMajor = getMajorNumber(i); int rotatedNumber = i; for (int j = 0; j < numberLength - 1; j++) { rotatedNumber = rotateNumber(rotatedNumber, numberMajor); if (numberLength == getNumberLength(rotatedNumber)) { if (rotatedNumber >= lowerLimit && rotatedNumber <= upperLimit && rotatedNumber > i) { if (!pairs.contains(rotatedNumber)) { recycledPairNumber++; pairs.add(rotatedNumber); } } } } } COutputEntry outputEntry = new COutputEntry(); outputEntry.setRecycledPairNumber(recycledPairNumber); return outputEntry; } // // private int rotateNumber(int i, int majorNumber) { // return (i / 10) + ((i % 10) * majorNumber); // } private int rotateNumber(int i, int majorNumber) { return ((i % majorNumber) * 10) + (i / majorNumber); } private int getMajorNumber(int i) { if (i < 10) { return 1; } else if (i < 100) { return 10; } else if (i < 1000) { return 100; } else if (i < 10000) { return 1000; } else if (i < 100000) { return 10000; } else if (i < 1000000) { return 100000; } else { return 1000000; } } private int getNumberLength(int i) { if (i < 10) { return 1; } else if (i < 100) { return 2; } else if (i < 1000) { return 3; } else if (i < 10000) { return 4; } else if (i < 100000) { return 5; } else if (i < 1000000) { return 6; } else { return 7; } } } " B11121,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package c; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author mrzk */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { try { Scanner inp = new Scanner(new File(""mm.in"")); FileWriter fw=new FileWriter(new File(""mm.out"")); String line=inp.nextLine(); int cnt=Integer.valueOf(line); int a=0,b=0; for (int i = 0; i < cnt; i++) { line=inp.nextLine(); int pos=line.indexOf(' '); String temp=line.substring(0, pos); a=Integer.valueOf(temp); temp=line.substring(pos+1, line.length()); b=Integer.valueOf(temp); int cntrclc=countRecycledNumbers(a, b); fw.write(""Case #""+String.valueOf(i+1)+"": ""+String.valueOf(cntrclc)+""\n""); } fw.close(); inp.close(); } catch (Exception ex) { } } private static int countRecycledNumbers(int a,int b) { int cnt=0; for(int num=a;num<=b;num++) { int len=((int) Math.log10(num))+1; for (int i = 0; i < len; i++) { int temp=num; temp=(int) ((temp % Math.pow(10, i)) * Math.pow(10, len - i) + (temp / Math.pow(10, i))); if((temp>=a)&&(temp<=b)&&(temp>num)) cnt++; } } return cnt; } }" B10262,"package core; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public abstract class Template { /************* TO BE IMPLEMENTED ******************************************/ public abstract void feedData(ExtendedBufferedReader iR); public abstract StringBuffer applyMethods(); /**************************************************************************/ public void readData(File iFile){ try { FileReader aReader = new FileReader(iFile); ExtendedBufferedReader aBufferedReader = new ExtendedBufferedReader(aReader); feedData(aBufferedReader); aBufferedReader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void writeResult(File iFile,StringBuffer iResult){ System.out.println(iResult.toString()); try { FileWriter aWriter = new FileWriter(iFile); aWriter.write(iResult.toString()); aWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void play(String[] args) { if (args.length>1) { File aFile = new File(args[0]); readData(aFile); StringBuffer result = applyMethods(); File aResultFile= new File(args[1]); writeResult(aResultFile,result); } else { System.out.println(""Your a bastard ! missing argument !""); } } } " B12839,"/** * @(#)test.java * * test application * * @author * @version 1.00 2012/4/13 */ import java.io.*; import java.util.*; import java.lang.*; public class test { public static void main(String[] args) { try { FileInputStream fstream = new FileInputStream (""B-small-attempt1.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); int T = Integer.parseInt (br.readLine()+""""); String [] line = new String[T]; String [] temp; int [] numbers; int numdancers = 0; int surprising = 0; int compare = 0; if (T>100)T=100; for (int i = 0; i33) numbers = new int[33]; else numbers = new int[temp.length]; for (int j = 0; j3)numdancers=3; surprising = numbers[1]; //Number of surprising cases if (surprising>numdancers)surprising = numdancers; compare = numbers[2]; //Find number of googlers that have a best result >= compare if (compare>10)compare = 10; int specialcombo = 0; int counter = 3; int[] scores = new int[3]; int casenum = 0; int max; int one; int prevmax; int prevcombo; boolean match = false; while (counter=0) { max = 0; if ((one+(one)+(one-1))==numbers[counter])//1 1 0 normal { match = true; //System.out.println ((one+""+""+(one)+""+""+(one-1))+""=""+(one+(one)+(one-1))); scores[0] = one; scores[1] = one; scores[2] = one-1; if (scores[0]>max) max = scores[0]; if (scores[1]>max) {max = scores[1];} if (scores[2]>max) {max = scores[2];} if (max>=compare && prevmax==0) { casenum++; prevmax = max; } //System.out.println (casenum); } else if ((one+(one-1)+(one-1))==numbers[counter])//0 0 1 normal { match = true; //System.out.println ((one+""+""+(one-1)+""+""+(one-1))+""=""+(one+(one-1)+(one-1))); scores[0] = one; scores[1] = one-1; scores[2] = one-1; if (scores[0]>max) max = scores[0]; if (scores[1]>max) {max = scores[1];} if (scores[2]>max) {max = scores[2];} if (max>=compare && prevmax==0) { casenum++; prevmax = max; } //System.out.println (casenum); } else if (((one)+(one)+(one+2))==numbers[counter]) //1 1 3 surprising { match = true; //System.out.println (((one)+""+""+(one)+""+""+(one+2))+""=""+((one)+(one)+(one+2))); specialcombo++; scores[0] = one; scores[1] = one; scores[2] = one+2; if (scores[0]>max) max = scores[0]; if (scores[1]>max) max = scores[1]; if (scores[2]>max) max = scores[2]; if (max>=compare && prevmax==0 && specialcombo<=surprising) { casenum++; prevmax = max; } //System.out.println (casenum); } else if (((one-1)+(one-2)+(one))==numbers[counter]) //1 2 3 //surprising { match = true; specialcombo++; //System.out.println ((one+""+""+(one-2)+""+""+(one-1))+""=""+(one+(one-2)+(one-1))); scores[0] = one-1; scores[1] = one-2; scores[2] = one; if (scores[0]>max) max = scores[0]; if (scores[1]>max) max = scores[1]; if (scores[2]>max) max = scores[2]; if (max>=compare && prevmax==0 && specialcombo<=surprising) { casenum++; prevmax = max; } //System.out.println (casenum); } else if (((one-1)+(one)+(one))==numbers[counter]) //0 1 1 { match = true; //System.out.println ((one+""+""+(one-1)+""+""+(one))+""=""+(one+(one-1)+(one))); scores[0] = one-1; scores[1] = one; scores[2] = one; if (scores[0]>max) max = scores[0]; if (scores[1]>max) max = scores[1]; if (scores[2]>max) max = scores[2]; if (max>=compare && prevmax==0) { casenum++; prevmax = max; } //System.out.println (casenum); } else if ((one+one+one)==numbers[counter])//1 1 1 normal { match = true; //System.out.println ((one+""+""+(one)+""+""+(one))+""=""+(one+(one)+(one))); scores[0] = one; scores[1] = one; scores[2] = one; if (scores[0]>max) max = scores[0]; if (scores[1]>max) {max = scores[1];} if (scores[2]>max) {max = scores[2];} if (max>=compare && prevmax==0) { casenum++; prevmax = max; } //System.out.println (casenum); } one--; } counter++; match = false; } System.out.println (""Case #""+(i+1)+"": ""+casenum); } } catch(Exception e){System.out.println (e);} } } " B10618,"package ProblemSolvers; import CaseSolvers.WiresCase; public class Wires extends ProblemSolver { public Wires(String filePath) { super(filePath); } @Override public void process() { cases = io.readInt(); for (int i = 1; i <= cases; i++) { new WiresCase(i, io.readInt(), io).process().printSolution(); } } } " B10775,"package com.codejam.twelve; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; public class ProbC { public static void main(String[] args) throws IOException { FileReader fr = new FileReader( ""D:\\Dev\\Workspaces\\Android\\codejam\\io\\qualification\\C-small-attempt0.in""); FileWriter fw = new FileWriter( ""D:\\Dev\\Workspaces\\Android\\codejam\\io\\qualification\\C-small-attempt0.out""); BufferedReader br = new BufferedReader(fr); BufferedWriter bw = new BufferedWriter(fw); int t = Integer.parseInt(br.readLine()); for (int l = 1; l <= t; l++) { String s = br.readLine(); bw.append(""Case #"" + l + "": ""); String ss[] = s.split("" ""); int A = Integer.parseInt(ss[0]); int B = Integer.parseInt(ss[1]); int ans = 0; HashSet hs = new HashSet(); for (int i = A; i < B; i++) { String n = """" + i; int len = n.length(); for (int j = 0; j < len - 1; j++) { n = n.charAt(n.length() - 1) + n.substring(0, n.length() - 1); int nn = Integer.parseInt(n); if (nn > i && nn <= B) { /*System.out.println(i + "","" + nn); if (hs.contains(i + "","" + nn)) { System.out.println(""**********""); } else*/ if (!hs.contains(i + "","" + nn)){ hs.add(i + "","" + nn); ans++; } } } } bw.append("""" + ans); bw.newLine(); } bw.flush(); bw.close(); br.close(); } } " B11984,"package Utils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class FileHelper { private String path; private int totalSize; private List inputList; private List outputList; public FileHelper(String path) { this.path = path; this.inputList = readFile(path); this.totalSize = Integer.parseInt(inputList.get(0)); } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public int getTotalSize() { return totalSize; } public void setTotalSize(int totalSize) { this.totalSize = totalSize; } public List getInputList() { return inputList; } public void setInputList(List inputList) { this.inputList = inputList; } public List getOutputList() { return outputList; } public void setOutputList(List outputList) { this.outputList = outputList; } public static List readFile(String filepath) { List rstList = new ArrayList(); try { FileInputStream fstream = new FileInputStream(filepath); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; // Read File Line By Line while ((strLine = br.readLine()) != null) { rstList.add(strLine); } // Close the input stream in.close(); } catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } return rstList; } public static void writeFile(String filepath, List resList) { try { FileWriter fstream = new FileWriter(filepath); BufferedWriter out = new BufferedWriter(fstream); for(int i = 0 ; i< resList.size();++i){ out.write(resList.get(i)); System.out.println(resList.get(i)); if( i != resList.size() - 1) out.newLine(); } // Close the output stream out.close(); } catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } public int getInputTotalSize() { return 0; } public void init(String[] inputStr) { for(int i = 1; i< this.inputList.size(); ++i ){ inputStr[i - 1] = inputList.get(i); } } } " B11888,"import java.util.*; import java.io.*; public class SOURCE041312_CJ_Qual_DancingWithGooglers { public static void main(String sargs[])throws IOException { System.setOut(new PrintStream(new File(""OUTPUT041312_CJ_Qual_DancingWithGooglers.dat""))); Scanner oScan=new Scanner(new File(""C-small-attempt0.in"")); int T=Integer.parseInt(oScan.nextLine().trim()); int Case=0; while(T-->0) { Set l=new HashSet(); int A=oScan.nextInt();int B=oScan.nextInt(); for(int i=A;i<=B;++i) { String n=i+""""; for(int ind=1;indInteger.parseInt(n)) l.add(""""+n+"" ""+m); } } System.out.println(""Case #""+ ++Case+"": ""+l.size()); } } }" B10750,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.*; public class main { static int numberPeriod(int n, int len) { if (len == 2 && n / 10 == n % 10) return 1; if (len == 4 && n % 100 == n / 100) return 2; if (len == 6 && n % 100 == n / 10000 && n % 100 == n / 100 % 100) return 2; if (len == 6 && n % 1000 == n / 1000) return 3; return len; } static int numberLength(int n) { int len = 0; while (n > 0) { n /= 10; len++; } return len; } public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(new File(""C-small-attempt0.in"")); PrintWriter out = new PrintWriter(""result.txt""); int tests = sc.nextInt(); for (int t = 1; t <= tests; t++) { int a = sc.nextInt(), b = sc.nextInt(), length = numberLength(a), tt = (int) Math.pow(10, length - 1), res = 0; for (int j = a; j <= b; j++) { int cur = j; int val = j; int per = numberPeriod(j, length); for (int k = 0; k < per; k++) { int c = val % 10; val = val / 10 + c * tt; if (val > cur && val <= b) { res++; } } } out.printf(""Case #%d: %d\n"",t,res); } out.flush(); } }" B12204,"package com.google.codejam; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; public class ContentReader { public static ArrayList getContents(String fileName) { ArrayList fileContents = new ArrayList(); try { //use buffering, reading one line at a time //FileReader always assumes default encoding is OK! InputStream is = ContentReader.class.getResourceAsStream(fileName); InputStreamReader in = new InputStreamReader(is); BufferedReader input = new BufferedReader(in); try { String line = null; //not declared within while loop /* * readLine is a bit quirky : * it returns the content of a line MINUS the newline. * it returns null only for the END of the stream. * it returns an empty String if two newlines appear in a row. */ while (( line = input.readLine()) != null){ fileContents.add(line); } } finally { input.close(); } } catch (IOException ex){ ex.printStackTrace(); } return (fileContents); } } " B12662,"import java.io.*; import java.util.*; public class C_RecycledNumbers { static String name = ""C-small-attempt0""; static boolean been[]; static int f(int a, int b) { //System.out.println(a + "" "" + b); been[a] = true; int c = a; int num = 1, k = -1, ans = 1; while (c != 0) { c /= 10; num *= 10; k++; } num /= 10; c = a; for (int i = 0; i < k; i++) { int rem = a % 10; a /= 10; a += rem * num; if (a <= b && a >= c) { if (been[a]) continue; // System.out.println(a+"" ""+c); been[a] = true; ans++; } } return ans * (ans - 1) / 2; } public static void main(String args[]) throws IOException { BufferedReader in = new BufferedReader(new FileReader(name + "".in"")); PrintWriter out = new PrintWriter(name + "".out""); int t = Integer.parseInt(in.readLine()), caseN = 1; been = new boolean[10000000]; while (caseN <= t) { long ans = 0; StringTokenizer tok = new StringTokenizer(in.readLine()); int a = Integer.parseInt(tok.nextToken()), b = Integer.parseInt(tok .nextToken()); for (int i = a; i <= b; i++) { ans += f(i, b); } Arrays.fill(been, a, b + 10, false); out.print(""Case #""); out.print(caseN++); out.print("": ""); out.println(ans); } out.flush(); } } " B13062,"package com.google.codejam.recycle; import java.util.List; /** * Created by IntelliJ IDEA. * User: sushant * Date: 14 Apr, 2012 * Time: 11:13:34 AM * To change this template use File | Settings | File Templates. */ public class RecycledNumbers { /** * Main method from where application start execution. * * @param args String [] */ public static void main(final String[] args) { if (args.length != 1) { System.out.println(""Problem with the command used for execution""); System.out.println(""Usage: java com.google.codejam.googlerese.RecycledNmbers ""); System.exit(1); } final List testCases = InputReader.prepareTestCases(args[0]); if (testCases != null && testCases.size() != 0) { long startTime = System.currentTimeMillis(); System.out.println(""Test Cases execution start time "" + startTime); for (TestCase testcase : testCases) { executeTestCase(testcase); } OutputRecorder.generateTestReport(testCases, args[0] + "".out""); long endTime = System.currentTimeMillis(); System.out.print(""Test cases execution end time "" + endTime); System.out.println(""Total Execution Time "" + (endTime - startTime) + "" milliseconds""); } } /** * Method to execute test cases. * * @param testcase TestCase */ private static void executeTestCase(final TestCase testcase) { int recycleNumberCount = 0; final int low = testcase.getLow(); final int high = testcase.getHigh(); final int length = Integer.toString(low).length(); for(int i = low; i <= high; i++) { int previoudNumber = 0; for(int j = 1; j < length; j++) { int divisor = getDivisor(length - j); int mod = i % divisor; int result = i / divisor; int recycleNumber = Integer.parseInt("""" + mod + result); if(previoudNumber != recycleNumber && recycleNumber > i && recycleNumber <= high) { previoudNumber = recycleNumber; recycleNumberCount = recycleNumberCount + 1; } } } testcase.setOutput(new TestResult(recycleNumberCount)); } private static int getDivisor(int noOfZeros) { StringBuilder builder = new StringBuilder().append(1); for(int i = 0; i < noOfZeros; i++) { builder.append(0); } return Integer.parseInt(builder.toString()); } } " B12663,"import java.io.BufferedReader; import java.io.InputStreamReader; public class Recycled{ public static void main(String[] args) throws java.io.IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); for(int i=0;in) { for(int j=n;j set = new HashSet(); for(int i=a;i<=b;i++){ String w = String.valueOf(i); for(int j=1;j=a) { String other = Math.min(i, q)+""-""+Math.max(i, q); set.add(other); } } } } // System.out.println(set.size()+"" - ""+set); System.out.println(""Case #""+act+"": ""+set.size()); out.println(""Case #""+act+"": ""+set.size()); // System.out.println(line); } in.close(); out.close(); System.exit(0); } } " B12484,"import java.util.*; public class C { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for (int i=0; i x)) count++; } } System.out.println(""Case #"" + (i+1) + "": "" + count); } fis.close(); bis.close(); dis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } " B10910,"import java.io.*; import java.util.ArrayList; /** * Created by IntelliJ IDEA. * User: Manish * Date: 4/14/12 * Time: 2:29 PM * To change this template use File | Settings | File Templates. */ public class CodeJamProblemC { CodeJamProblemC() { } public static void main(String args[]) throws Exception { String inputPath = ""C:\\Users\\Manish\\IdeaProjects\\Codejam\\src\\C-small-attempt0.in""; String outputPath = ""C:\\Users\\Manish\\IdeaProjects\\Codejam\\src\\C-small.out""; CodeJamProblemC rw = new CodeJamProblemC(); String[] str = rw.readFromFile(inputPath); String[] solution = getSolution(str); //Logic to change for (String solstr : solution) //System.out.println(""rotaion logic is working::"" + solstr); rw.writeToFile(outputPath, solution); } private static String[] getSolution(String[] str) { int noOftestCases = Integer.parseInt(str[0]); String[] output = new String[noOftestCases]; //Logic-try for only one for (int i = 1; i <= noOftestCases; i++) { String[] arr = str[i].split("" ""); int lowerLimit = Integer.parseInt(arr[0]); int upperLimit = Integer.parseInt(arr[1]); int count = 0; while (upperLimit > lowerLimit) { for (int j = 0; j < upperLimit - lowerLimit; j++) { //System.out.println(""pair::("" +String.valueOf(lowerLimit+j)+"",""+ String.valueOf(upperLimit)+"")""); count = count + isRecycledPossible(String.valueOf(lowerLimit + j), String.valueOf(upperLimit)); } upperLimit--; } output[i - 1] = ""Case #"" + i + "": "" + count; } return output; } public static int isRecycledPossible(String a, String b) { int countInRecycledPossible = 0; for (int i = 0; i < a.length(); i++) { for (int j = i; j < a.length(); j++) { if (Integer.parseInt(rotate(a,j)) - Integer.parseInt(b) == 0) { // System.out.println(""good :) found the number::"" + rotate(a, j) + "","" + b + "" pair::("" + a + "","" + b + "")""); countInRecycledPossible++; break; } } if(countInRecycledPossible>0){ break; } } if (countInRecycledPossible > 0) { //System.out.print(""countInRecycledPossible::"" + countInRecycledPossible + "" ----""); } return countInRecycledPossible; } public static String rotate(String a, int i) { String substring = a.substring(a.length() - i); String rotatedDigit = substring + a.substring(0,a.length() - i); return rotatedDigit; } public String[] readFromFile(String inputPath) throws FileNotFoundException, IOException { FileInputStream fis = null; DataInputStream dis = null; BufferedReader br = null; ArrayList strArrList = new ArrayList(); try { fis = new FileInputStream(inputPath); dis = new DataInputStream(fis); br = new BufferedReader(new InputStreamReader(dis)); String strLine; while ((strLine = br.readLine()) != null) { strArrList.add(strLine); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) { br.close(); } if (dis != null) { dis.close(); } if (fis != null) { fis.close(); } } catch (IOException e) { e.printStackTrace(); } } return strArrList.toArray(new String[strArrList.size()]); } public void writeToFile(String outputPath, String[] strArr) { BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter(outputPath)); for (int i = 0; i < strArr.length; i++) { bw.write(strArr[i]); bw.newLine(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (bw != null) { bw.flush(); bw.close(); } } catch (IOException e) { e.printStackTrace(); } } } } " B11449,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.StringTokenizer; public class recycle { public static void main(String[] args) { int lines; String input; StringTokenizer strk; int start=1111; int end=2222; int count; int old[] = new int[10]; try { BufferedReader inputStream = new BufferedReader(new FileReader(""C-large.in"")); BufferedWriter writer = new BufferedWriter(new FileWriter(""output.txt"")); lines = Integer.parseInt(inputStream.readLine()); String newj; int newjint; for(int line=0; line< lines; line++){ count=0; input = inputStream.readLine(); strk = new StringTokenizer(input,"" ""); start = Integer.parseInt(strk.nextToken()); end = Integer.parseInt(strk.nextToken()); for(int j=start; j<=end;j++){ newj = j+""""; for(int k=0;k< newj.length() ;k++){ newj = (newj.substring(1) + newj.charAt(0)); newjint = Integer.parseInt(newj); if(newjint > j && newjint <= end && !inside(old,10,newjint)){ //System.out.println(j + "" "" + newjint); old[k] = newjint; count++; } } old = new int[10]; /* for(int k=j; k<=end;k++){ if(isRecycled(j+"""",k+"""")){ //System.out.println(j + "" "" + k); count++; } } */ } if(line!=lines-1) writer.write(""Case #"" + (line+1) + "": "" + count+""\r\n""); else writer.write(""Case #"" + (line+1) + "": "" + count); } writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } static boolean isRecycled(String x, String y){ int len = x.length(); if(x.equals(y)){ return false; } for(int i=0; i=p10[j])bitcnt=j+1; } for (int j = a; j <= b; j++) { if(mark[j])continue; if(j>=p10[bitcnt])bitcnt++; int cur=j; int cnt=0; for (int k = 0; k < bitcnt; k++) { if(cur>=p10[bitcnt-1]&&cur>=a&&cur<=b&&mark[cur]==false){ mark[cur]=true; cnt++; } int next=cur%10*p10[bitcnt-1]+cur/10; cur=next; } if(cnt>=2){ res+=cnt*(cnt-1)/2; } } out.println(""Case #""+(i+1)+"": ""+res); } out.close(); System.exit(0); } static BufferedReader f; static StringTokenizer st; static void nl() throws IOException { st = new StringTokenizer(f.readLine()); } static String tk() { return st.nextToken(); } static void fill(Object array,int val){ if(array instanceof int[])Arrays.fill((int[])array,val); else for(Object o:(Object[])array)fill(o,val); } //static String min(String a,String b){return a.compareTo(b)<0?a:b;} static int ip(String s){return Integer.parseInt(s);} static long lp(String s){return Long.parseLong(s);} static int inf=Integer.MAX_VALUE/2; static int gcd(int a,int b){return b==0?a:gcd(b,a%b);} static boolean isPrime(int number) { if (number < 2) return false; if (number == 2) return true; if (number % 2 == 0) return false; for (int i = 3; i * i <= number; i += 2) if (number % i == 0) return false; return true; } static public class Comp implements Comparable { public int compareTo(Comp other) {// myself first asc if (len == other.len) return str.compareTo(other.str);// myself first asc return other.len - len;// other first desc } int len; String str; public Comp(int len, String str) { super(); this.len = len; this.str = str; } } } " B12203,"package com.google.codejam; import java.util.ArrayList; public class RecycledNumber { private static ArrayList getRandomCombinations(String number) { ArrayList combinations = new ArrayList(); String temp = null; for (int i = 1; i < number.length(); i++) { temp = String.valueOf(number.charAt(i)); if (temp.equals(""0"")) { continue; } temp = temp + number.substring(i+1, number.length()) + number.substring(0, i); combinations.add(temp); } return (combinations); } private static boolean checkAllCharactersSame(String s) { char charToCheck = s.charAt(0); boolean oneCharactersSame = true; for (int i=1; i < s.length(); i++) { if (charToCheck != s.charAt(i)) { oneCharactersSame = false; break; } } return (oneCharactersSame); } public static long countRandomNumbers(long A, long B) { long randomNumberCount = 0; ArrayList combinations = null; ArrayList mnMap = new ArrayList(); String temp = null, reverseTemp = null; for (long i = A; i <= B; i++) { if (checkAllCharactersSame(String.valueOf(i))) { continue; } combinations = getRandomCombinations(String.valueOf(i)); if (combinations.size() == 0) { continue; } for (String number: combinations) { if ((Long.parseLong(number) >= A) && (Long.parseLong(number) <= B)) { temp = String.valueOf(i)+""-""+number; reverseTemp = number+""-""+String.valueOf(i); if ((! number.equals(String.valueOf(i))) && (! mnMap.contains(temp)) && (! mnMap.contains(reverseTemp))) { mnMap.add(temp); randomNumberCount++; } } } } return (randomNumberCount); } public static void main(String[] args) { ArrayList testCases = ContentReader.getContents(""RecycledNumber.txt""); long A, B; for (int i = 1; i <= Integer.valueOf(testCases.get(0)); i++) { A = Integer.valueOf(testCases.get(i).split("" "")[0]); B = Integer.valueOf(testCases.get(i).split("" "")[1]); System.out.println(""Case #""+i+"": ""+countRandomNumbers(A, B)); } } }" B12968,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam2012; /** * * @author ESIEN */ public class C { static int numOfDigits; final static int max = 1001; static int div; static boolean[] found = new boolean[max]; static int[]p = new int[max]; public static void main(String[] args)throws java.io.IOException{ java.util.Scanner fromFile = new java.util.Scanner(new java.io.File(""input.txt"")); java.io.PrintStream intoFile = new java.io.PrintStream(""output.txt""); int testCase = fromFile.nextInt(); for (int test = 1; test <= testCase; test++){ int a = fromFile.nextInt(); int b = fromFile.nextInt(); numOfDigits = 0; int t = a; while((t/=10)!=0) numOfDigits++; div = (int)Math.pow(10,numOfDigits); int ind=0; int totalCount = 0; for (int i = a; i <= b; i++){ if (found[i]) continue; found[p[ind++]=i]=true; int c = 0; for (int j = 0,k=i%10*div+i/10; j < numOfDigits && k!=i; k=k%10*div+k/10, j++) if (k<=b&&k>=a){ c++; found[p[ind++]=k]=true; } totalCount+=(c&1)==0?(c>>1)*(c+1):((c+1>>1)*c); } for(int i = 0; i < ind; i++) found[p[i]]=false; intoFile.printf(""Case #%d: %d%n"",test,totalCount); } intoFile.close(); fromFile.close(); } } " B12315,"import java.io.*; public class Recycle { public static void main(String args[]) { try { InputStreamReader inReader = new InputStreamReader(new FileInputStream(""input.txt"")); BufferedReader br = new BufferedReader(inReader); File out = new File(""output.txt""); Writer output = new BufferedWriter(new FileWriter(out)); int amount = Integer.parseInt(br.readLine()); for (int i=0; i < amount; i++) { output.write(""Case #"" + (i+1) + "": ""); String line = br.readLine(); int min = Integer.parseInt(line.split("" "")[0]); int max = Integer.parseInt(line.split("" "")[1]); int result = 0; int digits = 1; int tmp = max; while (tmp/10 > 0) { tmp /= 10; digits++; } int[] assist = new int[digits]; for (int l=0; l < digits; l++) assist[l] = 0; for (int j=min; j <= max; j++) { int number = j; int counter = 0; for (int k=1; k < digits; k++) { int newNumber = (int) ((int) (number%Math.pow(10, k)) * Math.pow(10, digits-k) + (number/Math.pow(10, k))); if (newNumber > number && newNumber <= max) { for (int l=0; l < counter; l++) { if (assist[l] == newNumber) result--; } assist[counter++] = newNumber; result++; } } } output.write(result + ""\n""); } output.close(); } catch (Exception e) { e.printStackTrace(); } } }" B11901,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; public class GCJC { static HashMap map = new HashMap(); public static void main(String[] args) { try { FileReader in = new FileReader(""C-small-attempt1.in""); BufferedReader br = new BufferedReader(in); File file = new File(""./smallC.txt""); FileWriter fw = new FileWriter(file); String line; int num = Integer.valueOf(br.readLine()); int caseNum = 1; while ((line = br.readLine()) != null) { map = new HashMap(); StringBuilder sb = new StringBuilder(); sb.append(""Case #"" + caseNum + "": ""); caseNum++; int res = 0; int a = Integer.valueOf(line.split("" "")[0]); int b = Integer.valueOf(line.split("" "")[1]); for(int i = a; i <= b ; i++){ for(int j = 10; j <= i ; j*=10){ int digit = (int)Math.log10(i) + 1; int top = i/j; int back = i%j; int cycle = (int) (back * Math.pow(10, (digit - (int)Math.log10(j))) + top); if(map.get(i) != null && map.get(i) == cycle) continue; if(cycle <= b && i < cycle){ map.put(i, cycle); res++; } } } sb.append(res); fw.write(new String(sb)); fw.write(""\n""); } br.close(); in.close(); fw.close(); } catch (IOException e) { e.printStackTrace(); } } } " B12444,"import java.util.*; import java.io.*; public class problem3 { private final Scanner sc; private static final boolean debug = true; static void debug(Object ... objects) { if(debug) System.err.println(Arrays.toString(objects)); } problem3() { sc = new Scanner(new BufferedInputStream(System.in)); } public static void main(String [] args) { (new problem3()).solve(); } int AA,BB; int rot(int b) { int p=10; int cnt=0; int maxP = 1; int ans = 0; while(b/maxP > 0) maxP*=10; while(b/p>0) { int c = b/p + (maxP/p)*(b%p); //System.out.println(b+ "" "" + maxP+"" "" + c); if(c==b) break; if(c>b&&c<=BB&&c>=AA) ans++; p*=10; } return ans; } void solve() { int T = sc.nextInt(); int cs = 0; while(cs < T) { cs++; long ans = 0; int A = sc.nextInt(), B = sc.nextInt(); AA=A;BB=B; for(int i=A;i<=B;i++) { ans+=rot(i); } System.out.println(""Case #"" + cs+ "": ""+ans); } } } " B12562,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package gcjqual; import java.io.*; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author greg */ public class GCJQual3 { /** * @param args the command line arguments */ public static void main(String[] args) { GCJQual3 g = new GCJQual3(); g.run(); } private void run() { BufferedReader br = null; BufferedWriter bw = null; String eachLine; int count = 1; try { br = new BufferedReader(new FileReader(""input3.txt"")); // bw = new BufferedWriter(new OutputStreamWriter(System.out)); bw = new BufferedWriter(new FileWriter(""output3.txt"")); String numTests = br.readLine(); System.out.println(numTests); while ((eachLine = br.readLine()) != null) { bw.write(""Case #"" + count + "": ""); bw.write(solve(eachLine)); bw.newLine(); count++; } } catch (IOException ex) { ex.printStackTrace(); Logger.getLogger(GCJQual3.class.getName()).log(Level.SEVERE, null, ex); } finally { try { bw.close(); br.close(); } catch (IOException ex) { Logger.getLogger(GCJQual3.class.getName()).log(Level.SEVERE, null, ex); } } } private String solve(String eachLine) { String[] params = eachLine.split("" ""); int A = Integer.valueOf(params[0]); int B = Integer.valueOf(params[1]); int recycledCount = 0; for (int n=A; n<=B; n++) { Set possible = getRecycled(n); for (int m:possible) { if (m <= B) { recycledCount++; } } } return """" + recycledCount; } private Set getRecycled(int n) { Set possible = new HashSet (); int shift = 2; if ( n > 11 ) { // no single or 10 or 11 if ( n >= 1000000) { shift = 7; } else if ( n >= 100000) { shift = 6; } else if ( n >= 10000) { shift = 5; } else if ( n >= 1000) { shift = 4; } else if ( n >= 100 ) { shift = 3; } int newNum = n; for ( int i =0; i< shift-1; i++) { int last = newNum % 10; newNum = (int) (newNum / 10 + (Math.pow(10, shift-1)*last)); if ( newNum > n ) { possible.add(newNum); } } } // Cache possible return possible; } } " B10180,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class RecycledPairs { public static void main(String [] args) throws IOException { Scanner fileScan = new Scanner(new File(""C-small-attempt0.in"")); BufferedWriter out = new BufferedWriter(new FileWriter(""C-small-attempt0.out"")); int N = Integer.parseInt(fileScan.nextLine()); for (int i = 0; i < N; i++) { int A = fileScan.nextInt(); int B = fileScan.nextInt(); int numPairs = 0; int numDigits = 0; int temp = A; while (temp > 0) { numDigits++; temp /= 10; } for (int n = A; n <= B; n++) { int check = 0; for (int j = 1; j < numDigits; j++) { int m = (int) (n/Math.pow(10, j) + (n%Math.pow(10, j))*Math.pow(10, numDigits-j)); if (m > n && m <= B && m != check) { numPairs++; check = m; } } } int printTemp = i + 1; out.write(""Case #"" + printTemp + "": "" + numPairs + ""\n""); } out.close(); } } " B13084,"import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.Arrays; import java.util.HashSet; import java.util.StringTokenizer; public class Main { FastScanner in; PrintWriter out; Main() { in = new FastScanner(IO_Type.CONSOLE).getScanner(); out = new FastWriter(IO_Type.CONSOLE).getWriter(); // in = new FastScanner(IO_Type.TEST, ""test.txt"").getScanner(); // out = new FastWriter(IO_Type.TEST, ""result.txt"").getWriter(); // in = new FastScanner(IO_Type.FILE, ""input.txt"").getScanner(); // out = new FastWriter(IO_Type.TEST, ""output.txt"").getWriter(); } public static void main(String[] args) throws IOException { Main task = new Main(); task.solve(); task.close(); } public void close() { in.close(); out.close(); } public void solve() throws IOException { int T = in.nextInt(); for (int i = 0; i < T; i++) { int A = in.nextInt(); int B = in.nextInt(); int[]tab = new int[B - A + 1]; for (int j = 0; j < tab.length; j++) { tab[j] = j + A; // System.out.println(tab[j]); } HashSet set = new HashSet(); for (int j = 0; j < tab.length; j++) { int K = tab[j]; if (K != -1) for (int step = 10; ; step *= 10) { int tmp = K / step; if (tmp > 0) { int last = K % step; int q = K / step; StringBuilder sb = new StringBuilder(); sb.append(last); sb.append(q); int ans = Integer.parseInt(sb.toString()); String v = Integer.toString(ans); String x = Integer.toString(K); if (ans <= B && ans >= A) { if (tab[j] != tab[ans - A] && v.length() == x.length()) { Pair p = new Pair(); p.setN(Math.min(tab[j], tab[ans - A])); p.setM(Math.max(tab[j], tab[ans - A])); set.add(p); } } } else break; } } out.println(""Case #"" + (i + 1) + "": "" + set.size()); } } class Pair { int n; int m; public int getN() { return n; } public void setN(int n) { this.n = n; } public int getM() { return m; } public void setM(int m) { this.m = m; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getOuterType().hashCode(); result = prime * result + m; result = prime * result + n; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (!getOuterType().equals(other.getOuterType())) return false; if (m != other.m) return false; if (n != other.n) return false; return true; } private Main getOuterType() { return Main.this; } } } class Algebra { /**** * Number of co-prime numbers on [1, n]. Number a is Co-prime if gcd (a, n) * == 1 O (sqrt(n)) ****/ public static int phi(int n) { int result = n; for (int i = 2; i * i <= n; ++i) { if (n % i == 0) { while (n % i == 0) { n /= i; } result -= result / i; } } if (n > 1) { result -= result / n; } return result; } /**** * Raise number a to power of n. O (log n) ****/ public static int binpow(int a, int n) { int res = 1; while (n != 0) { if ((n & 1) == 1) res *= a; a *= a; n >>= 1; } return res; } /**** * Finding the greatest common divisor of two numbers. O (log min(a, b)) ****/ public static int gcd(int a, int b) { return (b != 0) ? gcd(b, a % b) : a; } /**** * Finding the lowest common multiple of two numbers. O (log min(a, b)) ****/ public static int lcm(int a, int b) { return a / gcd(a, b) * b; } /**** * Eratosthenes Sieve of numbers - [0..n]. True - simple, False - not * simple. O (n log log n) ****/ public static boolean[] sieveOfEratosthenes(int n) { boolean[] prime = new boolean[n + 1]; Arrays.fill(prime, true); prime[0] = prime[1] = false; for (int i = 2; i <= n; ++i) { if (prime[i]) { if (i * 1L * i <= n) { for (int j = i * i; j <= n; j += i) { prime[j] = false; } } } } return prime; } } class IO_Type { public static String CONSOLE = ""console""; public static String FILE = ""file""; public static String TEST = ""test""; } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner getScanner() { return this; } FastScanner(String type) { if (type.equals(""console"")) { FastScanner(System.in); } } FastScanner(String type, String inFileName) { if (type.equals(""file"")) { File f = new File(inFileName); try { FastScanner(new FileInputStream(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } else if (type.equals(""test"")) { File f = new File(inFileName); try { FastScanner(new FileInputStream(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } } void FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { System.err.println(e); return """"; } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } BigInteger nextBigInt() { return new BigInteger(next()); } void close() { try { br.close(); } catch (IOException e) { } } } class FastWriter { PrintWriter pw; PrintWriter getWriter() { return pw; } FastWriter(String type) { FastWriter(type); } FastWriter(String type, String outFileName) { FastWriter(type, outFileName); } PrintWriter FastWriter(String type) { if (type.equals(""console"")) { pw = new PrintWriter(System.out); } return pw; } PrintWriter FastWriter(String type, String outFileName) { if (type.equals(""console"")) { pw = new PrintWriter(System.out); } else if (type.equals(""test"")) { try { pw = new PrintWriter(new File(outFileName)); } catch (FileNotFoundException e) { e.printStackTrace(); } } else if (type.equals(""file"")) { try { pw = new PrintWriter(new File(outFileName)); } catch (FileNotFoundException e) { e.printStackTrace(); } } return pw; } } " B10209,"package qualification.problemC; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Set; public class ProblemC { static int num; static String[] lines; static String dir = ""./src/qualification/problemC""; static String inTxt = dir + ""/C-small-attempt0.in""; static String outTxt = dir + ""/C-small-attempt0.out""; public static void main(String[] args) { input(inTxt); String[] ansStrs = new String[num]; for (int i = 0; i < lines.length; i++) { String[] strs = lines[i].split(""\\s""); int[] nums = new int[strs.length]; for (int j = 0; j < strs.length; j++) { nums[j] = Integer.valueOf(strs[j]); } // Solve Problem int ans = solve(nums[0], nums[1]); ansStrs[i] = String.valueOf(ans); } output(outTxt, ansStrs); } static void input(String fname) { try { BufferedReader br = new BufferedReader( new InputStreamReader( new FileInputStream(fname))); String line = br.readLine(); num = Integer.valueOf(line); System.out.println(num); lines = new String[num]; for (int i = 0; i < num; i++) { lines[i] = br.readLine(); System.out.println(lines[i]); } br.close(); } catch (Exception e) { e.printStackTrace(); } } static void output(String fname, String[] output) { File outFile = new File(fname); try { FileWriter fw = new FileWriter(outFile); for (int i = 0; i < num && i < output.length; i++) { String out = ""Case #""+(i+1)+ "": "" + output[i] + '\n'; System.out.print(out); fw.write(out); fw.flush(); } fw.close(); } catch (Exception e) { e.printStackTrace(); } } public static int solve(int min, int max) { int count = 0; char maxFirst = String.valueOf(max).charAt(0); for (int i = Math.max(10, min); i < max; i++) { String num = String.valueOf(i); char first = num.charAt(0); Set set = new HashSet(); for (int j = 1; j < num.length(); j++) { char newFirst = num.charAt(j); if (newFirst < first || maxFirst < newFirst) continue; String tmp = num.substring(0, j); int newNum = Integer.valueOf(num.substring(j) + tmp); if (i < newNum && newNum <= max) { //System.out.println(num + "", "" + newNum); set.add(newNum); } } count += set.size(); } return count; } } " B11278,"package Numbers; import java.util.Scanner; public class CountRecycle { public static void main(String[] args) { Scanner r = new Scanner(System.in); int n = r.nextInt(); for(int i = 1; i <= n; i++) { int x = r.nextInt(); int y = r.nextInt(); int f = getAmt(x, y); System.out.println(""Case #"" + i + "": "" + f); } } public static int getAmt(int x, int y) { int cnt = 0; for(int i = x; i <= y; i++) { for(int j = i; j <= y; j++) { if(i == j) { continue; } String ix = Integer.toString(i); String jx = Integer.toString(j); if(ix.length() != jx.length()) { break; } for(int k = 1; k <= ix.length()-1; k++) { String tst = jx.substring(k) + jx.substring(0, k); if(tst.equals(ix)) { cnt++; break; } } } } return cnt; } } " B11346,"import java.io.BufferedInputStream; import java.io.BufferedOutputStream; 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.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * * Google Code Jam 2012. Qualification. Problem C. * * @author Ivan Pryvalov (ivan.pryvalov@gmail.com) * */ public class GCJ_2012_Q_C implements Runnable{ static class Data{ int i; int next; int prev; } private void solve() throws IOException { int MAX = 2000000 + 1; Data[] d = new Data[MAX]; for (int i = 0; i < d.length; i++) { Data dat = new Data(); dat.i = i; dat.next = -1; dat.prev = -1; d[i] = dat; } for (int i = 0; i < d.length; i++) { if (d[i].prev != -1) continue; String cur = """"+i; Set set = new HashSet(); while (!set.contains(cur)){ set.add(cur); cur = next(cur); } List list = new ArrayList(); for (String s : set) { if (s.charAt(0)!='0'){ int num = Integer.parseInt(s); if (num < MAX) list.add(num); } } Collections.sort(list); for (int j = 0; j < list.size(); j++) { if (j>0){ d[list.get(j)].prev = list.get(j-1); d[list.get(j-1)].next = list.get(j); } if (j 1){ char firstCh = curS.charAt(0); curS = curS.substring(1) + new String(new char[]{firstCh}); } return curS; } ////////////////////////////////////////////////// static class ArrayWrapper{ T[] ar; Comparator comparator; public ArrayWrapper(Set set) { ar = (T[]) set.toArray(); } public ArrayWrapper(T[] ar) { this.ar = ar; } public ArrayWrapper(T[] ar, Comparator comparator) { this.ar = ar; this.comparator = comparator; } public ArrayWrapper sort(){ if (comparator==null){ Arrays.sort(ar); }else{ Arrays.sort(ar, comparator); } return this; } public T getFirst(){ return ar[0]; } public T getLast(){ return ar[ar.length-1]; } } ///////////////////////////////////////////////// final int BUF_SIZE = 1024 * 1024 * 8;//important to read long-string tokens properly final int INPUT_BUFFER_SIZE = 1024 * 1024 * 8 ; final int BUF_SIZE_INPUT = 1024; final int BUF_SIZE_OUT = 1024; boolean inputFromFile = true; String filenamePrefix = ""C-small-attempt0""; String inSuffix = "".in""; String outSuffix = "".out""; //InputStream bis; //OutputStream bos; PrintStream out; ByteScanner scanner; ByteWriter writer; @Override public void run() { try{ InputStream bis = null; OutputStream bos = null; //PrintStream out = null; if (inputFromFile){ File baseFile = new File(getClass().getResource(""/"").getFile()); bis = new BufferedInputStream( new FileInputStream(new File( baseFile, filenamePrefix+inSuffix)), INPUT_BUFFER_SIZE); bos = new BufferedOutputStream( new FileOutputStream( new File(baseFile, filenamePrefix+outSuffix))); out = new PrintStream(bos); }else{ bis = new BufferedInputStream(System.in, INPUT_BUFFER_SIZE); bos = new BufferedOutputStream(System.out); out = new PrintStream(bos); } scanner = new ByteScanner(bis, BUF_SIZE_INPUT, BUF_SIZE); writer = new ByteWriter(bos, BUF_SIZE_OUT); solve(); out.flush(); }catch (Exception e) { e.printStackTrace(); System.exit(1); } } public interface Constants{ final static byte ZERO = '0';//48 or 0x30 final static byte NINE = '9'; final static byte SPACEBAR = ' '; //32 or 0x20 final static byte MINUS = '-'; //45 or 0x2d final static char FLOAT_POINT = '.'; } public static class EofException extends IOException{ } public static class ByteWriter implements Constants { int bufSize = 1024; byte[] byteBuf = new byte[bufSize]; OutputStream os; public ByteWriter(OutputStream os, int bufSize){ this.os = os; this.bufSize = bufSize; } public void writeInt(int num) throws IOException{ int byteWriteOffset = byteBuf.length; if (num==0){ byteBuf[--byteWriteOffset] = ZERO; }else{ int numAbs = Math.abs(num); while (numAbs>0){ byteBuf[--byteWriteOffset] = (byte)((numAbs % 10) + ZERO); numAbs /= 10; } if (num<0) byteBuf[--byteWriteOffset] = MINUS; } os.write(byteBuf, byteWriteOffset, byteBuf.length - byteWriteOffset); } /** * Please ensure ar.length <= byteBuf.length! * * @param ar * @throws IOException */ public void writeByteAr(byte[] ar) throws IOException{ for (int i = 0; i < ar.length; i++) { byteBuf[i] = ar[i]; } os.write(byteBuf,0,ar.length); } public void writeSpaceBar() throws IOException{ byteBuf[0] = SPACEBAR; os.write(byteBuf,0,1); } } public static class ByteScanner implements Constants{ InputStream is; public ByteScanner(InputStream is, int bufSizeInput, int bufSize){ this.is = is; this.bufSizeInput = bufSizeInput; this.bufSize = bufSize; byteBufInput = new byte[this.bufSizeInput]; byteBuf = new byte[this.bufSize]; } public ByteScanner(byte[] data){ byteBufInput = data; bufSizeInput = data.length; bufSize = data.length; byteBuf = new byte[bufSize]; byteRead = data.length; bytePos = 0; } private int bufSizeInput; private int bufSize; byte[] byteBufInput; byte by=-1; int byteRead=-1; int bytePos=-1; byte[] byteBuf; int totalBytes; boolean eofMet = false; private byte nextByte() throws IOException{ if (bytePos<0 || bytePos>=byteRead){ byteRead = is==null? -1: is.read(byteBufInput); bytePos=0; if (byteRead<0){ byteBufInput[bytePos]=-1;//!!! if (eofMet) throw new EofException(); eofMet = true; } } return byteBufInput[bytePos++]; } /** * Returns next meaningful character as a byte.
* * @return * @throws IOException */ public byte nextChar() throws IOException{ while ((by=nextByte())<=0x20); return by; } /** * Returns next meaningful character OR space as a byte.
* * @return * @throws IOException */ public byte nextCharOrSpacebar() throws IOException{ while ((by=nextByte())<0x20); return by; } /** * Reads line. * * @return * @throws IOException */ public String nextLine() throws IOException { readToken((byte)0x20); return new String(byteBuf,0,totalBytes); } public byte[] nextLineAsArray() throws IOException { readToken((byte)0x20); byte[] out = new byte[totalBytes]; System.arraycopy(byteBuf, 0, out, 0, totalBytes); return out; } /** * Reads token. Spacebar is separator char. * * @return * @throws IOException */ public String nextToken() throws IOException { readToken((byte)0x21); return new String(byteBuf,0,totalBytes); } /** * Spacebar is included as separator char * * @throws IOException */ private void readToken() throws IOException { readToken((byte)0x21); } private void readToken(byte acceptFrom) throws IOException { totalBytes = 0; while ((by=nextByte())=acceptFrom){ byteBuf[totalBytes++] = by; } } public int nextInt() throws IOException{ readToken(); int num=0, i=0; boolean sign=false; if (byteBuf[i]==MINUS){ sign = true; i++; } for (; i= A) cnt++; println(cnt); } // ************************************************************************************* // ****************** FRAMEWORK (borrowed from eireksten and modified) ***************** // ************************************************************************************* public static File input; public static FileReader inputreader; public static BufferedReader in; public static File output; public static FileWriter outputwriter; public static BufferedWriter out; public static StringTokenizer st; public static void main(String[] args) throws Exception { setInput(""problems/""+ PROBLEM_NAME +"".in""); setOutput(""problems/""+ PROBLEM_NAME +"".out""); HashSet dups = new HashSet(); for(int i=1; i<2000000; i++) { for(int j=0; j<7; j++) recycles[i][j] = -1; dups.clear(); String str = String.valueOf(i); int len = str.length(); for(int j=len-1; j>=1; j--) { String cycled = str.substring(len-j ) + str.substring(0, len-j ); Integer integer = Integer.valueOf(cycled); int val = integer.intValue(); if( val > i ) { if( dups.contains(integer) == false ) { dups.add(integer); recycles[i][j] = val; } } } } C c = new C(); int cases = INT(); for(int cc = 1;cc<=cases;cc++) { print(""Case #""+cc+"": ""); c.solveCase(); } close(); } // **************** HELPERS **************************** public static double[] converDoubletArray(ArrayList n){double[] ret=new double[n.size()];for(int i=0;i convertDoubleArray(double[] n){ArrayList arr = new ArrayList();for(int i=0; i n){long[] ret=new long[n.size()];for(int i=0;i convertLongArray(long[] n){ArrayList arr = new ArrayList();for(int i=0; i n){int[] ret=new int[n.size()];for(int i=0;i convertIntArray(int[] n){ArrayList arr = new ArrayList();for(int i=0; i void print( T[] array, String spacer){for(int i=0; i void println( T[] array, String spacer){print(array,spacer);println("""");} @SuppressWarnings(""unchecked"") public static void print( List list ){print(list, "" "");} @SuppressWarnings(""unchecked"") public static void print( List list, String spacer ){int doSpace=0;for( Object obj : list ){ if( doSpace != 0 )print(spacer);print( obj );doSpace++;}} @SuppressWarnings(""unchecked"") public static void println( List list ){println(list, "" "");} @SuppressWarnings(""unchecked"") public static void println( List list, String spacer ){int doSpace=0;for( Object obj : list ){ if( doSpace != 0 )print(spacer);print( obj );doSpace++;} println("""");} // ******************** INPUT DECLARATION ****************** public static void setInput(String filename) throws IOException {input = new File(filename);inputreader = new FileReader(input);in = new BufferedReader(inputreader);} public static void setOutput(String filename) throws IOException {output = new File(filename);outputwriter = new FileWriter(output);out = new BufferedWriter(outputwriter);} public static void close() throws IOException {if(in!=null)in.close();if(inputreader!=null)inputreader.close();if(out!=null)out.flush();if(out!=null)out.close();if(outputwriter!=null)outputwriter.close();} // ************************** INPUT READING ***************** static String LINE() throws IOException { return in.readLine(); } static String TOKEN() throws IOException {while (st == null || !st.hasMoreTokens())st = new StringTokenizer(LINE());return st.nextToken();} static int INT() throws IOException {return Integer.parseInt(TOKEN());} static long LONG() throws IOException {return Long.parseLong(TOKEN());} static double DOUBLE() throws IOException {return Double.parseDouble(TOKEN());} static BigInteger BIGINT() throws IOException {return new BigInteger(TOKEN());} //**************** PERMUTATIONS ********************** // new Permutation(20) will create 20 objects // and steps through the different orderings // // .hasMore() .getTotal() .getNumLeft() // .getNext() .reset() //--------------------------------- class Permutation { private int[] a; private long numLeft; private long total; public Permutation(int n) { a = new int[n]; total = getFactorial (n); reset (); } public void reset () {for (int i = 0; i < a.length; i++) { a[i] = i; } numLeft = total; } public long getNumLeft () { return numLeft; } public long getTotal () { return total; } public boolean hasMore () { return numLeft > 0; } private long getFactorial (int n) { long fact = 1;for (int i = n; i > 1; i--) {fact *= i; } return fact; } public int[] getNext () { if ( numLeft == total) { numLeft--; return a; } int temp; int j = a.length - 2; while (a[j] > a[j+1]) { j--; } int k = a.length - 1; while (a[j] > a[k]) { k--; } temp = a[k]; a[k] = a[j]; a[j] = temp; int r = a.length - 1; int s = j + 1; while (r > s) { temp = a[s]; a[s] = a[r]; a[r] = temp; r--; s++; } numLeft--; return a; } } //**************** COMBINATIONS ********************** //new Combination(24,5) will create 24 objects //and chooses 5 at a time // //.hasMore() .getTotal() .getNumLeft() //.getNext() .reset() //--------------------------------- class Combination { private int[] a; private int n; private int r;private long numLeft;private long total; public Combination (int n, int r) { this.n = n;this.r = r;a = new int[r]; BigInteger nFact = getFactorial (n);BigInteger rFact = getFactorial (r);BigInteger nminusrFact = getFactorial (n - r);total = nFact.divide (rFact.multiply (nminusrFact)).longValue();reset ();} public void reset () {for (int i = 0; i < a.length; i++) {a[i] = i;}numLeft=total;} public long getNumLeft () {return numLeft;} public boolean hasMore () {return numLeft > 0;} public long getTotal () {return total;} private BigInteger getFactorial (int n) {BigInteger fact = BigInteger.ONE;for (int i = n; i > 1; i--) {fact = fact.multiply (new BigInteger (Integer.toString (i)));}return fact;} public int[] getNext () {if (numLeft == total) {numLeft--; return a;}int i = r - 1;while (a[i] == n - r + i) {i--;}a[i] = a[i] + 1; for (int j = i + 1; j < r; j++) { a[j] = a[i] + j - i;} numLeft--; return a;} } //**************** Coloring ********************** //new Coloring(24,5) will create 24 objects //and color each up to 5 different ways. // //.hasMore() .getTotal() .getNumLeft() //.getNext() .reset() //--------------------------------- class Coloring { private int[] a;private int r;private long numLeft; private long total; public Coloring (int n, int r){this.r = r;a = new int[n];total = (long) Math.pow(r, n); reset();} public void reset(){for(int i=0;i 0;} public long getTotal () {return total;} public int[] getNext () {numLeft--;a[0]++;int j=0;while(a[j]==r){a[j]=0;a[j+1]++;j++;}return a;} } public static BigInteger lcm(BigInteger... values) { if (values.length == 0) return BigInteger.ONE; BigInteger lcm = values[0]; for (int i = 1; i < values.length; i++) { if (values[i].signum() != 0) { final BigInteger gcd = lcm.gcd(values[i]); if (gcd.equals(BigInteger.ONE)) { lcm = lcm.multiply(values[i]); } else { if (!values[i].equals(gcd)) { lcm = lcm.multiply(values[i].divide(gcd)); } } } } return lcm; } }" B12765,"import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.util.Arrays; import java.util.Scanner; public class B { public static void main(String[] args) throws FileNotFoundException, IOException { try (FileReader file = new FileReader(""entrada.in""); Scanner scanner = new Scanner(file)) { int T,A,B,i,j,k=0,total=0; String xs; T=scanner.nextInt(); boolean matriz[][] = new boolean[1000][]; for (i=0;i<1000;i++) matriz[i] = new boolean[1000]; System.setOut(new PrintStream(""salida.out"")); for (i=1;i<=T;i++){ for (j=0;j<1000;j++) Arrays.fill(matriz[j], false); A=scanner.nextInt(); B=scanner.nextInt(); for (j=A;j<=B;j++){ xs=Integer.toString(j); if (xs.length()==2 && xs.charAt(1)!='0'){ k=Integer.parseInt(xs.charAt(1)+""""+xs.charAt(0)); if (j!=k && k<=B && k>=A) matriz[j][k]=true; } if (xs.length()==3 && xs.charAt(2)!='0'){ k=Integer.parseInt(xs.charAt(2)+""""+xs.charAt(0)+""""+xs.charAt(1)); if (j!=k && k<=B && k>=A) matriz[j][k]=true; } if (xs.length()==3 && xs.charAt(1)!='0'){ k=Integer.parseInt(xs.charAt(1)+""""+xs.charAt(2)+""""+xs.charAt(0)); if (j!=k && k<=B && k>=A) matriz[j][k]=true; } } total=conteomatriz(matriz); System.out.println(""Case #""+i+"": ""+total); } } } public static int conteomatriz(boolean[][] m){ int total=0,i,j; for (i=0;i<1000;i++){ for (j=0;j<1000;j++){ if (m[i][j]){ m[j][i]=false; //System.out.println(i+"" ""+j); total++; } } } return total; } } " B11153,"package QualificationRound; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.PrintStream; public class RecycledNumbers { public static void main(String[] args) throws Exception { System.setIn(new FileInputStream(""recyclednumbers.in"")); System.setOut(new PrintStream(""recyclednumbers.out"")); BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(bf.readLine()); for(int t = 1; t <= T; t++) { System.out.print(""Case #"" + t + "": ""); String[] parts = bf.readLine().trim().split(""[ ]+""); int from = Integer.parseInt(parts[0]); int to = Integer.parseInt(parts[1]); boolean[] explored = new boolean[to - from + 1]; long result = 0l; for(int i = from; i <= to; i++) { if(explored[i - from]) continue; long count = 0L; String s = Integer.toString(i); int length = s.length(); for(int j = 0; j < length; j++) { s = s.substring(s.length() - 1) + s.substring(0, s.length() - 1); if(s.charAt(0) == '0') continue; int n = Integer.parseInt(s); if(n < from || n > to) continue; if(explored[n - from]) continue; explored[n - from] = true; count++; } result += count * (count - 1l) / 2l; } System.out.println(result); } } } " B11547,"import java.io.*; import java.util.HashSet; import java.util.Set; /** * *************************************************************************** * Created by IntelliJ IDEA. * User: Narender Singh Pal * Date: 4/14/12 * Time: 10:59 AM *

* *************************************************************************** *

* Copyright (c) 2012 All Rights Reserved. *

*

* *************************************************************************** */ public class RecycledNumbers { public static void main (String args[]) { try { BufferedReader Br = new BufferedReader(new FileReader(""C:\\Input\\C-small-attempt0.in"")); BufferedWriter Bw = new BufferedWriter(new FileWriter(""C:\\Input\\C-small-attempt0.out"")); try { //read number of test cases int $TC = Integer.valueOf(Br.readLine()); System.out.println(""Number of Test Cases :""+ $TC); int $A, $B; int [] $InputNum; for(int tc = 1; tc <= $TC; tc++) { String $InputStr = Br.readLine(); String []TempArr = $InputStr.split("" ""); $InputNum = new int[TempArr.length]; for(int j =0; j < TempArr.length; j++) { $InputNum[j] = Integer.valueOf(TempArr[j]); } //get numbers A, B from input number pair $A = $InputNum[0]; $B = $InputNum[1]; int $RecycledPairs = 0; //Iterate the given integer range for( int $n = $A; $n <= $B ; $n++ ) { String lStr = String.valueOf($n); int $length = lStr.length(); int [] $m = new int[$length-1]; Set $MSet = new HashSet(); //for each $n get all possible recycled number for(int k = 1; k < $length; k++ ) { StringBuffer s = new StringBuffer(); s.append(lStr.subSequence(k,$length)); s.append(lStr.subSequence(0,k)); $m[k-1] = Integer.valueOf(s.toString()); //Recycled pair found if the SA <= $n < $m <= $B if($m[k-1] > $n && $m[k-1] <= $B && $m[k-1] >= $A) { if($MSet.isEmpty()) { $MSet.add($m[k-1]); } else { if($MSet.contains($m[k-1])) { System.out.println(""###Repeat : skipping ($n, $m) :("" +$n +"", ""+ $m[k-1]+"")####"" ); continue; } $MSet.add($m[k-1]); } $RecycledPairs++; System.out.println(""$Recycled Pair (""+ $RecycledPairs +"") : ($n, $m) :("" +$n +"", ""+ $m[k-1]+"")""); } } } System.out.println(""Case #""+ tc+"": ""+$RecycledPairs); Bw.write(""Case #""+ tc+"": ""+ $RecycledPairs); Bw.write('\n'); } } finally { Br.close(); Bw.close(); } } catch (IOException e) { e.printStackTrace(); } } } " B10998," import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.StringTokenizer; import java.util.logging.Level; import java.util.logging.Logger; /* * To change this template, choose Tools | Templates and open the template in * the editor. */ /** * * @author dewmal */ public class QC { public static void main(String[] args) throws IOException { String[] readFile = readFile(""input.in""); for (int i = 1; i < readFile.length; i++) { String value = readFile[i]; StringTokenizer st = new StringTokenizer(value, "" ""); int numArray[] = new int[st.countTokens()]; int j = 0; while (st.hasMoreTokens()) { String nextToken = st.nextToken(); numArray[j] = Integer.parseInt(nextToken); j++; } int A = numArray[0]; int B = numArray[1]; int count = 0; for (int n = A; n <= B; n++) { String numberOne = n + """"; for (int m = n + 1; m <= B; m++) { String numberTwo = m + """"; char[] numOneCs = numberOne.toCharArray(); int[] numOnIs = getInArray(numOneCs); char[] numTwoCs = numberTwo.toCharArray(); int[] numTwoIs = getInArray(numTwoCs); boolean numberCoupleOk = true; if (numOnIs.length == numTwoIs.length) { Arrays.sort(numOnIs); Arrays.sort(numTwoIs); numberCoupleOk = (Arrays.equals(numOnIs, numTwoIs)); if (numOnIs.length > 2) { //if (numberCoupleOk) { numOnIs = getInArray(numOneCs); numTwoIs = getInArray(numTwoCs); int numNew[] = new int[numOnIs.length]; numNew[0] = numTwoIs[1]; numNew[1] = numTwoIs[2]; numNew[2] = numTwoIs[0]; numberCoupleOk = Arrays.equals(numNew, numOnIs); if (!numberCoupleOk) { numNew[0] = numTwoIs[2]; numNew[1] = numTwoIs[0]; numNew[2] = numTwoIs[1]; numberCoupleOk = Arrays.equals(numNew, numOnIs); } // } } } if (numberCoupleOk && n < m) { // System.out.println(n + "" "" + m); count++; } } if (n + 1 == B) { break; } } final String outValue = ""Case #"" + i + "": "" + count; System.out.println(outValue); writeFile(outValue); } } private static int[] getInArray(char[] numOneCs) throws NumberFormatException { int[] numOnIs = new int[numOneCs.length]; for (int i = 0; i < numOneCs.length; i++) { numOnIs[i] = Integer.parseInt(numOneCs[i] + """"); } return numOnIs; } private static String[] readFile(String trainEngin) throws IOException, FileNotFoundException { BufferedReader br = new BufferedReader(new FileReader(trainEngin)); String line = br.readLine(); List arraList = new ArrayList<>(); while (line != null) { arraList.add(line); line = br.readLine(); } String[] toArray = {}; toArray = arraList.toArray(toArray); return toArray; } private static BufferedWriter bw; static { try { bw = new BufferedWriter(new FileWriter(""out.in"")); } catch (IOException ex) { Logger.getLogger(QC.class.getName()).log(Level.SEVERE, null, ex); } } private static void writeFile(String value) throws IOException { bw.append(value); bw.newLine(); bw.flush(); } } " B10019,"import java.util.ArrayList; public class GCJUtils { public static Long[] getLongArray(ArrayList lines){ Long[] arrL = new Long[lines.size()]; for(int i=0;i s; /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner kb = new Scanner(System.in); int t = kb.nextInt(); int c = 1; int cnt, a, b; while(t-- > 0) { cnt = 0; a = kb.nextInt(); b = kb.nextInt(); for(int i=a; i(); for(int r=0; r xInt) { if(!s.contains(tmpInt)) { cnt++; s.add(tmpInt); } // System.out.println(""(""+x+"",""+tmp+"")""); } } } System.out.println(""Case #""+c+++"": ""+cnt); // for(int k=0; k 2) { parts = new int[count-1]; factor = 10; for(j=(count-2) ; j >= 0 ; j--) { parts[j] = seed/factor; factor = factor*10; } for(j=1 ; j<=parts.length ; j++) { factor = (int)Math.pow(10,count-j); temp = seed%factor; temp = temp*((int)Math.pow(10,j))+parts[j-1]; c2 = digitsCount(temp); if(count == c2) { if( (temp >= start) && (temp <= end) ) { if(!arr[seed]) arr[seed] = true; if(!arr[temp]) req_count++; } } } } else if(count == 2) { temp = seed%10; temp = (temp*10)+(seed/10); if( (temp >= start) && (temp <= end) ) { req_count++; arr[temp] = true; arr[seed] = true; } } } } out.write(""Case #"" + k + "": "" + req_count); out.newLine(); k++; } out.close(); } //---------------------------------------------------------------------- public static int digitsCount(int num) { int count = 0; while(num > 0) { count++; num = num/10; } return count; } //---------------------------------------------------------------------- public static void filterArray(boolean[] arr) { int length = arr.length; int i; int temp = 0; if( (length >= 10) && (length < 100) ) { temp = 11; for(i=2 ; i<=10 && temp <= length ; i++) { arr[temp] = true; temp = i*11; } } if( (length >= 100) && (length < 1000) ) { temp = 111; for(i=2 ; i<=10 && temp <= length ; i++) { arr[temp] = true; temp = i*111; } } if( (length >= 1000) && (length < 10000) ) { temp = 1111; for(i=2 ; i<=10 && temp <= length ; i++) { arr[temp] = true; temp = i*1111; } } if( (length >= 10000) && (length < 100000) ) { temp = 11111; for(i=2 ; i<=10 && temp <= length; i++) { arr[temp] = true; temp = i*11111; } } if( (length >= 100000) && (length < 1000000) ) { temp = 111111; for(i=2 ; i<=10 && temp <= length ; i++) { arr[temp] = true; temp = i*111111; } } if( (length >= 1000000) && (length <= 2000000) ) arr[1111111] = true; } } " B10992,"import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class RecycledNumbers { public static void main(String[] args) throws IOException { if(args.length != 2) { System.out.println(""Error""); System.exit(1); } RecycledNumbers recycle = new RecycledNumbers(); BufferedReader in = new BufferedReader(new FileReader(new File(args[0]))); PrintWriter out = new PrintWriter(new File(args[1])); in.readLine(); int index = 1; while(true) { String line = in.readLine(); if(line == null) break; String[] numbers = line.split("" ""); out.println(""Case #"" + index + "": "" + recycle.numOfRecycledNumbers(Integer.parseInt(numbers[0]), Integer.parseInt(numbers[1]))); index++; } out.close(); in.close(); } private Map recycledNumbersMap = new HashMap(); private class Pair { int n; int m; public Pair(int n, int m) { this.n = n; this.m = m; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getOuterType().hashCode(); result = prime * result + m; result = prime * result + n; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (!getOuterType().equals(other.getOuterType())) return false; if (m != other.m) return false; if (n != other.n) return false; return true; } private RecycledNumbers getOuterType() { return RecycledNumbers.this; } } public int numOfRecycledNumbers(int lowerLimit, int upperLimit) { int recycledNumbers = 0; for (int n = lowerLimit; n <= upperLimit; n++) { for (int m = n + 1; m <= upperLimit; m++) { Pair pair = new Pair(n, m); Pair otherPair = new Pair(m, n); if(recycledNumbersMap.containsKey(pair)) { if(recycledNumbersMap.get(pair)) recycledNumbers++; continue; } String nStr = String.valueOf(n); String mStr = String.valueOf(m); boolean foundRecycled; if (sameNumberOfDigits(nStr, mStr) && containSameDigits(nStr, mStr) && checkIfRecycledNumbers(nStr, mStr)) { recycledNumbers++; foundRecycled = true; } else { foundRecycled = false; } recycledNumbersMap.put(pair, foundRecycled); recycledNumbersMap.put(otherPair, foundRecycled); } } return recycledNumbers; } boolean sameNumberOfDigits(String n, String m) { return n.length() == m.length(); } boolean containSameDigits(String n, String m) { while(!n.isEmpty()) { String c = n.charAt(0) + """"; n = n.replaceFirst(c, """"); if (!m.contains(c)) return false; m = m.replaceFirst(c, """"); } return m.isEmpty(); } boolean checkIfRecycledNumbers(String n, String m) { int secondLength = m.length(); List allIndexes = getAllIndexes(m, n.charAt(0)); boolean foundRecycle; for(int index : allIndexes) { int secondIndex = index; foundRecycle = true; for(int firstIndex = 1; firstIndex < n.length(); firstIndex++) { secondIndex = (secondIndex + 1) % secondLength; if (n.charAt(firstIndex) != m.charAt(secondIndex)) { foundRecycle = false; break; } } if(foundRecycle) return true; } return false; } List getAllIndexes(String str, char c) { List indexes = new ArrayList(); int index = 0; while(true){ if(index >= str.length()) break; index = str.indexOf(c, index); if(index == -1) break; indexes.add(index); index++; } return indexes; } } " B12739,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; public class RecycledNumbers { private static String shiftLeft(String str) { char first_char = str.charAt(0); String new_number_str = str.substring(1); new_number_str += first_char; return new_number_str; } private static boolean recycled(int num1, int num2) { String num1Str = Integer.toString(num1); String num2Str = Integer.toString(num2); for(int i = 0; i < num2Str.length() - 1; i++) { String newStr2 = shiftLeft(num2Str); if(num1Str.equals(newStr2)) return true; num2Str = newStr2; } return false; } private static int numDigits(int number) { if(number == 0) return 1; int numDigits = 0; while(number != 0) { number /= 10; numDigits++; } return numDigits; } public static void main(String[] args) throws IOException { FileInputStream fstream = new FileInputStream(""input.txt""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter fstreamOut = new FileWriter(""output.txt""); BufferedWriter out = new BufferedWriter(fstreamOut); String strLine = br.readLine(); if(strLine.charAt(strLine.length() - 1) == '\n') strLine = strLine.substring(0, strLine.length() - 1); int numCases = Integer.parseInt(strLine); for(int i = 1; i <= numCases; i++) { strLine = br.readLine(); if(strLine.charAt(strLine.length() - 1) == '\n') strLine = strLine.substring(0, strLine.length() - 1); int space = strLine.indexOf(' '); int A = Integer.parseInt(strLine.substring(0, space)); int B = Integer.parseInt(strLine.substring(space + 1)); //System.out.println(A + "" and "" + B); int numCase = 0; for(int m = A + 1; m <= B; m++) { for(int n = A; n < m; n++) { if(recycled(n, m)) { //System.out.println(""WORKS: "" + m + "" and "" + n); numCase++; } } } out.write(""Case #"" + i + "": "" + numCase); if(i < numCases) out.write(""\n""); } in.close(); br.close(); out.close(); } } " B10112,"import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; public class Recycled { private static String in; private static String[] ins; private static BufferedReader buf; private static int cases; private static File arquivo = new File(""output.txt""); private static FileOutputStream fos; public static void main(String[] args) { buf = new BufferedReader(new InputStreamReader(System.in)); try { fos = new FileOutputStream(arquivo); } catch (FileNotFoundException e1) { e1.printStackTrace(); System.exit(0); } try { in = buf.readLine(); cases = Integer.parseInt(in); } catch (IOException e) { e.printStackTrace(); System.exit(0); } for (int i = 1; i <= cases; i++) { int result = 0; try { in = buf.readLine(); ins = in.split("" ""); } catch (IOException e) { e.printStackTrace(); System.exit(0); } int A = Integer.parseInt(ins[0]); int B = Integer.parseInt(ins[1]); for (int numb = A; numb <= B; numb++) { result += reciclar(numb, A, B); } try { String res = ""Case #"" + i + "": "" + result + System.getProperty(""line.separator""); fos.write(res.getBytes()); } catch (IOException e) { e.printStackTrace(); System.exit(0); } } } public static int reciclar(int numb, int A, int B) { int result = 0; ArrayList usados = new ArrayList(); char[] numbvec = String.valueOf(numb).toCharArray(); for (int i = 1; i < numbvec.length; i++) { String rot = new String(); for (int j = i; j < numbvec.length + i; j++) { if (j >= numbvec.length) { rot += numbvec[j-numbvec.length]; } else { rot += numbvec[j]; } } int numbrot = Integer.parseInt(rot); if (numbrot >= A && numbrot <= B && numb != numbrot && !usados.contains(numbrot)) { if (numb < numbrot){ result++; usados.add(numbrot); System.out.println(""("" + numb + ""),("" +numbrot+ "")""); } } } return result; } } " B11294,"import java.util.*; import java.io.*; public class Solution { public void doMain() throws Exception { Scanner sc = new Scanner(new FileReader(""/home/vivek/workspace/codejam2012problem2/src/input.txt"")); PrintWriter pw = new PrintWriter(new FileWriter(""/home/vivek/workspace/codejam2012problem2/src/output.txt"")); //Scanner sc = new Scanner(System.in); //PrintWriter pw = new PrintWriter(System.out); int T = sc.nextInt(); //sc.nextLine(); for (int j = 0; j < T; j++) { long a = sc.nextLong(); long b = sc.nextLong(); int count=0; pw.print(""Case #"" + (j + 1) + "": ""); for(long i=a;i<=b;i++){ String N=i+""""; String M=i+"""";int n=M.length(); int check=0; List al=new ArrayList(); for(int k=0;k=A)&&(num_pair<=B)) { pairs_2=pairs_2+1; //System.out.println(num_pair); } } } else if(numdigits==3) { int pair_a, pair_b, pair_c; //System.out.println(""3 digit number !""); ones = num%10; int temp1=num/10; tens=temp1%10; int temp2=temp1/10; hundrds=temp2%10; //System.out.println(hundrds+"" ""+tens+"" ""+ones); if((tens==hundrds)&&(hundrds==ones)) // Working { //System.out.println(""No pairs here""); } else { pair_a=num; pair_b= tens*100+ ones*10+ hundrds; pair_c= ones*100 + hundrds*10 + tens; int nod_a=3; int nod_b = (int) Math.log10((double)pair_b)+1; int nod_c= (int) Math.log10((double)pair_c)+1; if((nod_b==3)&&(nod_c==3)) { //System.out.println(""All have three digits""); if((pair_b>=A)&&(pair_b<=B)&&(pair_c>=A)&&(pair_c<=B)) { //System.out.println(""Inside the case where all 3 pairs lie in the range""); //System.out.println(""pair a""+pair_a+"" ""); //System.out.println(""Incremented""); pairs_3= pairs_3+1; // As each pair will add 1 thus 3 will be added anyways } else if(((pair_b>=A) && (pair_b<=B)) || (pair_c>=A) && (pair_c<=B)) { //System.out.println(""Inside the case where only 2 pairs lie in the range""); //System.out.println(""pair a""+ pair_a+""pair b""+ pair_b+""pair c""+ pair_c); //System.out.println(""Incremented""); pairs_3= pairs_3+0.5; } } else if((nod_b==3)||(nod_c==3)) { //System.out.println(""Inside case where only 2 numbers have 3 digits""); if(nod_b==3) { if((pair_b>=A) && (pair_b<=B)) { //System.out.println(""pair a""+ pair_a+""pair b""+ pair_b+""pair c""+ pair_c); //System.out.println(""Incremented""); pairs_3= pairs_3+0.5; } } else if(nod_c==3) { if((pair_c>=A) && (pair_c<=B)) { //System.out.println(""pair a""+ pair_a+""pair b""+ pair_b+""pair c""+ pair_c); //System.out.println(""Incremented""); pairs_3= pairs_3+0.5; } } } } } num++; } pairs= pairs_2/2+pairs_3; //System.out.println(""Number of 2 digit pairs ""+ pairs_2/2); //System.out.println(""Number of 3 digit pairs ""+ pairs_3); //System.out.println(""Total number pairs ""+ pairs); int ans = (int)pairs; System.out.println(""Case #""+line+"": ""+ans); } } " B11837,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.List; public class Numbers { public static FileReader fr; public static BufferedReader br; public static FileWriter fw; public static BufferedWriter bw; public void read(String path) throws Exception { fr = new FileReader(path); br=new BufferedReader(fr); } public void write(String path) throws Exception { } public void execute(BufferedReader br,String path)throws Exception { String s; fw =new FileWriter(path,false); bw=new BufferedWriter(fw); s=br.readLine(); int i1=1; while((s=br.readLine())!=null) { int count =0; String st[]=s.split(""\\s""); int a=Integer.parseInt(st[0]); int b=Integer.parseInt(st[1]); for(int i=a;i<=b;i++) { int temp=i; String abc=Integer.toString(temp); int length=abc.length(); int index=length-1; String tempString=abc; while(index>0) { String first=tempString.substring(0, index); String second=tempString.substring(index,length); abc=second+first; int newnumber=Integer.parseInt(abc); if((newnumber<=b && newnumber>temp )&& !abc.startsWith(""0"") && (Integer.toString(temp).length())==abc.length()) count++; index--; } } bw.write(""Case #""+ i1++ +"": "" +count +""\n""); } bw.close(); fr.close(); } public static void main(String[] args) throws Exception { Numbers t=new Numbers(); t.read(""E:\\codejam\\Files\\A.in""); t.execute(br,""E:\\codejam\\Files\\A.out""); } } " B10495,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Numbers { public static void main(String args[])throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String regex = "" ""; int T = Integer.parseInt(in.readLine()); String str; String[] split; String[] result = new String[T+1]; for(int x = 1; x <= T; x++){ result[x] = ""Case #"" + x + "": ""; str = in.readLine(); split = str.split(regex); if(split.length < 2) { result[x] = result[x].concat(""0""); } else { result[x] = result[x].concat(Integer.toString(getNumberOfPairs(Integer.parseInt(split[0]), Integer.parseInt(split[1])))); } } for(int u = 1; u <= T; u++){ System.out.println(result[u]); } } public static int getNumberOfPairs(int a, int b){ int pairs = 0; for(int x = a; x < b; x++) { for(int y = b; y > x; y--) { if(isRecycledPair(x,y)){ pairs++; } } } return pairs; } public static boolean isRecycledPair(int a, int b){ boolean result = false; String A = Integer.toString(a); String B = Integer.toString(b); String tempA; if(A.length() != 1 && B.length() != 1){ for(int x = 1; x < A.length();x++){ tempA = A.substring(x, A.length()); tempA = tempA.concat(A.substring(0, x)); if(tempA.equals(B)){ result = true; } } } return result; } } " B13152,"import java.io.*; import java.math.BigInteger; import java.util.*; public class GC { String s = null; String[] sp = null; public void run() throws Exception{ BufferedReader br = new BufferedReader(new FileReader(""C-small-attempt0.in"")); BufferedWriter bw = new BufferedWriter(new FileWriter(""OUTPUT.txt"")); s = br.readLine(); int T = Integer.parseInt(s); int t = 1; while(t <= T){ s = br.readLine(); sp = s.split("" ""); int ans = 0; int a = Integer.parseInt(sp[0]); int b = Integer.parseInt(sp[1]); if(a < 10){ a = 10; } while(a < b){ String sa = Integer.toString(a); Set set = new HashSet(); for(int i = 1; i < sa.length(); i++){ String f = sa.substring(0, i); String ba = sa.substring(i); String ns = ba + f; if(set.contains(ns)){ continue; } set.add(ns); int nb = Integer.parseInt(ns); if(nb > a && nb <= b){ ans++; } } a++; } bw.write(""Case #"" + t + "": "" + ans + ""\n""); t++; } bw.close(); } public static void main(String[] args) throws Exception { GC b = new GC(); b.run(); } } " B10496," import java.io.*; import java.util.*; public class RecycledNumbers{ public static void main(String[] args)throws Exception{ String file = ""C-small-attempt0""; BufferedReader br = new BufferedReader(new FileReader(file + "".in"")); FileWriter archivo = new FileWriter(file+"".out""); PrintWriter printer = new PrintWriter(archivo); printer.flush(); int n,a,b,aux,cont,tamano,auxiliar,cont2; String aux2,aux3,aux4; boolean probar; int [] v = new int[2000000]; String [] s = new String[2000000]; StringBuffer cadena; StringTokenizer st; String line; line=br.readLine(); n=Integer.parseInt(line); for(int i=0;i void solve(String filePath, String fileName, InputConverter inputConverter, SolverBase solver) { File folder = new File(filePath); File fin = getInputFile(folder, fileName); File fout = getOutputFile(folder, fileName); if (!fout.exists()) { try { fout.createNewFile(); } catch (IOException e) { System.err.println(""Error creating file "" + fout.getAbsolutePath()); e.printStackTrace(); } } InputReader reader = null; SolutionWriter writer = null; try { reader = new InputReader(fin, inputConverter); solver.init(reader); writer = new SolutionWriter(fout); int caseNum = 1; String solution; long startTime = System.currentTimeMillis(); while ((solution = solver.solveNext()) != null) { writer.writeSolution(caseNum++, solution); writer.flush(); } int time = (int)(System.currentTimeMillis() - startTime); System.out.println(""Done in "" + (time / 1000) + "" seconds ("" + (time / (caseNum - 1)) + ""ms average)""); } catch (Exception e) { System.err.println(""Error solving""); e.printStackTrace(); } if (reader != null) { try { reader.close(); } catch (IOException e) { // do nothing } } if (writer != null) { writer.flush(); writer.close(); } } public static File getInputFile(File folder, String fileName) { return new File(folder, fileName + FILE_IN_EXTENSION); } public static File getOutputFile(File folder, String fileName) { DateFormat dateFormat = new SimpleDateFormat(OUT_DATE_FORMAT); String date = dateFormat.format(Calendar.getInstance().getTime()); return new File(folder, fileName + date + FILE_OUT_EXTENSION); } public static String[] convertToStringArray(String line) { return line.split("" ""); } public static int[] convertToIntArray(String line, int count) { int[] items = new int[count]; int wordStart = 0; for (int i = 0; i < count; i++) { int wordEnd = line.indexOf(' ', wordStart); if (wordEnd < 0) { wordEnd = line.length(); } int param = Integer.parseInt(line.substring(wordStart, wordEnd)); items[i] = param; wordStart = wordEnd + 1; } return items; } public static int convertToIntArray(String line, int[] itemsOut) { int count = 0; int wordStart = 0; int length = line.length(); while (wordStart < length) { int wordEnd = line.indexOf(' ', wordStart); if (wordEnd < 0) { wordEnd = line.length(); } int param = Integer.parseInt(line.substring(wordStart, wordEnd)); itemsOut[count++] = param; wordStart = wordEnd + 1; } return count; } } " B12428,"import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.TreeSet; public class NumberQueue { String number; public NumberQueue(int number) { this.number = number + """"; } public void cycle() { char front = number.charAt(0); number = number.substring(1) + front; } public List distinctRoations(int min, int max) { List pairs = new ArrayList(); String original = number; int origNum = toInteger(); for(int i = 0; i < number.length(); i++) { if(!number.equals(original)) { // check bounds int numInt = toInteger(); if(numInt >= min && numInt <= max) { Pair ap = new Pair(origNum, numInt); if(!pairs.contains(ap)) { pairs.add(ap); } } cycle(); } else { cycle(); } } number = original; return pairs; } public int toInteger() { return Integer.valueOf(number); } public class Pair implements Comparable{ public int first; public int second; public Pair(int f, int s) { first = f; second = s; } // override default equals public boolean equals(Object o) { Pair other = (Pair) o; return (first == other.first && second == other.second) || (first == other.second && second == other.first); } public String toString() { return """" + first + ""<=>"" + second; } // compare to for ordering - mostly debugging public int compareTo(Pair other) { if(equals(other)) { return 0; } else { return first - other.first; } } } } " B12372,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; import java.io.*; /** * * @author Ka */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException, IOException { // TODO code application logic her File f = new File(""C-small-attempt0.in""); FileWriter fstream = new FileWriter(""output.txt""); BufferedWriter out = new BufferedWriter(fstream); //Solution s = new Solution(f); //s.scores(); // s.output(out); Recy r = new Recy(f); r.scores(); r.output(out); } } " B12636,"package com.google.codejam.C; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class Recycled { public static void main(String[] args) { String line = null; BufferedReader reader = null; File file = new File(""c:\\write.txt""); BufferedWriter output = null; try { output = new BufferedWriter(new FileWriter(file)); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { reader = new BufferedReader(new FileReader(""c:\\temp1.txt"")); line = reader.readLine(); int n = Integer.parseInt(line); for (int i=0;i set = new HashSet(); for (int number=n1;number<=n2;number++){ int digitarr[] = new int[8]; int numberOfDigits = 0; int no = number; while (no >0 ){ int d = no%10; no = no/10; digitarr[numberOfDigits]=d; numberOfDigits++; } if (numberOfDigits==1){ continue; } for (int j=0;jn2){ break; } } if (sum<=n2 && sum> number){ if (set.contains(new Pair(sum,number))){ // System.out.println(number +"" ""+ sum); continue; } set.add(new Pair(sum,number)); count++; } } } output.write(count+""""); if (i!=n-1) output.write(""\n""); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { reader.close(); output.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } class Pair{ int a; int b; public Pair(int sum, int number) { a = sum; b = number; } @Override public boolean equals(Object obj) { Pair p = (Pair)obj; if (p.a==a && p.b==b){ return true; } if (p.b==a && p.a==b) return true; return false; } @Override public int hashCode() { return ((a+b)%13); } } " B12429,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; public class recycle { static int count=0; static int A = 0; static int B = 0; public static void permutes(String start){ int n = Integer.valueOf(start); for(int i=1;i parseIntList(String str) { ArrayList res = new ArrayList(); String[] parts = str.split("" ""); for (int i = 0; i < parts.length; i++) { String part = parts[i]; res.add(Integer.parseInt(part)); } return res; } static String printTable(T[][] t) { StringBuilder res = new StringBuilder(); for (int i = 0; i < t.length; i++) { T[] ts = t[i]; for (int j = 0; j < ts.length; j++) { T t1 = ts[j]; res.append(t1+ "" ""); } res.append(""\n""); } return res.toString(); } } " B11531,"import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; // Qualification Round 2012 // Problem C public class RecycledNumbers { public static void main(String[] args) { Scanner sc = null; try { sc = new Scanner(new File(""C-small.in"")); } catch (FileNotFoundException e) { e.printStackTrace(); } PrintStream output = null; try { output = new PrintStream(new File(""C-small.out"")); } catch (IOException e) { e.printStackTrace(); } int cases = sc.nextInt(); sc.nextLine(); for(int c = 0; c < cases; c++){ int A = sc.nextInt(); int B = sc.nextInt(); HashSet pairs = new HashSet(); for(int n = A; n <= B; n++){ String testn = n + """"; String testm = testn; int l = testn.length(); for(int i = 0; i < l - 1; i++){ testm = testm.charAt(l - 1) + testm.substring(0, l - 1); int m = Integer.parseInt(testm); if(n < m && m <= B && m > A){ pairs.add(n + "" "" + m); } } } System.out.printf(""Case #%d: %s\n"", c + 1, pairs.size()); output.printf(""Case #%d: %s\n"", c + 1, pairs.size()); } } } " B13102," import java.io.*; import java.util.*; public class Recycled { public static final PrintStream out = System.out; public static final BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); public int numCases; public void doCase(int caseNumber) throws Exception { String line = in.readLine(); Scanner scan = new Scanner(line); int a = scan.nextInt(); int b = scan.nextInt(); int results = 0; for(int i = a; i <= b; i++) { //if(i%10000==0) out.println(""looking at "" + i); results += howManyCyclesGreaterThanMeButLessThanB(i,b); } out.println(results); } public int howManyCyclesGreaterThanMeButLessThanB(int i, int b) { int res = 0; int lastCycle = 0; for(int cycle : generateCycles(i)) { if(cycle==lastCycle) continue; if(cycle > i && cycle <= b) res++; lastCycle = cycle; } //if(i%10000==0) out.println(""found good cycles "" + res); return res; } public int[] generateCycles(int i) { int origi = i; int numDigits = numberOfDigits(i); int[] res = new int[numDigits-1]; int pow = tenToThePower(numDigits-1); for(int j = 0; j < res.length; j++) { i = i / 10 + i % 10 * pow; res[j] = i; } Arrays.sort(res); //if(origi%10000==0) out.println(""found cycles "" + Arrays.toString(res)); return res; } public static int tenToThePower(int i) { int res = 1; for(int j = 0; j < i; j++) { res *= 10; } return res; } public static int numberOfDigits(int i) { int res = 1; while(i/10 > 0) { i = i/10; res++; } return res; } public void run() throws Exception { numCases = Integer.parseInt(in.readLine().trim()); for (int i = 1; i <= numCases; i++) { out.print(""Case #"" + i + "": ""); doCase(i); } } public static void main(String[] args) throws Exception { new Recycled().run(); } } " B13035,"package qualification.q2; import qualification.common.InputReader; import qualification.common.OutputWriter; import qualification.q1.Q1Solver; /** * Created by IntelliJ IDEA. * User: ofer * Date: 14/04/12 * Time: 18:55 * To change this template use File | Settings | File Templates. */ public class Q2Sim { public static void main(String[] args){ String inputFile = ""input.txt""; String outPutFile = ""output.txt""; String[] lines = InputReader.getInputLines(inputFile); Q2Solver solver = new Q2Solver(); int numOfTests = Integer.parseInt(lines[0]); String[] output = new String[numOfTests]; for (int i = 0 ; i < numOfTests ; i++){ String[] splited = lines[i+1].split("" ""); int n = Integer.parseInt(splited[0]); int s = Integer.parseInt(splited[1]); int p = Integer.parseInt(splited[2]); int[] sums = new int[n]; for (int j = 0 ; j < n ; j++){ int sum = Integer.parseInt(splited[j+3]); sums[j] = sum; } int res = solver.solve(n,s,p,sums); output[i] = ""Case #"" + (i+1) + "": "" + res; } OutputWriter.writeOutput(outPutFile, output); } } " B12951,"package google.problems; import google.loader.Challenge; import google.loader.ChallengeReader; import java.util.ArrayList; import java.util.List; public abstract class AbstractReader implements ChallengeReader { private String[] lines; private List challenges; private int actualLine; public AbstractReader(){ challenges = new ArrayList(); } protected void setLines(String[] input) { lines=input; } protected String[] getLines(){ return lines; } protected int getNumberOfChallenges() { return Integer.parseInt(lines[0]); } @Override public List createChallenges(String[] input) { setLines(input); readChallenges(); return challenges; } private void readChallenges() { int numOfChallanges = getNumberOfChallenges(); setActualLine(1); actualLine = 1; for(int i=1;i<=numOfChallanges; i++){ challenges.add(createChallenge(i)); } } protected int[] asInt(String values) { String[] split = values.split("" ""); int res [] = new int[split.length]; for(int i=0;i asIntList(String values) { List res = new ArrayList(); for(int i : asInt(values)){ res.add(i); } return res; } protected abstract Challenge createChallenge(int i) ; protected void setActualLine(int i) { actualLine =i; } protected int getActualLine(){ return actualLine; } } " B12005,"package recycledNumbers; public class RecycledPair { private int n; private int m; public RecycledPair(int n, int m) { this.n = n; this.m = m; } /** * @return the n */ public int getN() { return n; } /** * @return the m */ public int getM() { return m; } @Override public boolean equals(Object o) { if (!(o instanceof RecycledPair)) { throw new ClassCastException(""Invalid object""); } RecycledPair rp = (RecycledPair) o; if ((this.getM() == rp.getM() && this.getN() == rp.getN()) || (this.getM() == rp.getN() && this.getN() == rp.getM())) { return true; } return false; } @Override public int hashCode() { if (this.getM() < this.getN()) { return this.getM() + 13 * this.getN(); } else { return this.getN() + 13 * this.getM(); } } } " B10163,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; /** * @author Paul LaMotte * */ public class RecycledNumbers { public static void main(String[] args) { Scanner in; try { System.setOut(new PrintStream(new File(""qualC.out""))); in = new Scanner(new File(""C-small-attempt0.in"")); int lines = Integer.parseInt(in.nextLine()); for (int i = 0; i < lines; i++) { int start = in.nextInt(); int end = in.nextInt(); int count = 0; for (int j = start; j <= end; j++) { int digits = 0; int num = j; while (num != 0) { digits++; num /= 10; } int tmp = j; int e = (int)Math.pow(10, digits - 1); HashSet set = new HashSet(); for (int k = 0; k < digits - 1; k++) { int front = tmp % 10; tmp /= 10; tmp += front * e; if (tmp > j && tmp <= end && !set.contains(tmp)) { count++; set.add(tmp); } } } System.out.printf(""Case #%d: %d\n"", i + 1, count); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B11621,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; public class RecycledNumbers { private static boolean isRecycled(long f,long s){ String str1 = String.valueOf(f); String str2 = String.valueOf(s); if(str1.length()!=str2.length()){ return false; } for(int i=1;i l = new ArrayList(); for (int i = 0; i < n; ++i){ String[] spt = stdin.readLine().split("" ""); int a = Integer.parseInt(spt[0]); int b = Integer.parseInt(spt[1]); int res = 0; for (int j = a; j <= b; ++j){ for (int k = j+1; k <= b; ++k){ if (check(j,k)){ res++; // check(j,k); // if (j == 178) { // int asd = 123; // check(j,k); // asd++; // } // System.out.println(j+"" ""+k); } } } l.add(""Case #""+(i+1)+"": ""+res); } for (String s : l) { System.out.println(s); } } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } static boolean check(int a, int b){ if (b <= a) return false; int x = 10; int n = 1; while (a/x > 0){ n++; x *= 10; } //System.out.println(n); for (int i = 1; i < n; ++i){ int c = a % pow(10,i); int f = pow(10,(n-i))*c; int g = a / pow(10,i); if ( f+g == b) return true; } return false; } static int pow (int x, int n){ int y = x; for (int i =0; i uniquePairs = new HashSet(); String inputValue = value.toString(); if (inputValue.length() <= 1) { return 0; } for (int i = 1; i < inputValue.length(); i++) { String tmp = inputValue; int split = i; String firstPart = tmp.substring(0, split); String secondPart = tmp.substring(split); String connected = secondPart + firstPart; if (inputValue.compareTo(connected) < 0) { BigInteger tmp2 = new BigInteger(connected); if (tmp2.compareTo(second) <= 0) { // System.out.println(inputValue + "" => "" + connected); uniquePairs.add(inputValue + connected); } } } return uniquePairs.size(); } } } " B13204,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class Main { /** * @param args */ public static void main(String[] args) { BufferedReader bu = null; PrintWriter pr = null; int T, A, B, counter, m, check; String in, con, sub, S; try { bu = new BufferedReader(new FileReader(args[0])); pr = new PrintWriter(new FileWriter(""out.out"")); T = Integer.parseInt(bu.readLine()); for(int i = 0; i < T; i++) { S = ""Case #"" + (i + 1) + "": ""; in = bu.readLine(); String[] sp = new String[in.length()]; sp = in.split(""\\s+""); A = Integer.parseInt(sp[0]); B = Integer.parseInt(sp[1]); counter = 0; check = 0; m = 0; for(int n = A; n <= B ; n++) { con = """"; sub = """"; for(int k = 0; k < sp[0].length(); k++) { con = """"+n; StringBuilder sb = new StringBuilder(con); sb.append(sb.substring(0, k)).delete(0, k); sub = sb.toString(); //pr.println(sub); m = Integer.parseInt(sub); if((n >= A) && (n < m) && (B >= m) && (check != m)) { counter++; check = m; } } } pr.println(S + counter); pr.flush(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B11028,"package org.moriraaca.codejam; import java.io.InputStream; public abstract class GeneralDataParser extends AbstractDataParser { public GeneralDataParser(InputStream input) { super(input); } @Override protected void parse() { testCases = new TestCase[scanner.nextInt()]; super.parse(); } } " B11171,"import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class RecycledNumbers { /** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new File(""C-small-attempt0.in"")); int numTests = in.nextInt(); in.nextLine(); for (int i = 0; i < numTests; ++i) { int A = in.nextInt(); int B = in.nextInt(); in.nextLine(); System.out.println(""Case #"" + (i + 1) + "": "" + recycle(A, B)); } } private static int recycle(int A, int B) { int count = 0; for (int n = A; n < B; ++n) { String nStr = """" + n; count += compareM(n, B, nStr); } return count; } private static int compareM(int n, int B, String nStr) { int numberOfMGreaterThanN = 0; // and they must be less than B too int nStrLength = nStr.length(); for (int i = 1; i < nStrLength; ++i) { String mBegin = nStr.substring(0, nStrLength - i); String mEnd = nStr.substring(nStrLength - i, nStrLength); String mStr = mEnd + mBegin; if (hasSameNumDigits(nStr, mStr)) { int m = Integer.parseInt(mStr); if (n < m && m <= B) { ++numberOfMGreaterThanN; } } } return numberOfMGreaterThanN; } private static boolean hasSameNumDigits(String n, String m) { boolean foundFirstNonZero = false; int numDigitsOfN = 0; int numDigitsOfM = 0; for (int i = 0; i < n.length(); ++i) { char curChar = n.charAt(i); if (curChar != '0') { foundFirstNonZero = true; } if (foundFirstNonZero) { ++numDigitsOfN; } } foundFirstNonZero = false; for (int i = 0; i < m.length(); ++i) { char curChar = m.charAt(i); if (curChar != '0') { foundFirstNonZero = true; } if (foundFirstNonZero) { ++numDigitsOfM; } } return numDigitsOfM == numDigitsOfN; } } " B10921,"package utils; /** * * @author Fabien Renaud */ public abstract class Jam implements Runnable, JamParser { protected final String[] lines; protected final JamCase[] cases; protected final int t; private final String filenameInput; private final String filenameOutput; private final String[] output; private final StopWatch timer; private int count; protected Jam(String filename) { this.filenameInput = filename; this.filenameOutput = filename.replace("".in"", "".out""); this.count = 0; this.lines = File.readAllLines(filenameInput); this.timer = new StopWatch(); this.t = Integer.parseInt(lines[0]); this.cases = new JamCase[t]; this.output = new String[t]; File.delete(filenameOutput); } protected final synchronized void appendOutput(int number, String result) { output[number - 1] = String.format(""Case #%1$d: %2$s"", number, result); count++; if (count == t) { timer.stop(); saveOutput(); } } private void saveOutput() { if (count != t) { System.err.println(String.format(""%1$d results are missing. File not saved."")); } else { File.writeAllLines(filenameOutput, output); System.out.println(""File saved at "" + filenameOutput); System.out.println(""---------- OUTPUT ----------""); for (String s : output) { System.out.println(s); } System.out.println(""--- Processed in "" + timer.getElapsedSeconds() + "" seconds.""); } } @Override public final void run() { int j; count = 0; timer.start(); for (int i = 1; i <= t; i++) { j = i - 1; cases[j] = getJamCase(i); if (cases[j] != null) { new Thread(cases[j]).start(); } } } } " B10367,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recycle; import java.util.*; import java.io.*; import java.util.logging.Level; import java.util.logging.Logger; public class Recycle { public static void main(String[] args) throws Exception { // TODO code application logic here File file=new File(""output.txt""); int cases=0; int A[]=null,B[]=null; int result[]=null; int temp=0,digits=0; FileInputStream fr=new FileInputStream(""C:\\Users\\Sachin\\Desktop\\C-small-attempt0.in""); @SuppressWarnings(""deprecation"") StreamTokenizer st=new StreamTokenizer(fr); st.eolIsSignificant(false); st.whitespaceChars(0,32); int learn=0,flag=0,j=0; while(true) { flag++; learn=st.nextToken(); if(learn==StreamTokenizer.TT_EOF) break; if(learn==StreamTokenizer.TT_NUMBER&&flag==1) { cases=(int)st.nval; A=new int[cases]; B=new int[cases]; result=new int[cases]; } if(learn==StreamTokenizer.TT_NUMBER&&flag==2) A[j]=(int)st.nval; else if(learn==StreamTokenizer.TT_NUMBER&&flag==3) { B[j]=(int)st.nval; flag=1; j++; } } for(int i=0;itemp) result[i]++; temp++; } else while(temp<=B[i]) { int o=temp%10,t=(temp/10)%10,h=temp/100; if((o*100+h*10+t)<=B[i]&&(o*100+h*10+t)>temp) result[i]++; if((t*100+o*10+h)<=B[i]&&(t*100+o*10+h)>temp) result[i]++; temp++; } } FileWriter fileWritter = new FileWriter(file.getName(),true); BufferedWriter bufferWritter = new BufferedWriter(fileWritter); for(int i=0;i result = new HashSet(); String val = """" + n; int tmpN; for (int i = 1; i < val.length(); i++) { tmpN = Integer.parseInt(val.substring(i) + val.substring(0, i)); if (tmpN >= low && tmpN < n && (String.valueOf(tmpN).length() == String.valueOf(n).length())) { result.add(tmpN); } } return result.size(); } private static int solve(int a, int b) { int result = 0; for (int i = a; i <= b; i++) { result += doit(i, a); } return result; } public static void main(String[] args) throws Exception { String[] in = ProblemUtils.readInput(""/home/laf/Downloads/C-small-attempt0.in""); //String[] in = ProblemUtils.readInput(""/home/laf/Desktop/in.txt""); String[] out = new String[in.length]; String[] tokens; for (int i = 0; i < out.length; i++) { tokens = in[i].split("" ""); out[i] = """" + solve(Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1])); } ProblemUtils.writeOutput(""/home/laf/Desktop/out.txt"", out); } } " B12371,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; import java.io.*; import java.util.ArrayList; import java.util.Scanner; /** * * @author Ka */ public class Recy { private File file; private int aantal; private ArrayList cases; private ArrayList max; public Recy(File f) throws FileNotFoundException { file = f; Scanner scanner = new Scanner(new FileReader(file)); aantal = scanner.nextInt(); cases = new ArrayList(aantal); max = new ArrayList(aantal); scanner.nextLine(); for(int i =0; i < aantal ; i++) { String s = scanner.nextLine(); cases.add(s); } System.out.println(cases); } public void scores() { for(String s : cases) { int counter = 0; ArrayList nb = new ArrayList(); String sb = """"; while(counter < s.length()) { if(s.charAt(counter)!= ' ') { sb = sb + s.charAt(counter); } if(s.charAt(counter) == ' '&& counter != s.length()-1) { int n = Integer.parseInt(sb); nb.add(n); sb = """"; } counter++; } if(counter == s.length()) { int n = Integer.parseInt(sb); nb.add(n); sb = """"; } System.out.println(nb); options(nb); } } public void options(ArrayListnr) { int n = nr.get(0), m = nr.get(1),amount=0; if(n < 10 && m < 10) amount = 0; else if(n >= 10 && n < 100&& n % 10 < 10) { for(int i = n ; i < m ; i++) { String s = Integer.toString(i); int g = Integer.parseInt(s); String s1 = s.charAt(1)+""""+ s.charAt(0)+""""; int r = Integer.parseInt(s1); if(g >= n && g <= m && r >= n && r <= m && g < r ) amount++; } } else if(n >= 100 && n < 1000) { for(int i = n ; i < m ; i++) { String s = Integer.toString(i); int g = Integer.parseInt(s); String s1 = s.charAt(2)+""""+ s.charAt(0)+""""+s.charAt(1); String s2 = s.charAt(1)+""""+ s.charAt(2)+""""+s.charAt(0); int r = Integer.parseInt(s1); int r1 = Integer.parseInt(s2); if(g >= n && g <= m && r >= n && r <= m && g < r ) amount++; if(r != r1) { if(g >= n && g <= m && r1 >= n && r1 <= m && g < r1 ) amount++; } } } else if(n >= 1000 && n < 10000) { for(int i = n ; i < m ; i++) { String s = Integer.toString(i); int g = Integer.parseInt(s); String s1 = s.charAt(3)+""""+s.charAt(0)+""""+ s.charAt(1)+""""+s.charAt(2); String s2 = s.charAt(2)+""""+s.charAt(3)+""""+ s.charAt(0)+""""+s.charAt(1); String s3 = s.charAt(1)+""""+s.charAt(2)+""""+ s.charAt(3)+""""+s.charAt(0); int r = Integer.parseInt(s1); int r1 = Integer.parseInt(s2); int r2 = Integer.parseInt(s3); if(g >= n && g <= m && r >= n && r <= m && g < r ) amount++; if(r != r1 && r1 != r2 && r != r2) { if(g >= n && g <= m && r1 >= n && r1 <= m && g < r1 ) amount++; if(g >= n && g <= m && r2 >= n && r2 <= m && g <= r2 ) amount++; } } } max.add(amount); } public void output(BufferedWriter out) throws FileNotFoundException, IOException { int counter = 1; for(Integer s : max ) { out.write(""Case #"" + counter + "": ""); out.write(s+""\n""); counter++; } out.close(); } } " B12363,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class RecycledNumbers { static final String input_path = ""data/input.c.txt""; private static Set ans = new HashSet(); private static Integer[] getBits(int n) { List lst = new ArrayList(); while (n != 0) { lst.add(n % 10); n /= 10; } Integer ans[] = new Integer[lst.size()]; return lst.toArray(ans); } private static int getInteger(Integer[] bits) { int ans = 0; int power = 1; for (int i = 0; i < bits.length; i ++) { ans += power * bits[i]; power *= 10; } return ans; } private static int judge(int n, int b) { Integer[] bits = getBits(n); if (bits.length == 1) return 0; int ret = 0; int len = bits.length; for (int pos = 0; pos < len - 1; pos ++) { if (bits[pos] == 0) continue; int new_bits_len = 0; Integer[] new_bits = new Integer[len]; for (int i = pos + 1; i < len; i++) new_bits[new_bits_len ++] = bits[i]; for (int i = 0; i <= pos; i++) new_bits[new_bits_len ++] = bits[i]; int new_int = getInteger(new_bits); if (new_int <= b && new_int > n) { String ans_str = String.format(""%d_%d"", n, new_int); if (!ans.contains(ans_str)) ans.add(ans_str); ret += 1; } } return ret; } private static int solve(int a, int b) { if (a == b) return 0; for (int i = a; i < b; i ++) { int tmp = judge(i, b); } return ans.size(); } /** * Good luck, Wash! * @param args * @throws IOException */ public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(input_path)); String intext = in.readLine(); int T = Integer.parseInt(intext); for (int caseIter = 0; caseIter < T; caseIter ++) { intext = in.readLine(); System.out.print(String.format(""Case #%d: "", caseIter + 1)); String[] parts = intext.split("" ""); int A = Integer.parseInt(parts[0]); int B = Integer.parseInt(parts[1]); System.out.println(solve(A, B)); ans.clear(); } in.close(); } } " B12543,"package contest; import java.awt.Desktop; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; public abstract class ContestProblem { File inputFile = new File(""input.txt""); File outputFile = new File(""output.txt""); public ContestProblem() { } public ContestProblem(String inputFilename) { this.inputFile = new File(inputFilename); calcOutputFromInput(); } public void run() throws Exception { BufferedReader in = new BufferedReader(new FileReader(inputFile)); PrintWriter out = new PrintWriter(new FileWriter(outputFile)); try { parseInput(new Input(in), out); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } out.close(); in.close(); } public abstract void parseInput(Input in, PrintWriter out); public static void runProblem(ContestProblem problem) { try { long start = System.currentTimeMillis(); problem.run(); long end = System.currentTimeMillis(); System.out.format(""Took: %d ms%n"", end - start); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if (Desktop.isDesktopSupported()) { Desktop.getDesktop().open(problem.outputFile); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public File getInputFile() { return inputFile; } public ContestProblem setInputFile(File inputFile) { this.inputFile = inputFile; return this; } public File getOutputFile() { return outputFile; } public ContestProblem setOutputFile(File outputFile) { this.outputFile = outputFile; return this; } public ContestProblem calcOutputFromInput() { this.outputFile = new File(inputFile.getParentFile(), inputFile.getName() + ""-output.txt""); return this; } } " B11580,"import java.io.*; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.Scanner; public class Q3 { public static void main(String[] args) throws IOException { Scanner reader=new Scanner(new File(""D:\\C-small-attempt0 (1).in"")); int noOfCases=reader.nextInt(); String finalAnswer=""""; PrintWriter writer=new PrintWriter(""D:\\out0.in""); for(int loop=0;loop set=new LinkedList(); int counter=0; int firstNum=reader.nextInt(); int secondNum=reader.nextInt(); for(int currentN=firstNum;currentN(Integer.parseInt(n))) { if(!set.contains(n+"",""+nSubString)) { set.add(n+"",""+nSubString); counter++; } } } } } } finalAnswer+=""Case #""+(loop+1)+"": ""+counter+""\n""; } writer.write(finalAnswer); writer.flush(); writer.close(); } } " B12639,"import java.util.Scanner; /** * * @author Yasura */ public class C { public static void main(String[] args) { Scanner scanInt = new Scanner(System.in); int noOfCases = scanInt.nextInt(); int count, length, A, B, tmp, base, invBase; for (int i = 0; i < noOfCases; i++) { count = 0; A = scanInt.nextInt(); B = scanInt.nextInt(); length = (Integer.toString(A)).length(); for (int k = A; k <= B; k++) { for (int j = 1; j < length; j++) { base = (int) Math.pow(10, j); invBase = (int) Math.pow(10, length - j); tmp = ((k % base) * invBase + k / base); if (tmp > k && tmp <= B ) { count++; } } } System.out.println(""Case #""+(i+1)+"": ""+count); } } } " B10926,"package codejam; import codejam.y12.round0.RecycledNumbers; import utils.Jam; /** * * @author Fabien Renaud */ public class MainEntryPoint { public static void main(String[] args) { Jam j = new RecycledNumbers(""/home/fabien/C-small-attempt1.in""); j.run(); } } " B11943,"import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class P3 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int t = Integer.parseInt(scan.nextLine()); for (int i = 0; i < t; i++) { String[] x = scan.nextLine().split("" ""); int a = Integer.parseInt(x[0]); int b = Integer.parseInt(x[1]); long count = 0; for (int j = a; j <= b; j++) { count += find(j, b); } System.out.println(""Case #"" + (i+1) + "": "" + count); } } public static long find(int x, int limit) { long result = 0; String s = String.valueOf(x); Set set = new HashSet(); for (int i = 1; i < s.length() ; i++) { if (s.charAt(i) != '0') { String first = s.substring(0, i); String second = s.substring(i, s.length()); int number = Integer.parseInt(second + first); if (!set.contains(number) && number > x && number <= limit) { result += 1; set.add(number); } } } return result; } } " B13093,"import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.HashMap; public class Recycled { public static void main(String args[]) { try { BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(""c:\\gcj\\C\\C-small-attempt0.in""))); String line=br.readLine(); PrintStream ps=new PrintStream(""c:\\gcj\\C\\C-Small.out""); int n=Integer.parseInt(line); for(int i=1;i<=n;i++) { line=br.readLine(); String[] nums=line.split("" ""); long A=Long.parseLong(nums[0]); long B=Long.parseLong(nums[1]); ps.println(""Case #""+i+"": ""+getCount(A,B)); } } catch(Exception e) { e.printStackTrace(); } } public static long getCount(long A, long B) { //long A=1111,B=2222; long count=0; //HashMap hm=new HashMap(); for(long i=A;i<=B;i++) { for(long j=i+1;j<=B;j++) { if(j>i && isRecycled(i,j)) { //hm.put(i, j); count++; } } } //count=hm.size(); //System.out.print(""count : ""+count); return count; } static boolean isRecycled(long n, long m) { long temp=n; int[] countN=new int[10]; int[] countM=new int[10]; int numDigits=0; //int[] orderN=new int[10]; //int[] orderM=new int[10]; for(int i=0;i<10;i++) { countN[i]=0; countM[i]=0; //orderN[i]=-1; //orderM[i]=-1; } //int firstDigit=0; while(temp!=0) { int digit=(int)temp%10; countN[digit]++; temp=temp/10; numDigits++; /* if(temp==0) firstDigit=digit; */ } temp=m; while(temp!=0) { int digit=(int)temp%10; countM[digit]++; temp=temp/10; } for(int i=0;i<10;i++){ if(countN[i]!=countM[i]) return false; } long denom=(long)Math.pow(10, numDigits-1); temp=m; // int digit=firstDigit; long sub=0; do { int firstDigit=(int)(temp/denom); sub=denom*firstDigit; //int digit=(int)temp%10; temp=temp-sub; temp=temp*10+firstDigit; if(temp==n) return true; } while(temp!=m); /* String strN=String.valueOf(n); StringBuilder strM=new StringBuilder(String.valueOf(m)); for(int i=0;i num) suma++; } } } return String.valueOf(suma); } private static int[] generaPermu(int num, int length) { int[] permu = null; if(length > 1) { permu = new int[length-1]; permu[0] = cambia(num, length); for(int j = 1 ; j < permu.length ; j++) { permu[j] = cambia(permu[j-1], length); } //Evito repetidos!!! for(int j = 0 ; j < permu.length ; j++) { for (int k = j + 1; k < permu.length ; k++) { if (permu[j] == permu[k]) permu[k] = -1; } } } return permu; } private static int cambia(int i, int l) { return (int) ((i + (i % 10) * Math.pow(10, l)) / 10); } } " B12030," import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; public class Recycle { public static void main(String[] args) { if (args.length == 1) { String file = args[0]; try { BufferedReader br = new BufferedReader(new FileReader(file)); PrintWriter pw = new PrintWriter(new FileWriter(""output.out"", false)); int count = Byte.parseByte(br.readLine()); String line; int i = 0; while ((line = br.readLine()) != null && (i++ < count)) { int i2 = Integer.parseInt(line.substring(line.lastIndexOf("" "") + 1)); int i1 = Integer.parseInt(line.substring(0, line.lastIndexOf("" ""))); int s = sendMeRange(i1, i2); pw.println(""Case #"" + i + "": "" + s); } br.close(); pw.close(); } catch (Exception err) { System.out.println(""An error occurred running the program\n"" + err); } } else { System.out.println(""Please use the input file as one of the parameters""); } } public static int sendMeRange(int i1, int i2) { byte len = (byte) ("""" + i1).length(); if ( len == 1){ return 0; } else{ String arr[][] = new String[(i2-i1)+1][2]; int counter=0; for (int u = i1; u <= i2; u++){ String tag = """" + u; String reverse = """"; for (int q = tag.length() - 1; q > -1; q--){ reverse += """" + tag.charAt(0); } if (! tag.equals(reverse)){ arr[counter][0] =tag; arr[counter][1] =tag + tag; } else{ arr[counter][0] =tag; arr[counter][1] =""NOPE""; } counter++; } counter=0; for (int u = 0; u < arr.length; u++){ for (int u2 = u+1; u2 < arr.length; u2++){ if (arr[u][1].contains("""" + arr[u2][0])){ counter++; } } } return counter; } } }" B12080,"package jp.funnything.competition.util; import java.io.File; import java.math.BigDecimal; import java.math.BigInteger; import org.apache.commons.io.FileUtils; public class CompetitionIO { private final QuestionReader _reader; private final AnswerWriter _writer; /** * Default constructor. Use latest ""*.in"" as input */ public CompetitionIO() { this( null , null , null ); } public CompetitionIO( final File input , final File output ) { this( input , output , null ); } public CompetitionIO( File input , File output , final String format ) { if ( input == null ) { for ( final File file : FileUtils.listFiles( new File( ""."" ) , new String[] { ""in"" } , false ) ) { if ( input == null || file.lastModified() > input.lastModified() ) { input = file; } } if ( input == null ) { throw new RuntimeException( ""No *.in found"" ); } } if ( output == null ) { final String inPath = input.getPath(); if ( !inPath.endsWith( "".in"" ) ) { throw new IllegalArgumentException(); } output = new File( inPath.replaceFirst( "".in$"" , "".out"" ) ); } _reader = new QuestionReader( input ); _writer = new AnswerWriter( output , format ); } public CompetitionIO( final String format ) { this( null , null , format ); } public void close() { _reader.close(); _writer.close(); } public String read() { return _reader.read(); } public BigDecimal[] readBigDecimals() { return _reader.readBigDecimals(); } public BigDecimal[] readBigDecimals( final String separator ) { return _reader.readBigDecimals( separator ); } public BigInteger[] readBigInts() { return _reader.readBigInts(); } public BigInteger[] readBigInts( final String separator ) { return _reader.readBigInts( separator ); } /** * Read line as single integer */ public int readInt() { return _reader.readInt(); } /** * Read line as multiple integer, separated by space */ public int[] readInts() { return _reader.readInts(); } /** * Read line as multiple integer, separated by 'separator' */ public int[] readInts( final String separator ) { return _reader.readInts( separator ); } /** * Read line as single integer */ public long readLong() { return _reader.readLong(); } /** * Read line as multiple integer, separated by space */ public long[] readLongs() { return _reader.readLongs(); } /** * Read line as multiple integer, separated by 'separator' */ public long[] readLongs( final String separator ) { return _reader.readLongs( separator ); } /** * Read line as token list, separated by space */ public String[] readTokens() { return _reader.readTokens(); } /** * Read line as token list, separated by 'separator' */ public String[] readTokens( final String separator ) { return _reader.readTokens( separator ); } public void write( final int questionNumber , final Object result ) { _writer.write( questionNumber , result ); } public void write( final int questionNumber , final String result ) { _writer.write( questionNumber , result ); } public void write( final int questionNumber , final String result , final boolean tee ) { _writer.write( questionNumber , result , tee ); } } " B10096,"import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; import java.util.StringTokenizer; class roundThree { public static void main(String[] args) { String text = """"; if( args.length > 0) { text = args[0]; } else { try { FileInputStream fos = new FileInputStream( ""text3.txt""); Scanner scanner = new Scanner(new FileInputStream(""text3.txt"")); try { while (scanner.hasNextLine()){ text += scanner.nextLine() + ""\n""; } } finally{ scanner.close(); } try { fos.read(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } StringTokenizer st = new StringTokenizer(text, ""[\r\n]+"", false); int cases = Integer.parseInt(st.nextToken()); for (int x=1; x<= cases; x++) { StringTokenizer st2 = new StringTokenizer(st.nextToken(), ""[ ]+"", false); int small = Integer.parseInt(st2.nextToken()); int large = Integer.parseInt(st2.nextToken()); ArrayList keep_track = new ArrayList(); String small_int = """" + small; int count = 0; int small_length = small_int.length(); for( int i = small; i < large; i++) { String number1 = """" + i; keep_track.clear(); for( int j = 1; j < small_length; j++) { String sub_2 = number1.substring(0,j); String sub_1 = number1.substring(j,small_length); int variation = Integer.parseInt( sub_1 + sub_2 ); if( variation > i && variation <= large && !keep_track.contains(variation)) { keep_track.add(variation); count++; } } } System.out.println( ""Case #"" + x + "": "" + count); } } }" B11128,"package com.codegem.zaidansari; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class CodeGemUtil { public static List getInputValues(File file) { List inputData = new ArrayList(); if (!file.exists()) { throw new RuntimeException(""File not fould:"" + file.getAbsolutePath()); } try { Scanner scanner = new Scanner(new FileReader(file)); while (scanner.hasNextLine()) { inputData.add(scanner.nextLine()); } } catch (FileNotFoundException e) { System.out.println(""Failed to find file :"" + file); } return inputData; } public static boolean createOutputFile(List outputData, String fileName) { File folderName = new File(""/Users/zaansari/Desktop/CodeGem2012/OutputFiles/""); File outputFile = new File(folderName, fileName); try { BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile)); int count = 0; for (String outputDatum : outputData) { writer.write(""Case #"" + (++count) + "": ""); writer.write(outputDatum); writer.newLine(); } writer.close(); return true; } catch (IOException e) { System.out.println(""Failed to write file :"" + outputFile + "", Error Message:"" + e.getMessage()); } // Failed to wrirte file return false; return false; } public static void main(String[] args) { File file = new File(""/Users/zaansari/Desktop/CodeGem2012/InputFiles/codeGem.in.txt""); List inputData = CodeGemUtil.getInputValues(file); for (String inputDatum : inputData) { System.out.println(inputDatum); } boolean createdOutputFile = CodeGemUtil.createOutputFile(inputData, ""Q2Small.txt""); if (createdOutputFile) { System.out.println(""Successfully created output file""); } else { System.out.println(""Failed to create output file""); } } } " B10353,"import java.io.*; public class RecycledNumbers { public static void main(String[] args) { if(args.length < 1) { System.out.println(""Need a filename.""); } else { File file = new File(args[0]); try { BufferedReader fin = new BufferedReader(new InputStreamReader(new FileInputStream(file))); int numCases = Integer.parseInt(fin.readLine()); for(int i=0; i list = new ArrayList(); Scanner s = new Scanner(new File(""C-small-attempt1.in"")); s.nextLine(); int count = 1; while (s.hasNext()) { int a = s.nextInt(); int b = s.nextInt(); int result = 0; list.clear(); for (int i = a; i < b; i++) { String as = i + """"; int l = as.length(); for (int j = 1; j < as.length(); j++) { String back = as.substring(l - j, l); String front = as.substring(0, l - j); String ts = back + front; if (back.charAt(0) == '0' || as.length() != ts.length() || as.equals(ts)) continue; int tsInt = Integer.parseInt(ts); if (tsInt <= b && i <= tsInt){ boolean hasPair = false; for(int k=0; k n = new ArrayList(); List m = new ArrayList(); ListRecycledNumbers recycledNumbers = new ListRecycledNumbers(); boolean recycledPairAlreadyPresent = false; for (int i = tc.A; i <= tc.B; i++) { for (int j = 1; j < Integer.toString(tc.B).length(); j++) { int newInt = Helper.rotateDigits(i, j, true); if (i != newInt) { if (newInt < tc.B && newInt > tc.A) { recycledPairAlreadyPresent = false; for(int k = 0; k < recycledNumbers.getM().size(); k++){ if((recycledNumbers.getN().get(k) == newInt && recycledNumbers.getM().get(k) == i) || (recycledNumbers.getM().get(k) == newInt && recycledNumbers.getN().get(k) == i)){ recycledPairAlreadyPresent = true; break; } } if(!recycledPairAlreadyPresent) recycledNumbers.add(newInt, i); } } } } return recycledNumbers; //removeRepetitiveRecycledNumbers(recycledNumbers); } /*public static ListRecycledNumbers finalList = new ListRecycledNumbers(); private static void removeRepetitiveRecycledNumbers( ListRecycledNumbers recycledNumbers) { for (int i = 0; i < recycledNumbers.getM().size(); i++) { for (int j = 0; j < recycledNumbers.getM().size(); j++) { if ((recycledNumbers.getM().get(i) != recycledNumbers.getM() .get(j) && recycledNumbers.getN().get(i) != recycledNumbers .getN().get(j) && i != j) || (recycledNumbers.getM().get(i) != recycledNumbers .getN().get(j) && recycledNumbers.getN().get(i) != recycledNumbers .getM().get(j) && i != j)) { finalList.add(recycledNumbers.getN().get(i), recycledNumbers.getM().get(i)); } } } } */ } " B11330,"package recycledNumbers; public class Solution { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub InputData inputdata = Flow.Readin(""src//recycledNumbers//C-small-attempt0.in""); OutputData outputdata = Algorithms.getOutput(inputdata); Flow.Writeout(outputdata, ""src//recycledNumbers//C-small-attempt0.out""); } } " B11600,"/** * * @author amit */ import java.io.*; import java.util.HashSet; import java.util.Set; //import java.util.Arrays; //import java.math.BigInteger; public class GCJ { BufferedReader rin; BufferedWriter wout; int numCases; public String calculate(long A, long B) { long count =0; for(long i=A;i set = new HashSet(); for(int k=0;k<=Bl-Al;k++) { //System.out.println(""\n""+s); for(int j=0;j=A && num<=B && i hs = new ArrayList(); public Case(int id, int a, int b) { super(); this.id = id; this.a = a; this.b = b; } public String solve() { int l = (int) (Math.log10(a)) + 1; for (int i = a; i <= b; i++) { for (int j : shifts(i)) { if (i != j && j >= a && j <= b && (((int) (Math.log10(j)) + 1) == l)) { Couple c = new Couple(i, j); if (!hs.contains(c)) hs.add(c); } } } return String.valueOf(hs.size()); } private int[] shifts(int i) { int l = (int) (Math.log10(i)) + 1; int[] dgt = new int[l]; int[] shf = new int[l-1]; int j = i; for (int k = l; k > 0; k--) { dgt[l-k] = j / pow(k-1); j = j % pow(k-1); } for (int k = 1; k < l; k++) { int x = 0; for (int h = 0; h < l; h++) { x = 10 * x + dgt[(k+h)%l]; } shf[k-1] = x; } return shf; } private int pow(int n) { switch(n) { case 0: return 1; case 1: return 10; case 2: return 100; case 3: return 1000; case 4: return 10000; case 5: return 100000; case 6: return 1000000; case 7: return 10000000; case 8: return 100000000; case 9: return 1000000000; } return 0; } private int pow99(int n) { int k = 1; int pow = 9; for (int i = 1; i < n; i++) pow = pow * 10 + 9; return pow; } @Override public void run() { output = solve(); } @Override public String toString() { return ""Case #"" + id + "": "" + output; } }" B10872,"package de.at.codejam.problem3; public class Problem3Case { private String numberA; private String numberB; public String getNumberA() { return numberA; } public void setNumberA(String numberA) { this.numberA = numberA; } public String getNumberB() { return numberB; } public void setNumberB(String numberB) { this.numberB = numberB; } @Override public String toString() { return ""Problem3Case [numberA="" + numberA + "", numberB="" + numberB + ""]""; } } " B11516,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class CodeJam2012C { public static void main(String [] args) throws FileNotFoundException { new CodeJam2012C().go(); } public void go() throws FileNotFoundException { PrintWriter writer = new PrintWriter(new File(""output.txt"")); Scanner in = new Scanner(new File(""C-small-attempt0.in"")); // Scanner in = new Scanner(System.in); int iterations = in.nextInt(); for (int i = 0; i < iterations; i++) { int A = in.nextInt(); int B = in.nextInt(); int counter = 0; for (int j = 0; j < (B - A); j++) { String s = (j + A) + """"; for (int k = 0; k < s.length() - 1; k++) { s = s.substring(1) + s.charAt(0); int temp = Integer.parseInt(s); if (temp <= B && (j + A) < temp) counter++; } } // System.out.println(""Case #"" + (i + 1) + "": "" + counter); writer.write(""Case #"" + (i + 1) + "": "" + counter + ""\n""); } writer.flush(); writer.close(); } } " B12151,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejamqualfication; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * */ public class QualificationC { public static void main(String[] args) { File file = new File(""C:\\codejam\\plik.txt""); File result = new File(""C:\\codejam\\result.txt""); try { BufferedReader input = new BufferedReader(new FileReader(file)); FileWriter writer = new FileWriter(result); int i = -1; String line; while ((line = input.readLine()) != null) { if (i == -1) { i = 0; } else { i++; writer.write(processLine(line, i)); writer.write(""\n""); } } input.close(); writer.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private static final Pattern LINE_PATTERN = Pattern.compile(""(\\d+)\\s(\\d+)""); private static String processLine(String line, int i) { StringBuilder sb = new StringBuilder(""Case #""); sb.append(i); sb.append("": ""); Matcher m = LINE_PATTERN.matcher(line); if(m.matches()){ sb.append(generateAndCountPairs(m.group(1), m.group(2))); } return sb.toString(); } private static int generateAndCountPairs(String a, String b) { int successCounter = 0; int aInt = Integer.valueOf(a); int bInt = Integer.valueOf(b); for (int nInt = aInt; nInt <= bInt; nInt++) { String n = String.valueOf(nInt); Set obtainedMs = new HashSet(); for (int i = 1; i <= n.length(); i++) { String m = n.substring(i, n.length()) + n.substring(0, i); int mInt = Integer.valueOf(m); if (mInt > nInt && mInt <= bInt && !m.startsWith(""0"") && !obtainedMs.contains(mInt)) { successCounter++; obtainedMs.add(mInt); } } } return successCounter; } } " B10114,"import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class C { // public final static String IN_FILE = ""C.in""; // public final static String OUT_FILE = ""C.out""; public final static String IN_FILE = ""C-small-attempt1.in""; public final static String OUT_FILE = ""C-small-attempt1.out""; private static Scanner IN; public static void main(String[] args) throws Exception { InputStream in = new FileInputStream(IN_FILE); PrintWriter out = new PrintWriter(new FileWriter(OUT_FILE)); IN = new Scanner(in); int T = IN.nextInt(); for (int t = 1; t <= T; t++) { int n = IN.nextInt(); int m = IN.nextInt(); int l = 0; int k = 1; while (k <= n) { k *= 10; l++; } k /= 10; int c = 0; for (int i = n; i <= m; i++) { Set p = new TreeSet(); int s = i; for (int j = 0; j < l; j++) { int r = s / 10 + (s % 10) * k; if (r > i && r <= m) { p.add(r); } s = r; } c += p.size(); } out.println(""Case #"" + t + "": "" + c); } out.flush(); out.close(); in.close(); } } " B13073,"package round1; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Collection; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { public static SetfindRecycledNumbersBetween(int number, int start, int end) { if (number < 12) { return new HashSet(); } String num = """" + number; Set nums = new HashSet(); for (int i = 1; i < num.length(); i++) { String firstPart = num.substring(0, i); String lastPart = num.substring(i); if (lastPart.charAt(0) == '0') { continue; } int candidate = Integer.parseInt(lastPart + firstPart); if (candidate > number && (candidate >= start && candidate <= end)) { nums.add(candidate); } } return nums; } public static int findRecycledNumbersBetween(int start, int end) { int numbers = 0; for (int i = start; i <= end; i++) { Collection recycles = findRecycledNumbersBetween(i, start, end); if (recycles.size() > 0) { //System.out.printf(""found following recycles for %d => %s\n"", i, recycles.toString()); } numbers += recycles.size(); } return numbers; } public static void findRecycledNumbersInFile(File input) throws IOException { InputStreamReader reader = new InputStreamReader(new FileInputStream(input)); BufferedReader br = new BufferedReader(reader); int numLines = Integer.parseInt(br.readLine()); for (int i = 1; i <= numLines; i++) { String line = br.readLine(); String[] parts = line.split("" ""); int start = Integer.parseInt(parts[0]); int end = Integer.parseInt(parts[1]); System.out.printf(""Case #%d: %d\n"", i, findRecycledNumbersBetween(start, end)); } } /** * @param args */ public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println(""Usage: RecycledNumbers ""); System.exit(-1); } findRecycledNumbersInFile(new File(args[0])); } }" B11970,"import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Scanner; import java.util.Set; import java.util.regex.Pattern; public class ProblemC { public static void main(String[] args) { Scanner input; try { input = new Scanner(new FileReader(""C-small-attempt0.in"")); PrintWriter output = new PrintWriter(new FileWriter(""output3.txt"")); int numberCases = input.nextInt(); String data = input.nextLine(); for (int i = 0; i < numberCases; i++) { output.print(""Case #"" + (i + 1) + "": ""); data = input.nextLine(); String[] intS = Pattern.compile("" "").split(data); int[] numbers = new int[intS.length]; for (int j = 0; j < intS.length; j++) { numbers[j] = Integer.parseInt(intS[j]); } int lowerBound = numbers[0]; int upperBound = numbers[1]; output.print(calculatePossibilities(lowerBound, upperBound)); output.print(""\n""); } output.flush(); output.close(); input.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static int calculatePossibilities(int lowerBound, int upperBound) { Set allPossibilities = new HashSet(); int numberDigits = (int) (Math.floor(Math.log10(lowerBound))) + 1; int currentNumber = 0; int lowPart = 0; int highPart = 0; //System.out.println(""Digits "" + numberDigits); for (int j = lowerBound; j <= upperBound; j++) { Set permutations = new HashSet(); for (int i = 1; i <= numberDigits - 1; i++) { lowPart = j % ((int) Math.pow(10, i)); highPart = j / ((int) Math.pow(10, i)); currentNumber = (lowPart * (int) Math.pow(10, numberDigits - i)) + highPart; //System.out.println(currentNumber + "" <- j: "" + j + "" i:"" + i + "" low "" + lowPart + "" high "" + highPart); if (currentNumber >= lowerBound && currentNumber <= upperBound && currentNumber > j) { permutations.add(currentNumber); } if (!permutations.isEmpty()) allPossibilities.add(permutations); } } //System.out.println(""A: "" + allPossibilities.size()); return allPossibilities.size(); } } " B11283,"package qualification; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.Scanner; public class C { static int pow(int b) { return (int)Math.pow(10,b); } public static void main(String args[]) throws FileNotFoundException { Scanner sin=new Scanner(new File(""C:\\Users\\DELL\\Desktop\\CodeJam\\C-small-attempt0.in"")); PrintStream ps=new PrintStream(new File(""C:\\Users\\DELL\\Desktop\\CodeJam\\COut.out"")); int cases=sin.nextInt(); for(int test=1;test<=cases;test++) { int start=sin.nextInt(); int stop=sin.nextInt(); int count=0; int max=0; while(start/pow(max) >0) max++; max--; String s=""""; for(int i=start;i<=stop;i++) { int temp=max; while(temp>0) { int t=((i%pow(temp))*(pow(max-temp+1)))+i/pow(temp); temp--; if(t>i && t<=stop) { if(s.indexOf(i+"":""+t+""|"")!=-1) continue; s+=i+"":""+t+""|""; count++; } } } ps.println(""Case #""+test+"": ""+count); } } } " B12353,"package com.google.jam.recycled.numbers; import java.util.HashMap; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; public class RNumber implements Comparable { private final int n; private final int rank; private final SortedSet recycledNumbers = new TreeSet(); private static final Map cache = new HashMap(); private RNumber() { assert false; n = 0; rank = 0; } private RNumber(int n) { this.n = n; int i = 0; for (i = 1; (n / (int) Math.pow(10, i)) > 0; i++) ; rank = i - 1; for (int x = (int) Math.pow(10, rank), y = 10; x > 0; x /= 10, y *= 10) { int recycledNumber = (n % x) * y + (n / x); if (recycledNumber > n) recycledNumbers.add(recycledNumber); } } public static RNumber valueOf(int i) { if (!cache.containsKey(i)) cache.put(i, new RNumber(i)); return cache.get(i); } @Override public int compareTo(RNumber o) { return n - o.n; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof RNumber)) return false; RNumber o = (RNumber) obj; return n == o.n; } @Override public int hashCode() { return n; } public int getNumRecycledNumbersLessThan(int m) { int count = 0; for (Integer rn : recycledNumbers) if (rn > m) break; else count++; return count; } } " B11738,"import java.util.*; import java.io.*; public class Solution { FastScanner in; PrintWriter out; int doFromStr(String s, int k) { int ans = 0; for (int i = k; i < s.length(); i++) { ans = ans * 10 + s.charAt(i) - '0'; } for (int i = 0; i < k; i++) { ans = ans * 10 + s.charAt(i) - '0'; } return ans; } public void solve() throws IOException { int cases = in.nextInt(); for (int nowCase = 1; nowCase <= cases; nowCase++) { int a = in.nextInt(); int b = in.nextInt(); long ans = 0; for (int x = a; x < b; x++) { ArrayList add = new ArrayList(); String s = (new Integer(x)).toString(); for (int k = 1; k < s.length(); k++) { int newVal = doFromStr(s, k); boolean newV = true; if (newVal > x && newVal <= b) { for (int i = 0; i < add.size(); i++) { if (add.get(i) == newVal) newV = false; } if (newV) add.add(newVal); } } ans += add.size(); } // out.print(""Case #""); out.print(nowCase); out.print("": ""); // out.print(ans); // out.println(); } } public void run() { try { in = new FastScanner(new File(""c.in"")); out = new PrintWriter(new File(""c.out"")); //in = new FastScanner(System.in); //out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } String readLine() { try { return br.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "" ""; } int nextInt() { return Integer.parseInt(next()); } } public static void main(String[] arg) { new Solution().run(); } }" B10881,"package de.at.codejam.util; public interface CaseSolver extends StatusListener { String solveCase(TaskStatus taskStatus, CASE caseToSolve); void addStatusListener(StatusListener statusListener); void removeStatusListener(StatusListener statusListener); } " B12840," import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.InputStream; import java.util.*; import javax.sql.rowset.Joinable; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.lang.Integer.*; import static java.lang.Character.*; public class C { static class Sol implements Runnable{ boolean started = false; Scanner scan; int caseN; int a,b; int intLine(){ return parseInt(scan.nextLine()); } int res = 0; void readInput() { a = scan.nextInt(); b = scan.nextInt(); } public void run(){ int[]u = new int[20]; for(int i=a;i<=b;i++){ String s = """"+i; int p =0; for(int j = 1;jb)ok = false; for(int k=0;koriginal && newInt<=max){ counter++; } newIntS = cycle(newIntS); newInt = Integer.parseInt(newIntS); } return counter; } public String cycle(int j){ return cycle(j+""""); } public String cycle(String j){ String s = j+""""; char ss=s.charAt(s.length()-1); s = s.substring(0,s.length()-1); return ss+s; } } " B11340,"package RecycledNumbers; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; public class RecycledNumbers { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new FileReader(""RecycledInput"")); PrintWriter pw = new PrintWriter(new File(""RecycledOutput"")); String cases = br.readLine(); String line; int lines = 1; while ((line = br.readLine()) != null) { String[] strs = line.split("" ""); int lowerbound = Integer.parseInt(strs[0]); int upperbound = Integer.parseInt(strs[1]); int number = lowerbound; int count = 0; // System.out.println(numberChars.); while (number <= upperbound) { char[] numberChars = String.valueOf(number).toCharArray(); for (int i = 0; i < numberChars.length; i++) { String recycled = """"; for (int j = 0; j < numberChars.length; j++) recycled += numberChars[(j + i + 1) % numberChars.length]; if (Integer.parseInt(recycled) <= upperbound && Integer.parseInt(recycled) > number) { count++; System.out.println(number + "" "" + recycled); } } number ++; } System.out.println(""Case #"" + lines + "": "" + count); pw.write(""Case #"" + lines + "": "" + count + ""\n""); lines++; } pw.flush(); pw.close(); } } " B12069,"/* * Google Code Jam 2012 - Qualification Round (14.04.2012) * Thomas ""ThmX"" Denoréaz - thomas.denoreaz@gmail.com */ package codejam._2012.qualif; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; public class C { static final String FILENAME = ""C-small-attempt0""; public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader reader = new BufferedReader(new FileReader(FILENAME + "".in"")); PrintWriter writer = new PrintWriter(FILENAME + "".out""); int N = Integer.valueOf(reader.readLine()); for (int i=1; i<=N; i++) { String[] nums = reader.readLine().split("" ""); // -> A B int A = Integer.valueOf(nums[0]); int B = Integer.valueOf(nums[1]); HashSet set = new HashSet(); for (int n = A; n <= B; n++) { String nStr = String.valueOf(n); int nLen = nStr.length(); for (int j = 1; j <= nLen-1; j++) { String mStr = String.valueOf( Integer.valueOf( nStr.substring(nLen-j) + nStr.substring(0, nLen-j) ) ); int m = Integer.valueOf(mStr); if ((mStr.length() == nStr.length()) && (n < m) && (m <= B)) { set.add(n + "":"" + m); } } } writer.println(""Case #"" + i + "": "" + set.size()); } writer.flush(); writer.close(); reader.close(); } } " B11386,"import java.io.*; import java.util.*; public class Main implements Runnable { Scanner in = new Scanner(System.in); HashMap map; long[] cnt = new long[2000000]; public Integer[] findPartner(int n) { ArrayList arr = new ArrayList(); String num = String.valueOf(n); for (int i = 1; i < num.length(); i++) { String s = num.substring(i); s += num.substring(0, i); arr.add(Integer.parseInt(s)); } return (Integer[]) arr.toArray(new Integer[arr.size()]); } public void run() { int a, b, c, t = in.nextInt(); long ans; for (int i = 1; i <= t; i++) { a = in.nextInt(); b = in.nextInt(); c = 0; Arrays.fill(cnt, 0); map = new HashMap(); for (int j = a; j <= b; j++) { if (!map.containsKey(j)) { c++; Integer[] arr = findPartner(j); map.put(j, c); for (int k = 0; k < arr.length; k++) if (arr[k] >= a && arr[k] <= b) map.put(arr[k], c); } } for (int j = a; j <= b; j++) cnt[(Integer)map.get(j)]++; ans = 0l; for (int j = 1; j <= c; j++) ans += (cnt[j] - 1l) * cnt[j] / 2; System.out.println(""Case #"" + i + "": "" + ans); } } public static void main(String[] args) { new Thread(new Main()).start(); } }" B12421," import java.io.*; import java.util.*; /** * * @author Hilos */ public class ProblemC { public static BufferedWriter bw; public static BufferedReader br; public static void main(String[] args) { try { String filename = ""C-small-attempt0""; br = new BufferedReader(new FileReader(""E:\\Downloads\\"" + filename + "".in"")); bw = new BufferedWriter(new FileWriter(""E:\\Downloads\\"" + filename + "".out"")); int caseCount = Integer.parseInt(br.readLine()); for (int c = 0; c < caseCount; c++) { String[] lineParts = br.readLine().split("" ""); int A = Integer.parseInt(lineParts[0]); int B = Integer.parseInt(lineParts[1]); SolveCase(c + 1, A, B); } } catch (Exception exc) { System.out.println(exc.toString()); } } public static void SolveCase(int caseNumber, int A, int B) throws Exception { int totalRecycledPairs = 0; HashSet uniqueNumbers = new HashSet(); for (int i = A; i <= B; i++) { String strVal = String.valueOf(i); if (!uniqueNumbers.contains(i)) { int recycles = 0; String nextStr = strVal; do { nextStr = leftShift(nextStr); int nextInt = Integer.parseInt(nextStr); if (A <= nextInt && nextInt <= B) { uniqueNumbers.add(nextInt); recycles++; } } while (!nextStr.equals(strVal)); totalRecycledPairs += NchooseK(recycles, 2); } } bw.write(""Case #"" + caseNumber + "": "" + totalRecycledPairs + ""\n""); bw.flush(); } public static String leftShift(String str) { return str.substring(1) + str.charAt(0); } public static int NchooseK(int n, int k) { return factorial(n) / (factorial(k) * factorial(n - k)); } public static int factorial(int i) { int result = 1; while (i > 1) { result *= i; i--; } return result; } } " B12122,"import java.io.DataInputStream; import java.io.EOFException; import java.io.FileInputStream; import java.io.FileWriter; import java.util.HashSet; public class shift { /** * @param args */ public static void main(String[] args) { try{ FileInputStream infile = new FileInputStream(""in""); DataInputStream datain = new DataInputStream(infile); //Reader reader = new InputStreamReader(new FileInputStream(infile)); FileWriter writer = new FileWriter(""out"", false); String s = datain.readLine(); Integer k = new Integer(s); for (int i=1;i<=k;i++){ s = datain.readLine(); String [] ABstring = s.split("" ""); Integer A = new Integer(ABstring[0]); Integer B = new Integer(ABstring[1]); int numShift = ABstring[0].length()-1; int numRecycledNum = 0; for (int n=A;n nSet = new HashSet(); int roundShift = 1; String stringN = Integer.toString(n); stringN = stringN.substring(1) + stringN.charAt(0); //nSet.add(stringN); while (roundShift<=numShift){ Integer shiftedNum = new Integer(stringN); if (n0) { tc--; int res = 0 ; int f = A.nextInt(); int s = A.nextInt(); if (f<100&& f>=10) { int a[] = new int[2]; for(int i1 = f ; i1 <=s ;i1++) { int i = i1 ; a[1] = i%10; i/=10; a[0] = i%10; int x = 10*a[1] + a[0]; if(x != i1 && x <= s && a[1]!=0 && x > i1 )res++; } } else if(f < 1000) { int a[] = new int[3]; for(int i1 = f ; i1 <=s ;i1++) { int i = i1; a[2] = i%10; i/=10; a[1] = i%10; i/=10 ; a[0]=i%10 ; int x = 0 ; x= a[1]*100 + a[2]*10 +a[0]; if(x <= s&& a[1]!=0&&x!=i&& x > i1) res++; x= a[2]*100 + a[0]*10 +a[1]; if(x <= s&& a[2]!=0&&x!=i&& x > i1) res++; } } System.out.println(""Case #""+(-tc+tc1)+"": ""+ res); } } } /* 50 149 921 174 911 815 985 10 99 163 981 10 10 110 989 1 2 123 991 135 986 116 971 107 931 187 951 142 954 163 935 188 991 154 950 186 916 173 936 122 936 158 993 6 9 154 991 182 943 112 950 18 66 120 933 105 925 149 943 463 814 190 980 118 973 551 551 182 981 143 919 125 936 125 993 110 950 139 990 59 77 163 978 103 954 10 99 6 6 135 964 187 983 214 879 133 953 189 968 177 948 */" B11763,"package de.johanneslauber.codejam; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import de.johanneslauber.codejam.model.ICase; import de.johanneslauber.codejam.model.IProblem; /** * provids the cases for a problem * * @author Johannes Lauber - joh.lauber@googlemail.com * */ public class CaseProvider { private int numberOfCases; private List listOfCases; /** * Read the file line by line and write it to a list of cases * * @author Johannes Lauber - joh.lauber@googlemail.com * @param fileName * @throws IOException * @throws IllegalAccessException * @throws InstantiationException */ public void importFile(String fileName, Class caseClass) throws IOException, InstantiationException, IllegalAccessException { BufferedReader reader = new BufferedReader(new InputStreamReader( new DataInputStream(new FileInputStream(fileName)))); // Read File Line By Line String stringLine = reader.readLine(); setNumberOfCases(Integer.valueOf(stringLine)); List listOfCases = new ArrayList(); ICase currentCase = createEmptyCase(caseClass); int i = 1; while ((stringLine = reader.readLine()) != null) { if (i <= currentCase.getNumberOfAttributes()) { currentCase.setLine(i, stringLine); i++; } else { listOfCases.add(currentCase); currentCase = createEmptyCase(caseClass); i = 1; currentCase.setLine(i, stringLine); i++; } } // don't forget to add the last case listOfCases.add(currentCase); reader.close(); this.listOfCases = listOfCases; } /** * * @author Johannes Lauber - joh.lauber@googlemail.com * @param caseClass * @throws IllegalAccessException * @throws InstantiationException */ private ICase createEmptyCase(Class caseClass) throws InstantiationException, IllegalAccessException { ICase currentCase = caseClass.newInstance(); return currentCase; } /** * * @author Johannes Lauber - joh.lauber@googlemail.com * @param forName */ public void solveCases(Class forName) { try { IProblem problem = (IProblem) forName.newInstance(); problem.setListOfCases(listOfCases); problem.solveCases(); } catch (Exception e) { e.printStackTrace(); } } // Setter & Getter public int getNumberOfCases() { return numberOfCases; } public void setNumberOfCases(int numberOfCases) { this.numberOfCases = numberOfCases; } public List getListOfCases() { return listOfCases; } public void setListOfCases(List listOfCases) { this.listOfCases = listOfCases; } } " B10621,"package CaseSolvers; import Controller.IO; public class GooglereseCase extends CaseSolver { static Character[] opa; static { opa = new Character[26]; opa['a' - 97] = 'y'; opa['b' - 97] = 'h'; opa['c' - 97] = 'e'; opa['d' - 97] = 's'; opa['e' - 97] = 'o'; opa['f' - 97] = 'c'; opa['g' - 97] = 'v'; opa['h' - 97] = 'x'; opa['i' - 97] = 'd'; opa['j' - 97] = 'u'; opa['k' - 97] = 'i'; opa['l' - 97] = 'g'; opa['m' - 97] = 'l'; opa['n' - 97] = 'b'; opa['o' - 97] = 'k'; opa['p' - 97] = 'r'; opa['q' - 97] = 'z'; opa['r' - 97] = 't'; opa['s' - 97] = 'n'; opa['t' - 97] = 'w'; opa['u' - 97] = 'j'; opa['v' - 97] = 'p'; opa['w' - 97] = 'f'; opa['x' - 97] = 'm'; opa['y' - 97] = 'a'; opa['z' - 97] = 'q'; } StringBuilder line; public GooglereseCase(int order, int numberOfLines, IO io) { super(order, numberOfLines, io); } @Override public void addLine(String line) { this.line = new StringBuilder(line); } @Override public void printSolution() { System.err.println(""Case #"" + getOrder() + "": "" + line); } @Override public CaseSolver process() { for (int i = 0; i < line.length(); i++) { char temp = line.charAt(i); if (temp != ' ') line.setCharAt(i, opa[temp - 97]); } return this; } @Override public void initializeVars() { // TODO Auto-generated method stub } } " B12110,"package com.renoux.gael.codejam.utils; import java.io.BufferedReader; import java.io.Closeable; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; public class Input implements Closeable { BufferedReader reader; private Input(BufferedReader reader) { this.reader = reader; } public static Input open(File f) { final BufferedReader r; try { r = FileUtils.getReader(f); } catch (FileNotFoundException e) { throw new TechnicalException(e); } return new Input(r); } public void close() { try { reader.close(); } catch (IOException e) { throw new TechnicalException(e); } } public String readLine() { try { return reader.readLine(); } catch (IOException e) { throw new TechnicalException(e); } } } " B10770,"package numbers; import java.util.*; import java.io.*; public class Numbers { public static void main(String[] args) throws Exception { Scanner br = new Scanner(new FileReader(""C-small-attempt0.in"")); BufferedWriter bw = new BufferedWriter(new FileWriter(""out.txt"")); int T = br.nextInt(); for(int t = 1; t<=T; t++){ int A = br.nextInt(); int B = br.nextInt(); int sum = 0; for(int i = A; i < B; i++){ sum += pcount(i, B); } bw.write(""Case #""+t+"": ""+sum); bw.newLine(); } br.close(); bw.close(); } private static int pcount(int n, int max){ if(n<10) return 0; int sum = 0; String r = rev(Integer.toString(n)); String sn = Integer.toString(n); while(!r.equals(sn)){ int ir = Integer.parseInt(r); if(ir>n && ir<=max){ sum++; } r = rev(r); } return sum; } private static String rev(String n){ if(n.length()<2) return n; StringBuilder sb = new StringBuilder(); sb.append(n.charAt(n.length()-1)); for(int i = 0; i< n.length()-1; i++){ sb.append(n.charAt(i)); } return sb.toString(); } } " B10279,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class RecycledNumbers { public static void main(String[] args) throws IOException { String msg = """"; BufferedReader br = null; String sCurrentLine = null; Map map = new HashMap(); br = new BufferedReader(new FileReader(""test"")); sCurrentLine = br.readLine(); int x = 0; if (sCurrentLine != null) { while ((sCurrentLine = br.readLine()) != null) { int sum = 0; msg = """"; x++; int a = Integer.parseInt(sCurrentLine.split("" "")[0]); int b = Integer.parseInt(sCurrentLine.split("" "")[1]); for (int n = a; n < b; n++) { // for (int m = n + 1; m <= b; m++) { sum += fetchUniquePairs(n, a, b); // } } msg += ""Case #"" + x + "": "" + sum; System.out.println(msg); } } } private static int fetchUniquePairs(int n, int a, int b) { List uniquePairs = new ArrayList(); int dupN = n; int i = 0; while (dupN > 0) { dupN = dupN / 10; i++; } dupN = n; for (int j = 0; j < i - 1; j++) { int mod = dupN % 10; int add = mod * (int) Math.pow(10, i - 1); dupN = (dupN / 10); dupN += add; if (dupN <= b && dupN > n) if (!uniquePairs.contains(dupN)) uniquePairs.add(dupN); } return uniquePairs.size(); } } " B10012,"package R2012; import java.io.File; import java.io.FileWriter; import java.util.Scanner; public class RecycledNumbers { public static boolean isCycle(int a,int b) { String aa=String.valueOf(a); StringBuffer ba=new StringBuffer(String.valueOf(b)); if(aa.length()!=ba.length()) return false; int l=aa.length(); for(int i=0;ii) counter+=1; } if (achar.length==3) { int one= Integer.parseInt("""" +achar[2])*100+Integer.parseInt("""" +achar[0])*10+Integer.parseInt("""" +achar[1]); if (one<=Integer.parseInt(b)&&one>i) counter+=1; int two= Integer.parseInt("""" +achar[1])*100+Integer.parseInt("""" +achar[2])*10+Integer.parseInt("""" +achar[0]); if (two<=Integer.parseInt(b)&&two>i) counter+=1; } } System.out.println(""Case #"" +x +"": "" +counter); } } } " B10952,"import java.util.Scanner; public class RecycledNumbers { public static void main (String [] args) { Scanner sc = new Scanner (System.in); int x = sc.nextInt(); for (int i = 0; i < x; i++) { int a = sc.nextInt(); int b = sc.nextInt(); int count = 0; for (int j = a; j < b; j++) { for (int k = j; k <= b; k++) { String one = new Integer(j).toString(); String two = new Integer(k).toString(); if (j < k && one.length() == two.length()) { for (int l = 0; l < one.length(); l++) { one = one.charAt(one.length()-1) + one.substring(0, one.length()-1); if (one.equals(two)) { count++; break; } } } } } System.out.println(""Case #"" + (i+1) + "": "" + count); } } } " B10317,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.Scanner; import java.util.TreeMap; import java.util.TreeSet; public class Recycled { private File file = new File(""D:\\Sources\\GoogleCodeJam\\files\\C-small-attempt0.in""); private File outFile = new File(""D:\\Sources\\GoogleCodeJam\\files\\result.out""); private Long[] results; private Integer solved = 0; public void readData() { boolean first = true; Scanner scanner; try { scanner = new Scanner(file); while (scanner.hasNextLine()) { String line = scanner.nextLine(); Scanner scan = new Scanner(line); if (first) { results = new Long[scan.nextInt()]; first = false; } else { long min = scan.nextLong(); long max = scan.nextLong(); results[solved] = solveProblem(min, max); solved++; } } printResult(); } catch (Exception e) { e.printStackTrace(); } } private Long solveProblem(long min, long max) { long sum = 0; TreeSet res = new TreeSet(); for (long val = min; val <= max; val++) { res.clear(); String number = String.valueOf(val); int len = number.length(); for (int i = 1; i < number.length(); i++) { String newVal = number.substring(i, len) + number.substring(0, i); long recycled = Long.valueOf(newVal); if(recycled > val && recycled <= max && res.add(val + recycled * Math.pow(10, len))) { sum++; } } } return sum; } private void printResult() { try { FileWriter fstream = new FileWriter(outFile); BufferedWriter out = new BufferedWriter(fstream); for (int i = 0; i < results.length; i++) { out.write(""Case #"" + (i + 1) + "": "" + results[i]); out.newLine(); } out.close(); } catch (Exception e) { e.printStackTrace(); } } } " B11312,"/** * Copyright 2012 Christopher Schmitz. All Rights Reserved. */ package com.isotopeent.codejam.lib; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class InputReader extends BufferedReader { private final InputConverter converter; public InputReader(File file, InputConverter converter) throws FileNotFoundException { super(new FileReader(file)); this.converter = converter; } public T readInput() { String data; try { do { data = readLine(); if (data == null) { return null; } } while (converter.readLine(data)); } catch (IOException e) { // do nothing } return converter.generateObject(); } } " B12437,"import java.util.Scanner; import java.io.*; public class Tobi { static String out="""",output=""""; public static void main(String[] args) { try { Scanner in = new Scanner(new File(""recycle.in"")); int n = in.nextInt(); int count = 1; String out = """"; while(in.hasNext()) { int a = in.nextInt(); int b = in.nextInt(); out += ""Case #""+count+"": ""+ activity(a,b)+""\n""; count++; try { File file = new File(""output.dat""); PrintWriter output = new PrintWriter(file); output.write(out); output.close(); } catch(Exception exception) { System.out.println(""ERROR""); } } }catch(Exception exception){ System.out.println(""ERROR""); } System.out.println(""DONE""); } public static int activity(int A, int B) { int counter = 0; //String all[] = myGenerator(Integer.toString(A)); for(int i = A; i <= B; i++) { String all[] = myGenerator(Integer.toString(i)); for(int j = 0; j < all.length; j++) { if((i < Integer.parseInt(all[j])) && (Integer.parseInt(all[j]) <= B)) { counter++; } } } return counter; } public static String[] myGenerator(String word) { String[] all = new String[word.length()-1];//changed frm len - 1 for(int i = 0; i < all.length; i++) { all[i] = generate(word); word = generate(word); } return all; } public static String generate(String w) { String ans = w.substring(w.length()-1); for(int i = 0; i < w.length()-1; i++) { ans += w.substring(i,i+1); } return ans; } } " B12753,"package google.codejam.recyclednumbers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.Hashtable; public class Main { public static void main(String[] args) throws Exception { String[] files = { ""Data/C-small-attempt0"" }; for (int f = 0; f < files.length; f++) { BufferedReader in = new BufferedReader(new FileReader(files[f] + "".in"")); BufferedWriter out = new BufferedWriter(new FileWriter(files[f] + "".out"")); int T = Integer.parseInt(in.readLine()); // number of test cases for (int i = 1; i <= T; i++) { String[] input = in.readLine().split("" ""); int A = Integer.parseInt(input[0]); int B = Integer.parseInt(input[1]); int result = getResult(A, B); out.write(String.format(""Case #%d: %d\n"", i, result)); } out.close(); in.close(); } } private static int getResult(int A, int B) { Hashtable pair = new Hashtable (); for (int n = A; n <= B; n++) { String number = String.valueOf(n); for (int pos = 1; pos < number.length(); pos++) { String rotatedNumber = number.substring(pos, number.length()); if (!rotatedNumber.substring(0).equals(""0"")) { rotatedNumber += number.substring(0, pos); int m = Integer.parseInt(rotatedNumber); if (n < m && m <= B && pair.get(number+rotatedNumber) == null) pair.put(number+rotatedNumber, """"); } } } return pair.size(); } } " B11864,"import java.io.*; import java.util.*; public class C { MyScanner in; PrintWriter out; final static String FILENAME = ""c""; public static void main(String[] args) throws Exception { new C().run(); } public void run() throws Exception { in = new MyScanner(FILENAME + "".in""); out = new PrintWriter(FILENAME + "".out""); int tests = in.nextInt(); for (int test = 0; test < tests; test++) { out.println(""Case #"" + (test + 1) + "": "" + solve()); } out.close(); } int ten(int length) { int ans = 1; for (int i = 0; i < length; i++) { ans *= 10; } return ans; } TreeSet ts; int recycle(int n, int max) { int l = String.valueOf(n).length(); int mod = ten(l - 1); int ans = 0; int m = n; String strm = String.valueOf(m); ts.clear(); for (int i = 0; i < l; i++) { m = (m / 10) + (m % 10) * mod; if (m > n && m <= max && !ts.contains(m)) { ans++; } ts.add(m); } return ans; } public int solve() throws Exception { ts = new TreeSet(); int A = in.nextInt(); int B = in.nextInt(); int ans = 0; for (int n = A; n <= B; n++) { ans += recycle(n, B); } return ans; } class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } String next() throws Exception { while ((st == null) || (!st.hasMoreTokens())) { String t = br.readLine(); if (t == null) { return null; } st = new StringTokenizer(t); } return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(next()); } double nextDouble() throws Exception { return Double.parseDouble(next()); } boolean nextBoolean() throws Exception { return Boolean.parseBoolean(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } } } " B12847,"import java.util.*; import java.io.*; public class recycled_numbers { public static void main(String[]a) throws Exception{ Scanner f = new Scanner(new File(a[0])); int result=0; int A,B; String n,m; HashSet s=new HashSet(); int T=f.nextInt(); //T total case count for (int t=1; t<=T;t++){//for each case t s.clear(); result=0; //reset A=f.nextInt();B=f.nextInt(); //get values for next case if (A==B)result=0;//remove case not meeting problem limits else{ for(int i=A;i<=B;i++){//for each int in range n=Integer.toString(i); m=new String(n); //System.out.println(n); for (int j=1;j arr = new ArrayList(); Scanner in = new Scanner( System.in ); String nStr, pref, suff; int i, j, a, b, count, test, lengthN, temp, lengthTemp; test = in.nextInt(); for( i = 0 ; i < test ; i++ ) { a = in.nextInt(); b = in.nextInt(); count = 0; arr.clear(); int low = a; if( a < 10 ) { a = 10; } while( a < b ) { nStr = Integer.toString( a ); lengthN = nStr.length(); for( j = 1 ; j < lengthN ; j++ ) { pref = nStr.substring( 0, lengthN - j ); suff = nStr.substring( lengthN - j, lengthN ); //if( i == 3 ) //System.out.println( pref + "" "" + suff ); String tempStr = suff + pref; temp = Integer.parseInt( tempStr ); lengthTemp = Integer.toString( temp ).length(); if( lengthTemp == lengthN && temp != a ) { String ct = nStr + tempStr; if( !arr.contains( ct ) && temp <= b && temp >= low ) { arr.add( ct ); arr.add( tempStr + nStr ); //if( i == 3 ) //System.out.println( a + "" "" + temp ); count++; } } else { //if( i == 3 ) //System.out.println( ""GA MASUK "" + a + "" "" + temp ); } } //System.out.println(); a++; } System.out.println( ""Case #"" + (i+1) + "": "" + count ); } } } class Pair { int x; int y; public Pair( int x, int y ) { this.x = x; this.y = y; } } " B11920,"import java.util.ArrayList; import java.util.Scanner; public class recycled { public static void main(String[] args) { Scanner in = new Scanner (System.in); String scases = in.nextLine(); int T = Integer.parseInt(scases); for(int i = 1; i<(T+1); i++) { String temp1 = in.nextLine(); String[] temp2 = temp1.split("" ""); int low = Integer.parseInt(temp2[0]); int high = Integer.parseInt(temp2[1]); int count = 0; ArrayList checked = new ArrayList(); for(int test = low; test < high; test++) { String stest = Integer.toString(test); int len = stest.length(); for(int pos = 1; pos < (len) ; pos++) { String scheck = """"; scheck += stest.charAt(len-1); scheck += stest.substring(0,len-1); stest = scheck; int check = Integer.parseInt(scheck); if(check > test && check <= high) { count = count +1; checked.add(scheck); } } } System.out.println(""Case #""+ i +"": ""+count); } } } " B12347,"package qualification.round.atual; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { File f = new File(""C-small-practice.in""); FileInputStream fis = new FileInputStream(f); Scanner scanner = new Scanner(fis); File fOut = new File(""C-small-practice.out""); Writer out = new BufferedWriter(new FileWriter(fOut)); try { int t = Integer.parseInt(scanner.nextLine()); for (int i = 1; i <= t; i++) { out.write(""Case #"" + i + "": "" + getNumberOfRecycledNumbers(scanner.nextLine()) + ""\n""); } } finally { scanner.close(); out.close(); } } private static int getNumberOfRecycledNumbers(String line) { int number = 0; Map> map = new HashMap>(); String v[] = line.split("" ""); int a = Integer.parseInt(v[0]); int b = Integer.parseInt(v[1]); int c = a; while (c <= b) { String cStr = """" + c; for (int i = 0; i < cStr.length(); i++) { String newNumber = cStr.substring(i + 1); newNumber = newNumber + cStr.substring(0, i + 1); int newIntNumber = Integer.parseInt(newNumber); if (newIntNumber != c && newIntNumber >= a && newIntNumber <= b) { List listNewInt = map.get(newIntNumber); boolean skip = false; if (listNewInt != null) { for (Integer integer : listNewInt) { if (integer == c) { skip = true; } } } if (skip) { continue; } if (map.get(c) == null) { List list = new ArrayList(); list.add(newIntNumber); map.put(c, list); } else { map.get(c).add(newIntNumber); } } } c++; } Set set = map.keySet(); for (Integer integer : set) { number += map.get(integer).size(); } return number; } }" B12857,"import java.io.IOException; import java.util.ArrayList; import java.util.List; public class Third { int left; int right; int[][] working; public Third(int left, int right) { this.left = left; this.right = right + 1; } public static void main(String[] args) throws IOException { List result = new ArrayList<>(); List input = FileRW.readFile(""input.txt""); for (String inp : input) { String[] range = inp.split("" ""); result.add(new Third(Integer.valueOf(range[0]), Integer.valueOf(range[1])).process()); } FileRW.writeOutput(""output.txt"", result); } public String process() throws IOException { int total = right - left; working = new int[total][total]; for (int i = 0; i < working.length; i++) { char[] cur = deriveArr(left + i); for (int j = i + 1; j < working.length; j++) { char[] next = deriveArr(left + j); if (next.length > cur.length) { working[i][j] = -1; break; } if (compare(cur, next)) { working[i][j] = 1; working[j][j] = -1; } } } int result = 0; for (int i = 0; i < working.length; i++) { // if (working[i][i] == -1) { // continue; // } int j = i + 1; while (j < working[i].length && working[i][j] != -1) { result += working[i][j]; j++; } } return """" + result; } public boolean compare(char[] cur, char[] next) { int start = findIndex(cur[0], next, -1); outer: while (start != -1) { int loop = start; for (int i = 0; i < cur.length; i++) { if (loop >= cur.length) { loop = 0; } if (cur[i] != next[loop]) { start = findIndex(cur[0], next, start); continue outer; } loop++; } return true; } return false; } private int findIndex(char c, char[] next, int from) { for (int i = from + 1; i < next.length; i++) { if (c == next[i]) { return i; } } return -1; } public char[] deriveArr(int i) { char[] digits = String.valueOf(i).toCharArray(); return digits; } } " B13244,"import java.io.*; import java.util.*; import java.math.*; //4/14/12 11:29 PM //by Abrackadabra public class RecycledNumbers { public static void main(String[] args) throws IOException { if (args.length > 0 && args[0].equals(""Abra"")) debugMode = true; new RecycledNumbers().run(); /*new Thread(null, new Runnable() { public void run() { try { new RecycledNumbers().run(); } catch (IOException e) { # e.printStackTrace(); } } }, ""1"", 1 << 24).start();*/ } int IOMode = 0; //0 - consoleIO, 1 - .in/out, 2 - input.txt/output.txt, 3 - test case generator String taskName = """"; void solve() throws IOException { int T = nextInt(); for (int Ti = 1; Ti <= T; Ti++) { int a = nextInt(), b = nextInt(); int res = 0; for (int i = a; i <= b; i++) { String q = Integer.toString(i); if (q.length() == 1) continue; for (int j = 0; j < q.length(); j++) { q = q.substring(1) + q.charAt(0); if (q.charAt(0) == '0') continue; if (Integer.parseInt(q) == i) break; if (Integer.parseInt(q) > i && Integer.parseInt(q) <= b) res++; } } out.println(""Case #"" + Ti + "": "" + res); } } long startTime = System.nanoTime(), tempTime = startTime, finishTime = startTime; long startMem = Runtime.getRuntime().totalMemory(), finishMem = startMem; void run() throws IOException { init(); if (debugMode) { con.println(""Start""); con.println(""Console:""); } solve(); finishTime = System.nanoTime(); finishMem = Runtime.getRuntime().totalMemory(); out.flush(); if (debugMode) { int maxSymbols = 1000; BufferedReader tbr = new BufferedReader(new FileReader(""input.txt"")); char[] a = new char[maxSymbols]; tbr.read(a); if (a[0] != 0) { con.println(""File input:""); con.println(a); if (a[maxSymbols - 1] != 0) con.println(""...""); } tbr = new BufferedReader(new FileReader(""output.txt"")); a = new char[maxSymbols]; tbr.read(a); if (a[0] != 0) { con.println(""File output:""); con.println(a); if (a[maxSymbols - 1] != 0) con.println(""...""); } con.println(""Execution time: "" + (finishTime - startTime) / 1000000000.0 + "" sec""); con.println(""Used memory: "" + (finishMem - startMem) + "" bytes""); con.println(""Total memory: "" + Runtime.getRuntime().totalMemory() + "" bytes""); } } boolean tick(double x) { if (System.nanoTime() - tempTime > x * 1e9) { tempTime = System.nanoTime(); con.println(""Tick at "" + (tempTime - startTime) / 1000000000 + "" sec""); con.print("" ""); return true; } return false; } static boolean debugMode = false; PrintStream con = System.out; void init() throws IOException { if (debugMode && IOMode != 3) { br = new BufferedReader(new FileReader(""input.txt"")); out = new PrintWriter(new FileWriter(""output.txt"")); } else switch (IOMode) { case 0: br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); break; case 1: br = new BufferedReader(new FileReader(taskName + "".in"")); out = new PrintWriter(new FileWriter(taskName + "".out"")); break; case 2: br = new BufferedReader(new FileReader(""input.txt"")); out = new PrintWriter(new FileWriter(""output.txt"")); break; case 3: out = new PrintWriter(new FileWriter(""input.txt"")); break; } } BufferedReader br; PrintWriter out; StringTokenizer in; boolean hasMoreTokens() throws IOException { while (in == null || !in.hasMoreTokens()) { String line = br.readLine(); if (line == null) return false; in = new StringTokenizer(line); } return true; } String nextString() throws IOException { return hasMoreTokens() ? in.nextToken() : null; } int nextInt() throws IOException { return Integer.parseInt(nextString()); } long nextLong() throws IOException { return Long.parseLong(nextString()); } double nextDouble() throws IOException { return Double.parseDouble(nextString()); } }" B13014,"import java.util.*; import java.io.*; public class recycled{ public static void main(String[] args) { Scanner in = new Scanner(System.in); //System.out.println(""Hello world!""); String scases = in.nextLine(); int cases = Integer.parseInt(scases); for(int i =1;i<=cases;i++) { String line = in.nextLine(); String[] split = line.split("" ""); String first = split[0]; String second = split[1]; int ifirst = Integer.parseInt(first); int isecond = Integer.parseInt(second); int count = cases(ifirst,isecond); System.out.println(""Case #""+i+"": ""+count); } //System.out.println(count); //cases(); } public static int cases(int lower, int upper) { int count =0; //int lower = 1111; //int upper = 2222; for(int i =lower; i<=upper; i++) { for(int j =lower; j<=upper; j++) { if(isRecycled(i,j)&&i!=j){ //System.out.println(i+"",""+j); count++; } } } //System.out.println(count/2); return count/2; //System.out.println(isRecycled(12345,34512)); } public static boolean isRecycled(int a, int b) { String aa = """"+a; String bb = """"+b; for(int i=0;i 2 || integers.length < 2) { throw new IllegalArgumentException(""Exactly two please""); } min = new Integer(integers[0]); max = new Integer(integers[1]); } public int recycledPairCountFromMinToMax() { int pairCount = 0; for(int i = min; i <= max; i++) { pairCount += cycledDigitsInRangeAndGreaterThan(i); } return pairCount; } private int cycledDigitsInRangeAndGreaterThan(final int value) { int matches = 0; final String originalValue = String.valueOf(value); String cycledValue = cycleFromBackToFront(originalValue); while(!cycledValue.equals(originalValue)) { int cycledVal = Integer.valueOf(cycledValue); if(cycledVal > value && cycledVal <= max) { matches++; } cycledValue = cycleFromBackToFront(cycledValue); } return matches; } public int getMin() { return min; } public int getMax() { return max; } public static String cycleFromBackToFront(String numToCycle) { final int numLength = numToCycle.length(); return numToCycle.substring(numLength - 1) + numToCycle.substring(0, numLength - 1); } } " B11376,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recyclednumbers; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Hashtable; /** * * @author PARIMAL */ public class RecycledNumbers { /** * @param args the command line arguments */ public static void main(String[] args) { String inputFile = ""E:\\C-small-attempt0.in""; String outputFile = ""E:\\C-small-attempt0.out""; File f = new File(inputFile); FileInputStream fis = null; BufferedReader reader = null; try { fis = new FileInputStream(f); reader = new BufferedReader(new InputStreamReader(fis)); String line = reader.readLine(); //ret=line.split("" ""); int loopCount = Integer.parseInt(line); int i; int a, b; long A, B; int RecycledPairs[] = new int[loopCount]; for (int j = 0; j < RecycledPairs.length; j++) { RecycledPairs[j] = 0; } //System.out.println(""loop""+loopCount); String out[] = new String[loopCount]; String bounds[] = new String[2]; for (i = 0; i < loopCount; i++) { String t = reader.readLine(); bounds = t.split("" ""); a = Integer.parseInt(bounds[0]); b = Integer.parseInt(bounds[1]); int lengthA = bounds[0].length(); if (lengthA == 1) { RecycledPairs[i] = 0; out[i] = String.valueOf(RecycledPairs[i]); } else { String tempA, lastA, firstA, finalA; int finalAns; for (int j = a; j <= b; j++) { tempA = String.valueOf(j); //System.out.println(""tempA "" + tempA); for (int k = 1; k < lengthA; k++) { lastA = tempA.substring(lengthA - k); //12345 ==> 45 //System.out.println(""lastA ""+lastA); //System.out.println(""firstA ""+firstA); if (Integer.parseInt(lastA) == 0) { //System.out.println(""Encountered zeros with "" + k + "" times""); } else { firstA = tempA.substring(0, lengthA - k); finalA = lastA + firstA; finalAns = Integer.parseInt(finalA); if (j < finalAns && finalAns <=b) { RecycledPairs[i]++; //System.out.println(""Re: "" + RecycledPairs[i]); } } } out[i] = String.valueOf(RecycledPairs[i]); } } } for (int j = 0; j < loopCount; j++) { String o = "" ""; StringBuffer sB = new StringBuffer(100); sB.append(""Case #"" + (j + 1) + "": ""); o=sB.append(out[j]).toString(); out[j] = o; } FileOutputStream fileOutputStream = null; try { File fOut = new File(outputFile); fileOutputStream = new FileOutputStream(fOut); for (int m = 0; m < out.length; m++) { out[m] += ""\n""; byte[] bytes = out[m].getBytes(); fileOutputStream.write(bytes); } fileOutputStream.flush(); fileOutputStream.close(); fis.close(); } catch (IOException ex) { ex.printStackTrace(); } } catch (IOException ex) { ex.printStackTrace(); } } } " B10811,"import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Task3 { private int parseLine(Scanner scanner) throws IOException { int A = scanner.nextInt(); int B = scanner.nextInt(); int c = ("""" + A).length(); int pow = (int) Math.pow(10, c - 1); int count = 0; for (int m = A; m < B; m++) { int tmpN = m; Set set = new HashSet(); for (int j = 0; j < c - 1; j++) { tmpN = tmpN / 10 + (tmpN % 10) * pow; if (m < tmpN && tmpN <= B && !set.contains(tmpN)) { set.add(tmpN); count++; } } } return count; } public void run(Scanner scanner, Writer bw) throws IOException { int rowCnt = scanner.nextInt(); for (int i = 0; i < rowCnt; i++) { bw.write(""Case #"" + (i + 1) + "": "" + parseLine(scanner) + '\n'); } bw.flush(); bw.close(); } /** * @param args */ public static void main(String[] args) { try { Scanner scanner = new Scanner(System.in); scanner.useDelimiter("" |\r\n|\n|\r""); new Task3().run(new Scanner(System.in), new OutputStreamWriter(System.out)); } catch (IOException e) { return; } } } " B11536,"package com.google.jam.eaque.stub; public class Util { private Util() { } public static long[] stringsToLongs(String[] strings) { long[] res = new long[strings.length]; for (int i = 0; i < strings.length; i++) { res[i] = Long.parseLong(strings[i]); } return res; } } " B11025,"package org.moriraaca.codejam; public enum DebugOutputLevel { SOLUTION, IMPORTANT, ALL; } " B10946,"package google.codejam; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.Scanner; public class Stark_C { /** * @param args */ public static int getDig(int t1){ if(t1==0) return 0; else if(t1<10) return 1; else if(t1<100) return 2; else if(t1<1000) return 3; else if(t1<10000) return 4; else if(t1<100000) return 5; else if(t1<1000000) return 6; else return 7; } public static int times(int t){ if(t==0)return 1; else if(t==1) return 10; else if(t==2) return 100; else if(t==3) return 1000; else if(t==4) return 10000; else if(t==5) return 100000; else if(t==6) return 1000000; else if(t==7) return 10000000; else return 100000000; } public static void main(String[] args) throws Exception { // TODO Auto-generated method stub Scanner sc = new Scanner(new FileReader(""C_small.in"")); PrintWriter pw = new PrintWriter(new FileWriter(""C_small.out"")); int total = sc.nextInt(); for(int i=0; it1 && m>n && m<=t2) ans++; //pw.print("" ans-->""+ans+"" ""); te = te*10; } n++; } pw.println(ans); } pw.flush(); pw.close(); sc.close(); } } " B12689,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; public class RecycledNumbers { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(""C-small-attempt0.in""))); //BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(""B-large.in""))); //BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter out = new BufferedWriter(new FileWriter(""RecycledNumbers.txt"")); int cases = Integer.parseInt(reader.readLine()); for(int i=1; i <= cases; i++) { String line = reader.readLine(); int beg = Integer.parseInt(line.split("" "")[0]); int end = Integer.parseInt(line.split("" "")[1]); HashSet h = new HashSet(); int count = 0; for(int j=beg; j<=end;j++) { String str = j+""""; int c = 0; for(int m = str.length()-1; m>=0; m--) { str = str.substring(1) + str.charAt(0); int number = Integer.parseInt(str); if(number >= beg && number <= end && !h.contains(number)) { h.add(number); c++; } } count = count + ((c-1)*c)/2; } //out.write((p*3-2) + "" "" + (p*3-4) + ""\n""); System.out.print(""Case #"" + i+ "": "" + count+""\n""); out.write(""Case #"" + i+ "": "" + count+""\n""); } out.close(); } } " B11769,"package de.johanneslauber.codejam.model; /** * * @author Johannes Lauber - joh.lauber@googlemail.com * */ public interface ICase { public void setLine(int lineNumber, String lineValue); public int getNumberOfAttributes(); } " B12165," import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Iterator; public class gjam { public static void main(String[] args) { int TestCases = 0; int currentCase = 0; try { FileInputStream fstream = new FileInputStream(""C-small-attempt0.in""); DataInputStream dstream = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(dstream)); String inputStr = br.readLine(); TestCases = Integer.parseInt(inputStr); while(currentCase != TestCases) { ArrayList results = new ArrayList(); inputStr = br.readLine(); int result = 0; String[] inputs = inputStr.split("" ""); int size = inputs[0].length(); int A = Integer.parseInt(inputs[0]); int B = Integer.parseInt(inputs[1]); if(A >= 10 && B > A) for(int i = A; i <= B; i++) { for(int j = 1; j <= size; j++) { int moved = moveDigits(j,i); if(A <= i && i < moved && moved <= B) { results.add(i); results.add(moved); result++; } } } System.out.println(""Case #"" + (currentCase +1) + "": "" + result); currentCase++; } } catch(Exception e) { System.err.println(""Err: "" + e.getMessage()); } } public static int moveDigits(int numTomove,int input) { String original = """" + input; int length = original.length(); String sub1 = original.substring(length - numTomove); String sub2 = original.substring(0,length - numTomove); String output = sub1 + sub2; return Integer.parseInt(output); } } " B10704,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.HashSet; public class ProblemB { static int A; static int B; static HashSet set; public static void main(String[] args) { try { /* Reading */ FileInputStream fstream = new FileInputStream(""input.txt""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); /* Writing */ FileWriter fw = new FileWriter(new File(""output"")); BufferedWriter bw = new BufferedWriter(fw); String strLine; Integer T = 0; int caseCounter = 0; while ((strLine = br.readLine()) != null) { if (caseCounter == 0) { T = new Integer(strLine); } else { set = new HashSet(); int index =strLine.indexOf(' '); A = new Integer(strLine.substring(0, index).trim()); B = new Integer(strLine.substring(index).trim()); int nbRecycledPairs = 0; for (int i = A; i <= B; i++) { if (!set.contains(i)) { nbRecycledPairs += findRecycled(i); } } String toPrint; if (caseCounter == T) { toPrint = ""Case #"" + caseCounter + "": "" + nbRecycledPairs; } else { toPrint = ""Case #"" + caseCounter + "": "" + nbRecycledPairs + ""\n""; } System.out.print(toPrint); bw.write(toPrint); } caseCounter++; } in.close(); bw.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } static int findRecycled(int n) { String s = Integer.toString(n); int nbRecycled = 0; int nbRecycledPairs = 0; for (int i = 0; i < s.length(); i++) { String t = s.substring(i) + s.substring(0, i); if (t.charAt(0) != '0' && isInSet(t) && !t.equals(s) && !set.contains(new Integer(t))) { set.add(new Integer(t)); nbRecycled++; } } if (nbRecycled != 0) { nbRecycled++; } nbRecycledPairs = nbRecycled * (nbRecycled - 1) / 2; return nbRecycledPairs; } static boolean isInSet(String n) { int i = new Integer(n); if (i >= A && i <= B) { return true; } return false; } } " B11033,"import java.io.File; import java.io.FileWriter; import java.util.Scanner; public class B { /** * @param args */ public static void main(String[] args) throws Exception { Scanner a = new Scanner(new File(""/Users/anurag/Dev/Java/workspace/CodeJam/src/input"")); FileWriter w = new FileWriter(new File(""/Users/anurag/Dev/Java/workspace/CodeJam/src/output"")); int T = a.nextInt(); for (int t = 1; t <= T; ++t) { int lower = a.nextInt(); int upper = a.nextInt(); int numInversions = 0; for (int i = lower; i <= upper; ++i) { int maxPower = (int) Math.log10(i); int rotatedNumber = i; do { int lastDigit = rotatedNumber % 10; rotatedNumber = ((int) (rotatedNumber/10)) + (int) (lastDigit * Math.pow(10, maxPower)); if (rotatedNumber >= lower && rotatedNumber <= upper && rotatedNumber != i) { ++numInversions; } } while (rotatedNumber != i); } w.write(String.format(""Case #%d: %d\n"", t, numInversions/2)); } w.close(); } } " B10216,"import java.util.HashSet; public class Recycler implements Runnable{ private int start,end; private HashSet set; public Recycler(int first,int second){ start=first; end=second; set=new HashSet(); } public void run(){ for(int i=start;i<=end;i++){ recycle(i); } } private void recycle(int num){ String temp=String.valueOf(num); int length=temp.length(); for(int i=length-1;i>0;i--){ String temp2=temp.substring(i)+temp.substring(0,i); int num2=Integer.parseInt(temp2); if(num= new Long(numberB).longValue() ? numberA +"" ""+ numberB : numberB +"" ""+ numberA; } public int size() { return pairNumberMap.size(); } } " B11131,"package com.codegem.zaidansari; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; public class ProblemA { public static Map mappedCharacters = new TreeMap(); public static Set validCharacters = new HashSet(); static { int startIndex = 97, endIndex = 122; // Fill mapped with all required mapping character with only keys populated for (int index = startIndex; index <= endIndex; index++) { validCharacters.add(Character.valueOf((char) index)); } Map sampleEntriesMap = new HashMap(); // Put Given Mapping in Map sampleEntriesMap.put(""a"", ""y""); sampleEntriesMap.put(""o"", ""e""); sampleEntriesMap.put(""z"", ""q""); sampleEntriesMap.put(""ejp mysljylc kd kxveddknmc re jsicpdrysi"", ""our language is impossible to understand""); sampleEntriesMap.put(""rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd"", ""there are twenty six factorial possibilities""); sampleEntriesMap.put(""de kr kd eoya kw aej tysr re ujdr lkgc jv"", ""so it is okay if you want to just give up""); loadMap(sampleEntriesMap); } private static void loadMap(Map sampleEntriesMap) { Set populatedCharacters = new HashSet(); for (String key : sampleEntriesMap.keySet()) { String value = sampleEntriesMap.get(key); if (key.length() != value.length()) { throw new RuntimeException(""Size of input :"" + key + "", and output don't match:"" + value); } // Read each character from key and if it's not present in mappedCharacters try to fill that char[] inputCharacterArray = key.toCharArray(); char inputCharacter; for (int index = 0; index < inputCharacterArray.length; index++) { inputCharacter = inputCharacterArray[index]; if (validCharacters.contains(inputCharacter) && !mappedCharacters.containsKey(inputCharacter)) { mappedCharacters.put(inputCharacter, value.charAt(index)); populatedCharacters.add(inputCharacter); } } } // Find any missing entry there can be only Zero or one entry missing in population if more than that than it means sample input are not // enough Set missingKeys = new HashSet(validCharacters); Set missingValues = new HashSet(validCharacters); missingKeys.removeAll(populatedCharacters); missingValues.removeAll(mappedCharacters.values()); if (missingKeys.size() > 1) throw new RuntimeException(""More than one keys are unresolved using provided samples...""); if (missingKeys.size() == 1) { Character missingKey = missingKeys.iterator().next(); Character missingValue = missingValues.iterator().next(); mappedCharacters.put(missingKey, missingValue); } } public static String getEnglishText(String googlereseText) { StringBuilder englishText = new StringBuilder(googlereseText); Character currentCharacter; for (int index = 0; index < englishText.length(); index++) { currentCharacter = englishText.charAt(index); if (validCharacters.contains(currentCharacter)) { englishText.setCharAt(index, mappedCharacters.get(currentCharacter)); } } return englishText.toString(); } public static void main(String[] args) { File file = new File(""/Users/zaansari/Desktop/CodeGem2012/InputFiles/ProblemA.txt""); List inputData = CodeGemUtil.getInputValues(file); int noOfInputs = Integer.parseInt(inputData.get(0)); inputData.remove(0); List outputData = new ArrayList(); for (int index = 0; index < noOfInputs; index++) { outputData.add(ProblemA.getEnglishText(inputData.get(index))); } boolean createdOutputFile = CodeGemUtil.createOutputFile(outputData, ""ProblemA_Output.txt""); if (createdOutputFile) { System.out.println(""Successfully created output file""); } else { System.out.println(""Failed to create output file""); } } } " B12720,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package atta.codejam.qualification; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collection; import java.util.Hashtable; import java.util.List; import java.util.StringTokenizer; /** * * @author a.sahito */ public class RotatoryNombers { static String strLine = null; static int result = 0; static int start = 0; static int end = 0; private static boolean is_recycle_number(int d, int d1) { int len = Integer.toString(d).length() - 1; //bool b = false; for (int i = String.valueOf(d).length() - 1; i >= 0; i--) { int r = d%10; d /= 10; d = (int) (r*( Math.pow(10,len)) + d); if (d == d1) { return true; } } return false; } public static void main(String[] args) { try { FileInputStream fstream = new FileInputStream(""final.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter ifstream = new FileWriter(""final.txt""); BufferedWriter out = new BufferedWriter(ifstream); int resultCounter = 1; int skip_value=0; while ((strLine = br.readLine()) != null) { if (skip_value < 1) { skip_value ++; continue; } result=0; String[] record = new String[2]; record=strLine.split("" ""); start= Integer.parseInt( record[0]); end= Integer.parseInt( record[1]); // int count = 0; for (int i = start; i < end; i++) { for (int j = i+1; j <= end; j++) { if (is_recycle_number(i, j)) result++; } } String output = ""Case #"" + resultCounter + "": "" + result+""\n"" ; System.out.println(""Case #"" + resultCounter + "": "" + result); try { out.write(output); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } resultCounter++; } in.close(); out.close(); } catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } } " B12340,"import java.io.File; import java.io.PrintWriter; import java.util.*; import java.util.jar.JarEntry; /** * Created with IntelliJ IDEA. * User: vitaly * Date: 4/14/12 * Time: 9:24 AM * To change this template use File | Settings | File Templates. */ public class Main { public static int bruteForce(int start, int end) { Set set = new HashSet(); for (int k = start; k <= end; k++) { String repr = Integer.toString(k); for (int i = 1; i < repr.length(); i++) { String a = repr.substring(0, i); String b = repr.substring(i, repr.length()); int comb = Integer.valueOf(b + a); if (comb > k & comb >= start && comb <= end) { String c = """" + k + "":"" + comb; set.add(c); } } } return set.size(); } public static void main(String[] args) throws Exception { Scanner scanner = new Scanner(new File(""C-small-attempt0.in"")); PrintWriter pw = new PrintWriter(new File(""google.out"")); int n = scanner.nextInt(); for(int i = 0; i < n; i++) { int start = scanner.nextInt(); int end = scanner.nextInt(); int comb = bruteForce(start, end); pw.print(String.format(""Case #%d: %d%n"", i + 1, comb)); } scanner.close(); pw.close(); } } " B12473,"package codejam.recyclednumbers; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class DigitsArray implements Comparable { private int[] digits; private DigitsArray() { } public DigitsArray(String numberAsString) { char[] charArray = numberAsString.toCharArray(); this.digits = new int[charArray.length]; for (int i = 0; i < digits.length; i++) { digits[i] = Integer.parseInt("""" + charArray[i]); } } public DigitsArray(int[] digits) { this.digits = digits; } public DigitsArray(Integer number) { this(number.toString()); } public int numberRecycles(DigitsArray minValue, DigitsArray maxValue) { Set correctRecycles = new HashSet<>(); for (int i = 1; i < digits.length; i++) { if (digits[i] < digits[0] || digits[i] < minValue.digits[0] || digits[i] > maxValue.digits[0]) { continue; } DigitsArray recycle = recycle(i); if (recycle.compareTo(this) > 0 && recycle.compareTo(minValue) >= 0 && recycle.compareTo(maxValue) <= 0) { correctRecycles.add(recycle); } } return correctRecycles.size(); } private DigitsArray recycle(int recycleIndex) { DigitsArray result = new DigitsArray(); int length = digits.length; result.digits = new int[length]; for (int i = 0; i < length; i++) { result.digits[i] = digits[(i + recycleIndex) % length]; } return result; } @Override public int compareTo(DigitsArray o) { if (digits.length > o.digits.length) { return 1; } if (digits.length < o.digits.length) { return -1; } for (int i = 0; i < digits.length; i++) { if (digits[i] > o.digits[i]) { return 1; } if (digits[i] < o.digits[i]) { return -1; } } return 0; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(digits); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DigitsArray other = (DigitsArray) obj; if (!Arrays.equals(digits, other.digits)) return false; return true; } } " B11064,"package fixjava; public class StringUtils { /** Repeat the given string the requested number of times. */ public static String repeat(String str, int numTimes) { StringBuilder buf = new StringBuilder(Math.max(0, str.length() * numTimes)); for (int i = 0; i < numTimes; i++) buf.append(str); return buf.toString(); } /** * Pad the left hand side of a field with the given character. Always adds at least one pad character. If the length of str is * greater than numPlaces-1, then the output string will be longer than numPlaces. */ public static String padLeft(String str, char padChar, int numPlaces) { int bufSize = Math.max(numPlaces, str.length() + 1); StringBuilder buf = new StringBuilder(Math.max(numPlaces, str.length() + 1)); buf.append(padChar); for (int i = 1, mi = bufSize - str.length(); i < mi; i++) buf.append(padChar); buf.append(str); return buf.toString(); } /** * Pad the right hand side of a field with the given character. Always adds at least one pad character. If the length of str is * greater than numPlaces-1, then the output string will be longer than numPlaces. */ public static String padRight(String str, char padChar, int numPlaces) { int bufSize = Math.max(numPlaces, str.length() + 1); StringBuilder buf = new StringBuilder(Math.max(numPlaces, str.length() + 1)); buf.append(str); buf.append(padChar); while (buf.length() < bufSize) buf.append(padChar); return buf.toString(); } /** Intern all strings in an array, skipping null elements. */ public static String[] intern(String[] arr) { for (int i = 0; i < arr.length; i++) arr[i] = arr[i].intern(); return arr; } /** Intern a string, ignoring null */ public static String intern(String str) { return str == null ? null : str.intern(); } } " B10264," import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.Reader; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.CharBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class Main { public static HashMap> mem = new HashMap>(); public static void main(String[] args) throws IOException { String inputName; Scanner in = new Scanner(System.in); System.out.print(""Enter input file name: ""); inputName = in.nextLine(); StringBuilder output = new StringBuilder(1000); QueueMagic data = new QueueMagic(new FileReader(new File(inputName))); int caseNum =1; data.next(); do { int A = data.nextInt(); int B = data.nextInt(); ArrayList recycled = new ArrayList(); for(int i = A; i <= B; i++) { String s = String.valueOf(i); recycled.addAll(findRecyled(s, i, B)); } String caseout = String.format(""Case #%d: %d\n"", caseNum++, recycled.size()); output.append(caseout); System.out.print(caseout); } while (data.isNotDepleted()); //System.out.print(output); PrintWriter writer = new PrintWriter(new File(inputName+"".output"")); writer.print(output); writer.flush(); writer.close(); } public static HashSet findRecyled(String s, int n, int B) { //if(mem.containsKey(s)) // return mem.get(s); HashSet ans = new HashSet(); for(int i = 0; i < s.length()-1; i++) { String r = s.substring(i+1)+s.substring(0, i+1); int m = Integer.parseInt(r); if(n < m && m <= B) ans.add(r); } mem.put(s, ans); return ans; } } /** * Makes parsing input from Uva problems easy. * @author Adam Anderson */ class QueueMagic{ private Queue data; private BufferedReader in; private String delimiter; private String secondary_delimiter; /** * The default delimiter is \\s+ * This is at least one or more white space characters */ public final static String DEFAULT_DELIMITER = ""\\s+""; public final static String DEFUALT_SECONDARY_DELIMITER = ""\\s+""; /** * Defaults to reading System.in * Defaults to using the following delimiter: \\s+ * @throws IOException */ public QueueMagic() throws IOException { this(new InputStreamReader(System.in), DEFAULT_DELIMITER); } /** * Build QueueMagic from any reader * Defaults to using the following delimiter: \\s+ * @param reader * @throws IOException */ public QueueMagic(Reader reader) throws IOException { this(reader, DEFAULT_DELIMITER); } /** * Defaults to reading from System.in * @param delimiter * @throws IOException */ public QueueMagic(String regex) throws IOException { this(new InputStreamReader(System.in), regex); } public QueueMagic(Reader reader, String regex) throws IOException { this.in = new BufferedReader(reader); this.delimiter = regex; readData(); } /** * Reads in all bytes in the stream and splits it into string tokens based on the delimiter. * @throws IOException */ private void readData() throws IOException { CharBuffer buf = CharBuffer.allocate(10000); StringBuilder input = new StringBuilder(10000); do { this.in.read(buf); input.append(buf.flip().toString()); }while(this.in.ready()); String [] parts = input.toString().split(this.delimiter); this.data = new LinkedList(Arrays.asList(parts)); close(); } /** * Returns the next string * @return */ public String next() { return data.poll(); } public Integer nextInt() { return Integer.parseInt(next()); } public Short nextShort() { return Short.parseShort(next()); } public Byte nextByte() { return Byte.parseByte(next()); } public Long nextLong() { return Long.parseLong(next()); } public Float nextFloat() { return Float.parseFloat(next()); } public Double nextDouble() { return Double.parseDouble(next()); } public BigInteger nextBigInt() { return new BigInteger(next()); } public BigDecimal nextBigDec() { return new BigDecimal(next()); } /** * Returns the next token split by the secondary delimiter. * @return */ public String [] arrayString() { return next().split(this.secondary_delimiter); } /** * Split by the secondary delimiter * @return */ public Byte [] arrayByte() { String [] parts = arrayString(); Byte [] vals = new Byte[parts.length]; for (int i = 0; i < vals.length; i++) { vals[i] = Byte.parseByte(parts[i]); } return vals; } /** * Split by the secondary delimiter * @return */ public Short [] arrayShort() { String [] parts = arrayString(); Short [] vals = new Short[parts.length]; for (int i = 0; i < vals.length; i++) { vals[i] = Short.parseShort(parts[i]); } return vals; } /** * Split by the secondary delimiter * @return */ public Integer [] arrayInt() { String [] parts = arrayString(); Integer [] vals = new Integer[parts.length]; for (int i = 0; i < vals.length; i++) { vals[i] = Integer.parseInt(parts[i]); } return vals; } /** * Split by the secondary delimiter * @return */ public Long [] arrayLong() { String [] parts = arrayString(); Long [] vals = new Long[parts.length]; for (int i = 0; i < vals.length; i++) { vals[i] = Long.parseLong(parts[i]); } return vals; } /** * Split by the secondary delimiter * @return */ public Float [] arrayFloat() { String [] parts = arrayString(); Float [] vals = new Float[parts.length]; for (int i = 0; i < vals.length; i++) { vals[i] = Float.parseFloat(parts[i]); } return vals; } /** * Split by the secondary delimiter * @return */ public Double [] arrayDouble() { String [] parts = arrayString(); Double [] vals = new Double[parts.length]; for (int i = 0; i < vals.length; i++) { vals[i] = Double.parseDouble(parts[i]); } return vals; } /** * Split by the secondary delimiter * @return */ public BigInteger [] arrayBigInteger() { String [] parts = arrayString(); BigInteger [] vals = new BigInteger[parts.length]; for (int i = 0; i < vals.length; i++) { vals[i] = new BigInteger(parts[i]); } return vals; } /** * Split by the secondary delimiter * @return */ public BigDecimal[] arrayBigDecimal() { String [] parts = arrayString(); BigDecimal [] vals = new BigDecimal[parts.length]; for (int i = 0; i < vals.length; i++) { vals[i] = new BigDecimal(parts[i]); } return vals; } public ArrayList listString() { return new ArrayList(Arrays.asList(arrayString())); } public ArrayList listByte() { return new ArrayList(Arrays.asList(arrayByte())); } public ArrayList listShort() { return new ArrayList(Arrays.asList(arrayShort())); } public ArrayList listInt() { return new ArrayList(Arrays.asList(arrayInt())); } public ArrayList listLong() { return new ArrayList(Arrays.asList(arrayLong())); } public ArrayList listFloat() { return new ArrayList(Arrays.asList(arrayFloat())); } public ArrayList listDouble() { return new ArrayList(Arrays.asList(arrayDouble())); } public ArrayList listBigInteger() { return new ArrayList(Arrays.asList(arrayBigInteger())); } public ArrayList listBigDecimal() { return new ArrayList(Arrays.asList(arrayBigDecimal())); } /** * @return true if there is no more data */ public boolean isDepleted() { return this.data.isEmpty(); } /** * * @return true if there is data */ public boolean isNotDepleted() { return !isDepleted(); } /** * The primary delimiter is used to split the data into tokens * @return */ public String getDelimter() { return this.delimiter; } /** * The primary delimiter is used to split the data into tokens * @param regex */ public void setDelimiter(String regex) { this.delimiter = regex; } /** * The secondary delimiter is used to split tokens into lists/arrays * @return */ public String getSecondaryDelimiter() { return this.secondary_delimiter; } /** * The secondary delimiter is used to split tokens into lists/arrays * @param regex */ public void setSecondaryDelimiter(String regex) { this.secondary_delimiter = regex; } public void close() throws IOException { if(this.in != null) { in.close(); } } }" B10774,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.PrintWriter; public class RecycledNumbers { public RecycledNumbers() { solve(); } /** * Solves Problem A. Speaking in Tongues */ private void solve() { try { File f = new File(""./C-small-attempt0.in.txt""); File output = new File(""./output2.out""); if (output.exists()) output.delete(); output.createNewFile(); PrintWriter pw = new PrintWriter(output); FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr); String linea = br.readLine(); linea = br.readLine(); int i = 1; while (linea != null) { int a = Integer.parseInt(linea.split("" "")[0]); int b = Integer.parseInt(linea.split("" "")[1]); pw.println(""Case #"" + i + "": "" + getRecycledAmmount(a, b)); linea = br.readLine(); i++; } pw.close(); br.close(); fr.close(); } catch (Exception e) { e.printStackTrace(); } } private int getRecycledAmmount(int start, int end) { int ammount = 0; for (int n = start; n <= end; n++) { for (int m = start; m <= end; m++) { if (n < m && isRecycled("""" + n, """" + m)) ammount++; } } return ammount; } private boolean isRecycled(String n, String m) { for (int i = m.length()-1; i > 0; i--) { String prefix = m.substring(0, i); String suffix = m.substring(i); String recycled = suffix + prefix; if(recycled.equals(n)) return true; } return false; } /** * @param args */ public static void main(String[] args) { new RecycledNumbers(); } } " B11003,"package org.tritree_tritree; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Scanner; import java.util.Set; public class ProblemCSmall { public static void main(String[] args) throws IOException { File source = new File(""C-small-attempt0.in""); Scanner scan = new Scanner(source); int t = scan.nextInt(); scan.nextLine(); List resultList = new ArrayList(); for (int i = 1; i < t + 1; i++) { int n = scan.nextInt(); int m = scan.nextInt(); String result = ""Case #"" + i + "": "" + resolve(n, m); resultList.add(result); } SimpleDateFormat dateFormat = new SimpleDateFormat(""yyyy-MM-dd_hhmmss""); File resultFile = new File(""C-small-"" + dateFormat.format(new Date()) + "".out""); FileOutputStream fileOutputStream = new FileOutputStream(resultFile); for (String result: resultList) { result = result + ""\n""; fileOutputStream.write(result.getBytes()); } fileOutputStream.flush(); fileOutputStream.close(); } private static int resolve(int n, int m) { int cnt = 0; Set pool = new HashSet(); for (int i = n; i < m + 1; i++) { if (i < 10 || pool.contains(i)) { continue; } List recycleNumbers = getRecycleNumbers(i); System.out.println(""i="" + i + "",recycleNumbers="" + recycleNumbers); Collections.sort(recycleNumbers); for (Iterator iterator = recycleNumbers.iterator(); iterator.hasNext();) { int value = (Integer) iterator.next(); if (n <= value && value <= m) { // do nothing } else { iterator.remove(); } } if (1 < recycleNumbers.size()) { pool.addAll(recycleNumbers); cnt = cnt + getCombination(recycleNumbers.size()); } } return cnt; } private static int getCombination(int size) { int result = (size * (size - 1)) / 2; return result; } private static List getRecycleNumbers(int intValue) { Set set = new LinkedHashSet(); String str = String.valueOf(intValue); for (int i = 0; i < str.length(); i++) { String string = getStartIndexString(str, i); if (string.startsWith(""0"")) { continue; } set.add(Integer.valueOf(string)); } return new ArrayList(set); } private static String getStartIndexString(String str, int startIndex) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < str.length(); i++) { // System.out.print(""start:"" + (startIndex + i) % str.length()); // System.out.println("",end:"" + ((startIndex + i) % str.length() + 1)); builder.append(str.substring((startIndex + i) % str.length(), (startIndex + i) % str.length() + 1)); } return builder.toString(); } } " B11871,"import java.io.*; import java.util.Scanner; import java.util.*; public class B { public static int reverse(int a, int b) { Vector vec = new Vector(); Vector vec2 = new Vector(); int result = 0; if(a > 9) { for(int i=a; i <= b; i++) { String x=i+""""; for(int j = 1; j < x.length();j++) { int status = 0; String p =(x.substring(j,x.length()))+x.substring(0,j); int num2 = Integer.parseInt(p); if(i!=num2 && num2 <= b && num2 >=a) { //System.out.println(""P VALUE >> "" + p); //System.out.println(""INDEX OF""+x+"" : ""+vec.indexOf(x)); for(int k = 0; k < vec.size(); k++) { String tmp = (String) vec.elementAt(k); String tmp2 = (String) vec2.elementAt(k); int c = Integer.parseInt(tmp); int d = Integer.parseInt(tmp2); if((c == num2 && i == d) || (c==i && d == num2)) { status = 1; break; } } if(status == 0) { vec.add(x); vec2.add(p); //System.out.println("">>>""+x+"" ""+p); result++; } } } } } return result; } public static void main(String [] args) { File fFile = new File(""B.in""); Scanner scanner = null; try { scanner = new Scanner(new FileReader(fFile)); //first use a Scanner to get each line int line = 1; while ( scanner.hasNextLine() ){ String name = scanner.nextLine(); String []x = name.split("" ""); int p1 = Integer.parseInt(x[0]); int p2 = Integer.parseInt(x[1]); System.out.println(""Case #""+line+"": ""+reverse(p1,p2)); line++; } } catch(Exception ex) { } finally { scanner.close(); } } }" B10648,"import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.base.Charsets; import com.google.common.base.Predicate; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Collections2; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import com.google.common.io.Files; public class Main { public static void main(String[] args) throws IOException { // File f = new File(""C-small-attempt0.in""); File f = new File(""C-small-attempt1.in""); // File f = new File(""C-small-attempt2.in""); // File f = new File(""C-large.in""); // File f = new File(""B-large.in""); // File f = new File(""A-large-practice.in""); // File f = new File(""example.in""); // File f = new File(""test.in""); List lines = Files.readLines(f, Charsets.UTF_8); int cases = Integer.valueOf(lines.get(0)); int c = 0; while (c < cases) { int result = 0; c++; String[] tokens = lines.get(c).split("" ""); int a = Integer.valueOf(tokens[0]); int b = Integer.valueOf(tokens[1]); Set set = new HashSet(); for(int n = a; n < b; n++) { set.clear(); String s = """" + n; // System.out.println("" >> "" + s); int sl = s.length(); for (int i = 0; i < sl; i++) { Integer shifted = shift(s, i); if (shifted != null && shifted <= b && shifted > n) { // System.out.println(shifted); set.add(shifted); } } result += set.size(); } System.out.println(""Case #"" + c + "": "" + result); } } private static Integer shift(String n, int i) { i++; int l = n.length(); String s = n.substring(l - i, l) + n.substring(0,l - i); if (s.compareTo(n) <= 0) { return null; } else { return Integer.valueOf(s); } } }" B11161,"import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; public class Pl_C { /** * @param args */ public static void main(String[] args) { try { BufferedReader bf = new BufferedReader(new FileReader( ""C:\\Users\\Administrator\\Desktop\\CodeJam\\C-small-attempt0.in"")); String[] line = new String[Integer.parseInt(bf.readLine())]; String [] answer =new String [line.length]; int numberOutput=0; for (int i = 0; i < line.length; i++) { line[i] = bf.readLine(); answer[i]=""Case #""+(i+1)+"":""; } for(int i=0;i blackList=new ArrayList(); int count=0; for(int j=start;j<=end;j++){ String b1=addZero(data[1].length()-(j+"""").length())+""""+j; ArrayList sam=new ArrayList(); addSample(b1, sam); for(int k=0;k=start&&key<=end&&inBlackL(b1+"" ""+sam.get(k), blackList)==false&&Integer.parseInt(b1)!=Integer.parseInt(sam.get(k))){ //System.out.println(b1+"" ""+sam.get(k)); count++; //System.out.println(""Count= ""+count); blackList.add(sam.get(k)+"" ""+b1); } } } answer[numberOutput]=answer[numberOutput]+"" ""+count; numberOutput++; } for(int i=0;i b){ boolean check=false; for(int i=0;i b){ boolean check=false; String []keySlot=key.split("" ""); boolean check2=false,check3=false,check4=false; for(int i=0;i sample){ for(int j=0;j 0; j--) { String f = a.substring(e-j) + a.substring(0, e-j); //System.out.println(f); int g = Integer.parseInt(f); //System.out.println(g); s1[j] = g; for(int y = 0; y < s1.length; y++) { if(y == j); else if(s1[y] == g) { g = 0; break; } } if(g > c && g > h && g <= d) iter = iter + 1; //System.out.println(""interations: ""+ iter); } } if(i < d-c){ a = String.valueOf(s[i]); } } return iter; } public static void main(String[] args) throws FileNotFoundException, IOException { FileReader theFileID = new FileReader(""C-small-attempt0.in""); BufferedReader inFile = new BufferedReader(theFileID); FileWriter fw = new FileWriter(""output.txt""); PrintWriter output = new PrintWriter(fw); String line; int numCases = 0; if((line = inFile.readLine()) != null) numCases = Integer.parseInt(line); String[] x = null; for(int i = 0; (line = inFile.readLine()) != null && i < numCases; i++) { x = line.split("" ""); String a = x[0]; String b = x[1]; int y = recyclepos(a, b); output.write(""Case #""+ (i + 1) + "": "" + y); output.println(); } inFile.close(); output.close(); fw.close(); System.out.println(recyclepos(""1"", ""9"")); System.out.println(recyclepos(""10"", ""40"")); System.out.println(recyclepos(""100"", ""500"")); System.out.println(recyclepos(""1111"", ""2222"")); } } " B10719,"import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.PrintStream; import java.text.MessageFormat; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class QualQ3 { private final Scanner inputScanner = new Scanner(System.in); private Scanner testCaseScanner; int[] scores; private Set set; private int A; private int B; /** * @param args */ public static void main(String[] args) { QualQ3.init(); QualQ3 speaking = new QualQ3(); speaking.solve(); } private static void init() { try { System.setIn(new FileInputStream(""in.txt"")); System.setOut(new PrintStream(""out.txt"")); } catch (FileNotFoundException e) { e.printStackTrace(); } } private void solve() { // Number of test cases int T = inputScanner.nextInt(); inputScanner.nextLine(); for (int i = 1; i <= T; i++) { initTestCase(); readTestCase(); solveTestCase(); printTestCase(i); } } private void initTestCase() { set = new HashSet(); } private void readTestCase() { testCaseScanner = new Scanner(inputScanner.nextLine()); A = testCaseScanner.nextInt(); B = testCaseScanner.nextInt(); } private void solveTestCase() { String sA = (new Integer(A)).toString(); int strLen = sA.length(); for (int i=A; i<=B; i++) { String current = (new Integer(i)).toString(); for (int j=1;j "" + newNumVal); if (newNumVal > i && newNumVal<=B) { String pair = """" + i + "","" + newNum; // System.out.println("""" + i + "" -> "" + newNumVal); set.add(pair); } } } } private final MessageFormat printFormat = new MessageFormat(""Case #{0}: ""); private void printTestCase(int num) { System.out.print(printFormat.format(new Object[] { num })); System.out.println(set.size()); } } " B12886,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String fileName = args[0]; try { BufferedReader br = new BufferedReader(new FileReader(fileName)); BufferedWriter bw = new BufferedWriter(new FileWriter(""numbers.out"")); String T = br.readLine(); //System.out.println(T); int numT = Integer.parseInt(T); int countReturn = 0; String returnLine; String line; String[] input; int n; int m; String temp; String leading; for(int i=1; i<=numT; i++){ line = br.readLine(); input = line.split("" ""); n = Integer.parseInt(input[0]); m = Integer.parseInt(input[1]); //System.out.println(""START "" + n + "" to "" + m); for(int j=n; j j) { //System.out.println(j + "" "" + check); countReturn++; } } } //System.out.println(countReturn); returnLine = ""Case #""+i+"": ""+countReturn; System.out.println(returnLine); bw.write(returnLine,0,returnLine.length()); bw.flush(); bw.newLine(); countReturn = 0; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } " B10568,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Qualifier2012.c; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.TreeMap; /** * * @author Ant Ongun Kefeli */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException, IOException { FileInputStream fis = new FileInputStream(""src\\Qualifier2012\\c\\C-small-attempt0.in""); Scanner sc = new Scanner(fis); FileWriter fw = new FileWriter(""src\\Qualifier2012\\c\\output.out""); BufferedWriter out = new BufferedWriter(fw); int caseCount = 0; caseCount = sc.nextInt(); for (int i = 0; i < caseCount; i++) { long smallLimit = sc.nextLong(); long bigLimit = sc.nextLong(); doit(out, i + 1, smallLimit, bigLimit); } out.close(); sc.close(); } private static void doit(BufferedWriter out, int casec, long smallLimit, long bigLimit) throws IOException { long res = 0; if (bigLimit < 21) { res = 0; } else { int digits = (int) Math.log10(smallLimit) + 1; Map> map = new HashMap(); for (long i = smallLimit; i <= bigLimit; i++) { for (int j = 1; j <= digits - 1; j++) { String str = Long.toString(i); StringBuilder sb = new StringBuilder(); sb.append(str.substring(str.length() - j, str.length())); sb.append(str.substring(0, str.length() - j)); long cr = Long.parseLong(sb.toString()); if (cr >= smallLimit && cr <= bigLimit) { long sm = i; long big = cr; if (i == cr) { continue; } if (cr < i) { sm = cr; big = i; } if (map.containsKey(sm) && map.get(sm).contains(big)) { continue; } if (map.get(sm) == null) { List list = new ArrayList(); list.add(big); map.put(sm, list); } else { List list = map.get(sm); list.add(big); map.put(sm, list); } res++; } } } } out.write( ""Case #"" + casec + "": "" + res + ""\n""); } } " B10375,"import java.util.*; import java.io.*; import java.math.*; import java.awt.*; import static java.lang.Math.*; import static java.lang.Integer.parseInt; import static java.lang.Double.parseDouble; import static java.lang.Long.parseLong; import static java.lang.System.*; import static java.util.Arrays.*; import static java.util.Collection.*; public class C { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(in)); int T = parseInt(br.readLine()); for(int t = 0; t++ < T; ) { String[] line = br.readLine().split("" ""); int A = parseInt(line[0]), B = parseInt(line[1]); long[] V = new long[B - A + 1], S = new long[B - A + 1]; int order = 1; S[0] = V[0] = 0; while(order < B) order *= 10; for(int i = A + 1; i <= B; i++) { int index = -1; for(int j = 10; j <= i; j *= 10) { int count = i / j + (i % j) * (order / j); if(index < count && count < i) index = count; } V[i - A] = index >= A ? V[index - A] + 1 : 0; S[i - A] = V[i - A] + S[i - A - 1]; } out.println(""Case #"" + t +"": "" + S[B-A]) ; } } } " B10537,"import java.util.*; public class C { public static void main (String [] args) { Scanner s = new Scanner(System.in); int T = s.nextInt(); int[] old = new int[7]; for (int t = 1; t <= T; t++) { int A = s.nextInt(); int B = s.nextInt(); int ans = 0; for (int n = A; n < B; n++) { int time = 0; int d = 10; while (n >= d) { time++; d *= 10; } int oldSize = 0; for (int i = 0; i < time; i++) { int m = movingFront(n, i, time - i); if (m > n && m <= B) { boolean unique = true; for (int k = 0; k < oldSize; k++) { if (old[k] == m) { unique = false; break; } } if (unique) { ans++; old[oldSize++] = m; } } } } System.out.println(""Case #"" + t + "": ""+ans); } } public static int movingFront(int n, int index, int postMult) { int front = 0; int mult = 1; while (index-- >= 0) { front += ((n % 10) * mult); n /= 10; mult *= 10; } int frontMult = 1; while (postMult-- > 0) { frontMult *= 10; } return (front * frontMult) + n; } }" B11147,"import java.util.*; class c { public static void main(String [] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for(int t=1;t<=T;++t) { int a,b; a = in.nextInt(); b = in.nextInt(); long pairs = 0; for(int i=a;i<=b;++i) { HashSet m = new HashSet(); String istr = """" + i; int numDigits = istr.length(); for(int j=1;j i && newnum <= b) { if(!m.contains(newnum)) { ++pairs; m.add(newnum); } } } } System.out.println(""Case #""+t+"": "" + pairs); } } } " B11183,"import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.HashSet; import java.io.FileWriter; public class RecyclingNumbers { public static void main(String... args) { RecyclingNumbers obj = new RecyclingNumbers(); obj.run(); } public void run() { try { File f = new File(""C-small-attempt0.in""); File outFile = new File(""output.txt""); FileWriter w = new FileWriter(outFile); Scanner s = new Scanner(f); int T = s.nextInt(); s.nextLine(); for(int i = 1; i<= T; i++) { int lower = s.nextInt(); int upper = s.nextInt(); int maxRecycled = findRecycled(lower, upper); String str = ""Case #"" + i +"": "" + maxRecycled + '\n'; w.write(str); if(s.hasNextLine()) s.nextLine(); } w.close(); } catch(Exception e) { System.out.println(e.toString()); } } private int findRecycled(int lower, int upper) { int recycled = 0; HashSet set = new HashSet(); for(int n = lower; n <= upper; n++) { String current = (new Integer(n)).toString(); for(int r = 0; r < current.length(); r++) { String check = current.substring(1) + current.charAt(0); int m = Integer.parseInt(check); if( lower <= n) { if(n < m) { if( m <= upper) { set.add(new Pair(n,m)); } } } current = check; } } return set.size(); } private class Pair { public int x, y; public Pair(int x, int y) { this.x = x; this.y = y; } public boolean equals(Object obj) { if(this == obj) return true; if((obj == null) || (obj.getClass() != this.getClass())) return false; Pair p = (Pair)obj; return x == p.x && y == p.y; } public int hashCode() { int hash = 7; hash = 31 * hash + x; hash = 31 * hash + y; return hash; } } } " B10768," public class MyPair { public MyPair(String str) { lowerLimit = Integer.parseInt(str.split("" "")[0]); higherLimit = Integer.parseInt(str.split("" "")[1]); } public MyPair(int str, int str2) { lowerLimit = str; higherLimit = str2; } public boolean sameAs(MyPair other) { if ((other.lowerLimit == lowerLimit && other.higherLimit == higherLimit )|| (other.lowerLimit == higherLimit && other.higherLimit == lowerLimit ) ) { return true; } return false; } public int lowerLimit; public int higherLimit; }" B11205,"import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; /** * * @author ZIYAN */ public class Test { /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException, IOException { Scanner scanner = new Scanner(new File(""C:\\Documents and Settings\\ZIYAN\\Desktop\\C-small-attempt0.IN"")); FileWriter fstream = new FileWriter(""C:\\Documents and Settings\\ZIYAN\\Desktop\\out.txt""); BufferedWriter out = new BufferedWriter(fstream); int cases=scanner.nextInt(); for(int l=0;l=dgt) { dgt*=10; rs++; } return rs; } } " B10541,"import java.io.*; import java.util.*; public class ProblemC { public static void main(String[] args) throws Throwable { Scanner in = new Scanner(new File(""c.in"")); PrintWriter out = new PrintWriter(""c.out""); int testCount = Integer.parseInt(in.nextLine().trim()); for (int i = 0; i < testCount; i++) { out.print(""Case #"" + (i + 1) + "": ""); solve(in, out); } out.close(); } static void solve(Scanner in, PrintWriter out) { int a = in.nextInt(); int b = in.nextInt(); int ans = 0; for (int i = a; i <= b; i++) { int z = getD(i) / 10; int p = i; do { p = p / 10 + p % 10 * z; if (p > i && p <= b) { ++ans; } } while (p != i); } out.println(ans); } static int getD(int i) { return i == 0 ? 1 : getD(i / 10) * 10; } } " B13061,"package com.google.codejam.recycle; /** * Class to represent each test case. * It will hold details like test case no, input to be operated and TestResult. * @author Sushant Deshpande * */ public class TestCase { /** * Variable to hold value for test case number. */ private int caseNo; /** * Variable to hold lower limit. */ private int low; /** * Variable to hold upper limit. */ private int high; /** * Variable holding test case result. */ private TestResult output; /** * Constructor for creating TestCase with case no. * @param caseNo int * @param low int * @param high int */ public TestCase(final int caseNo, final int low, final int high) { this.caseNo = caseNo; this.low = low; this.high = high; } /** * Settter method for TestResult. * @param output TestResult */ public final void setOutput(final TestResult output) { this.output = output; } public int getHigh() { return high; } public int getLow() { return low; } /** * Method to format the test output for printing in the report. * @return String formatted output for the given input. */ public final String printTestResult() { StringBuilder resultBuilder = new StringBuilder(""Case #""); resultBuilder.append(caseNo).append("": ""); resultBuilder.append(output.getTestOutput()).append(""\n""); return resultBuilder.toString(); } }" B12869,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package numbers; /** * * @author Serban */ public class Numbers { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Input in = new Input(""C-small-attempt0.in""); } } " B10132,"package in.co.google.jam; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class Recycled { public Recycled() throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader( new FileInputStream(""C:/C-small.in.txt""))); int numTests = Integer.parseInt(br.readLine()); for (int i = 0; i < numTests; i++) { int result = 0; String s = br.readLine(); String[] numbers = s.split("" ""); int A = Integer.parseInt(numbers[0]); int B = Integer.parseInt(numbers[1]); if (A < 10 && B < 10) { result = 0; } else { List allNumbers = new ArrayList(); for (int x = A; x <= B; x++) { allNumbers.add(x); } int middle = allNumbers.size() / 2; int base = 0; int t = A; int tester = 1; while (t >= 10) { t = t / 10; base++; tester *= 10; } for (int c = 0; c < allNumbers.size() - 10; c++) { for (int d = c + 9; d < allNumbers.size(); d++) { int numToTest = allNumbers.get(d); for (int b = 0; b < base; b++) { numToTest = recycle(numToTest, tester); if (allNumbers.get(c) == numToTest) { result++; break; } } } } } System.out.println(""Case #"" + (i + 1) + "": "" + result); } } private int recycle(int num, int base) { int ret = num; int t = num; ret = ((t % base) * 10) + (t / base); return ret; } public static void main(String[] args) { try { new Recycled(); } catch (Exception e) { e.printStackTrace(); } } } " B12788,"import java.util.List; import java.util.Map; public class Recycled { List>> input; public Recycled(List>> input){ this.input = input; } public boolean recycled(int n, int m){ boolean r = false; String stringN = Integer.toString(n); for(int i = 1; i < stringN.length(); i++){ String tmp = new String(); tmp += stringN.substring(i, stringN.length()); tmp += stringN.substring(0, i); if(Integer.parseInt(tmp) == m){ r = true; break; } } return r; } public void solve(){ for(int i = 0; i < input.size(); i++){ int cpt = 0; int a = Integer.parseInt(input.get(i).get(0).get(0)); int b = Integer.parseInt(input.get(i).get(0).get(1)); for(int x = a; x < b; x++){ for(int y = x + 1; y <= b; y++){ if(recycled(x, y)) cpt++; } } System.out.println(""Case #"" + (i+1) + "": "" + cpt); } } } " B10982,"// Google Code Jam Qualification Round 2012 // Problem C. Recycled Numbers import java.util.*; import java.io.*; public class RecycledNumbers{ static String inname = ""C-small-attempt0.in""; // input file name here static String outname = ""C-small-attempt0.out""; // output file name here public static void main(String[] args){ try{ Scanner in = new Scanner(new BufferedReader(new FileReader(inname))); //Scanner in = new Scanner(System.in); BufferedWriter out = new BufferedWriter(new FileWriter(outname)); int t = in.nextInt(); int a, b; for (int cas = 1; cas <= t; cas++){ int ans = 0; a = in.nextInt(); b = in.nextInt(); for (int n = a; n < b; n++){ String ns = Integer.toString(n); int d = ns.length(); int mss[] = new int[d]; for(int i = 1; i < d; i++){ String ms = ns.substring(i); ms += ns.substring(0,i); int m = Integer.parseInt(ms); mss[i] = m; if (n < m && m > a && m <= b){ boolean flag = true; for (int j = 0; j < i; j++) if (m == mss[j]) flag = false; if (flag) ans++; } } } //System.out.print(""Case #"" + cas + "": "" + ans + ""\n""); out.write(""Case #"" + cas + "": "" + ans + ""\n""); } in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } }" B11186,"import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class Prob { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(new File(""C-small-practice.in"")); FileWriter fw = new FileWriter(""C-small-practice.out""); int t = sc.nextInt(); //Mapping m = new Mapping(); for (int i = 1; i <= t; i++) { int A = sc.nextInt(); int B = sc.nextInt(); fw.write(""Case #""+i+"": ""+Hehe.n(A, B)+""\n""); } fw.close(); } } " B10659,"import java.io.*; public class google3 { void main()throws IOException { try{ // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(""C-small-attempt0.in.txt""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; strLine=br.readLine(); int a=Integer.parseInt(strLine);//Read File Line By Line String b[]=new String[a]; int i=0; while ((strLine = br.readLine()) != null) { // Print the content on the console b[i]=strLine;i++; } in.close(); FileOutputStream out = new FileOutputStream(new File(""output.txt"")); int g=0;for(int l=0;l= 0; i--) { int r = d%10; d /= 10; d = (int) (r*( Math.pow(10,len)) + d); if (d == d1) { return true; } } return false; } public static void main(String[] args) { try { FileInputStream fstream = new FileInputStream(""input.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter ifstream = new FileWriter(""output.txt""); BufferedWriter out = new BufferedWriter(ifstream); int resultCounter = 1; int skip_value=0; while ((strLine = br.readLine()) != null) { if (skip_value < 1) { skip_value ++; continue; } result=0; String[] record = new String[2]; record=strLine.split("" ""); start= Integer.parseInt( record[0]); end= Integer.parseInt( record[1]); // int count = 0; for (int i = start; i < end; i++) { for (int j = i+1; j <= end; j++) { if (is_recycle_number(i, j)) result++; } } String output = ""Case #"" + resultCounter + "": "" + result+""\n"" ; System.out.println(""Case #"" + resultCounter + "": "" + result); try { out.write(output); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } resultCounter++; } in.close(); out.close(); } catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } }" B10809,"import java.io.File; import java.util.HashSet; import java.util.Scanner; public class C { public static void main(String[] args) throws Exception { Scanner in = new Scanner(new File(""C-small-attempt0.bin"")); // Scanner in = new Scanner(new File(""test.in"")); int T = in.nextInt(); for (int zz = 1; zz <= T; ++zz) { int A = in.nextInt(); int B = in.nextInt(); int r = 0; // HashSet tested = new HashSet<>(); for (int i = A; i < B; ++i) { int log = (int) Math.log10(i); int n = i; int p = (int) Math.pow(10, log+1); HashSet tested = new HashSet<>(log); for (int l = 1; l <= log; ++l) { n *= 10; n = (n%p) + (n/p); if (tested.add(n) && n > i && n <= B) r++; } } System.out.format(""Case #%d: %d\n"", zz, r); } } } " B12547,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recyclednumbers; import java.io.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * @author WC */ public class CodeJamFileManager { private final static String problemIntro = ""Problem reading file: ""; private final static String location = ""C:\\CodeJamTests\\""; public static String getStringOfFile(String filename) { String filepath = location + filename; byte[] buffer = new byte[(int) new File(filepath).length()]; BufferedInputStream stream = null; try { stream = new BufferedInputStream(new FileInputStream(filepath)); stream.read(buffer); } catch (Exception ex) { return problemIntro + ex.getMessage(); } finally { if (stream != null) { try { stream.close(); } catch (IOException ex) { return problemIntro + ex.getMessage(); } } } return new String(buffer); } public static int getIntFromFirstLineOfFile(String filename, String separator) { String[] lines = getTextLinesOfFile(filename, separator); int i = 1; return extractInt(lines[0]); } public static String[] getTextLinesOfFile(String filename, String separator) { String fileStr = getStringOfFile(filename); return fileStr.split(separator); } public static void saveOutputFile(String output, String filename, String separator) { String filepath = location + filename; try { File outFile = new File(filepath); FileWriter writer = new FileWriter(outFile); BufferedWriter bWriter = new BufferedWriter(writer); bWriter.write(output); bWriter.close(); } catch (Exception ex) { System.out.println(""Failed to save file with error: "" + ex.getMessage()); } } private static int extractInt(String line) { Matcher intMatcher = Pattern.compile(""[0-9]*"").matcher(line); int i = 0; if (intMatcher.find()) { String numStr = intMatcher.group(0); i = Integer.parseInt(numStr); } return i; } } " B12791,"import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Scanner; public class Main { private static int recycled(int n, int m) { String sN = (new Integer(n)).toString(); String sM = (new Integer(m)).toString(); int nL = sN.length(); int mL = sM.length(); HashMap> pairs = new HashMap>(); for(int i = 0; i < nL; i++) { String swap = sN.substring(nL-1-i); String test = swap + sN.substring(0, nL-1-i); int testS = Integer.parseInt(test); if(testS == m) { if(!pairs.containsKey(testS)) { HashSet newSet = new HashSet(); newSet.add(m); pairs.put(testS, newSet); } else { pairs.get(testS).add(m); } } } Iterator iter = pairs.keySet().iterator(); int sum = 0; while(iter.hasNext()) { sum += pairs.get(iter.next()).size(); } return sum; } public static void main(String[] args) { Scanner inScan = new Scanner(System.in); int T = inScan.nextInt(); //System.out.println(T); for(int t = 0; t < T; t++) { int A, B; A = inScan.nextInt(); B = inScan.nextInt(); //System.out.println(A); //System.out.println(B); int sum = 0; for(int n = A; n <= B; n++) { for(int m = B; m > n; m--) { sum += recycled(n, m); //System.out.println(""LOOP""); } } System.out.println(""Case #"" + (t+1) + "": "" + sum); } } }" B10283,"import java.util.*; import java.io.*; import java.lang.Number; public class number { public static void main(String[] args) throws FileNotFoundException { Scanner fileReader = new Scanner(new File(""C-small-attempt0.in"")); PrintStream output = new PrintStream(new File(""outputAwesome2.txt"")); // Process file int repetitions = fileReader.nextInt(); for(int i = 1; i <= repetitions; i++) { output.print(""Case #"" + i + "": ""); int start = fileReader.nextInt(); int stop = fileReader.nextInt(); if (start < 10 || stop < 10) { output.println(""0""); } else { int digits = 0; int foo = start; while (foo != 0) { foo = foo / 10; digits++; } int count = 0; for(int j = start; j <= stop; j++) { String number = j + """"; for(int k = 1; k < digits; k++) { // number = 10, k = 2 String stuff = number.substring(1) + number.charAt(0); if(!stuff.equals(number)) { number = stuff; //System.out.println(number); if(Integer.parseInt(number) <= stop && Integer.parseInt(number) >= start){ //System.out.println(""yes""); count++; } } } } output.println(count / 2); } } } }" B12523," import java.util.HashSet; import java.util.LinkedList; import java.util.Scanner; import java.util.Set; /** * * @author leonardo */ public class RecyclingNumbers { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); long inputSize = Integer.parseInt(scanner.nextLine()); for (long i = 1; i <= inputSize; i++) { String[] input = scanner.nextLine().split("" "") ; /* No solution exists. */ if (input.length == 1) continue ; long a = Long.parseLong(input[0]) ; long b = Long.parseLong(input[1]) ; System.out.println(""Case #"" + i + "": "" + countRecyclablePairs(a, b)) ; } } private static long countRecyclablePairs(long a, long b) { if (a == b) return 0 ; long count = 0 ; for(long n = a; n <= b; n++) { LinkedList digits = toLinkedList(n) ; Set counted = new HashSet() ; for(long i = 0; i < digits.size(); i++) { digits.addFirst(digits.removeLast()) ; long m = toNumber(digits) ; if (! counted.contains(m) && n < m && m <= b) { counted.add(m) ; count++ ; } } } return count ; } private static LinkedList toLinkedList(long number) { LinkedList digits = new LinkedList() ; long remainer = 0 ; while(number >= 10) { remainer = number % 10 ; digits.addFirst(remainer); number = number / 10 ; } digits.addFirst(number) ; return digits ; } private static long toNumber(LinkedList digits) { long number = 0 ; long expoent = digits.size() - 1 ; for(long d : digits) { number += d * Math.pow(10, expoent) ; expoent-- ; } return number ; } } " B10712,"import java.io.*; import java.util.*; public class Main{ String inputFile = ""C-small-attempt0.in""; String outputFile = """"; PrintStream output; Scanner fileScanner; int outputLine = 0; double start = System.currentTimeMillis(); public Main(){ newCodeJam(); fileScanner.nextLine(); while (fileScanner.hasNextLine()){ String line = fileScanner.nextLine(); Scanner scanner = new Scanner(line); int A = scanner.nextInt(); int B = scanner.nextInt(); println(solve(A, B) +""""); } output.close(); System.out.println(""Finished.""); System.out.println(""Time Taken: "" + ((System.currentTimeMillis()-start)/1000) + "" seconds.""); } private int solve(int A, int B){ int ans = 0; for (int n=A; n<=B-1; n++){ for (int m=n+1; m<=B; m++){ if (recycledPair(n, m)){ ans++; } } } return ans; } private static boolean recycledPair(int n, int m){ String N = n + """"; String M = m + """"; int L = M.length(); for (int i=1; i<=L; i++){ M = M.substring(1) + M.charAt(0); // rotate if (N.equals(M)){ return true; } } return false; } // CodeJam Utility Methods: public void newCodeJam(){ String outputFile = inputFile.substring(0, inputFile.length()-3) + ""-OUTPUT.out""; System.out.print(""\f""); // open input file try { fileScanner = new Scanner(new File(inputFile)); }catch(IOException e) {} // open output file try { output = new PrintStream(new File(outputFile)); }catch(IOException ex) {} } public void println(String s){ outputLine++; output.println(""Case #"" + outputLine + "": "" + s); } public static void main(String[] args){ new Main(); } }" B11444,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.StringTokenizer; public class Main { public static int keta; public static void main(String[] args) throws Exception { FileReader in = new FileReader(""F:\\download\\C-small-attempt0.in""); BufferedReader br = new BufferedReader(in); FileWriter out = new FileWriter(""F:\\download\\out.txt""); BufferedWriter bw = new BufferedWriter(out); int t = Integer.parseInt(br.readLine()); for (int c = 0; c < t; c++){ String line = br.readLine(); StringTokenizer aSt = new StringTokenizer(line, "" ""); int a = Integer.valueOf(aSt.nextToken()).intValue(); int b = Integer.valueOf(aSt.nextToken()).intValue(); keta = (int)Math.log10(a) + 1; int pairs = 0; for (int n = a; n <= b; n++){ pairs += pairs(a, b, n); } bw.write(String.format(""Case #%d: %d\n"", c+1, pairs)); } br.close(); in.close(); bw.close(); out.close(); } public static int pairs(int a, int b, int num){ int numbers = 1; int[] stock = new int[keta]; stock[0] = num; for (int x = 1; x < keta; x++){ int recycle = (num % (int)Math.pow(10, keta - x)) * (int)Math.pow(10, x) + (int)(num / (int)Math.pow(10, keta - x)); if ((a <= recycle)&&(recycle <= b)){ if (recycle < num) return 0; boolean flag = false; for (int st = 0; st < numbers; st++){ if (stock[st] == recycle) flag = true; } if (!flag){ stock[numbers] = recycle; numbers ++; } } } return numbers * (numbers - 1) / 2; } } " B10582,"package codeJam; import java.util.ArrayList; import utilities.FileReadWrite; public class RecycledNumbers { public static ArrayList myDic; public static void main(String[] args) { FileReadWrite myFile = new FileReadWrite(); String outputString =""""; ArrayList lines = myFile.readFile(); int N = Integer.parseInt(lines.get(0)); int A, B, counter; for (int i = 1; i < lines.size(); i++) { counter=0; String[] w= lines.get(i).split("" ""); A = Integer.parseInt(w[0]); B = Integer.parseInt(w[1]); System.out.println(""A=""+A+"" B=""+B); String tempLine = ""Case #""+(i)+"": ""; myDic = new ArrayList(); for (int j = A; j <= B; j++) { if(!RecycledNumbers.hasSameDigits(j)) { int[] h = RecycledNumbers.getOtherNumbers(j); for (int k = 0; k < h.length; k++) { if(h[k]<=B && h[k]>=A && j1) { int c = 0; int d = 0; for (int i = 1; i < str.length(); i++) { if(str.charAt(i)=='0') c++; if(str.charAt(i)==str.charAt(0)) d++; } if(c==str.length()-1) { return true; } else { if(d==str.length()-1) return true; else return false; } } return true; } public static int[] getOtherNumbers (int x) { // System.out.println(""x=""+x); // System.out.println(); String str = Integer.toString(x); int length = str.length(); int[] y = new int[length-1]; int counter = 0; String temp1, temp2, temp3; for (int i = 0; i < str.length(); i++) { counter = i+1; // System.out.println(""counter=""+counter); if(counter==str.length()) continue; temp1 = str.substring(counter); // System.out.println(""temp1=""+temp1); temp2 = str.substring(0, counter); // System.out.println(""temp2=""+temp2); temp3 = temp1 + temp2; // System.out.println(""temp3=""+temp3); if(temp3.charAt(0)=='0') temp3=RecycledNumbers.excludeLeadingzeros(temp3); y[i]=Integer.parseInt(temp3); } return y; } public static String excludeLeadingzeros (String str) { for (int i = 0; i < str.length(); i++) if(str.charAt(i)!='0') { str = str.substring(i); break; } return str; } public static boolean exist (int[] g) { for (int i = 0; i < myDic.size(); i++) { int[] j = myDic.get(i); if(j[0]==g[0] && j[1]==g[1]) return true; } return false; } } " B10060,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package googlejam; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; /** * * @author AEK */ public class Problem_C_small { public static void main(String[] args)throws IOException { BufferedReader reader = new BufferedReader(new FileReader(""C-small-attempt0.in"")); FileWriter writer = new FileWriter(""C-small-output0""); int amount_of_test_case = Integer.parseInt(reader.readLine()); for(int test_case = 1;test_case <= amount_of_test_case;test_case++) { Scanner parser = new Scanner(reader.readLine()); int A = Integer.parseInt(parser.next()); int B = Integer.parseInt(parser.next()); int count = 0; for(Integer n = A;n < B;n++) { String outer = n.toString(); int length = outer.length(); for(int begin = 0;begin < outer.length();begin++) { String substring = outer.substring(begin) + outer; substring = substring.substring(0, length); Integer m = Integer.parseInt(substring); //Integer m = Integer.parseInt(outer.substring(begin) + outer.substring(0, begin)); if(A <= n && n < m && m <= B) { count+=1; } }// end inner loop }// end outer loop //System.out.println(count); writer.write(""Case #"" + test_case + "": "" + count + ""\n""); } reader.close(); writer.close(); }// end function } " B11550," import java.io.*; import java.math.*; import java.util.Arrays; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) { try{ FileWriter fw = new FileWriter(""C:\\Users\\Razvan\\Documents\\NetBeansProjects\\Google Code Jam\\src\\Out.out""); Scanner input = new Scanner(new File(""C:\\Users\\Razvan\\Documents\\NetBeansProjects\\Google Code Jam\\src\\C-small-attempt0.in"")); PrintWriter outfile; outfile = new PrintWriter(fw); int runs = input.nextInt(); for (int i = 1; i <= runs; i++) { int a = input.nextInt(); int b = input.nextInt(); int count = 0; // int y = a + 1; for (int x = a; x <= b; x++) { int[] hi = null; if (x >= 100 && x <= 999) { hi = method_threedigit(x); } if (x >= 10 && x <= 99) { int num1 = x % 10; int num2 = (int) (x / 10); hi = method_twodigit(num2, num1); } if (x > 0 && x < 10) { count = 0; } else { Arrays.sort(hi); for (int k = 0; k < hi.length; k++) { if (hi[k] > x && hi[k] <= b) { if (hi[k] > hi[k - 1]) { //get rid of repeat... count++; } } } } } outfile.println(""Case #"" + i + "": "" + count); } input.close(); fw.close(); outfile.close(); }catch (Exception e){ System.out.println(e); } } static int[] method_threedigit(int b) { int[] a = new int[6]; a[0] = (b % 10) * 100 + (int) (b / 10); a[1] = (b % 100) * 10 + (int) (b / 100); return a; } static int[] method_twodigit(int a1, int a2) { int a[] = new int[2]; a[0] = a1 * 10 + a2; a[1] = a2 * 10 + a1; return a; } }" B12163,"import java.util.*; import java.io.*; import static java.lang.Math.*; public class C { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(""C-small-attempt1.in"")); FileWriter fw = new FileWriter(""C-small.out""); /*BufferedReader in = new BufferedReader(new FileReader(""C-large.in"")); FileWriter fw = new FileWriter(""C-large.out"");*/ StringTokenizer stn = new StringTokenizer(in.readLine()); int N = new Integer(stn.nextToken()); for(int i=0;i all = new Vector(); String num = """"+j; for(int x=num.length()-2;x>=0;x--){ String poss = num.substring(x+1,num.length())+num.substring(0,x+1); int val = Integer.parseInt(poss); if (val <= B && val > j) { //if (val <= B && val >= A) { /*Boolean found = true; char first = poss.charAt(0); for(int z=1;z map = new HashMap(); int a = parseInt(ss[0]); int b = parseInt(ss[1]); for(int n=a;n<=b;n++) { String s = go(n); if(map.containsKey(s)) { map.put(s,map.get(s)+1); } else { map.put(s,1); } } long ans = 0; for(int x : map.values()) { ans += (long)x*(x-1)/2; } // out.println(map); out.println(""Case #""+z+"": ""+ans); } } static int p[] = {0, 1,10,100,1000,10000,100000,1000000,10000000}; static String go(int n) { int c = 0; int x = n; while(x > 0) { x /= 10; c++; } int max = 0; for(int i=0;i map = new HashMap(); public static void main(String[] args) throws IOException { // new Thread(new Solution()).start(); RecycleNum sol = new RecycleNum(); sol.start(); } public RecycleNum() { } public void start() throws IOException { BufferedReader br = new BufferedReader(new FileReader(""C-small-attempt0.in"")); BufferedWriter wStream=new BufferedWriter( new FileWriter(""C-small_attempt0.out"")); String input; StringTokenizer st=null; int T=0; if((input=br.readLine()) != null) { st=new StringTokenizer(input); T=Integer.parseInt(st.nextToken()); } for(int i=0;ii && res<= b){ cont++; } } return cont; } public static void main(String[] args){ int n,a,b,cont=0; try { System.setIn(new FileInputStream(""file.in"")); } catch (FileNotFoundException ex) { Logger.getLogger(CodejamC.class.getName()).log(Level.SEVERE, null, ex); } Scanner reader=new Scanner(System.in); n=reader.nextInt(); for(int i=0;i set = new HashSet(); int b = a,c; String s = a+""""; int len =s.length()-1; for(int i = 0 ; i <= len ; i++ ){ c = (int) (b/10 + b%10* Math.pow(10, len)); if(c > a && c <= lim){ set.add(c); } b = c; } return set.size(); } } " B10013,"import java.util.*; import java.io.*; public class C { public static void main(String[] args) throws Exception { String inputfilename = args[0]; String outputfilename = args[1]; BufferedReader br = new BufferedReader(new FileReader(inputfilename)); BufferedWriter bw = new BufferedWriter(new FileWriter(outputfilename)); int cases = Integer.valueOf(br.readLine()); for(int i = 0; i < cases; i++) { String[] ele = br.readLine().split("" ""); int A = Integer.valueOf(ele[0]); int B = Integer.valueOf(ele[1]); int result = C.solve(A,B); bw.write(""Case #"" + (i + 1) + "": "" + result + ""\n""); } br.close(); bw.close(); } public static int solve(int A,int B) { int cnt = 0; //System.out.println(""\nDoing "" + A + "" "" + B); String Astr = String.valueOf(A); String Bstr = String.valueOf(B); for(int cur = A; cur <= B; cur++) { String cstr = String.valueOf(cur); //System.out.println(""\n"" + cstr + ""\n""); Set tset = new HashSet(); for(int i = 1; i < cstr.length(); i++) { String tmp = cstr.substring(i) + cstr.substring(0,i); //System.out.println("" "" + tmp); if(tmp.compareTo(cstr) > 0 && tmp.compareTo(Bstr) <= 0 && !tset.contains(tmp)) { cnt++; tset.add(tmp); //System.out.print("" "" + cstr + ""!!"" +tmp); } } } return cnt; } }" B10717,"import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.HashSet; import java.util.Set; public class Recycled { public static void main(String [] args) throws NumberFormatException, IOException { BufferedReader in = new BufferedReader(new StringReader(args[0])); int rows = Integer.parseInt(in.readLine()); for ( int i = 1; i <= rows; i++) { String line = in.readLine(); String [] tokens = line.split("" ""); int low = Integer.parseInt(tokens[0]); int high = Integer.parseInt(tokens[1]); int count = 0; Set used = new HashSet(); for ( int j = low; j <= high; j++ ) { String str = Integer.toString(j); //System.out.println(""Original: "" + str); for ( int k = 0; k < str.length()-1; k++ ) { String newStr = str.substring(k+1) + str.substring(0,k+1); int newInt = Integer.parseInt(newStr); if ( Integer.toString(j).length() == Integer.toString(newInt).length() && newInt<=high && !used.contains(j+"",""+newInt) && !used.contains(newInt+"",""+j) && j < newInt ) { count++; used.add(j+"",""+newInt); } } } System.out.println(""Case #""+i+"": "" + count); //System.out.println(used); } } } " B12434,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; public class RecycledPairs { static String line=""Code Jam""; static int noOfTCs; static long lowerLimit,upperLimit; static ArrayList pairs = new ArrayList(); public static void main(String[] args) { //initialize(); calculate(); //generateOPFile(); } private static void calculate() { try { BufferedReader br = new BufferedReader(new FileReader(""C:/CodeJam/C-small-attempt2.in"")); FileWriter fw = new FileWriter(""C:/CodeJam/output.txt""); BufferedWriter bw = new BufferedWriter(fw); line = br.readLine().trim(); noOfTCs = Integer.parseInt(line); for(int testCase=0;testCase= awal && temp <= akir && temp > j) { count++; } } else if(temp<1000){ for(int k = 0; k<2; k++){ int a = temp%10; temp = temp/10; temp += a*100; if(temp >= awal && temp <= akir && temp > j) { count++; } else if (temp == j) break; } } else if(temp < 10000){ for(int k = 0; k<3; k++){ int a = temp%10; temp = temp/10; temp += a*1000; if(temp >= awal && temp <= akir && temp > j) { count++; } else if (temp == j) break; } } } System.out.println(""Case #""+(i+1)+"": ""+count); } } } " B10949,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class Q3 { public static Problem[] probs; static class Problem { public int A; public int B; } public static void main(String[] args) { long time = System.currentTimeMillis(); String inputFile = args[0]; parseFile(inputFile); try { BufferedWriter bw = new BufferedWriter(new FileWriter(inputFile + "".out"")); for (int i=0; in && testM<=p.B) { pairs++; } shiftNum++; testM = shift(n, shiftNum); } } return """" + pairs; } public static void parseFile(String inputFile) { BufferedReader br; try { br = new BufferedReader(new FileReader(inputFile)); String line = br.readLine(); probs = new Problem[Integer.parseInt(line)]; line = br.readLine(); for (int i=0; i parseInts(List strings) { ArrayList list = new ArrayList(); for (String s : strings) { list.add(Integer.valueOf(s)); } return list; } } " B11721,"import java.io.*; import java.util.*; class recycledNumbers{ public static void main(String arg[]){ System.out.println(""Please Enter the name of your file""); Scanner input = new Scanner(System.in); String fileName = input.next(); recycle(fileName); } public static void recycle(String fileName){ try{ BufferedReader br = new BufferedReader(new FileReader(fileName)); BufferedWriter bw = new BufferedWriter(new FileWriter(""recycle.out"")); int numCases = Integer.parseInt(br.readLine()); int A=0; int B=0; String line=""""; for(int i=0; iA) && (combined<=B)){ temp = combined; verified++; } } return verified; } }" B13215,"import java.io.*; import java.util.*; public class RecycledNumbers { static LinkedList seen = new LinkedList(); static int min, max; static int count; public static void main (String[] args) throws IOException { Scanner in = new Scanner(new File(""C-small.txt"")); int cases; cases = in.nextInt(); for (int n = 0; n < cases; n++) { seen = new LinkedList(); min = in.nextInt(); max = in.nextInt(); count = 0; for (int i = min; i < max; i++) { findPairs(i); } System.out.println(""Case #"" + (n+1) + "": "" + count); } } public static void findPairs(int num) { String n = """" + num; int result; for (int i = 1; i < n.length(); i++) { result = Integer.parseInt(n.substring(i) + n.substring(0, i)); if (result > num && result <= max && !(seen.contains(n + "" "" + result))) { count ++; seen.add(n + "" "" + result); } } } }" B12541,"package CJ2; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.LinkedList; import java.util.StringTokenizer; public class Recycle { static LinkedList> db2 = new LinkedList>(); public static void main(String [] args){ BufferedReader br = null; String line=""""; if(args.length != 1){ System.out.println(""please input test file name as a command line argument""); System.exit(0); } try{ br = new BufferedReader(new FileReader(args[0])); line = br.readLine(); } catch (IOException e) { e.printStackTrace(); } int numOfTests = Integer.parseInt(line); BufferedWriter bw = null; try{ FileWriter fw = new FileWriter(""resultsM.txt""); bw = new BufferedWriter(fw); }catch(IOException e){ e.printStackTrace(); } for(int i = 0; i < numOfTests ; i++){ try{ line = br.readLine(); bw.write(""Case #""+(i+1)+"": ""); bw.flush(); bw.write(String.valueOf(checkPairs(line))); bw.flush(); bw.newLine(); bw.flush(); }catch(IOException e){ e.printStackTrace(); } } } public static int checkPairs(String input){ StringTokenizer tok = new StringTokenizer(input); int minRange = Integer.parseInt(tok.nextToken()); int maxRange = Integer.parseInt(tok.nextToken()); int digits=0; int tmp = minRange; while(tmp!=0){ tmp/=10; digits+=1; } db2 = new LinkedList>(); int counter = 0; for(int i = minRange ; i <= maxRange ; i++){ for(int j = 1; j < digits ; j++){ tmp = rotate(i,j,digits); if(tmp <= maxRange && tmp >= minRange && tmp != i){ if(checkExists2(i,tmp)) counter++; } } } return counter; } public static int rotate(int toRotate, int times, int length){ String rotation = String.valueOf(toRotate); for(int i=0;i pair = new LinkedList(); if(base > rotated){ pair.add(rotated); pair.add(base); }else{ pair.add(base); pair.add(rotated); } if(db2.contains(pair)){ return false; }else{ db2.add(pair); return true; } } } " B11455,"import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.Scanner; public class C { public static int factorial(int x) { int fact = 1; for (int i = 2; i <= x; i++) { fact *= i; } return fact; } /** * @param args */ public static void main(String[] args) { Scanner s = new Scanner(System.in); // Scanner s = null; // try { // s = new Scanner(new FileInputStream(""s.in"")); // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } int lines = s.nextInt(); for (int i = 1 ; i <= lines ;i++){ int A = s.nextInt(); int B = s.nextInt(); HashSet h = new HashSet(); for (int j = A;j<=B;j++){ h.add(j); } int comb = 0; for (int j = A;j<=B;j++){ if (!h.remove(j)){ continue; } int len = (int)Math.log10(j); int c = 1; int newj = j; for (int k = 0; k < len;k++){ newj = newj/10 + (newj % 10)*((int)Math.pow(10, len)); if (h.remove(newj)){ c++; } } if (c !=1){ comb += factorial(c)/(factorial(c-2)*2); } } System.out.printf(""Case #%d: %d\n"",i,comb); } } } " B12708,"import java.io.FileNotFoundException; import java.io.FileReader; import java.util.HashSet; import java.util.Iterator; import java.util.Scanner; public class RecycledNumbers { public static int recycle(int source, int digits) { int pow = (int) Math.pow(10, digits - 1); int mod = source % 10; return pow * mod + source / 10; } public static class Range { public final int A; public final int B; public Range(int A, int B) { this.A = A; this.B = B; } } public static Iterator iterator(Readable input) { final Scanner scanner = new Scanner(input); return new Iterator() { private int cases = scanner.nextInt(); @Override public boolean hasNext() { return cases > 0; } @Override public Range next() { int A = scanner.nextInt(); int B = scanner.nextInt(); cases--; return new Range(A, B); } @Override public void remove() { throw new AbstractMethodError(); } }; } public static int recycledPairs(Range scores) { int digits = Integer.toString(scores.A).length(); HashSet pairs = new HashSet(); for (int i = scores.A; i <= scores.B; i++) { int recycled = recycle(i, digits); while (recycled != i) { if (recycled >= scores.A && recycled <= scores.B) { int first = i < recycled ? i : recycled; int second = i > recycled ? i : recycled; pairs.add(String.format(""%d%d"", first, second)); } recycled = recycle(recycled, digits); } } return pairs.size(); } public static void main(String[] args) throws FileNotFoundException { FileReader fileReader = new FileReader(args[0]); int caseId = 1; Iterator iterator = iterator(fileReader); while (iterator.hasNext()) { int result = recycledPairs(iterator.next()); System.out.format(""Case #%s: %s\n"", caseId, result); caseId++; } } } " B13027,"import java.io.*; class qu3{ public static void main(String arg[])throws Exception { File f=new File(""/Users/rishabhsonthalia/Downloads/C-small-attempt0.in.txt""); FileInputStream fin=new FileInputStream(f); File fo=new File(""opt.txt""); FileOutputStream fout=new FileOutputStream(fo); BufferedWriter bwr=new BufferedWriter(new OutputStreamWriter(fout)); BufferedReader br=new BufferedReader(new InputStreamReader(fin)); String g=""""; long len=Long.parseLong(br.readLine()); long ca=1; long a,b; String e=""""; long n,m; while(--len >=0) { long count=0; g=br.readLine(); a=Long.parseLong(g.substring(0,g.indexOf("" "")) ); b=Long.parseLong( g.substring(g.indexOf("" "")+1,g.length())) ; for(long i=a;i<=b;i++) { n=i; for(long j=0 ; j<(i+"""").length()-1; j++) { m=shift(n); if(m>-1 & i vis=new HashSet(); for(int j=0;j=a&&n<=b){ if(vis.contains(n)){ continue; } vis.add(n); res++; } } } System.out.printf(""Case #%d: %d\n"", tt,res); } } }" B10515,"import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class GCIFileReader { public GCIFileReader(File file) throws FileNotFoundException { mBufferedReader = new BufferedReader(new FileReader(file)); mFile = file; } public String getLine() { try { String s = mBufferedReader.readLine(); if (s == null) { mBufferedReader.close(); } return s; } catch (IOException e) { return null; } } public void reset () throws IOException { mBufferedReader.close(); mBufferedReader = new BufferedReader(new FileReader(mFile)); } private BufferedReader mBufferedReader; private File mFile; }" B12667,"import java.util.*; public class C { static int[] ten; static { ten = new int[10]; ten[0] = 1; for (int i = 1; i < ten.length; ++i) { ten[i] = ten[i - 1] * 10; } } static int max(int x) { int n = 0; while (ten[n + 1] <= x) { ++n; } int y = x; for (int i = 0; i < n; ++i) { x = x / 10 + x % 10 * ten[n]; y = Math.max(x, y); } return y; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int re = in.nextInt(); int[] c = new int[10000000]; for (int ri = 1; ri <= re; ++ri) { int a = in.nextInt(); int b = in.nextInt(); Arrays.fill(c, 0); for (int i = a; i <= b; ++i) { ++c[max(i)]; } long s = 0; for (int i: c) { s += i * (i - 1) / 2; } System.out.println(""Case #"" + ri + "": "" + s); } } } " B10645,"import java.util.Collection; import java.util.ArrayList; import java.util.Arrays; import java.lang.Integer; import java.io.*; import java.util.Scanner; public class RecycledNumbers{ private long inversions = 0; public static void main(String[] args) throws FileNotFoundException{ String filename = args[0]; RecycledNumbers countInversions = new RecycledNumbers(); countInversions.readArray(filename); // list = countInversions.sortAndCount(list); // System.out.println(list); // System.out.println(countInversions.inversions); } private void readArray( String filename ) throws FileNotFoundException{ ArrayList list = new ArrayList(); File fFile = new File(filename); Scanner scanner = new Scanner(new FileReader(fFile)); try { BufferedWriter out = new BufferedWriter(new FileWriter(""outfilename"")); int k = Integer.valueOf(scanner.nextLine()); for (int j=1; j<=k; ++j){ String szoveg = scanner.nextLine(); Object[] szamok =szoveg.split(""[^0-9]""); int A = Integer.valueOf((String)szamok[0]); int B = Integer.valueOf((String)szamok[1]); String mashogy = new String(); mashogy = mashogy.concat(""Case #""); mashogy = mashogy.concat(((Integer)j).toString()); mashogy = mashogy.concat("": ""); int s=0; for (int i=A; i elerh = new ArrayList(); for (int f=1; fi && ford<=B && !elerh.contains(ford)){ // System.out.println(pow+"" ""+ael+"" ""+aveg+"" ""+ford); elerh.add(ford); s++; } } } // String mashogy = (String)(szoveg.clone()); // System.out.println(szoveg); mashogy = mashogy.concat(((Integer)s).toString()); mashogy = mashogy.concat(""\n""); out.write(mashogy); } out.close(); } catch (IOException e) { } scanner.close(); return; } } " B12894,"import java.util.Scanner; public class RecycledNumbers { public static void main(String[] argv) { int lineCount,counter,mHold; int n,m,recycledNumbers; Scanner input = null; try { input = new Scanner(System.in); } catch (Exception e) { System.err.println(""FileNotFoundException: "" + e.getMessage()); } lineCount = input.nextInt(); for (counter = 0; counter < lineCount; counter++) { recycledNumbers = 0; input.nextLine(); n = input.nextInt(); mHold = input.nextInt(); m = mHold; for (; n < m; n++) { for (; m > n; m--) { if (Integer.toString(n).length() == Integer.toString(m).length()) { if (checkRecycled(n,m)) recycledNumbers++; } } m = mHold; } System.out.printf(""Case #%d: %d\n"",counter+1,recycledNumbers); } } public static boolean checkRecycled(int n, int m) { int check,cursor; String toCheck; String holder = Integer.toString(n); for (cursor = holder.length() - 1; cursor > 0; cursor--) { toCheck = """"; toCheck += holder.substring(cursor,holder.length()); toCheck += holder.substring(0,cursor); check = Integer.valueOf(toCheck); if (check == m) return true; } return false; } } " B12564,"import java.util.Scanner; public class CodeC{ public static void main(String[] args){ Scanner sc=new Scanner(System.in); int tcase; int a, b; int numDigit; int num; tcase=sc.nextInt(); for(int q=1;q<=tcase;q++){ a=sc.nextInt(); b=sc.nextInt(); num=0; for(int i=a;i<=b;i++){ numDigit=(i+"""").length(); int j=i+1; int limit=10*j; if(limit>b){ limit=b; } //System.out.println(""DIGIT ""+numDigit+"" LIMIT ""+j+"" - ""+limit); for(;j<=limit;j++){ String bil=i+""""; for(int k=0;k pairs = new HashSet(); for(int x = A; x<=B; x++) { String n = String.valueOf(x); int digits = n.length(); if(digits > 1) { for(int p = 1; p < digits; p++) { String m = n.substring(n.length()-p)+n.substring(0,n.length()-p); int mN = Integer.parseInt(m); if(m.startsWith(""0"") || !(mN >= A && mN <=B)){ continue; } else { if(x < mN){ pairs.add(""(""+n+"",""+m+"")""); } } } } } System.out.println(""Case #""+i+"": ""+pairs.size()); out.write(""Case #""+i+"": ""+pairs.size()); out.newLine(); } out.flush(); out.close(); in.close(); } } " B11383,"import java.io.IOException; import java.util.ArrayList; import java.util.BitSet; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class Main { /** * @param args */ // public static void main(String[] args) // { // try // { // Map m = new HashMap(); // start_googlerese(""ejp mysljylc kd kxveddknmc re jsicpdrysi"",""our language is impossible to understand"",m); // start_googlerese(""rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd"",""there are twenty six factorial possibilities"",m); // start_googlerese(""de kr kd eoya kw aej tysr re ujdr lkgc jv"",""so it is okay if you want to just give up"",m); // // m.put('z','q'); // m.put('q','z'); // // int a=0; // a= a+1; // // char letter; // for (letter='a'; letter <= 'z'; letter++) // { // if(m.containsKey(letter)) // System.out.println(letter+"" ""+m.get(letter)); // else // System.out.println(letter+"" ""+""!!!""); // } // // googlerese(m); // // } // catch (IOException e) // { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } public static void main(String[] args) { try { recycled(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void recycled() throws IOException { ArrayList input = Tools.getInput(""C:\\Users\\Yannick\\Dropbox\\GCJ_JAVA\\Q_2012\\C-small.in""); ArrayList output = new ArrayList(); int num_cases = Integer.parseInt(input.get(0)[0]); Set done = new HashSet(); //!!!!!!!!!!!!!!!!!!! num_cases for (int i=0;i ms = new HashSet(length-1); for (int n=lower;n<=upper;n++) { int m=n; ms.clear(); for(int j=0;jn && m<=upper && !ms.contains(m)) { System.out.println(n+"" ""+m); result++; ms.add(m); } } } StringBuilder sbO = new StringBuilder(); sbO.append(""Case #""+(i+1)+"": ""); sbO.append(result); output.add(sbO.toString()); } Tools.saveOutputSingle(""C:\\Users\\Yannick\\Dropbox\\GCJ_JAVA\\Q_2012\\C-small.out"", output); } public static void start_googlerese(String input, String output, Map m) throws IOException { if(input.length()!=output.length()) throw new IOException(); for(int i=0;i m) throws IOException { ArrayList input = Tools.getInputSingle(""C:\\Users\\Yannick\\Dropbox\\GCJ_JAVA\\Q_2012\\A-small.in""); ArrayList output = new ArrayList(); int num_cases = Integer.parseInt(input.get(0)); for (int i=0;i input = Tools.getInput(""D:\\Documents\\Dropbox\\GCJ_JAVA\\1A_2008\\A-large-practice.in""); ArrayList output = new ArrayList(); int T = Integer.parseInt(input.get(0)[0]); for (int i=0;i vectorA = new ArrayList(); ArrayList vectorB = new ArrayList(); for(int j=0;j input = Tools.getInput(""C:\\Users\\Yannick\\Dropbox\\GCJ_JAVA\\Q_2012\\B-small.in""); ArrayList output = new ArrayList(); int num_cases = Integer.parseInt(input.get(0)[0]); for (int i=1;i<=num_cases;i++) { int result=0; int N=Integer.parseInt(input.get(i)[0]); int S=Integer.parseInt(input.get(i)[1]); int p=Integer.parseInt(input.get(i)[2]); int a,b,c; for(int j=0;j=p || b>=p || c>=p ) result++; else { if(S>0 && ( (a==b && a==p-1 && a>0) || (a==c && a==p-1 && a>0) || (b==c && b==p-1 && b>0) ) ) { S--; result++; } } } StringBuilder sbO = new StringBuilder(); sbO.append(""Case #""+(i)+"": ""); sbO.append(result); output.add(sbO.toString()); } Tools.saveOutputSingle(""C:\\Users\\Yannick\\Dropbox\\GCJ_JAVA\\Q_2012\\B-small.out"", output); } } " B11541,"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 intProperties; private Map> intArrayProperties; private Map>> intArray2DProperties; private Map doubleProperties; private Map> doubleArrayProperties; private Map>> doubleArray2DProperties; private Map stringProperties; private Map> stringArrayProperties; private Map>> stringArray2DProperties; private Map booleanProperties; private Map> booleanArrayProperties; private Map>> booleanArray2DProperties; private Map longProperties; private Map> longArrayProperties; private Map>> 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 l) { intArrayProperties.put(s, l); } public void setIntegerMatrix(String s, ArrayList> l) { intArray2DProperties.put(s, l); } public ArrayList getIntegerList(String s) { return intArrayProperties.get(s); } public Integer getIntegerListItem(String s, int i) { return intArrayProperties.get(s).get(i); } public ArrayList> getIntegerMatrix(String s) { return intArray2DProperties.get(s); } public ArrayList 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 getIntegerMatrixColumn(String s, int column) { ArrayList out = new ArrayList(); for(ArrayList 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 l) { doubleArrayProperties.put(s, l); } public void setDoubleMatrix(String s, ArrayList> l) { doubleArray2DProperties.put(s, l); } public ArrayList getDoubleList(String s) { return doubleArrayProperties.get(s); } public Double getDoubleListItem(String s, int i) { return doubleArrayProperties.get(s).get(i); } public ArrayList> getDoubleMatrix(String s) { return doubleArray2DProperties.get(s); } public ArrayList 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 getDoubleMatrixColumn(String s, int column) { ArrayList out = new ArrayList(); for(ArrayList 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 l) { stringArrayProperties.put(s, l); } public void setStringMatrix(String s, ArrayList> l) { stringArray2DProperties.put(s, l); } public ArrayList getStringList(String s) { return stringArrayProperties.get(s); } public String getStringListItem(String s, int i) { return stringArrayProperties.get(s).get(i); } public ArrayList> getStringMatrix(String s) { return stringArray2DProperties.get(s); } public ArrayList 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 getStringMatrixColumn(String s, int column) { ArrayList out = new ArrayList(); for(ArrayList 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 l) { booleanArrayProperties.put(s, l); } public void setBooleanMatrix(String s, ArrayList> l) { booleanArray2DProperties.put(s, l); } public ArrayList getBooleanList(String s) { return booleanArrayProperties.get(s); } public Boolean getBooleanListItem(String s, int i) { return booleanArrayProperties.get(s).get(i); } public ArrayList> getBooleanMatrix(String s) { return booleanArray2DProperties.get(s); } public ArrayList 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 getBooleanMatrixColumn(String s, int column) { ArrayList out = new ArrayList(); for(ArrayList 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 l) { longArrayProperties.put(s, l); } public void setLongMatrix(String s, ArrayList> l) { longArray2DProperties.put(s, l); } public ArrayList getLongList(String s) { return longArrayProperties.get(s); } public Long getLongListItem(String s, int i) { return longArrayProperties.get(s).get(i); } public ArrayList> getLongMatrix(String s) { return longArray2DProperties.get(s); } public ArrayList 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 getLongMatrixColumn(String s, int column) { ArrayList out = new ArrayList(); for(ArrayList row : longArray2DProperties.get(s)) { out.add(row.get(column)); } return out; } } " B10490,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; public class RecycledNumbers { static HashSet set = new HashSet(); public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new FileReader(""small-C.in"")); BufferedWriter out = new BufferedWriter(new FileWriter(""small-C.out"")); int n = Integer.parseInt(br.readLine()); for(int i = 1; i <= n; i++){ set.clear(); int total = 0; String [] temp = br.readLine().split("" ""); int a = Integer.parseInt(temp[0]); int b = Integer.parseInt(temp[1]); for(int j = a; j < b; j++) total += check(j, a, b, temp[0], temp[1]); out.write(""Case #"" + i + "": "" + set.size()); if(i < n) out.write(""\n""); } System.out.println(set.size()); br.close(); out.close(); } private static int check(int n, int a, int b, String astr, String bstr) { int num = 0; String temp = n + """"; for(int len = 1; len < astr.length(); len++){ String one = temp.substring(0, len); String two = temp.substring(len); int temp2 = Integer.parseInt(two + one); if(temp2 > n && temp2 <= b){ num++; if(set.contains(n + "" "" + temp2)) System.out.println(""Contained *********************************************************\n*****\n***""); else{ set.add(n + "" "" + temp2); } //System.out.println(one + "" "" + two + "" --> "" + two + "" "" + one + "" len = "" + len); } } if(num > 0) System.out.println(); return num; } } " B12233,"import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers{ public static void main(String[] args) throws IOException { BufferedReader br = null; try { br = new BufferedReader(new FileReader(""C-small-attempt0.in"")); PrintStream out = new PrintStream(new File(""C-Small.out"")); int testcases = Integer.parseInt(br.readLine()); for (int casenr = 1; casenr <= testcases; casenr++) { String line = br.readLine(); Scanner scanner= new Scanner(line); int min = scanner.nextInt(); int max = scanner.nextInt(); HashSet recycledPairs = new HashSet (); for (int i = min ;i<= max ;i++){ String numberString = String.valueOf(i); int strLen = numberString.length(); if (strLen <= 1) continue; for (int j = 0 ;j< strLen;j++){ char firstChar= numberString.charAt(0); numberString = numberString.substring(1).concat(String.valueOf(firstChar)); int newNumber= Integer.parseInt(numberString); if ( (newNumber > i) && newNumber >= min && newNumber <= max ){ String pair = String.valueOf(i)+"",""+String.valueOf(newNumber); recycledPairs.add(pair); } } } System.out.printf(""Case #%d: %d\n"", casenr, recycledPairs.size()); out.printf(""Case #%d: %s\n"", casenr, recycledPairs.size()); } } catch(FileNotFoundException fe) { fe.printStackTrace(); } catch(IOException ie) { ie.printStackTrace(); } finally { try { if(br != null) { br.close(); } } catch (IOException ex) { ex.printStackTrace(); } } } } " B10819,"import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.util.HashSet; import java.util.Set; public class main { /** * @param args */ @SuppressWarnings(""deprecation"") public static void main(String[] args) { long now = System.currentTimeMillis(); // TODO Auto-generated method stub File file = new File(""./input.txt""); FileInputStream fis = null; BufferedInputStream bis = null; DataInputStream dis = null; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); dis = new DataInputStream(bis); int testCaseCount = Integer.parseInt(dis.readLine()), testCase; for(testCase = 0; testCase < testCaseCount; testCase ++) { String[] line = dis.readLine().split("" ""); int A = Integer.parseInt(line[0]), B = Integer.parseInt(line[1]), found = 0, n, m, k; String N, M; Set used = new HashSet(); for(n = A; n <= B; n ++) { N = n + """"; for(k = 1; k < N.length(); k ++) { M = N.substring(k, N.length()) + N.substring(0, k); M = M.replaceAll(""^0+"", """"); m = Integer.parseInt(M); if(m > n && m <= B && ! used.contains(N+M)) { found ++; used.add(N+M); } } } System.out.println(""Case #"" + (testCase + 1) + "": "" + found); } fis.close(); bis.close(); dis.close(); } catch(Exception e) { e.printStackTrace(); } } } " B10745,"package net.nickball.gcj.qual.recyclednumbers; import java.io.*; import java.util.HashSet; import java.util.Set; import org.apache.commons.lang3.StringUtils; /** * * @author nick */ public class RecycledNumbers { /** * @param args the command line arguments */ public static void main(String[] args) { BufferedReader reader = null; try { if(args.length != 2) throw new IllegalArgumentException(""Usage: RecycledNumbers ""); File inputFile = new File(args[0]); if (! inputFile.exists()) throw new FileNotFoundException(""File not found! File: ""+ args[0]); reader = new BufferedReader(new FileReader(inputFile)); String cases = reader.readLine(); String line; int caseCounter = 1; while((line = reader.readLine()) != null) { String[] parts = line.split("" ""); int A = Integer.parseInt(parts[0]); int B = Integer.parseInt(parts[1]); System.out.println(""Case #"" + caseCounter + "": "" + getRecycledPairs(A,B)); caseCounter++; } } catch(Exception e) { e.printStackTrace(); System.exit(255); } finally { try { if(reader != null) reader.close(); } catch(IOException e) { e.printStackTrace(); } } } private static long getRecycledPairs(int A, int B) { long count = 0; Set uniques = new HashSet(); for(int n = A; n <=B; n++) { String nStr = Integer.toString(n); for(int m = n+1; m <=B; m++) { String mStr = Integer.toString(m); if(mStr.length() > nStr.length()) break; for(int index = 1; index < nStr.length(); index++) { String start = new StringBuffer(nStr.substring(0,index)).reverse().toString(); String end = new StringBuffer(nStr.substring(index)).reverse().toString(); String rotated = StringUtils.stripStart(new StringBuffer(start).append(end).reverse().toString(),""0""); //System.out.println(start +"","" + end + "","" + rotated); if(rotated.equals(mStr) && (! uniques.contains(n + """" + m))) { //System.out.println(n + "","" + m); uniques.add(n + """" + m); count++; } } } } return count; } } " B10303,"package qual1; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.StringTokenizer; public class C { public static void main(String[] args) throws IOException { // Use BufferedReader rather than RandomAccessFile; it's much faster BufferedReader f = new BufferedReader(new FileReader(""C-small-attempt0.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""C-small-attempt0.out""))); int cases = Integer.parseInt(f.readLine()); for (int zz = 1; zz <= cases; zz++) { StringTokenizer st = new StringTokenizer(f.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); int[] list = new int[b-a+1]; for (int i=a; i<=b; i++) { list[i-a] = i; } HashMap> dump = new HashMap>(); long ans = 0; for (int i=a; i<=b; i++) { if (list[i-a]==0) continue; String x = i+""""; ArrayList xzc = new ArrayList(); for (int j=1; j=a && t2<=b) { if (list[t2-a]==0) { continue; } list[t2-a] = 0; xzc.add(t2); } } dump.put(i, xzc); } for (int key : dump.keySet()) { ArrayList xzc = dump.get(key); if (xzc.isEmpty()) continue; //Collections.sort(xzc); //System.out.println(key+"" : ""+xzc); if (xzc.size()==1) ans++; else ans+= ((xzc.size()+1)*(xzc.size())/2); } System.out.println(""Case #"" + zz + "": ""+ans); out.println(""Case #"" + zz + "": ""+ans); } out.close(); // close the output file System.exit(0); // don't omit this! } }" B11523," import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class Principal { public static void main (String Args[]){ boolean numeros[]= new boolean[2000000]; Scanner input = new Scanner(System.in); File saida = new File(""c:/saida.txt""); BufferedWriter bw; int A, B, T; String entrada; String a,b; String search; int tamanho_string, teste; int resposta=0, temp=0; String texto=""""; entrada=input.nextLine(); T= Integer.parseInt(entrada); for(int i=1;i<=T;i++){ a = input.next(); b = input.next(); A = Integer.parseInt(a); B = Integer.parseInt(b); for(int j=A; j<=B; j++){ if(numeros[j]){ continue; } numeros[j]=true; search = """"+j+j; tamanho_string= a.length(); for (int k=0;kj && teste <=B && !numeros[teste]){ numeros[teste]=true; temp++; } } for(;temp>0;temp--) resposta+=temp; temp=0; } texto=""Case #""+i+"": ""+resposta+""\n""; try { bw=new BufferedWriter(new FileWriter(saida, true)); bw.write(texto); bw.newLine(); bw.close(); } catch (IOException e) { e.printStackTrace(); } for(int asd=0;asd<2000000;asd++) numeros[asd]=false; temp=0; resposta=0; } } } " B11534,"package com.google.jam.eaque.stub; import java.io.IOException; public abstract class Stub { private String outputFileName; public String getOutputFileName() { return outputFileName; } public void setOutputFileName(String outputFileName) { this.outputFileName = outputFileName; } public abstract String runTestCase(InputFileManager ifm) throws NumberFormatException, IOException; } " B11292,"import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(); for (int x = 0; x < t; x++) { int a = scanner.nextInt(); int b = scanner.nextInt(); int y = RecycledNumbers.recycledCount(a, b); System.out.printf(""Case #%d: %d%n"", x + 1, y); } scanner.close(); } public static int recycledCount(int n1, int n2) { int recycled = 0; for (int x = n1; x <= n2; x++) { String s = String.valueOf(x); for (int i = 0; i < s.length() - 1; i++) { String s2 = s.substring(i + 1) + s.substring(0, i + 1); int x2 = Integer.parseInt(s2); if (x2 >= n1 && x2 <= n2 && x2 > x) { recycled++; } } } return recycled; } } " B10599,"import java.io.*; import java.util.Scanner; public class Main { public static void main (String[] args) { int i = 1; try{ BufferedReader in = new BufferedReader(new FileReader(""input.txt"")); String ligne; ligne = in.readLine(); ligne = in.readLine(); while (ligne != null) { int res = 0; System.out.print(""Case #"" + i + "": ""); Scanner sc = new Scanner(ligne); int A = sc.nextInt(); int B = sc.nextInt(); for (int m=A;m0 b>0 public static boolean recycle (int a, int b) { long nbDigitsA = Math.round(Math.ceil(Math.log10(a))); long nbDigitsB = Math.round(Math.ceil(Math.log10(b))); if (nbDigitsA != nbDigitsB || nbDigitsA == 1) { return false; } for (int i=1;i inputs = new ArrayList(); for (int i = 100; i < 120; i++) inputs.add(i); ParallelWorkQueue.CallableFactory callableFactory = new CallableFactory() { @Override public Callable newInstance(final Integer input) { return new Callable() { @Override public String call() throws Exception { Thread.sleep((int) (Math.random() * 4000)); System.out.println("" Input: "" + input); return ""***"" + (input + 1); } }; } }; try { for (Future result : new ParallelWorkQueue(4, inputs, callableFactory)) System.out.println(""Got : "" + result.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } } " B11997,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.HashSet; public class Num { /** * @param args */ public static void main(String[] args) { try { String fname = ""C-small-attempt0""; FileInputStream fstream = new FileInputStream(fname + "".in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; int numCase = 0; int i = 0; while ((strLine = br.readLine()) != null) { if (numCase == 0) numCase = Integer.valueOf(strLine); else if (strLine.length() > 0) runCase(strLine, ++i); } in.close(); } catch (Exception e) {// Catch exception if any e.printStackTrace(); } } static void runCase(String line, int caseNum) { String[] borders = line.split("" ""); int length = borders[0].length(); int a = Integer.valueOf(borders[0]); int b = Integer.valueOf(borders[1]); HashSet pairs = new HashSet(); for (int i = a; i <= b; i++) { for (int j = 1; j < length; j++) { int pos = (int) Math.pow(10, j); int pair = i / pos + (i % pos) * (int) Math.pow(10, length - j); if (pair >= a && pair <= b && pair != i) { if (i < pair) pairs.add(i + "","" + pair); else pairs.add(pair + "","" + i); } } } System.out.println(""Case #"" + caseNum + "": "" + pairs.size()); } } " B10936,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; public class qc { public static void main(String [] args) { String fileName = ""C-small-attempt0.in""; try{ FileReader fr = new FileReader(fileName); BufferedReader br = new BufferedReader(fr); FileWriter fw = new FileWriter(""output.txt""); BufferedWriter bw = new BufferedWriter(fw); String line=""""; int count = 0; int solution = 0; while((line=br.readLine())!=null) { if(count == 0) { count++; continue; } String [] sp = line.split("" ""); int [] range = new int[sp.length]; for(int i =0; i map = new HashMap(); for (int i = a; i <= b; i ++) { String key = """" + i; map.put(key, new DJ()); } for (int i = a; i <= b; i ++) { String s = """" + i; String t = move(s); while (true) { if (t.charAt(0)!='0') { DJ dj1 = map.get(s); DJ dj2 = map.get(t); if (dj2 != null && dj1 != null) merge(dj1, dj2); } t = move(t); if (s.equals(t)) break; } } int res = 0; for (Entry e: map.entrySet()) { DJ dj = e.getValue(); if (dj.count > 1) { res += dj.count * (dj.count-1) / 2; } } out.println(""Case #""+id+"": "" + res); } static String move(String s) { if (s.length() == 1) return s; char c = s.charAt(s.length()-1); return """" + c + s.substring(0, s.length()-1); } static DJ merge(DJ d1, DJ d2) { DJ p1 = d1.getP(); DJ p2 = d2.getP(); if (p1 != p2) { if (p1.rank == p2.rank) { p2.parent = p1; p1.rank ++; p1.count += p2.count; return p1; } else if (p1.rank > p2.rank) { p2.parent = p1; p1.count += p2.count; return p1; } else { p1.parent = p2; p2.count += p1.count; return p2; } } else { return p1; } } static class DJ { DJ parent = null; int rank = 0; int count = 1; DJ getP() { if (parent == null) { return this; } DJ p = parent.getP(); this.parent = p; return p; } } } " B13185,"import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.math.BigInteger; import java.util.Scanner; public class C { static String inner = ""input.in""; static Scanner scan; public static void main (String[]args) throws IOException { File f = new File (inner); File out = new File(""output.out""); FileWriter wr; wr = new FileWriter(out); scan = new Scanner(f); int test = scan.nextInt(); scan.nextLine(); for(int i = 0 ;i < test ; i++) wr.write( ""Case #""+ (i+1)+"": ""+testcase( new BigInteger(""""+scan.nextInt()) , new BigInteger(""""+scan.nextInt()) ) + ""\n""); wr.flush(); } public static int testcase (BigInteger A , BigInteger B) { int ret = 0; int len = A.toString().length(); for(BigInteger b = A ; b.compareTo(B) < 1 ;b= b.add(BigInteger.ONE) ) { String []ff = new String [len-1]; String s =b.toString(); for(int i = 1 ;i public static void main(String[] args) { // Iterate over a list: ArrayList list = new ArrayList(); list.add(""apple""); list.add(""banana""); list.add(""pear""); for (IndexedItem it : IndexedItem.iterate(list)) System.out.println(it.getIndex() + "": "" + it.getItem()); // Iterate over an array: String[] arr = new String[] {""a"", ""b"", ""c""}; for (IndexedItem it : IndexedItem.iterate(arr)) System.out.println(it.getIndex() + "": "" + it.getItem()); } * * @author (c) Luke Hutchison 2010. Covered under the BSD license. * * @param * The type of the Iterable. */ public class IndexedItem { private T item; private int index = -1; /** Get the current item in the iteration. */ public T getItem() { return item; } /** Get the index of the current item (zero-indexed). */ public int getIndex() { return index; } private static class IndexedIterator implements Iterable>, Iterator> { private final Iterator collectionIter; private final IndexedItem currItem = new IndexedItem(); public IndexedIterator(Iterable collection) { this.collectionIter = collection.iterator(); } public IndexedIterator(final U[] array) { collectionIter = new Iterator() { U[] arr = array; IndexedItem it = currItem; @Override public boolean hasNext() { return it.index + 1 < arr.length; } @Override public U next() { return arr[it.index + 1]; } @Override public void remove() { for (int i = it.index + 2; i < arr.length; i++) arr[i] = arr[i + 1]; } }; } @Override public Iterator> iterator() { return this; } @Override public boolean hasNext() { return collectionIter.hasNext(); } @Override public IndexedItem next() { currItem.item = collectionIter.next(); currItem.index++; return currItem; } @Override public void remove() throws UnsupportedOperationException, IllegalStateException { collectionIter.remove(); currItem.index--; currItem.item = null; } } /** Iterate over an Iterable and keep track of the index */ public static Iterable> iterate(Iterable collection) { return new IndexedIterator(collection); } /** Iterate over an array T[] and keep track of the index */ public static Iterable> iterate(T[] array) { return new IndexedIterator(array); } } " B10528,"package Practice; import java.util.ArrayList; import java.util.Scanner; public class B { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int t = 1; int a, b; ArrayList[] v = new ArrayList[2000010]; for (int i = 0; i < v.length; i++) v[i] = new ArrayList(); while (n-- > 0) { a = in.nextInt(); b = in.nextInt(); int cnt = 0; int x; String s = a + """"; int len = s.length(); int pow = 1; for (int i = 0; i < len - 1; i++) pow *= 10; for (int i = a; i <= b; i++) v[i].clear(); for (int i = a; i <= b; i++) { x = i; for (int j = 0; j < len; j++) { if (x % 10 == 0) { int tm = 10; while (x % tm == 0) { tm *= 10; } x = (x % tm) * pow / (tm / 10) + x / (tm); if (x > i && x <= b && !v[i].contains(x)) { cnt++; v[i].add(x); } } else { x = (x % 10) * pow + x / 10; if (x > i && x <= b && !v[i].contains(x)) { cnt++; v[i].add(x); } } } } System.out.printf(""Case #%d: %d\n"", t++, cnt); } } }" B12063,"import java.awt.geom.*; import java.io.*; import java.math.*; import java.util.*; import java.util.regex.*; import static java.lang.Math.*; public class Main { public Main() throws IOException { String input; int t; input = br.readLine(); t = Integer.valueOf(input); for (int i = 0; i < t; i++) { if (i > 0) sb.append(""\r\n""); input = br.readLine(); work(input, i); } System.out.print(sb); } private int rightShiftDec(int num) { int num2 = 10; if (num < 10) return num; while (true) { if (num < num2) break; num2 *= 10; } return num / 10 + (num % 10) * num2 / 10; } private void work(String input, int t) { //debug(input); int ret = 0; String[] inputArray = input.split("" ""); int min = Integer.valueOf(inputArray[0]); int max = Integer.valueOf(inputArray[1]); boolean[] doneList = new boolean[2000000]; int total; for (int i = min; i <= max; i++) doneList[i] = false; for (int i = min; i <= max; i++) { int num = i; int multiply = 1; if (doneList[i]) continue; doneList[i] = true; while (true) { num /= 10; if (num == 0) break; multiply *= 10; } num = i; total = 0; while (true) { num = num / 10 + (num % 10) * multiply; //debug(""i:"", i, "" num:"", num); if (num < multiply) continue; if (num == i) break; if ((min <= num) && (num <= max)) { //debug(""i:"", i, "" num:"", num, "" 1111""); total++; doneList[num] = true; } } ret += (total + 1) * total / 2; } sb.append(""Case #""); sb.append(String.valueOf(t + 1)); sb.append("": ""); sb.append(String.valueOf(ret)); } StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); public static void main(String[] args) throws IOException { new Main(); } public static void debug(Object... arr) { System.err.println(Arrays.deepToString(arr)); } } " B10384,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { public static void main(String[] args) throws IOException { File in = new File(""c:\\temp\\input.txt""); File out = new File(""c:\\temp\\output.txt""); BufferedWriter w = new BufferedWriter(new FileWriter(out)); Scanner sc = new Scanner(in); int testCases = Utils.readIntegerLine(sc); for (int i = 1; i <= testCases; i++) { int min = Utils.readInteger(sc); int max = Utils.readInteger(sc); long count = solve(min, max); String result = String.format(""Case #%d: %d"", i, count); w.write(result); System.err.println(result); w.newLine(); } w.close(); } private static long solve(int min, int max) { long count = 0; for(int n = min; n <= max; n++) { long countForN = countGreaterAnagrams(n, max); count += countForN; } return count; } private static long countGreaterAnagrams(int n, int max) { String s = String.valueOf(n); char[] chars = s.toCharArray(); int length = chars.length; Set numbers = new HashSet(); StringBuilder sb = new StringBuilder(length); for(int permStart = 1; permStart < chars.length; permStart++) { sb.setLength(0); for(int j = 0; j < length; j++) { sb.append(chars[(permStart + j) % length]); } int newN = Integer.parseInt(sb.toString()); if (newN > n && newN <= max) { numbers.add(newN); } } return numbers.size(); } } " B11843,"package info.m3o.gcj2012.recyclednumber; import java.util.TreeSet; //import java.util.HashSet; public class MyNumberStringPairSet extends TreeSet { /** * */ private static final long serialVersionUID = 1L; } " B10401,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; public class Test2 { /** * @param args */ public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new FileReader(""in.txt"")); BufferedWriter bw = new BufferedWriter(new FileWriter(""out.txt"")); int noOfCases = Integer.parseInt(br.readLine()); int units; int tens; int hundreds; int n,m; for(int i=0; i < noOfCases; ++i) { int count = 0; String line = br.readLine(); //System.out.println(""line=""+line); String[] values = line.split("" ""); int a = Integer.parseInt(values[0]); int b = Integer.parseInt(values[1]); if(a < 10 && b < 10) { bw.write(""Case #"" + (i+1) + "": "" + count + ""\n""); continue; } for(n = a; n <= b; ++n) { if(n < 10) { continue; } else if(n < 100) { units = n % 10; if(units == 0) { continue; } tens = n/10; //recycle by 1 digit m = units * 10 + tens; if((n < m) && (m <= b)) { ++count; } } else { units = n % 10; tens = (n/10) % 10; hundreds = n/100; //recycle by 1 digit if(units != 0) { m = units * 100 + hundreds * 10 + tens; if((n < m) && (m <= b)) { ++count; } } //recycle by 2 digits if (tens != 0) { m = tens * 100 + units * 10 + hundreds; if((n < m) && (m <= b)) { ++count; } } } //else } //for(n = a; n <= b; ++n) bw.write(""Case #"" + (i+1) + "": "" + count + ""\n""); } bw.close(); br.close(); } } " B11204," package gcj; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.HashMap; import java.util.Scanner; /** * * @author Mervin.Lavin */ public class Gcj { public static void main (String[] args) throws Exception { doProb3( ""C-small-attempt1.in"", ""output.txt"" ); } private static void doProb3 ( String inputFileName, String outputFileName ) throws Exception { File inputFile = new File( inputFileName ); Scanner scanner = null; scanner = new Scanner( inputFile ); File outputFile = new File( outputFileName ); BufferedWriter output = new BufferedWriter( new FileWriter( outputFile ) ); int a, b, otherPairs; HashMap distinctPairs; int testCases = scanner.nextInt(); for ( int caseNum = 1; caseNum <= testCases; caseNum++ ) { a = scanner.nextInt(); b = scanner.nextInt(); distinctPairs = new HashMap(); otherPairs = 0; for ( int n = a; n < b; n++ ) { String stringN = Integer.toString(n); if ( stringN.length() == 1 ) { continue; } for ( int index = 1; index < stringN.length(); index++ ) { String stringM = stringN.substring( index, stringN.length() ) + stringN.substring( 0, index ); int m = Integer.parseInt( stringM ); if ( ( !stringN.equals( stringM ) ) && ( n < m ) && ( m <= b ) ) { if ( distinctPairs.containsKey( n ) && !distinctPairs.containsValue( m ) ) { otherPairs++; } else { distinctPairs.put( n, m ); } } } } output.append( ""Case #"" + caseNum + "": "" + ( distinctPairs.size() + otherPairs ) ); output.newLine(); } scanner.close(); output.close(); } } " B11702,"import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class RecycledNumbers { /** * Input 4 1 9 10 40 100 500 1111 2222 * * Output * * Case #1: 0 Case #2: 3 Case #3: 156 Case #4: 287 */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub // Reading the input file Scanner in = new Scanner(new File(""C-small-attempt0.in"")); // writting the input file FileOutputStream fos = new FileOutputStream(""C-small-attempt0.out""); PrintStream out = new PrintStream(fos); // Close the output stream int testCase = in.nextInt(); for (int i = 0; i < testCase; i++) { // System.out.println(""Case #"" + (i + 1) + "":\t""); out.print(""Case #"" + (i + 1) + "":\t""); long A = in.nextInt(); long B = in.nextInt(); long small; long large; if (A < B) { small = A; large = B; } else { small = B; large = A; } long numberOfDistinctDigit = 0; /* Start The Problem */ while (small <= large) { // count the digit String convert = String.valueOf(small); // System.out.println(convert); String src; String dest; String result; ArrayList firstRecord = new ArrayList<>(); for (int q = 0; q <= convert.length() - 1; q++) { if ((convert.length() == q) || (convert.length() == 1)) { dest = ""\t""; src = convert.substring(0, q + 1); result = dest + src; } else { dest = convert.substring(q + 1); src = convert.substring(0, q + 1); result = dest + src; } result = result.trim(); long resultlong = Integer.parseInt(result); if (result.length() == 1) { // System.out.println(""Single Digit Number""); } else { if ((resultlong <= large) && (resultlong > small) && (result.length() == convert.length()) && (Integer.parseInt(convert) != resultlong) && (!firstRecord.contains(resultlong))) { numberOfDistinctDigit++; firstRecord.add(resultlong); // System.out.println(""Result "" + resultlong + // "" Result "" + numberOfDistinctDigit); if (i == 3) { System.out.println(resultlong); } } } } small++; // System.out.println(""\n""); }// while out.print(numberOfDistinctDigit); out.print(""\n""); }// for in.close(); out.close(); fos.close(); // System.out.println(""________________________END___________________""); } public static String reverse(String s) { return new StringBuffer(s).reverse().toString(); } } " B10989,"package at.jaki.codejam.qr2012.C; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.LinkedList; import java.util.List; import java.util.Scanner; public class C { private static final String TEMPLATE = ""Case #%d: %d""; private static final String IN = ""C-small-attempt0.in""; private static final String OUT = ""C-small-attempt0.out""; private static Scanner sc; private static PrintWriter pw; public static void main(String[] args) throws FileNotFoundException { sc = new Scanner(new File(IN)); pw = new PrintWriter(new File(OUT)); int tests = sc.nextInt(); for (int i = 1; i <= tests; i++) { resolve(i); } pw.flush(); pw.close(); } private static void resolve(int TT) { int A = sc.nextInt(); A = Math.max(A, 10); int B = sc.nextInt(); long total = 0; boolean[] used = new boolean[B + 1]; for (Integer i = A; i <= B; i++) { if (!used[i]) { used[i] = true; List res = turn(i.toString(), A, B); int n = res.size(); total += (n * (n + 1) / 2); for (Integer j : res) { used[j] = true; } } } System.out.println(total); pw.println(String.format(TEMPLATE, TT, total)); } private static final List turn(String x, int min, int max) { StringBuilder sb = new StringBuilder(x); List l = new LinkedList(); for (int i = 0; i < x.length() - 1; i++) { char ch = sb.charAt(0); sb.delete(0, 1); sb.append(ch); if (sb.charAt(0) != '0') { String string = sb.toString(); if (!string.equals(x)) { Integer y = Integer.valueOf(string); if (y >= min && y <= max) { if (!l.contains(y)) l.add(y); } } } } return l; } } " B12141,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Codejam2012; import java.io.*; /** * * @author Brian */ public class recycled { public static void main(String[] args) throws FileNotFoundException, IOException { String data; int result; String printout = """"; String[] output; String inputFileName = ""C:/input/recycledIn.txt""; String outputFileName = ""C:/input/recycledOut.txt""; BufferedReader reader = new BufferedReader(new FileReader(inputFileName)); FileWriter out = new FileWriter(outputFileName); PrintWriter print = new PrintWriter(out); data = reader.readLine(); int size = Integer.parseInt(data); output = new String[size]; data = reader.readLine(); int k = 0; while (data != null) { //result=data; String[] nums = data.split(""\\s""); int firstNum = Integer.parseInt(nums[0]); int secNum = Integer.parseInt(nums[1]); boolean res; if (secNum < 10) { result = 0; } else { if (String.valueOf(firstNum).length() == String.valueOf(secNum).length()) { result = checkNumOfArrangements(firstNum, secNum); } else { result = 0; } } output[k++] = String.valueOf(result); data = reader.readLine(); } for (int p = 0; p < output.length; p++) { printout += ""Case #"" + (p + 1) + "": "" + output[p] + ""\n""; } print.println(printout); print.close(); reader.close(); } public static boolean compareNumChars(int first, int second) { // int k = 0; // boolean cond = true; // String firstNum = String.valueOf(first); // String secNum = String.valueOf(second); // while (k < firstNum.length()) { // if (firstNum.charAt(k) == secNum.charAt(k)) { // k++; // continue; // } else { // cond = false; // break; // } // } // return cond; if(first == second){ return true; } else{ return false; } } public static int checkNumOfArrangements(int first, int second) { int control = first; int count = 0; while (control <= second) { int control_alt = control + 1; while (control_alt <= second) { if (compareNums(control, control_alt)) { count++; } control_alt++; } control++; } return count; } public static boolean compareNums(int first, int second) { String str = String.valueOf(first); StringBuffer buf; if (compareNumChars(first, second)) { return true; } else { for (int k = 0; k < str.length()-1; k++) { buf = new StringBuffer(str); for (int p = 0; p < str.length(); p++) { if (p == 0) { buf.setCharAt(p, str.charAt(str.length() - 1)); } else { buf.setCharAt(p, str.charAt(p - 1)); } } if (compareNumChars(Integer.parseInt(buf.toString()), second)) { return true; } else { str = buf.toString(); } } return false; } } } " B10289,"import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; public class C { static int[] tens = { 1, 10, 100, 1000, 10000, 100000, 1000000 }; static HashSet set = new HashSet(); static private int countPairs(int a, int max, int len) { int rhs, lhs, num; set.clear(); int res = 0; for (int i = 1; i < len; i++) { lhs = a % tens[i]; rhs = a / tens[i]; if (lhs == 0) continue; num = lhs * tens[len - i] + rhs; if (set.contains(num)) continue; if (a < num && num <= max) { res++; set.add(num); } } return res; } static private int numberLength(int n) { int len = Arrays.binarySearch(tens, n); if (len < 0) len = ~len; else len++; return len; } public static void main(String[] args) throws IOException { Scanner in = new Scanner(new FileInputStream(""C-small-attempt0.in"")); FileWriter out = new FileWriter(new File(""C-small-attempt0.out"")); int t = in.nextInt(),cnt = 1; while (t-->0) { int a = in.nextInt(), b = in.nextInt(); int tmp = 0; for (int i = a; i <= b; i++) tmp += countPairs(i, b, numberLength(i)); out.write(""Case #"" + cnt++ + "": "" + tmp+""\n""); } in.close(); out.close(); } } " B11099," import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class PC { private static int[] div = {10, 100, 1000, 10000, 100000, 1000000}; public static void main(String[] args) throws FileNotFoundException { if (args.length != 1) { System.exit(1); } File inFile = new File(args[0]); Scanner sc = new Scanner(inFile); int T = sc.nextInt(); try (PrintWriter out = new PrintWriter(""out.txt"")) { for (int i = 1; i <= T; i++) { int A = sc.nextInt(), B = sc.nextInt(), count = 0, maxPow = 0; for (int j = 0; j < 6; j++) { if (A / div[j] == 0) { maxPow = j - 1; break; } } int[] prevFound = new int[2000000]; for (int j = A; j <= B; j++) { int pow = 0; while (true) { int numFront = j / div[pow]; if (numFront == 0) { break; } int numBack = j % div[pow]; int newNum = numBack * div[maxPow - pow] + numFront; if (j < newNum && A <= newNum && newNum <= B && prevFound[newNum - 1] < j) { prevFound[newNum - 1] = j; count++; } pow++; } } out.println(""Case #"" + i + "": "" + count); } } System.out.println(""Completed!""); } }" B11507,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class Recycled { /** * @param args */ public static void main(String[] args) { try{ BufferedReader bf=null; try { int T; bf = new BufferedReader(new FileReader(""src/com/codejam/input/C-small-attempt0.in"")); T = Integer.parseInt(bf.readLine()); for(int i=0;i uniqueNum = new HashSet(); for(int i=N.length()-1;i>0;i--){ if( Character.getNumericValue(N.charAt(i)) > Character.getNumericValue(max.charAt(0)) ) continue; String M; M=N.substring(0, i); M=N.substring(i,N.length())+M; mNum = Integer.parseInt(M); nNum = Integer.parseInt(N); maxNum = Integer.parseInt(max); if(mNum>nNum && mNum<=maxNum){ uniqueNum.add(M); } } return uniqueNum.size(); } } " B11136,"package recyclednumbers.recycler; public class Recycler { public int countPairs(int startValue, int endValue) { int count = 0; for (int i = startValue; i < endValue; i++) { for (int j = i + 1; j <= endValue; j++) { if (isRecycledPair(i, j)) { count++; } } } return count; } public boolean isRecycledPair(int original, int target) { String originalString = original + """"; for (int i = originalString.length() - 1; i > 0; i--) { String testString = originalString.substring(i) + originalString.substring(0, i); if (Integer.parseInt(testString) == target) { return true; } } return false; } } " B10502,"import java.io.*; import java.util.*; public class Q3 { public static boolean isPermut (int a, int b) { String str = String.valueOf (a); for (int i = 1; i < str.length(); i++) { str = str.charAt (str.length() - 1) + str.substring (0, str.length() - 1); if (Integer.parseInt (str) == b) { return true; } } return false; } public static void main (String[] args) throws IOException { BufferedReader reader = new BufferedReader (new FileReader (""input-q3.txt"")); PrintWriter writer = new PrintWriter (""output-q3.txt""); String line = reader.readLine(); int nb = Integer.parseInt (line); for (int i = 0; i < nb; i++) { line = reader.readLine(); String[] tokens = line.split ("" ""); int min = Integer.parseInt (tokens[0]); int max = Integer.parseInt (tokens[1]); // System.out.printf (""\nmin %d, max %d\n"", min, max); // Try all rotations int counter = 0; Set set = new HashSet(); for (int val = min; val < max; val++) { String str = String.valueOf (val); int nbDigits = str.length(); // System.out.println(""Val : "" + val + "" with "" + nbDigits + "" digits""); int major = String.valueOf (max).charAt (0) - '0'; set.clear(); for (int j = 1; j < nbDigits; j++) { char last = str.charAt (nbDigits - 1); str = str.charAt (nbDigits - 1) + str.substring (0, nbDigits - 1); if (last != '0' && (last - '0') <= major) { // System.out.println ("" Trying "" + str); int res = Integer.valueOf (str); if (res <= max && res > val && ! set.contains (res)) { // System.out.printf ("" (%d, %d)\n"", val, res); set.add (res); if (! (val != res && val < res && val >= min && res <= max && isPermut (res, val))) { System.out.println(""ERROR""); } counter++; } } } } // System.out.println (""Counter : "" + counter); writer.println (""Case #"" + (i + 1) + "": "" + counter); } writer.close(); reader.close(); } }" B13174,"package recycle; import java.io.*; import java.util.logging.Level; import java.util.logging.Logger; public class Recycle { public static void main(String[] args) throws Exception { FileInputStream fr=new FileInputStream(""/home/priyankle/Desktop/recycle.txt""); StreamTokenizer st=new StreamTokenizer(fr); st.eolIsSignificant(false); st.whitespaceChars(0,32); int i=1,j=0,cases=0,count=0; int A[]=null; int B[]=null; File file=new File(""output.txt""); FileWriter fileWritter = new FileWriter(file.getName(),true); BufferedWriter bufferWritter = new BufferedWriter(fileWritter); int learn=0,flag=0; while(true) { flag++; learn=st.nextToken(); if(learn==StreamTokenizer.TT_EOF) break; if(learn==StreamTokenizer.TT_NUMBER&&flag==1) { cases=(int)st.nval; A= new int[cases+1]; B= new int[cases+1]; } if(learn==StreamTokenizer.TT_NUMBER&&flag==2) A[i]=(int)st.nval; else if(learn==StreamTokenizer.TT_NUMBER&&flag==3) { B[i]=(int)st.nval; flag=1; i++; } } int resultant=0; int y1=0,y2=0,y3=0,temp=0; for(j=1;j<=cases;j++) { count=0; for(i=A[j];i<=B[j];i++) { y1=i/100; temp=i%100; y2=temp/10; y3=temp%10; if(y1==0&&y2==0&&y3==0) { count=0; } else if(y1==0&&y2!=0) { if(y3>y2) { resultant=y3*10+y2; if(resultant<=B[j]) count++; } } else { if((y2>y1)||(y2==y1&&y2y1)||(y3==y1&&y3>y2)) { resultant=y3*100+y1*10+y2; if(resultant<=B[j]) count++; } } } bufferWritter.write(""Case #""+j+"": ""+count+""\n""); } bufferWritter.close(); } } " B10250,"import java.io.*; import java.util.HashSet; import java.util.Set; public class Recycled { public static void main(String []args) { int T,counter = 1; try { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(""output.txt"")))); String input = reader.readLine(); T = Integer.parseInt(input); while (T-->0) { input= reader.readLine(); String []in = input.split("" ""); int A,B; A=Integer.parseInt(in[0]); B=Integer.parseInt(in[1]); int numPairs = 0; for(int i=A;i<=B;i++) { Set pairs = new HashSet(); String num = String.valueOf(i); int currentHighestFaceValue = num.charAt(0); for(int j=num.length()-1;j>0;j--) { if(num.charAt(j)=='0') { continue; } if(num.charAt(j) implements CodeJamConstants, InputFileParser { private final File inputFile; private TaskStatus taskStatus; private int numberCases = UNDEFINED; public AbstractInputFileParser(File inputFile) { this.inputFile = inputFile; } @Override public void initialize(TaskStatus taskStatus) { this.taskStatus = taskStatus; countCases(); taskStatus.setNumberCases(numberCases); taskStatus.setNumberCurrentCase(1); } @Override public TaskStatus getTaskStatus() { return taskStatus; } public int countCases() { FileReader fileReader; BufferedReader bufferedReader; try { fileReader = new FileReader(inputFile); bufferedReader = new BufferedReader(fileReader); numberCases = Integer.parseInt(bufferedReader.readLine().trim()); bufferedReader.close(); fileReader.close(); } catch (FileNotFoundException e) { // FIXME Error logging } catch (IOException e) { // FIXME Error logging } finally { } return numberCases; } public int getNumberCases() { return numberCases; } public boolean hasNextCase() { return (null != taskStatus) && (taskStatus.getNumberCases() > taskStatus .getNumberCurrentCase()); } public BufferedReader checkoutBufferedReader() throws FileNotFoundException { FileReader fileReader = null; BufferedReader bufferedReader = null; fileReader = new FileReader(inputFile); bufferedReader = new BufferedReader(fileReader); return bufferedReader; } public void checkinBufferedReader(BufferedReader bufferedReader) throws IOException { // Does this call also close the FileReader instance? bufferedReader.close(); } public List readLines(BufferedReader bufferedReader, int numberOfLines) throws IOException { List lineList = new ArrayList(); int linesRead = 0; while (numberOfLines > linesRead) { // Reading Line String currentLine = bufferedReader.readLine(); if (null == currentLine) { throw new RuntimeException(""Unexpected end of file.""); } lineList.add(currentLine); linesRead++; } return lineList; } public List readLines(BufferedReader bufferedReader, int firstLine, int numberOfLines) throws IOException { int nrCurrentLine = 1; while (firstLine > nrCurrentLine) { // Skipping line, probably not the sweetest way to do it ... by any // means. if (null == bufferedReader.readLine()) { throw new RuntimeException(""Unexpected end of file.""); } nrCurrentLine++; } return readLines(bufferedReader, numberOfLines); } } " B12550," package grn; import java.io.*; import java.util.ArrayList; /** * * @author alexho */ public class GRN { private static int [] result; private static ArrayList permutation = new ArrayList(); private void readInput (String infn) throws FileNotFoundException, IOException { String line = null; int testCases = 0; BufferedReader bufRdr = null; String delimiter = "" ""; File file = new File(infn); bufRdr = new BufferedReader(new FileReader(file)); testCases = Integer.valueOf(bufRdr.readLine()); GRN.result = new int [testCases]; for (int i=0;i n && !GRN.usedperm.contains(alphabet) && !GRN.usedperm.contains(GRN.permutation.get(i))) { if (m <= B && m > n ) { // GRN.usedperm.add(alphabet); // GRN.usedperm.add(GRN.permutation.get(i)); GRN.result[ind]++; } } } private void output (String outfn) throws IOException { PrintWriter out = new PrintWriter(new FileWriter(outfn)); for (int i=0;i B || newNum <= number) { continue; } for ( int j=0; j < acceptedPairs.length; j++) { if ( acceptedPairs[j] == newNum ) { //Duplicate number break; } else if ( acceptedPairs[j] == 0 ) { //New number acceptedPairs[j] = newNum; break; } } } // Count non-zero accepted pairs for ( int j = 0; j < acceptedPairs.length; j++ ) { if ( acceptedPairs[j] == 0 ) { break; } count++; } } StringBuilder builder = new StringBuilder(""Case #""); builder.append(i+1).append("": ""); builder.append(count); System.out.println(builder.toString()); } } private static int getNumDigits(int a, int b) { int count = 0; while ( a > 0) { count++; a /= 10; } return count; } } " B11098,"package bchang; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; /** * Created with IntelliJ IDEA. * User: bchang * Date: 4/14/12 * Time: 9:48 PM * To change this template use File | Settings | File Templates. */ public class ProblemC { private static void cycle(char[] charArray) { char first = charArray[0]; for (int i = 1; i < charArray.length; i++) { charArray[i - 1] = charArray[i]; } charArray[charArray.length - 1] = first; } private static Set toSet(int a, int b) { Set set = new HashSet(); for (int x = a; x <= b; x++) { set.add(Integer.toString(x)); } return set; } private static int combos(int n) { if (n == 1) { return 1; } return n + combos(n-1); } private static int process(BufferedReader reader) throws IOException { String[] pair = reader.readLine().split("" ""); int a = Integer.parseInt(pair[0]); int b = Integer.parseInt(pair[1]); Set set = toSet(a, b); int counter = 0; while (set.size() > 0) { Iterator iterator = set.iterator(); String n = iterator.next(); iterator.remove(); char[] working = n.toCharArray(); Set matchingPairs = new HashSet(); for (int idx = 1; idx < working.length; idx++) { cycle(working); String mStr = new String(working); int mInt = Integer.parseInt(mStr); if (a <= mInt && mInt <= b && !n.equals(mStr) && mStr.charAt(0) != '0') { set.remove(mStr); matchingPairs.add(mInt); } } if (matchingPairs.size() > 0) { int numPairs = combos(matchingPairs.size()); counter += numPairs; } } return counter; } public static void main(String[] args) throws Exception { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(reader.readLine()); for (int i = 0; i < t; i++) { int result = process(reader); System.out.println(""Case #"" + (i + 1) + "": "" + result); } } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { } } } } } " B10243,"import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int ti = 0; ti < t; ti++) { int a = sc.nextInt(), b = sc.nextInt(); int sum = 0; for (int i = a; i <= b; i++) { int numOfDigits, power; if (i < 10) { numOfDigits = 1; power = 1; } else if (i < 100) { numOfDigits = 2; power = 10; } else if (i < 1000) { numOfDigits = 3; power = 100; } else if (i < 10000) { numOfDigits = 4; power = 1000; } else if (i < 100000) { numOfDigits = 5; power = 10000; } else if (i < 1000000) { numOfDigits = 6; power = 100000; } else { numOfDigits = 7; power = 1000000; } int tmp = i; for (int j = 0; j < numOfDigits - 1; j++) { int leastSig = tmp % 10; tmp = power * leastSig + tmp / 10; if (tmp == i) break; if (leastSig != 0 && tmp < i && tmp >= a) sum++; } } System.out.printf(""Case #%d: %d%n"", ti + 1, sum); } } } " B10399,"/* Problem Do you ever become frustrated with television because you keep seeing the same things, recycled over and over again? Well I personally don't care about television, but I do sometimes feel that way about numbers. Let's say a pair of distinct positive integers (n, m) is recycled if you can obtain m by moving some digits from the back of n to the front without changing their order. For example, (12345, 34512) is a recycled pair since you can obtain 34512 by moving 345 from the end of 12345 to the front. Note that n and m must have the same number of digits in order to be a recycled pair. Neither n nor m can have leading zeros. Given integers A and B with the same number of digits and no leading zeros, how many distinct recycled pairs (n, m) are there with A = n < m = B? Input The first line of the input gives the number of test cases, T. T test cases follow. Each test case consists of a single line containing the integers A and B. Output For each test case, output one line containing ""Case #x: y"", where x is the case number (starting from 1), and y is the number of recycled pairs (n, m) with A = n < m = B. Limits 1 = T = 50. A and B have the same number of digits. Small dataset 1 = A = B = 1000. Large dataset 1 = A = B = 2000000. Sample Input Output 4 1 9 10 40 100 500 1111 2222 Case #1: 0 Case #2: 3 Case #3: 156 Case #4: 287 */ import java.io.*; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; public class RecycledNumbers { BufferedReader read; BufferedWriter write; public static void main(String args[]) { try { new RecycledNumbers().init(""C-small-attempt0""); } catch (Exception ex) { //Logger.getLogger(RecycledNumbers.class.getName()).log(Level.SEVERE, null, ex); System.out.println(""Error"" + ex); } } void init(String name) throws Exception { read=new BufferedReader(new FileReader(new File(name+"".in""))); write=new BufferedWriter(new FileWriter(new File(name+"".out""))); String x=""""; try { x = read.readLine(); int nos = Integer.parseInt(x.trim()); for(int z=0;z ar=new ArrayList(); for(int j=0;ji && num<=b) { ar.add(num); //System.out.println("" i.... ""+i+""...num.... ""+num); count++;} } } } write.write(""Case #""+(z+1)+"":""+"" ""+count+""\n""); System.out.println(""Case #""+(z+1)+"":""+"" ""+count+""\n""); } write.flush(); write.close(); read.close(); // System.out.println(a+"" ""+b); } catch (Exception ex) { System.out.println(""Error"" + ex); System.exit(0); } } }" B12645,"import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class P03 { public static void main(String[] args) { Scanner inp = new Scanner(System.in); int t = inp.nextInt(); inp.nextLine(); int i = 1; while (t > 0) { int a = inp.nextInt(); int b = inp.nextInt(); System.out.println(""Case #"" + i + "": "" + find(a, b)); --t; ++i; } } private static long find(int a, int b) { long ret = 0; boolean[] done = new boolean[b + 1]; for (int i = a; i <= b; i++) { if (!done[i]) { Set vals = new HashSet(); String is = String.valueOf(i); if (is.length() > 1) { vals.add(i); for (int j = 1; j < is.length(); j++) { String newS = is.substring(j) + is.substring(0, j); int newInt = Integer.parseInt(newS); if (newInt >= a && newInt <= b) { vals.add(newInt); } } } if (vals.size() > 1) { for (int val : vals) { done[val] = true; } ret += (vals.size() * (vals.size() - 1)) / 2; } } } return ret; } } " B10232,"import java.io.*; import java.util.*; /** * Write a description of class Googlerese here. * * @author (your name) * @version (a version number or a date) */ public class RecycledNumbers { public static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); private int x; private int max; public RecycledNumbers(int n) { x=0; max=n; } public int countdigit(int b) { int ctr=0; while(b>0) { b/=10; ctr++; } return ctr; } public int fact(int a) { int fact=1; int b=countdigit(a)-1; while(b>0) { fact*=10; b--; } return fact; } public void input(int n,int m) { int success=0; for(int i=n;i<=m;i++) { for(int j=n;j<=m;j++) { if(j>i) { if(calculate(i,j)) success++; } } } //System.out.println(""Success=""+success); System.out.print(""Case #""+(x+1)+"": ""); System.out.println(success); x+=1; if(x==max) return; } public boolean calculate(int n,int m ) { int cpy=countdigit(n); int aux=0; int success=0; int test=n; while(auxcountdigit(n)) n*=10; //System.out.println(n); if(m==n) { //System.out.println(test+""=""+m); //success++; return true; } aux++; } return false; } public void start()throws IOException { // put your code here int i=1; File file = new File(""C-small-attempt.txt""); FileInputStream fis = null; BufferedInputStream bis = null; DataInputStream dis = null; try { fis = new FileInputStream(file); // Here BufferedInputStream is added for fast reading. bis = new BufferedInputStream(fis); dis = new DataInputStream(bis); // dis.available() returns 0 if the file does not have more lines. while (dis.available() != 0) { if(x==max) return; // this statement reads the line from the file and print it to // the console. // System.out.println(dis.readLine()); String s=dis.readLine(); StringTokenizer st=new StringTokenizer(s,"" ""); while(st.hasMoreElements()) { int x=Integer.parseInt(st.nextElement().toString()); //System.out.println(x); int y=Integer.parseInt(st.nextElement().toString()); //System.out.println(y); input(x,y); } } // dispose all the resources after using them. fis.close(); bis.close(); dis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //Read File Line By Line //Close the input stream } public static void main(String[]args)throws IOException { int n; do{ n=Integer.parseInt(br.readLine()); }while(n<1||n>50); RecycledNumbers obj=new RecycledNumbers(n); for(int i=0;i i) { boolean f = true; for (int k = 0; k < j; k++) { if (it[k] == it[j]) f = false; } if (f) count++; } } } return count; } public String getRotate(String s, int r) { char[] ch = s.toCharArray(); int n = ch.length; char[] buf = new char[n]; for (int i = 0; i < r; i++) { buf[n-r+i] = ch[i]; } for (int i = 0; i < n-r; i++) { buf[i] = ch[r+i]; } return new String(buf); } } " B10173,"package qualification; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class RecycledNumbers { static int T; static int[] result; public static void main(String[] args) throws IOException { read(); write(); } static void read() throws IOException { File input = new File(""input.txt""); Scanner scanner = new Scanner(input); T = scanner.nextInt(); result = new int[T]; for (int t=0; t existing = new ArrayList(bs.length()); int result = 0; for (int n=A; n 0 && ms.compareTo(bs) <= 0) { if (!existing.contains(ms)) { existing.add(ms); result++; } } } } return result; } static void write() throws IOException { File output = new File(""output.txt""); PrintWriter pw = new PrintWriter(output); for (int t=0; t lista; for(int j = primero; j <= ultimo; j++) { lista = deparse(j); for(int k = j+1; k <= ultimo; k++) { for(int r = 0; r < lista.size(); r++) { int prueba = monta(lista); if(k == prueba) i++; int x = lista.pop(); lista.addLast(x); } } } return i; } public int monta(LinkedList l) { int res = 0; int a = 1; for(int i = 0; i < l.size(); i++) { for(int k = i;k < l.size(); k++) a *= 10; res += l.get(i) * a; a = 1; } res = res / 10; return res; } public LinkedList deparse(int k) { LinkedList ret = new LinkedList(); int r = k; while(r != 0) { ret.addFirst(r % 10); r = r / 10; } return ret; } } " B10526,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class Third { public static void main(String[] args) { try { BufferedReader reader = new BufferedReader(new FileReader(new File(""input.txt""))); PrintWriter writer = new PrintWriter(new FileWriter(new File(""output.txt""))); reader.readLine(); int test = 1; String str = """"; while((str = reader.readLine()) != null){ long result = 0; String[] temp = str.split("" ""); int a = Integer.parseInt(temp[0]); int b = Integer.parseInt(temp[1]); boolean[] visited = new boolean[b + 1]; for(int num = a; num <= b; num++){ if(visited[num]) continue; int[] digits = GetDigit(num); Set recycledNum = new HashSet(); for(int i = 0; i < digits.length; i++){ int thisNum = GetNum(digits, i); int thisNumDigit = (int) (Math.log10(thisNum) + 1); if(thisNum >= a && thisNum <= b && thisNumDigit == digits.length) recycledNum.add(thisNum); } if(recycledNum.size() > 1){ result += recycledNum.size() * (recycledNum.size() - 1) / 2; Iterator iterator = recycledNum.iterator(); while(iterator.hasNext()){ visited[iterator.next()] = true; } } } writer.println(""Case #"" + test + "": "" + result); test++; } writer.close(); } catch (Exception e) { e.printStackTrace(); } } private static int[] GetDigit(long num){ int digits = (int) (Math.log10(num) + 1); int[] result = new int[digits]; while(digits > 0){ result[--digits] = (int) (num % 10); num /= 10; } return result; } private static int GetNum(int[] digits, int startDigit){ int number = 0; int pos = startDigit; do{ number = number * 10 + digits[pos]; pos++; if(pos >= digits.length) pos -= digits.length; } while(startDigit != pos); return number; } } " B12381,"import java.util.*; public class RecycledNums { static Scanner cin = new Scanner(System.in); public static void main(String[] args) { String out = """"; System.out.println(""GO""); int repeat = cin.nextInt(); cin.nextLine(); int ans=0; for(int i = 0; i < repeat; i++) { int in1 = cin.nextInt(); int in2 = cin.nextInt(); ans = findAns(in1, in2); out+=""Case #"" + (i+1) + "": "" +ans+""\n""; } System.out.println(out); } public static int findAns(int in1, int in2) { ArrayList found = new ArrayList(); int ans = 0; for(int i = in1; i < in2; i++) { for(int j = i+1; j<=in2; j++) { int[] recycledNums = numsFor(i); for(int k = 0; k < recycledNums.length; k++) { if((recycledNums[k]+"""").length() == (j+"""").length()) if(recycledNums[k] == j) { /*boolean foundN = false; for(int a = 0 ; a < found.size(); a++) { if(j == found.get(a).intValue()) { foundN = true; } } if(!foundN) { ans++; found.add(new Integer(j)); }*/ ans++; } } } } return ans; } public static int[] numsFor(int in) { String num = in+""""; int[] ans = new int[num.length()-1]; for(int i = 1; i < num.length(); i++) { ans[i-1] = Integer.parseInt(num.substring(num.length()-i,num.length()) + num.substring(0,num.length()-i)); for(int j = 0; j < i-1; j++) { if(ans[i-1] == ans[j]) ans[i-1] = 0; } } return ans; } } " B12198,"package client; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.StringTokenizer; import java.util.TreeSet; public class Recycle { public Recycle() { super(); } public static void main(String[] args) throws FileNotFoundException, IOException { Recycle recycle = new Recycle(); // FileReader fr = new FileReader(""B-large.in""); FileReader fr = new FileReader(""C-small-attempt0.in""); BufferedReader br = new BufferedReader(fr); String noofT = br.readLine(); int noOfTestCases = Integer.parseInt(noofT); BufferedWriter bw = new BufferedWriter(new FileWriter(""output.txt"")); for (int i=0;i < noOfTestCases;i++ ){ StringTokenizer st = new StringTokenizer(br.readLine(),"" ""); String sA = st.nextToken(); int A = Integer.parseInt(sA); String sB = st.nextToken(); int B = Integer.parseInt(sB); int cnt = 0; int count = 0; int[] numArray = new int[30000]; TreeSet a1 = new TreeSet(); for (int j = A; j<=B ;j++){ String jS = Integer.valueOf(j).toString(); char[] jS1 = new char[jS.length()]; for (int m = 0; m < jS.length() - 1;m++){ for (int k = jS.length() - 1; k >0 ; k--){ char temp = jS.charAt(jS.length() - 1); jS1[k] = jS.charAt(k-1); jS1[0] = temp; } String jS2 = """"; for (int n=0;n < jS1.length; n++){ jS2 = jS2 + Character.valueOf(jS1[n]).toString(); } int newNum = Integer.parseInt(jS2); boolean flag = false; boolean flagR = false; if (( newNum >= A) && (newNum <= B) && (newNum != j)) { if (a1.contains(newNum)== true){ flag = true; // System.out.println(""flag = "" + flag); //break; } // numArray[cnt++] = newNum; else{ String reverseNum = """"; for (int l= jS1.length - 1;l >= 0;l--){ reverseNum = reverseNum + Character.valueOf(jS1[l]).toString(); } if (jS1.length == 2){ if (!a1.contains(new Integer(reverseNum))){ a1.add(newNum); cnt++; } } else{ a1.add(newNum); cnt++; } } //System.out.println(""newNum = "" + newNum); } /* if (flag == false){ //System.out.println(""count = "" + count); count++; }*/ } } String out = ""Case #"" + (i+1) + "": "" + cnt; bw.write(out); bw.newLine(); System.out.println(""Case #"" + (i+1) + "": "" + cnt); } bw.close(); } } " B11372,"import java.io.*; import java.util.*; import static java.lang.System.*; public class C { // small input version public static String next(String x) { return x.substring(1)+x.charAt(0); } public static void main(String[] args) { Scanner sc = new Scanner(in); int t = sc.nextInt(); boolean[][] match = new boolean[1001][1001]; for (int i = 1; i <= 1000; i++) { String str = Integer.toString(i); for (int j = 0; j < 4; j++) { str = next(str); int k = Integer.parseInt(str); match[Math.min(i,k)][Math.max(i,k)] = true; } } for (int c = 1; c <= t; c++) { int u = sc.nextInt(); int v = sc.nextInt(); int ctr = 0; for (int i = u; i <= v; i++) { for (int j = i+1; j <= v; j++) { if (match[i][j]) { ctr++; } } } out.printf(""Case #%d: %d\n"", c, ctr); } } } " B12755,"package com.dagova.recycledNumbers; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); int testCasesNumber = 0; try { testCasesNumber = Integer.parseInt(bufferedReader.readLine()); for(int testCase = 0; testCase < testCasesNumber; testCase++) { int solution = RecycledNumbersSolver.solve(bufferedReader.readLine()); System.out.println(""Case #"" + (testCase+1) + "": ""+solution); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B12545,"package contest; import java.io.BufferedReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Input { BufferedReader in; public Input(BufferedReader in) { this.in = in; } // public String readStr() { return readStr(in); } public int readInt() { return readInt(in); } public int[] readIntArr() { return readIntArr(in, "" ""); } public List readIntList() { return readIntList(in, "" ""); } public List readStrList() { return readStrList(in, "" ""); } // public String readStr(BufferedReader in) { try { return in.readLine(); } catch (Exception e) { e.printStackTrace(); return null; } } public int readInt(BufferedReader in) { return Integer.parseInt(readStr(in)); } public int[] readIntArr(BufferedReader in) { return readIntArr(in, "" ""); } public int[] readIntArr(BufferedReader in, String delimiter) { String[] tokens = readStr(in).split(delimiter); int[] ints = new int[tokens.length]; for (int i = 0; i < tokens.length; i++) { ints[i] = Integer.parseInt(tokens[i]); } return ints; } public List readIntList(BufferedReader in) { return readIntList(in, "" ""); } public List readIntList(BufferedReader in, String delimiter) { String[] tokens = readStr(in).split(delimiter); List ints = new ArrayList(tokens.length); for (int i = 0; i < tokens.length; i++) { ints.add(Integer.parseInt(tokens[i])); } return ints; } public List readStrList(BufferedReader in, String delimiter) { return Arrays.asList(readStr(in).split(delimiter)); } } " B10043,"import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; /** * template class for code jam Contest * * @author Tudor * */ public class Main { public static final String INPUT_FILE = ""src/in.txt""; public static final String OUTPUT_FILE = ""out.txt""; java.io.BufferedWriter br; /* * the number of tests */ int tests; /* * the size of the test */ int a, b; /* * the array */ int[] tree; public static void main(String args[]) { Main classMain = new Main(); try { Scanner scanner = new Scanner(new File(Main.INPUT_FILE)); classMain.br = new java.io.BufferedWriter(new FileWriter(Main.OUTPUT_FILE)); classMain.setData(scanner); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * method to set the initial data and run the tests * @param br the reader obtained from file */ public void setData(Scanner scanner) { try { tests = scanner.nextInt(); // System.out.println(""Tests "" + tests); for (int i = 0; i < tests; i++) { a = scanner.nextInt(); b = scanner.nextInt(); solve(i + 1); } br.close(); } catch (Exception e) { e.printStackTrace(); } } /** * method to solve the problem * @param testNr the index of the test */ public void solve(int testNr) { int result = 0; int digits = getDigits(a); for (int i=a; i<=b; i++) { int number = i; for (int d=0; d set = new HashSet (); for (int j = 1; j < num.length(); j++) { char t = tmp.charAt(0); tmp = tmp.substring(1); tmp = tmp + t; if((Integer.parseInt(tmp)+"""").length() == num.length() && Integer.parseInt(num) < Integer.parseInt(tmp) && Integer.parseInt(tmp) <= B) { if(!set.contains(tmp+"" ""+num)) ans++; set.add(tmp+"" ""+num); } } } System.out.println(""Case #""+(count++)+"": ""+ans); } reader.close(); } } " B10844,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.HashMap; import java.util.HashSet; import java.util.Scanner; public class RecylcedNumbers { public static void main(String[] args) throws Exception { Scanner in = new Scanner(new File(""input.in"")); BufferedWriter bfrw = new BufferedWriter(new FileWriter(""output.out"")); long N = in.nextLong(); String output = """"; for(long i = 0; i < N;i++){ long A = in.nextLong(); long B = in.nextLong(); output += ""Case #""+(i+1)+"": "" + solve(A,B) + ""\n""; } bfrw.write(output); in.close(); bfrw.close(); } private static long solve(long A,long B){ long ans = 0; if(B <= 9) return 0; HashSet set = new HashSet(); for(long i = A; i <=B; i++){ String s = i+""""; for(int j = 0; j < s.length();j++){ String one = s.substring(s.length()-j); String two = s.substring(0,s.length()-j); if(Integer.parseInt(one+two) <= B && i < Integer.parseInt(one+two)) { ans++; //System.out.println(s + "" --> "" + one + two); set.add(i+"",""+Integer.parseInt(one+two)); } } } return set.size(); } } " B12337,"import java.util.*; public class Recycled { public static void main (String[] args) { Scanner sc = new Scanner(System.in); int lines = sc.nextInt(); for (int i=0; i swappedValues = new ArrayList(); for (int s=1; s<=d; s++) { int tens = tenPowerOf(s); int headDigits = d-s; int head = n/tens; int tail = n%tens; int minTail = minWithNumberOfDigits(s); if (tail>=minTail) { int newNum = tail*tenPowerOf(headDigits)+head; if (newNum>=min && newNum<=max && newNum!=n) { int size = swappedValues.size(); Boolean isNew = true; for (int j=0; j0) { digits++; n = n/10; } return digits; } static int tenPowerOf(int p) { int res = 0; if (p>0) { res = 10; // power of 1 for (int i=2; i<=p; i++) { res *= 10; } } return res; } static int minWithNumberOfDigits(int d) { return tenPowerOf(d-1); } } " B10027,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class GoogleC { public String szamol(String input){ String result=""""; String a=input; Integer min=Integer.parseInt(a.substring(0,a.indexOf(' '))); a=a.substring(a.indexOf(' ')+1); Integer max=Integer.parseInt(a); Long count=0l; for(Integer i=min; i<=max; i++){ String e1=i.toString(); Set db=new HashSet(); for (int j=1; ji && k<=max){ db.add(k); //System.out.println(e1+""\t""+e2); } } count+=db.size(); } return count.toString(); } public static void main(String[] args) { GoogleC a=new GoogleC(); //String filename=""input.txt""; String filename=""C-small-attempt0.in""; //String filename=""B-large.in""; String thisLine; try { BufferedReader br = new BufferedReader(new FileReader(filename)); BufferedWriter bw= new BufferedWriter(new FileWriter(filename+"".out"")); thisLine=br.readLine(); Integer tnum=Integer.parseInt(thisLine); for(int i=0;i= 0; ) { if(sm.equals(sn.substring(i, l) + sn.substring(0, i))) return true; } return false; } private static long recycledNumbers(String s) { StringTokenizer st = new StringTokenizer(s); final int A = Integer.parseInt(st.nextToken()); final int B = Integer.parseInt(st.nextToken()); long r = 0; for(int n = A; n < B; n++) for(int m = n; ++m <= B; ) { if(isRecycledPair(n, m)) r++; } return r; } public static void main(String args[]) throws Exception { //String fileName = ""C.in""; String fileName = ""C-small-attempt0.in""; //String fileName = ""C-large.in""; BufferedReader in = new BufferedReader(new FileReader(fileName)); PrintStream out = new PrintStream(fileName.substring(0, fileName.lastIndexOf('.')) + "".out""); int T = Integer.parseInt(in.readLine()); for(int i = 1; i <= T; i++) { out.print(""Case #"" + i + "": ""); String s = in.readLine(); out.println(recycledNumbers(s)); } out.close(); in.close(); } }" B10215,"import java.io.*; public class gcj3 { static int T; static int AB[][]; static void beolvas (String f) throws IOException { BufferedReader be = new BufferedReader(new FileReader(f)); String sor = be.readLine(); T = Integer.parseInt(sor); AB = new int[T][2]; for (int i = 0; i < T; i++) { sor = be.readLine(); AB[i][0] = Integer.parseInt(sor.split("" "")[0]); AB[i][1] = Integer.parseInt(sor.split("" "")[1]); } } static boolean recyclable (int n, int m) { if ( ((int) ((Math.log(n))/(Math.log(10)))) != ((int) ((Math.log(m))/(Math.log(10)))) ) return false; String ns = n+""""; String ms = m+""""; for (int i = 1; i <= ms.length(); i++) { char c = ms.charAt(ms.length()-1); ms = c + ms.substring(0,ms.length()-1); if (ns.equals(ms)) return true; } return false; } static void kiir () { System.out.println(T); for (int i = 0; i < T; i++) { System.out.println(AB[i][0]+"" ""+AB[i][1]); } } static int count (int a, int b) { int er = 0; for (int n = a; n < b; n++) { for (int m = n+1; m <= b; m++) { if (recyclable(n,m)) { // System.out.println(n+"" es ""+m+"" ***IGEN***""); er++; } else { // System.out.println(n+"" es ""+m+"" nem""); } } } return er; } public static void main (String args[]) throws IOException { beolvas(""C-small-attempt0.in""); // kiir(); for (int k = 1; k <= T; k++) { System.out.println(""Case #""+k+"": ""+count(AB[k-1][0],AB[k-1][1])); } } } " B12677,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class RecycledNumbers { static class NumberPairs{ int a ; int b ; int large ; int small; NumberPairs(String input){ populateInput(input); } private void populateInput(String input) { StringTokenizer tokenizer = new StringTokenizer(input, "" ""); a = Integer.parseInt((String) tokenizer.nextElement()); b = Integer.parseInt((String) tokenizer.nextElement()); if(ab){ small = b; large = a; } } private int computeResult(){ int count=0; for(int number = small ; number <= large; number ++){ // Get every number under small Set set = new HashSet(); for(int i = 0 ; i < Integer.toString(number).length()-1 ;i++){ // Rotate number to get another number int rotated = rotateCircular(number, i+1); if(number < rotated && rotated <= large){ if(set.contains(rotated)) continue; else set.add(rotated); count++; } } } return count; } private static int rotateCircular(int number, int n){ char [] val =rotateCircularly(Integer.toString(number), n); return Integer.parseInt(new String(val)); } public void printResult(int i) { System.out.println(""Case #"" + i + "": "" + computeResult()); } public static char[] rotateCircularly(String input1 , int n) { char[] input = input1.toCharArray(); input = reverse (input, 0 , input.length-1); input = reverse (input , 0 , n-1); input = reverse (input, n , input.length-1); // Reverse the last n return input; } public static char[] reverse(char[] input, int start, int end){ for(int i = 0 ; i < (end - start + 2) / 2 ; i ++){ char temp = input[start + i]; input[start + i] = input[end-i]; input[end-i] = temp; } return input; } } public static void main(String[] args) { try { String [] input = getInput(""C-small-attempt0.in""); for(int i=0;i< input.length; i++){ new NumberPairs(input[i]).printResult(i+1); } } catch (IOException e) { } } static String[] getInput(String fileName) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(fileName)); try { String message = reader.readLine(); int numberOfTestCases = Integer.parseInt(message); String[] input = new String[numberOfTestCases]; for (int i = 0; i < numberOfTestCases; i++) { message = reader.readLine(); input[i] = message; } return input; } finally { reader.close(); } } } " B10506,"import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Hossam Yasseen */ public class ProblemC { /** * @param args */ static Integer startEdge , endEdge ; public static void main(String[] args) { int numberOfRecycledNumbers = 0; String[] result = null ; for (int counter0 = 1; counter0 < args.length; counter0++) { result = args[counter0].split(""\\s""); startEdge = Integer.parseInt(result[0]); endEdge = Integer.parseInt(result[1]); numberOfRecycledNumbers=0 ; for (int counterA = startEdge; counterA < endEdge; counterA++) { List recycledNumber = recycledNumbers(counterA); for (int counter = 0; counter < recycledNumber.size(); counter++) { if (recycledNumber.get(counter) <= endEdge ) numberOfRecycledNumbers++; } } System.out.println(""Case #"" + counter0 + "": "" + numberOfRecycledNumbers); } } private static List recycledNumbers(Integer number) { Map map = new HashMap(); String dummyValue = null ; String candidateNumber = """"; char[] characters = number.toString().toCharArray(); int index; for (int counter = 0; counter < characters.length; counter++) { index = counter ; int loops = 0 ; candidateNumber=""""; for ( ; loops < characters.length; index++) { candidateNumber += characters[index % characters.length]; loops++ ; } if(Integer.parseInt(candidateNumber)>number.intValue()) map.put(Integer.parseInt(candidateNumber),dummyValue); } List recycledNumber = new ArrayList( map.keySet()); return recycledNumber; } } " B10720,"import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; public class C { public static ArrayList toArray(String number){ ArrayList array = new ArrayList(); char[] numbers = number.toCharArray(); for (int i=0; i array1, ArrayList array2){ String number1=""""; String number2=""""; for (int i=0; i array1; ArrayList array2; String number1, number2; int n = Integer.parseInt(line); int pairs, n1, n2; for (int i = 0; i < n; i++) { n1 = in.nextInt(); n2 = in.nextInt(); pairs = 0; for (int j=n1; j set = new HashSet(); for (int k = 1; k <= t; k++){ ans = 0; a = in.nextInt(); b = in.nextInt(); max = Integer.toString(b); for (int i = a; i < b; i++){ set.clear(); x = i; min = buf = Integer.toString(x); l = min.length(); for (int j = 0; j < l-1; j++){ buf = min.substring(l - j - 1) + min.substring(0, Math.max(0, l - j - 1)); if ((buf.length() == l) && (min.compareTo(buf) < 0) && (buf.compareTo(max) <= 0)) { if (!set.contains(buf)){ set.add(buf); ans++; } } } } out.println(""Case #"" + k + "": "" + ans); } out.close(); } catch(Exception e){ } } public static void main(String[] args){ (new Thread(new C())).start(); } } " B10853,"// Skeleton program used for reading and outputing the results // Part3 program import java.util.*; public class part3 { public static void main(String args[]) { Scanner scanner = new Scanner(System.in); int number = scanner.nextInt(); for (int i = 0; i < number; i++) { doMagic(scanner.nextInt(), scanner.nextInt(), i + 1); } } private static void doMagic(int lower, int upper, int caseNumber) { if (lower >= 10) { int count = 0; for (int number = lower; number <= upper; number++) { for (int i = number + 1; i <= upper; i++) { String numberString = Integer.toString(number); String iString = Integer.toString(i); boolean found = false; for (int shift = 1; shift < iString.length() && !found; shift++) { String shiftedString = iString.substring(shift) + iString.substring(0, shift); if (numberString.equals(shiftedString)) { count++; found = true; } } } } System.out.println(""Case #"" + caseNumber + "": "" + count); } else { System.out.println(""Case #"" + caseNumber + "": 0""); } } } " B11150,"package QualificationRound; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Dictionary; import java.util.regex.Pattern; public class C { public C() { } public int shiftNumber(int num,int NumOfDigints) { int tempDigit = num % 10; num = num/10; for (int i=0;i<(NumOfDigints-1); i++) { tempDigit *= 10; } tempDigit += num; return tempDigit; } public int solveLine(String in) { String[] input = in.split("" ""); int A = Integer.parseInt(input[0]); //N - number of googlers int B = Integer.parseInt(input[1]); //S - suprising results int numberOfRecycledNumbers = 0; for (int i=A; i<=B; i++) { int shifted = i; int tempNum = i; int NumOfDigints = 0; while (tempNum > 0) { NumOfDigints++; tempNum /= 10; } do { shifted = shiftNumber(shifted,NumOfDigints); if ((shifted > i)&& (shifted<=B)) { numberOfRecycledNumbers++; } }while(shifted != i); } return numberOfRecycledNumbers; } public static void calcFromFile(String fileName) { File file = new File(fileName); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String sentence = null; // repeat until all lines is read int numOfLine = 1; C q3 = new C(); sentence = reader.readLine(); //Read the n test cases while ((sentence = reader.readLine()) != null) { System.out.println(""Case #"" + numOfLine++ + "": ""+q3.solveLine(sentence)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { e.printStackTrace(); } } } } " B13119,"/** * */ /** * @author Mostafa * */ public class RecycledNumbers { public static String traverse(String x) { char[] m = x.toCharArray(); m[0] = x.charAt(1); m[1] = x.charAt(0); String t = new String(m); return t; } public static String traverse1(String x) { char[] m = x.toCharArray(); m[0] = x.charAt(2); m[1] = x.charAt(0); m[2] = x.charAt(1); String t = new String(m); return t; } public static String traverse2(String x) { char[] m = x.toCharArray(); m[0] = x.charAt(1); m[1] = x.charAt(2); m[2] = x.charAt(0); String t = new String(m); return t; } public static int renumber(int first, int last) { String[] test = new String[last-first+1]; int i, j; int testc = 0; int count = 0; for (i = first; i<=last; i++) { String x = Integer.toString(i); test[testc] = x; testc++; } if (test[0].length() == 1) { count = 0; } else if (test[0].length() == 2) { for (i=0; i duplicates = new TreeSet<>(); for(int i = 1; i <= testCase; i++) { int a = in.nextInt(), b = in.nextInt(); int count = 0; for(int n = a; n < b; n++) { String s = String.valueOf(n); String s2 = s+s; duplicates.clear(); for(int j = 1, len = s.length(); j < len; j++) { int m = Integer.parseInt(s2.substring(j, j+len)); if(m > n && m <= b && !duplicates.contains(m)) { count++; duplicates.add(m); } } } System.out.printf(""Case #%d: %d%n"", i, count); } } } " B10374,"import java.io.*; import java.util.*; import java.math.*; import java.awt.geom.*; import static java.lang.Math.*; public class Solution implements Runnable { static final int [] mul = {1, 10, 100, 1000, 10000, 100000, 1000000}; int getLen (int num) { int ret = 0; while (num > 0) { num /= 10; ret++; } return ret; } public void solve () throws Exception { int tt = nextInt(); for (int test = 1; test <= tt; test++) { int l = nextInt(); int r = nextInt(); int result = 0; int has [] = new int [r + 1]; for (int num = l; num <= r; num++) { int len = getLen(num); for (int j = 1; j <= len - 1; j++) { if ((num % mul[j]) / mul[j - 1] == 0) continue; int numto = num / mul [j] + (num % mul [j]) * mul [len - j]; if (numto > num && numto <= r) { if (has [numto] != num) result++; has[numto] = num; } } } out.println(""Case #""+test+"": ""+result); } } final String fname = """"; long stime = 0; BufferedReader in; PrintWriter out; StringTokenizer st; private String nextToken () throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } private int nextInt () throws Exception { return Integer.parseInt(nextToken()); } private long nextLong () throws Exception { return Long.parseLong(nextToken()); } private double nextDouble () throws Exception { return Double.parseDouble(nextToken()); } @Override public void run() { try { in = new BufferedReader(new FileReader(""input.txt"")); out = new PrintWriter(new FileWriter(""output.txt"")); solve (); } catch (Exception e) { throw new RuntimeException(e); } finally { out.close(); } } public static void main(String[] args) { new Thread(null, new Solution(), """", 1<<26).start(); } }" B10525,"package qualification2012; import java.io.BufferedReader; import java.io.FileReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; public class RecycledNumbers { static int rotationCount(int x, int lower) { String s = String.valueOf(x); List rotations = new ArrayList(); for (int i = 1; i < s.length(); i++) if (s.charAt(i) != '0') { int r = Integer.parseInt(s.substring(i) + s.substring(0, i)); if(r >= lower && r < x && !rotations.contains(r)) rotations.add(r); } return rotations.size(); } static int solve(int A, int B) { int result = 0; for (int x = A + 1; x <= B; x++) result += rotationCount(x, A); return result; } public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(args[0])); PrintWriter writer = new PrintWriter(args[1]); int ntests = Integer.parseInt(reader.readLine()); for (int test = 0; test < ntests; test++) { String[] fields = reader.readLine().split("" ""); int A = Integer.parseInt(fields[0]); int B = Integer.parseInt(fields[1]); writer.println(""Case #"" + (test + 1) + "": "" + solve(A,B)); writer.flush(); } writer.close(); } } " B12768,"package gcj2012.qr; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** * * @author Scott DellaTorre */ public class C { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(""src/gcj2012/qr/in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""src/gcj2012/qr/C.out""))); int T = Integer.parseInt(in.readLine()); for (int i = 0; i < T; i++) { StringTokenizer st = new StringTokenizer(in.readLine()); int A = Integer.parseInt(st.nextToken()); // Number of Googlers int B = Integer.parseInt(st.nextToken()); // Number of suprising cases int pairs = 0; for (int j = A; j <= B; j++) { pairs += countRecycled(j, B); } out.println(""Case #"" + (i + 1) + "": "" + pairs); } out.close(); } private static int countRecycled(int number, int max) { List list = new ArrayList<>(); int log10 = (int) Math.log10(number); for (int i = 1; i <= log10; i++) { int recycled = recycle(number, i, max); if (recycled != -1 && !list.contains(recycled)) { list.add(recycled); } } return list.size(); } private static int recycle(int number, int count, int max) { int oldNumber = number; int divisor = (int) Math.pow(10, count); int end = number % divisor; number /= divisor; int multiplicand = (int) Math.pow(10, (int) Math.log10(number) + 1); number += end * multiplicand; if (number <= oldNumber || number > max) { return -1; } return number; } } " B12060,"import java.io.*; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { public static void main(String[] args) throws FileNotFoundException { Scanner scanner = new Scanner(new File(""c0.in"")); PrintStream outputStream = new PrintStream(new FileOutputStream(""c.out"")); // PrintStream outputStream = System.out; int n = scanner.nextInt(); // System.out.println(n); for (int i = 0; i < n; i++) { int a = scanner.nextInt(); int b = scanner.nextInt(); outputStream.println(""Case #"" + (i+1) + "": "" + ile(a, b)); } } private static int ile(int a, int b) { int para = 0; int ilenie = 0; int next = a; while (next <= b) { String now = String.valueOf(next); // if (!uzyte.contains(now)) { int przed = para; Set uzyte = new HashSet(); for (int i = 0; i < ilecyfr(next)-1; i++) { now = rotuj(now); int nowInt = Integer.valueOf(now); // if (ilecyfr(next) != ilecyfr(nowInt)) { // continue; // } if (nowInt >= a && nowInt <= b && nowInt != next && !uzyte.contains(now)) { // if (now > next) { // System.out.println(""hehe "" + now + "" "" + next); // } // System.out.println(next + "" "" + now); para++; uzyte.add(now); } } if (przed == para) { ilenie++; // System.out.println(next); } // } else { // System.out.println(now + "" used""); // } next++; } // System.out.println(ilenie); // return b - a - ilenie; return para / 2; } private static String rotuj(String n) { String s = String.valueOf(n); String substring = s.substring(1); return substring + s.charAt(0); // int len = ilecyfr(n); // int reszta = n %10; // n/=10; // return (int) (n + (reszta * Math.pow(10, len - 1))); } private static int ilecyfr(int n) { int ile = 0; while (n > 0) { ile++; n/=10; } return ile; } } " B11282,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class Recycled { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader (""data/input"")); PrintWriter pw = new PrintWriter(new FileWriter(""data/output"")); int lines = Integer.parseInt(br.readLine()); for(int j = 0; j < lines; j++){ String sol = ""Case #"" + (j+1) + "": ""; StringTokenizer st = new StringTokenizer(br.readLine()); int min = Integer.parseInt(st.nextToken()); int max = Integer.parseInt(st.nextToken()); int num = 0; for(int i = min; i<=max;i++){ String numb = """"+i; List duplicates = new ArrayList(); for(int k=0;k i && newNumb >= min && newNumb <= max){ //System.out.println(i+""\t""+newNumb); duplicates.add(""""+newNumb); num++; } } } pw.println(sol + """"+ num); } pw.close(); } } " B10418,"import java.io.File; import java.io.FileWriter; import java.util.Arrays; import java.util.Scanner; /** * Author: Andriy Gusyev * Date: 14.04.12 */ public class Task2 { static private int[] multiplers = {0, 0, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 10000000}; static private int cases; static private int[] lowerBounds; static private int[] upperBounds; static private int[] results; private static void readBounds(String s, int index) { s = s.trim(); String[] arr = s.split("" ""); lowerBounds[index] = Integer.parseInt(arr[0]); upperBounds[index] = Integer.parseInt(arr[1]); } public static void main(String args[]) throws Exception { Scanner sc = new Scanner(new File(""d:/codejam/2/small""), ""UTF-8""); cases = Integer.parseInt(sc.nextLine()); lowerBounds = new int[cases]; upperBounds = new int[cases]; results = new int[cases]; for (int i = 0; i < cases; i++) { readBounds(sc.nextLine(), i); } System.out.println(cases); System.out.println(Arrays.toString(lowerBounds)); System.out.println(Arrays.toString(upperBounds)); for (int i = 0; i < cases; i++) { results[i] = calcRecycled(i); } System.out.println(Arrays.toString(results)); FileWriter fw = new FileWriter(new File(""d:/codejam/2/small_out"")); int k = 0; for (int i : results) { k++; fw.write(String.format(""Case #%s: %s\n"", String.valueOf(k), String.valueOf(i))); } fw.close(); } private static int calcRecycled(int index) { int result = 0; int lower = lowerBounds[index]; int upper = upperBounds[index]; for (int i = lower; i <= upper; i++) { System.out.println(i); int[] possibles = getPossibleRecycled(i); for (int j : possibles) { if (i < j && j <= upper && areRecycled(i, j)) { result++; } } } return result; } private static boolean areRecycled(int i, int j) { // if (!Arrays.equals(toSortedChars(i), toSortedChars(j))) { // return false; // } int digits = String.valueOf(i).length(); int initialI = i; int initialJ = j; for (int p = 0; p < digits; p++) { i = changeValue(i, digits); if (i == j) { return true; } } ; return false; } private static int[] getPossibleRecycled(int i) { // if (!Arrays.equals(toSortedChars(i), toSortedChars(j))) { // return false; // } int digits = String.valueOf(i).length(); int possibles[] = new int[digits]; for (int p = 0; p < digits; p++) { int candidate = changeValue(i, digits); i = candidate; if (isInArray(candidate, possibles)) { possibles[p] = 0; } else { possibles[p] = candidate; } } return possibles; } private static boolean isInArray(int c, int[] array) { for (int i : array) { if (i == c) { return true; } } return false; } private static int changeValue(int i, int digits) { if (i < 10) { return i; } else { //get last digit int last = i % 10; //cut last digit i = i / 10; // add last digit to the front i = multiplers[digits] * last + i; return i; } } private static char[] toSortedChars(int i) { char[] chars = String.valueOf(i).toCharArray(); Arrays.sort(chars); return chars; } }" B10146,"import java.util.Scanner; public class RecycledNumbers { public static int Recycled(int k,int begin,int end){ int length =String.valueOf(k).length(); int inc=0; int con=(int) Math.pow(10,length); int div=1; int temp; for(int i=1;ik){ if(temp>=begin&&temp<=end){ inc++; } } } return inc; } public static int testcase(int begin,int end){ int inc=0; for(int i=begin;i<=end;i++){ inc+=Recycled(i,begin,end); } return inc; } public static void main(String[] args) { Scanner scan = new Scanner(System.in); int T = scan.nextInt(); for(int i=0;i l = new ArrayList(); for (int k=0;kB||ti<=i) continue; if (!l.contains(ti)) { l.add(ti); n++; } } } return n; } public static void main(String args[]) throws IOException { BufferedReader in = new BufferedReader(new FileReader(""input.txt"")); int num = Integer.parseInt(in.readLine()); for (int i=0;i * @version 2012.0414 */ public class RecycledNumbers { public static void main(String[] args) throws Exception { // Get input files File dir = new File(""/Users/Chris/Documents/UniSVN/code-jam/recycled-numbers/data""); File[] inputFiles = dir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith("".in""); } }); // Process each input file for (File inputFile : inputFiles) { System.out.printf(""Processing \""%s\""...\n"", inputFile.getName()); String outputPath = inputFile.getPath().replaceAll(""\\.in$"", "".out""); BufferedWriter writer = new BufferedWriter(new FileWriter(outputPath)); Scanner scanner = new Scanner(inputFile); System.out.printf(""Number of test cases: %s\n"", scanner.nextLine()); int count = 0; while (scanner.hasNext()) { String line = scanner.nextLine(); String output = String.format(""Case #%d: %d\n"", ++count, process(line)); System.out.print(output); writer.write(output); } writer.close(); System.out.println(""Done.\n""); } // Compare to reference files (if any) for (File inputFile : inputFiles) { System.out.printf(""Verifying \""%s\""...\n"", inputFile.getName()); String referencePath = inputFile.getPath().replaceAll(""\\.in$"", "".ref""); String outputPath = inputFile.getPath().replaceAll(""\\.in$"", "".out""); File referenceFile = new File(referencePath); if (referenceFile.exists()) { InputStream referenceStream = new FileInputStream(referencePath); InputStream outputStream = new FileInputStream(outputPath); boolean matched = true; int referenceRead, outputRead; do { byte[] referenceBuffer = new byte[4096]; byte[] outputBuffer = new byte[4096]; referenceRead = referenceStream.read(referenceBuffer); outputRead = outputStream.read(outputBuffer); matched = referenceRead == outputRead && Arrays.equals(referenceBuffer, outputBuffer); } while (matched && referenceRead != -1); if (matched) { System.out.println(""Verified.\n""); } else { System.out.println(""*** NOT VERIFIED ***\n""); } } else { System.out.println(""No reference file found.\n""); } } } public static int process(String line) { Scanner scanner = new Scanner(line); final int a = scanner.nextInt(); final int b = scanner.nextInt(); final int[] pow10 = new int[] { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; int count = 0; for (int n = a; n < b; n++) { Set set = new HashSet(); int numDigits = numDigits(n); for (int d = 1; d < numDigits; d++) { int back = n % pow10[d]; int front = n / pow10[d]; int m = front + back * pow10[numDigits - d]; if (n < m && m <= b && numDigits == numDigits(m)) { set.add(m); } } count += set.size(); } return count; } public static int numDigits(int n) { if (n < 0) { return numDigits(-n); } else if (n < 1) { return 0; } else if (n < 10) { return 1; } else if (n < 100) { return 2; } else if (n < 1000) { return 3; } else if (n < 10000) { return 4; } else if (n < 100000) { return 5; } else if (n < 1000000) { return 6; } else if (n < 10000000) { return 7; } else if (n < 100000000) { return 8; } else if (n < 1000000000) { return 9; } else { return 10; } } }" B11780,"import java.util.*; import java.io.*; public class googleC { public static void main(String[] args) throws IOException { Scanner scan = new Scanner(new File(""inputC.txt"")); FileWriter stream = new FileWriter(""outputC.txt""); BufferedWriter out = new BufferedWriter(stream); int cases = scan.nextInt(); for (int i = 0; i < cases; i++) { int A = scan.nextInt(); int B = scan.nextInt(); int pairs = 0; for (int n = A; n < B; n++) { for (int m = n+1; m <=B; m++) { String first = """" + m; String second = """" + n; if (isRecycled(first, second) == true) pairs++; } } out.write(""Case #"" + (i+1) + "": "" + pairs + ""\n""); } out.close(); } public static boolean isRecycled(String s1, String s2) { return (s1.length() == s2.length()) && ((s1+s1).indexOf(s2) != -1); } } " B12213,"package hk.polyu.cslhu.codejam.lib; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; public class FileStream { public static Logger logger = Logger.getLogger(FileStream.class); /** * Read the content of file with the given file path * * @param filePath String The location of file * @return The content of file as an instance of list */ public static List read(String filePath) { List content = new ArrayList(); try { BufferedReader br = new BufferedReader(new FileReader(filePath)); String line; while ((line = br.readLine()) != null) { content.add(line); } br.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block logger.error(""File is not found with the path \"""" + filePath + ""\""""); } catch (IOException e) { // TODO Auto-generated catch block logger.error(e.getMessage()); } return content; } /** * Save the content to a file * * @param filePath String The location of file to be saved * @param content String The content to be saved */ public static void save(String filePath, String content) { try { BufferedWriter bw = new BufferedWriter(new FileWriter(filePath)); bw.write(content); bw.flush(); bw.close(); } catch (IOException e) { // TODO Auto-generated catch block logger.error(e.getMessage()); } } } " B11599,"package codeJam; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; public class RecycledNumbers { private static int inputLength = 1; /** * @param args the command line arguments */ public static void main(String[] args) { String filename = ""RecycledNumbers/input.txt""; if (args.length > 0) { filename = args[0]; } try { Scanner sc = new Scanner (new File(filename)); String input; int testCount = Integer.parseInt(sc.nextLine()); String out = """"; // Split the input into separate tests and collect the output. for (int i = 0; i < testCount; i++) { input = """"; for (int row = 0; row < inputLength; row++) { input += sc.nextLine() + System.lineSeparator(); } out += ""Case #"" + (i+1) + "": ""; out += runTest(input); out += System.lineSeparator(); } System.out.println(out); BufferedWriter output = new BufferedWriter(new FileWriter( ""RecycledNumbers/output.txt"")); output.write(out); output.close(); } catch (FileNotFoundException ex) { System.err.println(""Input file not found""); System.exit(1); } catch (IOException ex) { } } public static String runTest(String input) { boolean[] found = new boolean[2000000]; Scanner sc = new Scanner(input); int lowest = sc.nextInt(); int highest = sc.nextInt(); int recycled = 0; int length = 0; long current = 0; int inRange = 0; ArrayList permutations = new ArrayList(); for (long i = lowest; i <= highest; i++) { if(found[(int)i] == true) { continue; } length = getLength(i); permutations.clear(); current = i; inRange = 1; found[(int)current] = true; while (rotate(current, length) != i) { current = rotate(current, length); if (current <= highest && current >= lowest) { inRange++; found[(int)current] = true; } } recycled += combinations(inRange); } return String.valueOf(recycled); } public static long rotate(Long in, int length) { if (length < 2) { return in; } return in / 10 + ((in % 10) * (int)(java.lang.Math.pow(10.0, (double)length - 1))); } public static int getLength(Long in) { return (int)java.lang.Math.floor(java.lang.Math.log10((double)in))+ 1; } public static int combinations(int count) { if (2 == count) { return 1; } // We don't go high enough to worry about overflow (< 8) long answer = 1; for (int i = count - 2 + 1; i <= count; i++) { answer = answer * i; } for (int j = 2; j > 1; j--) { answer = answer / j; } return (int)answer; } } " B10875,"package de.at.codejam.problem3.util; import de.at.codejam.problem3.Problem3Case; import de.at.codejam.util.AbstractCaseSolver; import de.at.codejam.util.TaskStatus; public class Problem3CaseSolver extends AbstractCaseSolver { @Override public String solveCase(TaskStatus taskStatus, Problem3Case caseToSolve) { StringBuilder resultBuilder = new StringBuilder("" ""); String numberA = caseToSolve.getNumberA(); String numberB = caseToSolve.getNumberB(); int length = numberA.length(); Integer numberN = Integer.parseInt(numberA); Integer numberM = Integer.parseInt(numberB); int numberRecycled = 0; while (numberN.intValue() < numberM.intValue()) { while (numberN.intValue() < numberM.intValue()) { for (int i = 1; i < length; i++) { String substringStartNumberN = numberN.toString() .substring(length - i); String substringEndNumberM = numberN.toString().substring( 0, (length - i)); log(LOGLEVEL_TRACE, numberN + "", "" + numberM + "", "" + substringStartNumberN + "", "" + substringEndNumberM); if (numberM.toString().startsWith(substringStartNumberN) && numberM.toString().endsWith(substringEndNumberM)) { log(LOGLEVEL_TRACE, ""Found: "" + numberN + "","" + numberM); numberRecycled++; break; } } numberM = numberM.intValue() - 1; } numberM = Integer.parseInt(numberB); numberN = numberN.intValue() + 1; } resultBuilder.append(numberRecycled); return getDefaultResultBegin(taskStatus) + resultBuilder.toString(); } } " B12790,"package qualification; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import loader.InputReader; import loader.OutPutWriter; public class RecycledNumber { static String inputName = ""C-small-attempt0.in""; /** * @param args */ public static void main(String[] args) { // List list = new LinkedList(); // list.add(1); // list.add(2); // System.out.println(listToInt(list)); // int a = 4009; // System.out.println(intToList(a)); start(); } private static void start(){ InputReader reader = new InputReader(); reader.read(inputName); List inputs = reader.getInputs(); List outputs = new ArrayList(); for(String in: inputs){ String[] aLine = in.split("" ""); int a = Integer.parseInt(aLine[0]); int b = Integer.parseInt(aLine[1]); int amount = findPairs(a,b); outputs.add(new Integer(amount).toString()); } OutPutWriter writer = new OutPutWriter(); writer.write(""question3.out"", outputs); } private static int findPairs(int a, int b) { Set resultSet = new HashSet(); // int res = 0; if(a == b) return 0; for(int n=a; n nList = intToList(n); int shiftTimes = nList.size()-1; for(int i=1; i<=shiftTimes; i++){ int m = shift(i, nList); if(n < m && m <= b){ Pair pair = new Pair(n, m); // res += 1; if(!resultSet.contains(pair)) resultSet.add(pair); } } } List view = new ArrayList(resultSet); Collections.sort(view); System.out.println(view); return resultSet.size(); // return res; } private static int shift(int shiftTimes, List list){ List copyList = new ArrayList(); copyList.addAll(list); for(int i=0; i intToList(int a){ List l = new LinkedList(); while(a > 0){ int digit = a%10; l.add(0, digit); a /= 10; } return l; } private static int listToInt(List list){ int res = 0; int length = list.size(); int pow = 0; for(int i=length-1; i>=0; i--){ int digit = list.get(i); int value = (int) (digit * Math.pow(10.0, pow)); res += value; pow++; } return res; } } " B11135,"package recyclednumbers.recycler; import junit.framework.Assert; import org.junit.Test; public class RecyclerTest { @Test public void exampleTest() { Recycler recycler = new Recycler(); Assert.assertTrue(recycler.isRecycledPair(12345, 34512)); Assert.assertEquals(0, recycler.countPairs(1, 9)); Assert.assertEquals(3, recycler.countPairs(10, 40)); Assert.assertEquals(156, recycler.countPairs(100, 500)); Assert.assertEquals(287, recycler.countPairs(1111, 2222)); } } " B11354,"package main; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.swing.JFileChooser; import javax.swing.filechooser.FileNameExtensionFilter; import com.google.common.base.Charsets; import com.google.common.base.Splitter; import com.google.common.io.Files; public class Recycle2 { public static void main(String[] args) throws IOException{ final JFileChooser fc = new JFileChooser(new File(""C:\\Users\\munsey\\Documents\\jam"")); FileNameExtensionFilter filter = new FileNameExtensionFilter(""txt"", ""txt""); fc.setFileFilter(filter); int returnVal = fc.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); List lines = Files.readLines(file, Charsets.UTF_8); Iterator itr = lines.iterator(); itr.next(); int caseNum = 0; while(itr.hasNext()) { caseNum++; Iterator minMax = Splitter.on("" "").split(itr.next()).iterator(); int min = Integer.parseInt(minMax.next()); int max = Integer.parseInt(minMax.next()); int size = 0; for(int k = min; k <= max ; k++){ size += recycle(k, min, max); } System.out.println(""Case #"" + caseNum + "": "" + (size/2)); } } } public static int recycle(int input, int min, int max){ Set output = new HashSet(); String sInput = Integer.valueOf(input).toString(); StringBuffer build; for(int i = 0; i < sInput.length(); i++){ build = new StringBuffer(); for(int j = 0; j < sInput.length(); j++){ build.append(sInput.charAt((i + j) % sInput.length())); } if(build.charAt(0) != 0 && !build.toString().equals(sInput)){ int x = Integer.parseInt(build.toString()); if(x >= min && x <= max){ output.add(x); } } } return output.size(); } } " B11736,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package javaapplication2; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Scanner; /** * * @author portz */ public class Main { /** * @param args the command line arguments */ public static void readFile(String filename,String outFile){ // Buffer inpfile=new Buffer() {} Scanner scanner=null; Writer out=null; try { out = new OutputStreamWriter(new FileOutputStream(outFile)); } catch (FileNotFoundException ex) { System.out.println(ex.toString()); } try { scanner = new Scanner(new FileInputStream(filename)); try { String text=""""; int i=0; int limit=0; String []abstr;int A;int B; while (scanner.hasNextLine()){ text=scanner.nextLine(); if(i==0){ i=1; limit=Integer.parseInt(text); }else{ if(i<=limit){ try { abstr=text.split("" ""); A=Integer.parseInt(abstr[0]); B=Integer.parseInt(abstr[1]); out.write(""Case #""+i+"": ""+getrecycle( A, B)); if(i!=limit){ out.write(""\n""); } i++; } catch (IOException ex) { System.out.println(ex.toString()); } } } } } finally{ if(out!=null){ try { out.close(); } catch (IOException ex) { System.out.println(ex.toString()); } } scanner.close(); } } catch (FileNotFoundException ex) { System.out.println(ex.toString()); //Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } public static int getrecycle(int A,int B){ String nostr;//=""""+n; int digitno;//=nostr.length(); int m;//=n; String temp;//=""""+n; int j=0; for(int n=A;n<=B;n++){ //System.out.println(""---------------------------------""); nostr=""""+n; digitno=nostr.length(); m=n; temp=""""+n; //j=0; // System.out.println(temp); if(temp.charAt(0)=='0'){ }else{ for(int i=0;in&&m<=B&&m>=A){ System.out.println(m); j++; } } } } } return j; } public static void main(String[] args) { readFile(""C-small-attempt0.in"", ""C-small-attempt0.out""); // TODO code application logic here // System.out.println(getrecycle( 1, 9));//1 9 10 40 100 500 1111 2222 // System.out.println(getrecycle( 10, 40));//1 9 10 40 100 500 1111 2222 // System.out.println(getrecycle( 100, 500));//1 9 10 40 100 500 1111 2222 // System.out.println(getrecycle( 1111, 2222));//1 9 10 40 100 500 1111 2222 } } " B10626,"package CaseSolvers; import java.util.ArrayList; import Controller.IO; public class AllYourBaseCase extends CaseSolver { private String originalLine; private StringBuilder currentLine; private long numOfSeconds; public AllYourBaseCase(int order, int numberOfLines, IO io) { super(order, numberOfLines, io); } @Override public void addLine(String line) { this.originalLine = line; this.currentLine = new StringBuilder(line); } @Override public void initializeVars() { } @Override public void printSolution() { System.err.println(""Case #"" + getOrder() + "": "" + numOfSeconds); } @Override public CaseSolver process() { ArrayList chars = getDifDigits(); int base = chars.size() > 1 ? chars.size() : 2; replaceDigits(chars, base); numOfSeconds = getNumberInBase10(base); return this; } private long getNumberInBase10(int originalBase) { long num = 0, lenght = currentLine.length(); for (int i = 0; i < lenght; i++) { num += getIntByChar(currentLine.charAt(i)) * Math.pow(originalBase, lenght - (i + 1)); } return num; } private int getIntByChar(char charAt) { if (charAt <= 58) { return charAt - 48; } return charAt - 96 + 9; } private void replaceDigits(ArrayList chars, int base) { replace(chars.remove(0), getNumberChar(1)); if (chars.size() == 0) { return; } replace(chars.remove(0), getNumberChar(0)); int tmp = 2; for (char aaa : chars) { replace(aaa, getNumberChar(tmp)); tmp++; } } private String replace(char a, char b) { String temp = null; int index = -1; do { index = originalLine.indexOf(a, index + 1); if (index > -1) { currentLine.setCharAt(index, b); } } while (index > -1); return temp; } private char getNumberChar(int number) { if (number < 10) { return (char) (number + 48); } return (char) (97 + number - 10); } private ArrayList getDifDigits() { ArrayList tmp = new ArrayList(); char tempChar; for (int i = 0; i < originalLine.length(); i++) { tempChar = originalLine.charAt(i); if (!tmp.contains(tempChar)) { tmp.add(originalLine.charAt(i)); } } return tmp; } } " B11417,"/** * Written By Kylin * Last modified: 2012-4-15 * State: Pending */ package me.kylin.gcj.c2012Q; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class RecycledNumbers { String file; Scanner sc; PrintWriter pr; int caseNO; boolean showDebug; void out(Object str) { str = ""Case #"" + caseNO + "": "" + str; System.out.println(str); if (pr != null) pr.println(str); } void outNoPre(Object str) { System.out.println(str); if (pr != null) pr.println(str); } void debug(Object str) { if (showDebug) System.out.printf(""DEBUG - Case #%d: %s\n"", caseNO, str); } void work() { if (file != null) { try { sc = new Scanner(new FileInputStream(new File(file + "".in""))); pr = new PrintWriter(new File(file + "".out"")); } catch (FileNotFoundException e) { e.printStackTrace(); System.exit(1); } } else { sc = new Scanner(System.in); } int tc = sc.nextInt(); sc.nextLine(); for (caseNO = 1; caseNO <= tc; caseNO++) { solveACase(); if (pr != null) pr.flush(); } if (pr != null) pr.close(); } static String generateFilename(String x, int scale, int t) { String fn = x.toUpperCase(); if (scale == 0) return ""sample""; if (scale == 1) fn += ""-small""; if (scale == 2) fn += ""-large""; if (t < 0) return fn + ""-practice""; if (t > 0) { if (scale == 1) fn += ""-attempt"" + (t - 1); return fn; } return fn; } public static void main(String[] args) { RecycledNumbers cls = new RecycledNumbers(); String base = ""data/2012Q/""; cls.file = base + generateFilename(""C"", 1, 1); cls.showDebug = true; cls.work(); } final static int[] P10 = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000}; int leftShift(byte[] nArr) { byte t = nArr[0]; for (int i = 1; i < nArr.length; i++) { nArr[i - 1] = nArr[i]; } nArr[nArr.length - 1] = t; int m = 0; for (int i = 0; i < nArr.length; i++) { m = m * 10 + nArr[i]; } return m; } void solveACase() { int min = sc.nextInt(); int max = sc.nextInt(); int num = 0; for (int n = min; n < max; n++) { int k = 0; while (n >= P10[k]) k++; byte[] nArr = new byte[k]; int t = n; while (t > 0) { nArr[--k] = (byte)(t % 10); t /= 10; } int m = leftShift(nArr); while (m != n) { if (m > n && m >= min && m <= max) num++; m = leftShift(nArr); } } out(num); } }" B11718,"import java.util.Scanner; public abstract class Question extends Thread{ protected Result result; protected Counter counter; public Question(Result result, Counter counter) { super(); this.result = result; this.counter = counter; } public abstract void readInput(Scanner scanner); public void solveTestCase(){ setResult(solution()); } public abstract String solution(); public String getResult() { return result.output; } public void setResult(String output) { this.result.output = output; } public void run() { solveTestCase(); //System.out.println(result); counter.increase(); } } " B13017,"import java.util.*; import java.io.*; public class ProblemC { public static void main(String[] args){ try{ //Scanner scan = new Scanner(new File(""C-small-attempt0.in"")); Scanner scan = new Scanner(new File(""C-small-attempt0.in"")); int nLines = scan.nextInt(); scan.nextLine(); for(int testCase = 1; testCase <= nLines; testCase++){ int x = scan.nextInt(); int y = scan.nextInt(); int recycled = 0; for(int a = x; a < y; a++){ for(int b = a+1; b <= y; b++){ if(isRecycled(a, b)){ recycled++; } } } System.out.printf(""Case #%d: %d\n"", testCase, recycled); } } catch(FileNotFoundException fnfe){ System.err.println(""File Not Found""); } } public static boolean isRecycled(int a, int b){ String aStr = """" + a; String bStr = """" + b; char firstChar = aStr.charAt(0); int strLen = aStr.length(); int startIndex = bStr.indexOf(firstChar); while(startIndex >= 0){ if(testLocation(aStr, bStr, startIndex)){ return true; } if(startIndex < (strLen-1)){ int newIndex = bStr.substring(startIndex + 1).indexOf(firstChar); if(newIndex >= 0){ startIndex += newIndex + 1; } else { break; } } else { startIndex = -1; } } return false; } public static boolean testLocation(String a, String b, int startPos){ for(int i = 0; i0){ linea = bf.readLine(); String[] nums = linea.split("" ""); int result = 0; int a = Integer.parseInt(nums[0]); int b = Integer.parseInt(nums[1]); for (int i = a; i <=b; i++) { int actual = i; ArrayList transpuestos = trasponer(actual); result+=generarParejas(actual, b,transpuestos); } System.out.println(""Case #""+cont+"": ""+result); cont++; casos--; } } private static int generarParejas(int actual, int b, ArrayList lista) { int cont = 0; for (int i = actual+1; i <=b; i++) { if(lista.contains(i)) cont++; } return cont; } private static ArrayList trasponer(int actual) { String ini = actual+""""; ArrayList resp = new ArrayList(); for (int i = 0; i < ini.length()-1; i++) { String s = ini.substring(ini.length()-1-i)+ini.substring(0,ini.length()-1-i); resp.add(Integer.parseInt(s)); } return resp; } }" B12095,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class main { /** * @param args */ public static void main(String[] args) { try { System.setOut(new PrintStream(new File(""C-small-attempt0.out""))); Scanner sc = new Scanner(new File(""C-small-attempt0.in"")); int T = sc.nextInt(); sc.nextLine(); for (int t = 1; t<=T; t++) { int y = 0; int A = sc.nextInt(); int B = sc.nextInt(); for (int n = A; n> recycled = new HashMap>(); String[] AB = line.split("" ""); for (int min = Integer.valueOf(AB[0]), max = Integer.valueOf(AB[1]), i = min ; i < max ; i++) { String currVal = String.valueOf(i); String rotatedVal = currVal; for (int j = 0; j < currVal.length() - 1; j++){ rotatedVal = rotateRight(rotatedVal); if (String.valueOf(Integer.valueOf(rotatedVal)).length() != String.valueOf(Integer.valueOf(currVal)).length()) continue; int iVal = Integer.valueOf(rotatedVal); if (iVal >= min && iVal <= max && iVal != i) { int key, val; if (i < iVal) { key = i; val = iVal; } else { key = iVal; val = i; } if (recycled.containsKey(key)) { List allVal = recycled.get(key); if (allVal != null) { if (!allVal.contains(val)) { allVal.add(val); result++; } } } else { List addedVal = new ArrayList(); addedVal.add(val); recycled.put(key, addedVal); result++; } } } } writer.write(""Case #"" + ++currentLine + "": "" + result + ""\n""); } reader.close(); writer.close(); } } catch (Exception exc) { exc.printStackTrace(); } } private static String rotateRight(String sInput) { int len = sInput.length(); char[] outstring = sInput.toCharArray(); char ch = outstring[len - 1]; for (int j = len -1; j > 0; j--) { outstring[j] = outstring[j - 1]; } outstring[0] = ch; return String.valueOf(outstring); } } " B11795,"package gcj2012.qualificationround; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { public static void main(String[] args) throws Exception { solve(System.in, System.out); } private static void solve(InputStream in, PrintStream out) throws IOException { Scanner scanner = new Scanner(in); int T = scanner.nextInt(); for (int t=1; t<=T; t++) { final int A = scanner.nextInt(); final int B = scanner.nextInt(); Map> pairs = new LinkedHashMap>(); for (int i=A; i<=B; i++) { pairs.put(i, new LinkedHashSet()); } for (int i=A; i<=B; i++) { String s = Integer.toString(i); for (int splitPoint=1; splitPoint<=numDigitsIn(A)-1; splitPoint++) { String sa = s.substring(0, splitPoint); String sb = s.substring(splitPoint); int newnum = Integer.parseInt(sb+sa); if (i < newnum && newnum <= B) { pairs.get(i).add(newnum); } } } int numRecycledPairs = 0; for (int n=A; n it = hm.entrySet().iterator(); while (it.hasNext()) { contador++; it.next(); } out.print(""Case #""+z+"": ""); out.print(contador); out.println(""""); } out.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B12919,"package com.afarok.google.codejam2012.qualificationround; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class CRecycledNumber { public static void main(String[] ags) { //System.setIn(new FileInputStream(""src/com/afarok/google/codejam2012/qualificationround/C-small-attempt0.in"")); //System.setOut(new PrintStream(new File(""src/com/afarok/google/codejam2012/qualificationround/C-small-attempt0.out""))); Scanner stdIn = new Scanner(System.in); int t = stdIn.nextInt(); for(int tCase = 1;tCase<=t;++tCase) { int a = stdIn.nextInt(); int b = stdIn.nextInt(); //boolean[] recycled = new boolean[b+1]; int y=0; for(int i=a;i<=b;++i) { Set recyledSet = new HashSet(); for(int x=10;;x=x*10) { int r = i%x; if(r==0) continue; int d = i/x; if(d==0) break; int lenghtOfd = (int) Math.floor(Math.log10(d)) + 1; int recycledNum = (int) (r*Math.pow(10, lenghtOfd))+d; if(recycledNum<=i) continue; if(recyledSet.contains(recycledNum)) continue; if(recycledNum>=a&&recycledNum<=b) { ++y; recyledSet.add(recycledNum); } } } System.out.println(""Case #""+tCase+"": "" + y); } } } " B12831,"package com.cj.rn; import com.cj.utils.*; import java.io.*; import java.util.Scanner; public class RecycledNumbers { int from; int to; public String getResult(int caseNo, int from, int to){ int tempFrom = from; int result = 0; while(tempFrom""+mS); } } tempFrom++; } return ""Case #""+caseNo+"": ""+result; } public static int countOccurrences(String haystack, char needle) { int count = 0; for (int i=0; i < haystack.length(); i++) { if (haystack.charAt(i) == needle) { count++; } } return count; } public static void main(String[] args){ RecycledNumbers obj = new RecycledNumbers(); System.out.println(obj.getResult(1, 1111, 2222)); InputReader ir = new InputReader(); Scanner input = ir.loadInput(""C-small-attempt0.in""); int cases = ir.cases; OutputWriter ow = new OutputWriter(""C-small-attempt0.out""); for(int count=0 ; count seen = new ArrayList<>(); for (int j = 1; j < length; j++) { int cycle = Integer.parseInt(s.substring(j, length) + s.substring(0, j)); if (!seen.contains(cycle) && cycle <= high && cycle > i) { ans++; //System.out.println(Integer.toString(i) + "" "" + Integer.toString(cycle)); } seen.add(cycle); } } writer.writeLine(""Case #"" + caseNo + "": "" + ans); } private static boolean isRecycled(int n, int m) { String ns = Integer.toString(n); String ms = Integer.toString(m); if (ns.length() != ms.length()) { return false; } for (int i = 1; i < ns.length(); i++) { if (ns.equals(ms.substring(i, ms.length()) + ms.substring(0, i))) { return true; } } return false; } } " B13033,"package qualification.q1; import com.sun.deploy.net.proxy.StaticProxyManager; import qualification.common.InputReader; import qualification.common.OutputWriter; /** * Created by IntelliJ IDEA. * User: ofer * Date: 14/04/12 * Time: 17:36 * To change this template use File | Settings | File Templates. */ public class Q1Sim { public static void main(String[] args){ String inputFile = ""input.txt""; String outPutFile = ""output.txt""; String[] lines = InputReader.getInputLines(inputFile); Q1Solver solver = new Q1Solver(); int numOfTests = Integer.parseInt(lines[0]); String[] output = new String[numOfTests]; for (int i = 0 ; i < numOfTests ; i++){ String decrypted = solver.convertString(lines[i+1]); output[i] = ""Case #"" + (i+1) + "": "" + decrypted; } OutputWriter.writeOutput(outPutFile,output); } } " B11321,"import java.io.*; public class Numbers{ public static void main(String args[]){ try{ FileInputStream fstream = new FileInputStream(args[0]); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); PrintWriter out = new PrintWriter(args[0] + ""_out""); String strLine = br.readLine(); int cases = Integer.parseInt(strLine); for (int i = 0; i < cases; i++){ //System.out.println("" i "" + i); strLine = br.readLine(); String[] a_and_b = strLine.split("" ""); int a = Integer.parseInt(a_and_b[0]); int b = Integer.parseInt(a_and_b[1]); int length = String.valueOf(a).length(); int[] found_as = new int[(int)java.lang.Math.pow(10,length+1)]; int solutions = 0; for (double j = java.lang.Math.pow(10,length-1); j < java.lang.Math.pow(10,length); j++){ //System.out.println("" j "" + j); String this_number = String.valueOf(j); //System.out.println(""this_number = "" + this_number); char[] this_numbers_ciphers = this_number.toCharArray(); //for (int k = 0; k < this_numbers_ciphers.length; k++) System.out.println(""this_numbers_ciphers = "" + this_numbers_ciphers[k]); for (int k = 0; k < length; k++){ //System.out.println("" k "" + k); char[] this_recycles_ciphers = new char[length]; for (int l = 0; l < length; l++) { //System.out.println("" l "" + l); //System.out.println(""vor mod""); int new_pos = (l + k) % length; //System.out.println(""new pos = "" + new_pos); //System.out.println(""length = "" + length); //System.out.println(""this_numbers_ciphers[new_pos] = "" + this_numbers_ciphers[new_pos]); //System.out.println(""this_recycles_ciphers[l] = "" + this_recycles_ciphers[l]); this_recycles_ciphers[l] = this_numbers_ciphers[new_pos]; //System.out.println(""nach mod"" + l); } //System.out.println(""-- vor new String""); int m = Integer.parseInt(new String(this_recycles_ciphers)); //System.out.println(""-- nach new String""); //System.out.println(""--- vor if-Block""); if ( a <= m && m < j && j <= b){ boolean double_flag = false; //System.out.println(""---- vor double_flag schleife""); for (int l = 0; l < 2*solutions; l++) { //System.out.println(""---- vor if-block in double_flag schleife""); //System.out.println(""found_as[2*l] = "" + found_as[2*l]); //System.out.println(""(int)j = "" + (int)j); //System.out.println(""found_as[2*l+1] = "" + found_as[2*l+1]); //System.out.println(""(int)m) = "" + (int)m); if (found_as[2*l] == (int)j && found_as[2*l+1] == (int)m) { //System.out.println(""----- vor anweisung""); double_flag = true; //System.out.println(""----- nach anweisung""); } //System.out.println(""---- nach if-block in double_flag schleife""); } //System.out.println(""---- nach double_flag schleife""); found_as[2*solutions] = (int)j; found_as[2*solutions+1] = (int)m; if (double_flag != true) solutions++; double_flag = false; //System.out.println(""case "" + i + "" solution "" + solutions + "" a "" + a + "" b "" + b + "" j "" + j + "" m "" + m); } //System.out.println(""--- nach if-Block""); } } out.println(""Case #"" + (i+1) + "": "" + solutions); } in.close(); out.close(); } catch (Exception e){ System.err.println(""Error: "" + e.getMessage()); } } } " B12184,"import java.io.*; public class ProC { public static void main(String args[]) { try { BufferedReader br = new BufferedReader(new FileReader(""E:\\test.txt"")); int n; n= Integer.parseInt(br.readLine()); int casen=0,i,j; int a,b,count; String temp,t,u; String outp; outp=""""; String spl[]; String memory; while( casen < n ) { temp = br.readLine(); outp += ""Case #""+(casen+1)+"": ""; spl = temp.split("" ""); a = Integer.parseInt(spl[0]); b = Integer.parseInt(spl[1]); count = 0; memory = """"; //for(i=a;i<= Math.ceil( a+(b-a)/2f ); i++) for(i=a;i<=b; i++) { t = i+""""; for(j=1;j= a) { count++; //if( casen == n-1 ) // System.out.println(Integer.parseInt(u)+"" ""+i); memory += Integer.parseInt(u) + "" "" + i+""\n""; } } } outp += count; if( casen != n-1 ) outp += ""\n""; casen++; } System.out.println(outp); BufferedWriter bw = new BufferedWriter( new FileWriter(""E:\\result.txt"")); bw.write(outp); bw.close(); br.close(); } catch( Exception e ) { e.printStackTrace(); } } } " B10723,"package nl.maartenvangrootel.googlecodejam.qualifier.recycling; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.regex.Pattern; /** * Hello world! * */ public class Recycling { private File file; private static Pattern pattern = Pattern.compile(""[\\ ]""); public Recycling(String filename) { if (filename == null) throw new IllegalArgumentException(""filename should not be null""); file = new File(filename); if (!(file.exists() && file.isFile())) throw new IllegalArgumentException(String.format( ""'%s' does not exist or is not a file."", filename)); } private BufferedReader getReader() { BufferedReader reader = null; try { FileReader stream = new FileReader(file); reader = new BufferedReader(stream); } catch (FileNotFoundException e) { e.printStackTrace(); } return reader; } public String calculateResult() { BufferedReader reader = getReader(); StringBuilder builder = new StringBuilder(); try { int numberOfCases = Integer.parseInt(reader.readLine()); int i = 1; String line; while ((line = reader.readLine()) != null) { if (i > 1) { builder.append(""\n""); } builder.append(""Case #""); builder.append(i); builder.append("": ""); builder.append(parseLine2(line)); i++; } } catch (IOException e) { e.printStackTrace(); } return builder.toString(); } public static long parseLine2(String line) { String[] input = pattern.split(line); int length = input[0].length(); boolean even = length % 2 == 0; long mod = (long) Math.pow(10, (length / 2)); long A = Integer.parseInt(input[0]); long B = Integer.parseInt(input[1]); long cnt = 0; long compensation = 0; for (long n = A; n <= B; n++) { String strN = String.valueOf(n); for (int i = length - 1; i > 0; i--) { for (int j = length; j > i; j--) { String deel1 = strN.substring(i, j); String deel2 = strN.substring(0, i); String strM = deel1 + deel2; if ("""".equals(strM)) continue; long m = Long.parseLong(strM); if (m >= A && m <= B && n < m) { if (even && n % mod == n / mod) { compensation++; } cnt++; } } } } return cnt - compensation / 2; } public static void main(String[] args) { Recycling starter = new Recycling(""src/main/resources/small.txt""); String result = starter.calculateResult(); System.out.println(result); } } " B11058,"package fixjava; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; /** * Pair: typed 2-tuple */ public class Pair { private final L left; private final R right; public R getRight() { return right; } public L getLeft() { return left; } public Pair(final L left, final R right) { this.left = left; this.right = right; } /** Convenience method so type params of pair don't have to be specified: just do Pair.make(l, r) */ public static Pair make(L left, R right) { return new Pair(left, right); } // --------------------------------------------------------------------------------------------------- private static final boolean objEquals(Object p1, Object p2) { if (p1 == null) return p2 == null; return p1.equals(p2); } @Override public final boolean equals(Object o) { if (!(o instanceof Pair)) { return false; } else { final Pair other = (Pair) o; return objEquals(getLeft(), other.getLeft()) && objEquals(getRight(), other.getRight()); } } @Override public int hashCode() { int hl = getLeft() == null ? 0 : getLeft().hashCode(); int hr = getRight() == null ? 0 : getRight().hashCode(); return (hl + (127 * hr)) ^ (hr << 1); } // --------------------------------------------------------------------------------------------------- @Override public String toString() { return ""("" + getLeft() + "", "" + getRight() + "")""; } // --------------------------------------------------------------------------------------------------- public static ArrayList getAllLefts(Iterable> list) { ArrayList result = new ArrayList(); for (Pair pair : list) result.add(pair.getLeft()); return result; } public static ArrayList getAllRights(Iterable> list) { ArrayList result = new ArrayList(); for (Pair pair : list) result.add(pair.getRight()); return result; } // --------------------------------------------------------------------------------------------------- public static , B> Comparator> comparatorOnLeft(Collection> tupleCollection) { return new Comparator>() { @Override public int compare(Pair o1, Pair o2) { return o1.getLeft().compareTo(o2.getLeft()); } }; } public static , B> Comparator> comparatorOnLeftRev(Collection> tupleCollection) { return new Comparator>() { @Override public int compare(Pair o1, Pair o2) { return -o1.getLeft().compareTo(o2.getLeft()); } }; } public static > Comparator> comparatorOnRight(Collection> tupleCollection) { return new Comparator>() { @Override public int compare(Pair o1, Pair o2) { return o1.getRight().compareTo(o2.getRight()); } }; } public static > Comparator> comparatorOnRightRev(Collection> tupleCollection) { return new Comparator>() { @Override public int compare(Pair o1, Pair o2) { return -o1.getRight().compareTo(o2.getRight()); } }; } static , B> Comparator> comparatorOnLeft(Collection> tupleCollection, final boolean ascending) { return new Comparator>() { final int weight = ascending ? 1 : -1; @Override public int compare(Pair o1, Pair o2) { return o1.getLeft().compareTo(o2.getLeft()) * weight; } }; } static > Comparator> comparatorOnRight(Collection> tupleCollection, final boolean ascending) { return new Comparator>() { final int weight = ascending ? 1 : -1; @Override public int compare(Pair o1, Pair o2) { return o1.getRight().compareTo(o2.getRight()) * weight; } }; } // --------------------------------------------------------------------------------------------------- /** Sort a List> in-place into order of increasing or decreasing K */ public static , V> void sortPairsByLeft(List> list, boolean ascending) { Collections.sort(list, comparatorOnLeft(list, ascending)); } /** Sort a List> in-place into order of increasing K */ public static , V> void sortPairsByLeft(List> list) { Collections.sort(list, comparatorOnLeft(list, true)); } /** Sort a List> in-place into order of increasing or decreasing V */ public static > void sortPairsByRight(List> list, boolean ascending) { Collections.sort(list, comparatorOnRight(list, ascending)); } /** Sort a List> in-place into order of increasing V */ public static > void sortPairsByRight(List> list) { Collections.sort(list, comparatorOnRight(list)); } /** Convert a map into a list of Pair, final order unspecified */ public static ArrayList> mapToList(HashMap map) { ArrayList> list = new ArrayList>(); for (Entry ent : map.entrySet()) list.add(new Pair(ent.getKey(), ent.getValue())); return list; } } " B10699,"import java.io.*; import java.util.*; import java.math.*; public class Main implements Runnable { static int power = 1; private static String filename; public static void main(String[] args) { if (args.length>0 && args[0].equals(""f"")) filename = ""input.txt""; else filename = """"; new Thread(new Main()).start(); } private static void debug(Object ... str) { for (Object s : str) System.out.print(s + "", ""); System.out.println(); } private void check(int x, int y, int ndig) { int temp = x; int[] digx = new int[ndig]; int[] digy = new int[ndig]; for (int i = 0; i < ndig; ++i, temp = temp / 10) { digx[i] = temp % 10; } temp = y; for (int i = 0; i < ndig; ++i, temp = temp / 10) { digy[i] = temp % 10; } boolean equal = false; for (int sh = 1; !equal && sh < ndig; ++sh) { equal = true; for (int i = 0; equal && i < ndig; ++i) { if (digx[(i + sh) % ndig] != digy[i]) { equal = false; } } } if (!equal || x >= y) System.out.println(""HAHAHA "" + x + "" "" + y); } public void run() { try{ MyScanner in; Locale.setDefault(Locale.US); if (filename.length()>0) in = new MyScanner(filename); else in = new MyScanner(System.in); PrintWriter out = new PrintWriter(System.out); int T = in.nextInt(); for (int test = 0; test < T; ++test) { int a = in.nextInt(); int b = in.nextInt(); int temp = a; int ndig = 0; while (temp > 0) { temp /= 10; ndig++; } int[] dig = new int[ndig]; power = 1; for (int i = 1; i slices = new ArrayList(); int k = 10, d=1; int l = L, h=H; while(true) { if (l>=k) { k*=10;d++; continue; } if (h ps = new ArrayList(); int ret = 0; //System.out.println(slices); for(Slice slice:slices) { for(int i=slice.L; i<=slice.H; i++) { int n=i; ArrayList past = new ArrayList(); for (int j=0;j<(slice.dig-1);j++) { int dd=n%10; n=(n/10)+dd*slice.mul; if (n>i && n<=slice.H && !past.contains(n)) { //System.out.println(""checking ("" + i + "", "" + n + "")""); /*Pair p=new Pair(i,n); for(Pair c:ps) { if (c.equal(p)) { System.out.println(""Duplicate: "" + p); } } ps.add(p);*/ ret++; past.add(n); } } } } return ret; } /** * @param args */ public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for(int t=1;t<=T;t++) { int L = in.nextInt(); int H = in.nextInt(); System.out.printf(""Case #%d: %d%n"", t, solve(L,H)); } } } " B10404,"import java.io.*; public class RecycledNumbers { /** * @param args */ static int isOK(int m, int n) { String sm = """" + m; String sn = """" + n; if (sm.length() != sn.length()) return 0; int k = sm.length(); for (int i = 1; i < k; i++) { String tmp = sm.substring(i) + sm.substring(0, i); if (tmp.equals(sn)) return 1; } return 0; } public static void main(String[] args) { try { FileReader fileReader = new FileReader(""C-small-attempt0.in.txt""); FileWriter fileWriter = new FileWriter(""out.txt""); BufferedReader reader = new BufferedReader(fileReader); BufferedWriter writer = new BufferedWriter(fileWriter); String inputString; inputString = reader.readLine(); int cases = Integer.parseInt(inputString); for (int caseCount = 0; caseCount < cases; caseCount++) { inputString = reader.readLine(); String output = ""Case #"" + (caseCount+1) + "": ""; String[] split = inputString.split("" ""); int m = Integer.parseInt(split[0]); int n = Integer.parseInt(split[1]); int ans = 0; for (int i = m; i <= n; i++) for (int j = i + 1; j <= n; j++) { ans += isOK(i, j); } output += ans; output += '\n'; writer.write(output); } reader.close(); writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B11987,"import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class RecycledPair{ public static ArrayList pairsList; public static void main(String[] args) throws Exception{ System.setIn(new BufferedInputStream(new FileInputStream("".\\input\\C-small-attempt0.in""))); System.setOut(new PrintStream(new File("".\\output\\C-small-attempt0.out""))); Scanner in = new Scanner(System.in); pairsList=new ArrayList(); int caseNum=in.nextInt(); for(int i=0;ipairs -->""+count); } //getPairOf(movedTarget, begin, end,count); } } return count; } public static int[] parseIntToIntArray(int param){ int i=1; int target=param; while(target/10>=1){ i++; target=target/10; } int[] result=new int[i]; for(i=0;ib)return 1; if(a 0 ; i++, d *= 10, a /= 10){ int b = n % d; int m = (k10/d) * b + a; if (m > n){ boolean add = true; for (int exists : mar){ if (exists == m){ add = false; break; } } if (add) { mar[i] = m; } } } nm[n] = mar; } //System.out.println(System.currentTimeMillis() - t); } @Override protected String solve() { int A = scanner.nextInt(); int B = scanner.nextInt(); int count = 0; for (int n = A ; n < B; n++) { for (int m : nm[n]) { if (m > 0 && m <= B){ count++; } } } return count + """"; } } " B10007,"import java.io.*; import java.math.BigInteger; import java.util.*; import org.jfree.data.function.PowerFunction2D; public class r2a { Map numMap = new HashMap(); int output = 0; /** * @param args */ public static void main(String[] args) { r2a mk = new r2a(); try { FileInputStream fstream = new FileInputStream(""d:/cjinput.txt""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String str; int i = 0; while ((str = br.readLine()) != null) { int begin=0,end = 0; i++; if (i == 1) continue; mk.numMap = new HashMap(); StringTokenizer strTok = new StringTokenizer(str, "" ""); while (strTok.hasMoreTokens()) { begin = Integer.parseInt(((String) strTok.nextToken())); end = Integer.parseInt(((String) strTok.nextToken())); } mk.evaluate(i, begin, end); } in.close(); } catch (Exception e) { System.err.println(e); } } private void evaluate(int rowNum, int begin, int end) { output=0; for (int i = begin; i<= end; i++) { if(numMap.containsKey(Integer.valueOf(i))) continue; List l = getPairElems(i); if (l.size() > 0) { Iterator itr = l.iterator(); int ctr = 0; ArrayList tempList = new ArrayList(); while (itr.hasNext()) { int next = ((Integer)itr.next()).intValue(); if (next <= end && next > i) { numMap.put(Integer.valueOf(next), i); tempList.add(next); ctr++; } } ctr = getCounter(ctr+1,2); /* if (tempList.size() > 0 || ctr > 0) System.out.println(""DD: "" + i + "": "" + tempList +"" ; ctr = "" + ctr);*/ output = output + ctr; } } String outputStr = ""Case #"" + (rowNum -1) + "": "" + output; System.out.println(outputStr); } private int getCounter(int n, int r) { int ret = 1; int nfactorial =1; for (int i = 2; i<=n; i++) { nfactorial = i*nfactorial; } int nrfact =1; for (int i = 2; i<=n-r; i++) { nrfact = i*nrfact; } return nfactorial/(2*nrfact); } private ArrayList getPairElems(int num) { ArrayList retList = new ArrayList(); int temp = num; if (num/10 == 0) return retList; String str = String.valueOf(num); int arr[] = new int[str.length()]; int x = str.length(); while (temp/10 > 0) { arr[x-1] = temp%10; temp=temp/10; x--; } arr[0]=temp; int size = arr.length; for (int pos = size -1; pos >0; pos--) { if(arr[pos] == 0) continue; int pairNum = 0; int multiplier =1; for (int c=0; c < size-1; c++) { multiplier = multiplier*10; } pairNum = pairNum + (arr[pos]*multiplier); for(int ctr = pos+1, i=1; i < size; i++,ctr++) { if (ctr == size) ctr=0; if (multiplier!=1) multiplier=multiplier/10; pairNum = pairNum + (arr[ctr]*multiplier); } if (pairNum != num) retList.add(Integer.valueOf(pairNum)); } return retList; } } " B13116,"package com.vp.fact; import com.vp.iface.Problem; import com.vp.impl.DancingWithGooglers; import com.vp.impl.RecycledNumbers; import com.vp.impl.SpeakGooglerese; public class SolutionFactory { public static Problem getInstance(int problem) { Problem s = null; switch(problem) { case 1: s= new SpeakGooglerese(); break; case 2: s= new DancingWithGooglers(); break; case 3: s= new RecycledNumbers(); break; } return s; } } " B10955,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package pkg2012codejam; import java.io.*; import java.util.ArrayList; /** * * @author Nimos */ public class QuestionC { public static void main(String args[]) { try { File input = new File(""C:\\Users\\Nimos\\Desktop\\INPUTS\\2012\\C-small-attempt0(1).in""); FileReader fr = new FileReader(input); BufferedReader br = new BufferedReader(fr); PrintWriter out = new PrintWriter(new File(""C:\\Users\\Nimos\\Desktop\\INPUTS\\2012\\C-small-ans.in"")); String no = br.readLine(); int number = Integer.parseInt(no); for (int h = 0; h <= number - 1; h++) { int done =0; String nos = br.readLine(); String[] n = nos.split("" ""); int s = Integer.parseInt(n[0]); int e = Integer.parseInt(n[1]); int size = n[0].length(); // ArrayList al = new ArrayList(); for (int i=s;i<=e;i++){ String t = Integer.toString(i); for (int j = 1;ji && k<=e && k>=s){ done++; //System.out.println(done + "" "" + i); //al.add(t); } } } int m = 1 + h; String ans = ""Case #"" + m + "": "" + done; out.println(ans); out.flush(); } br.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } } " B11910,"import java.io.*; import java.math.*; import java.util.*; class Main{ static BufferedReader br; static PrintWriter pw; static File in; static File out; static String name=""C-small-attempt0""; public static void main(String[] args){ try{ in=new File(name+"".in""); out=new File(name+"".out""); br=new BufferedReader(new FileReader(in)); pw=new PrintWriter(new BufferedWriter(new FileWriter(out))); int nbCase = Integer.parseInt(br.readLine()); for (int n=1;n<=nbCase;n++){ String line=br.readLine(); long a=Long.parseLong(line.substring(0,line.indexOf("" ""))); long b=Long.parseLong(line.substring(line.indexOf("" "")+1)); long count=0; for (long n1=a;n110 && (sn.length() == sm.length())){ for (int i = 1; i listOfCases); public void solveCases(); } " B10766,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package RecycledNumbers; import java.io.File; import java.io.FileWriter; import java.io.Writer; import java.util.LinkedList; import java.util.List; import java.util.Scanner; /** * * @author Rishabh */ public class RecycledNumbers { public void readFile(String path) throws Exception{ File f = new File(path); Scanner scan = new Scanner(f); String name = f.getName().substring(0,f.getName().indexOf('.')); Writer writer = new FileWriter(name+"".out""); int total_cases = Integer.parseInt(scan.nextLine()); int caseno=0; while(scan.hasNextLine()){ caseno++; long[] toIntArray = toIntArray(scan.nextLine().split("" "")); int ans = compute((int)toIntArray[0],(int)toIntArray[1]); writer.write(""Case #""+caseno+"": ""+ans+""\r\n""); } writer.close(); scan.close(); } public static long[] toIntArray(String[] arr){ long[] new_arr = new long[arr.length]; int count = 0; for(String g : arr){ new_arr[count] = Long.parseLong(g); count++; } return new_arr; } private int compute(int A, int B) { int count=0; List[] l = new LinkedList[B-A+1]; for(int i=A;i<=B;i++){ int c = getAllPermutations(i, A, B, l); count += c; //System.out.println(""permutations for : ""+i+"" are "" + c); } return count; } private int getAllPermutations(int num, int A, int B, List[] l){ String g = String.valueOf(num); List permutations = new LinkedList(); boolean found = false; for(int i=1;iB||parseInt= B) res = 0; else res = findRecycle(A,B); int x = i+1; p.println(""Case #"" + x + "": "" + res); } } catch(Exception e) { e.printStackTrace(); } } public static int findRecycle(int A, int B) { System.out.println(""Find recycle "" + A +"", "" + B); int count = 0; for (int n = A; n < B; n++) { for (int m = n + 1; m <= B; m++) { if(isRecycled(Integer.toString(n), Integer.toString(m))) count++; //System.out.println(count); } } return count; } public static boolean isRecycled(String n, String m) { int suffixes = n.length(); for (int i = 1; i < suffixes; i++) { String tmp = n.substring(i); String toComp = tmp; for (int x = 0; x < i; x++) { toComp += n.charAt(x); } if(toComp.equals(m)) return true; } return false; } }" B11719,"import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class QuestionA extends Question{ private static Map translationMap; private static boolean isInit; private StringBuilder sb; public QuestionA(Result result, Counter counter) { super(result, counter); if (!isInit) { init(); isInit=true; } } private void init() { translationMap = new HashMap(); String text = ""zyeq""+""ejp mysljylc kd kxveddknmc re jsicpdrysi""+""rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd""+""de kr kd eoya kw aej tysr re ujdr lkgc jv""; String translation = ""qaoz""+""our language is impossible to understand""+""there are twenty six factorial possibilities""+""so it is okay if you want to just give up""; for (int i = 0; i < text.length(); i++) { if (!translationMap.containsKey(text.charAt(i))) translationMap.put(text.charAt(i), translation.charAt(i)); } } @Override public void readInput(Scanner scanner) { sb = new StringBuilder(); sb.append(scanner.nextLine()); } @Override public String solution() { for (int i = 0; i < sb.length(); i++) { sb.setCharAt(i, translationMap.get(sb.charAt(i))); } return sb.toString(); } } " B10873,"package de.at.codejam.problem3.util; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.util.List; import java.util.StringTokenizer; import de.at.codejam.problem3.Problem3Case; import de.at.codejam.util.AbstractInputFileParser; import de.at.codejam.util.TaskStatus; public class Problem3InputFileParser extends AbstractInputFileParser { private int nextCaseNumber = 1; private int nextCaseLine = 2; public Problem3InputFileParser(File inputFile) { super(inputFile); } @Override public Problem3Case getNextCase() throws IOException { Problem3Case problem3Case = new Problem3Case(); TaskStatus taskStatus = getTaskStatus(); BufferedReader bufferedReader = null; try { bufferedReader = checkoutBufferedReader(); taskStatus.setNumberCurrentCase(nextCaseNumber); List lineList = readLines(bufferedReader, nextCaseLine, 1); String stringCase = lineList.get(0); StringTokenizer stringTokenizer = new StringTokenizer(stringCase, "" ""); String numberA = stringTokenizer.nextToken().trim(); String numberB = stringTokenizer.nextToken().trim(); problem3Case.setNumberA(numberA); problem3Case.setNumberB(numberB); nextCaseNumber++; nextCaseLine += 1; } finally { if (null != bufferedReader) { try { checkinBufferedReader(bufferedReader); } catch (IOException e) { } } } return problem3Case; } } " B12278,"import java.util.*; public class C { public static void main (String [] arg) { int [][] store = new int [2000010][7]; for (int i = 1; i i) store[i][ptr++] = j; j = rotate(j); } } Scanner sc = new Scanner(System.in); int T = Integer.parseInt(sc.nextLine()); for (int ii = 1; ii<=T; ++ii) { //Something int A = sc.nextInt(); int B = sc.nextInt(); int count = 0; for (int a = A; a 0; ++i) if (store[a][i] <= B) count++; int ans = count; System.out.printf(""Case #%d: %s\n"",ii,ans); } } public static int rotate(int a) { String s = Integer.toString(a); do { s = s.substring(1) + s.charAt(0); } while (s.charAt(0) == '0'); return Integer.parseInt(s); } }" B10688,"package utils; import java.io.FileInputStream; import java.io.FileWriter; import java.io.PrintWriter; import java.util.Scanner; public class Numbers { public static void main(String[] args) { lecture(""/Users/valentinbonneaud/Downloads/C-small-attempt0.in""); } public static void lecture(String name){ Scanner flux = null; PrintWriter out; try { flux = new Scanner(new FileInputStream(name)); out = new PrintWriter(new FileWriter(""/Users/valentinbonneaud/Downloads/C-small-practice out.in"", false)); } catch (Exception e1) { e1.printStackTrace(); return; } int nb = flux.nextInt(); flux.nextLine(); for(int i =0;i hash; public int powersOfTen[]; private void solve(String filePrefix) throws Exception { StreamTokenizer st = new StreamTokenizer(new BufferedReader(new FileReader(filePrefix + "".in""))); PrintWriter pw = new PrintWriter(new FileWriter(filePrefix + "".out"")); st.nextToken(); int testsCount = (int) st.nval; for (int tc=0; tc 0) { temp /= 10; digits++; } powersOfTen = new int[digits]; powersOfTen[0] = 1; for (int i=1; i(); for (int n=a; n b) continue; long encoded = (n+0L) << 30L; encoded += m; if (encoded < 0) throw new RuntimeException(); hash.add(encoded); } } } " B12279,"package cj2012.qual; import java.io.File; import java.io.PrintWriter; import java.util.Scanner; import java.util.TreeSet; public class C { public static void main(String[] args) throws Exception { Scanner scan = new Scanner(new File(""in/C-small-attempt0.in"")); int T = scan.nextInt(); PrintWriter out = new PrintWriter(new File(""out/C-small-attempt0.txt"")); for (int z = 1; z <= T; z++) { int A = scan.nextInt(); int B = scan.nextInt(); int D = 1 + (int) Math.log10(B); int C = (int) Math.pow(10, D - 1); int res = 0; TreeSet set = new TreeSet(); for (int n = A; n <= B; n++) { for (int s = 1; s < D; s++) { int m = n; for (int k = 0; k < s; k++) m = (m % 10) * C + (m / 10); if (m < A || m > B || n >= m) continue; set.add(m); } res += set.size(); set.clear(); } out.println(""Case #"" + z + "": "" + res); } out.close(); } } " B11081,"/** * */ package fixjava; public class ConcurrentCounter { private int count = 0; public synchronized int getAndIncrement() { return count++; } }" B10884,"package de.at.codejam.util; public interface StatusListener { public static final int LOGLEVEL_TRACE = 4; public static final int LOGLEVEL_INFO = 3; public static final int LOGLEVEL_WARN = 2; public static final int LOGLEVEL_ERROR = 1; void updateStatus(TaskStatus taskStatus); void log(int logLevel, String message); } " B11734,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package test3; import java.io.*; import java.util.LinkedList; import java.util.Scanner; /** * * @author Student */ public class Test3 { public static int rotations(int number, int max) { int l = 0; int start = number; int numdigits = (int) Math.log10((double) number); int multiplier = (int) Math.pow(10.0, (double) numdigits); while (true) { int q = number / 10; int r = number % 10; number = number / 10; number = number + multiplier * r; if (number > start && Integer.toString(number).length() == numdigits + 1 && number <= max) { l++; } if (number == start) { break; } } return l; } public static int possibilities(int A, int B){ int K = 0; for (int i = A; i <= B; i++) { K += rotations(i,B); } return K; } public static void main(String[] args) throws FileNotFoundException { // TODO code application logic here int i=1; int max = 0; Scanner ss=new Scanner(new File(""C-small-attempt1.in.txt"")); PrintWriter x=new PrintWriter(new File(""C-small-attempt1.out.txt"")); if(ss.hasNext()) max=Integer.parseInt(ss.next()); while(ss.hasNextLine()&&i<=max){ int A = 0; if(ss.hasNext()) A=Integer.parseInt(ss.next()); int B = 0; if(ss.hasNext()) B=Integer.parseInt(ss.next()); x.println(""Case #""+i+"": ""+possibilities(A, B)); i++; } x.close(); } } " B11841,"package info.m3o.gcj2012.recyclednumber; public class ResultUtil { MyNumberStringSet testedNumberSet; MyNumberStringPairSet recycledNumberSet; public ResultUtil() { testedNumberSet = new MyNumberStringSet(); recycledNumberSet = new MyNumberStringPairSet(); assert (testedNumberSet.isEmpty() == true) : ""ResultUtil Constructor Error.""; assert (recycledNumberSet.isEmpty() == true) : ""ResultUtil Constructor Error.""; } public void clearSets() { this.testedNumberSet.clear(); this.recycledNumberSet.clear(); } public boolean isTested(String s) { return (this.testedNumberSet.contains(s)); } public boolean isInRecycledNumberSet(String s) { return (this.recycledNumberSet.contains(s)); } } " B12531,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; public class Google2 { public static void main(String[] args) throws NumberFormatException, IOException { FileInputStream fstream = new FileInputStream(""/tmp/input.txt""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); int cases = Integer.parseInt(br.readLine()); for(int mCas=0; mCas1; i-- ){ String n=""""; int j=i; do{ n+=bs.charAt(j-1); if(j==bs.length()) j=0; j++; }while(j!=i); if(n.equals(as)){ // System.out.println(""(""+a+"", ""+b+"") ""+n); return true; } } return false; } } " B11672,"import java.util.ArrayList; import java.util.Scanner; public class RecycleNumber { /** * @param args */ int NoOfTestCase = 0; int A = 0; int B = 0; ArrayList knownList = new ArrayList(); public static void main(String[] args) { // TODO Auto-generated method stub RecycleNumber rn = new RecycleNumber(); Scanner sc = new Scanner(System.in); rn.NoOfTestCase = Integer.parseInt(sc.nextLine()); for(int i=0;i=newInt) { while(newInt>A) { newInt = temp; resultStr = rotate(resultStr); newInt = Integer.parseInt(resultStr); } } if(newInt>currInt) { if(A< newInt && B >= newInt) { knownList.add(newInt); result++; } } firstTime = false; } } } return result; } private String rotate(String s){ String[] str = s.split(""""); String last = str[str.length-1]; for(int i=str.length-1;i>1;i--) { str[i] = str[i-1]; } str[1] = last; String result = """"; for(int i=1;i read(String name){ ArrayList data=new ArrayList(); try{ BufferedReader br = new BufferedReader(new FileReader(""C://codejam/""+name)); String line = br.readLine(); while(line != null){ data.add(line); line = br.readLine(); } br.close(); }catch(Exception e){} return data; } public void write(ArrayList data,String name){ try{ BufferedWriter bw = new BufferedWriter(new FileWriter(""C://codejam/""+name)); for(int i = 0; i < data.size(); i++){ bw.write(data.get(i)); bw.newLine(); } bw.close(); }catch(Exception e){} } /** * @param args */ public static void main(String[] args) { Run3 x= new Run3(); ArrayListdata =new ArrayList(); ArrayListout =new ArrayList(); data=x.read(""input3.txt""); for(int i=1;i<=Integer.parseInt(data.get(0));i++){ String res=x.solve(data.get(i)); System.out.println(res); out.add(""Case #""+i+"": ""+res); } x.write(out, ""output3.txt""); } private String solve(String string) { String result=""""; int results=0; String[]x=string.split("" ""); int a=Integer.parseInt(x[0]); int b=Integer.parseInt(x[1]); for(int i=a;il) return 0; else { ch2=ch.substring(l-p); if (Integer.valueOf(ch2)==0){ return 0;} else { ch3=ch.substring(0, l-p); ch=ch2+ch3; return Integer.valueOf(ch); } } } public static void main(String[] args) throws IOException{ String fichierentree= ""/home/marwen/Téléchargements/C-small-attempt0.in""; String fichiersortie= ""/home/marwen/Bureau/output.in""; BufferedWriter wr= new BufferedWriter(new FileWriter(fichiersortie)); DataInputStream rd= new DataInputStream(new FileInputStream(fichierentree)); int i,l,nb,r,j,a,b,k; String ligne= rd.readLine(); int T= Integer.valueOf(ligne); for (k=1;k<=T;k++) { nb=0; ligne=rd.readLine(); a=Integer.valueOf(ligne.substring(0, ligne.indexOf("" ""))); b=Integer.valueOf(ligne.substring(ligne.indexOf("" "")+1)); l=RecycledNumbers.longeur(a); int [] Valr=new int[l-1]; for(i=0;i0)&&(r<=b)&&(r>a)&&(r>i)){nb++;} } } } wr.write(""Case #""+k+"": ""+nb); wr.newLine(); } wr.close(); rd.close(); } } " B10202,"package gcj2012.qual; import java.util.Arrays; import common.AbstractRunner; import common.AbstractRunner.SIZE; public class C extends AbstractRunner { @Override public void handleCase(int caseNumber) throws Exception { int A = scanner.nextInt(); int B = scanner.nextInt(); int pow = 1; int n = 0; for (int p = A; p>=10; p = p/10) { n++; pow *= 10; } int res = 0; int [] rr = new int[n]; for (int x=A; x<=B; x++) { Arrays.fill(rr, 0); int rrlen = 0; int xx = x; cycle: for (int i=0; i x && xx <=B) { for (int j=0; j=a&&Integer.parseInt(s)<=b) recycled++; } } file.write(""Case #""+Integer.toString(j+1)+"": ""+Integer.toString(recycled/2)+""\r\n""); } file.close(); } } " B10616,"package ProblemSolvers; import CaseSolvers.DancingGooglersCase; public class DancingGooglers extends ProblemSolver { public DancingGooglers(String filePath) { super(filePath); } @Override public void process() { cases = io.readInt(); for (int i = 1; i <= cases; i++) { new DancingGooglersCase(i, 1, io).process().printSolution(); } } } " B13159,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package googlecodejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.io.Writer; /** * * @author rerngrak */ public class RecycledNumber { public static void main(String[] args) throws Exception { File input = new File(""src/googlecodejam/C-small-attempt0.in""); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(input))); //first line for number of line long row = Long.valueOf(reader.readLine()); File file = new File(""output.txt""); Writer writer = new BufferedWriter(new FileWriter(file)); for (long l=1;l<=row;l++){ String line = reader.readLine(); String in[] = line.split("" ""); long m = Long.valueOf(in[0]); long n = Long.valueOf(in[1]); int counter = 0; for (long i=m;i<=n;i++){ char[] ab = String.valueOf(i).toCharArray(); if (ab.length == 1){ continue; }else if (ab.length == 2){ String x = new String(""""+ab[0]); String y = new String(""""+ab[1]); if (!x.equals(y) && !y.equals(""0"")){ long swap = new Long(y+x).longValue(); if (swap > i && swap <= n) { counter++; continue; } } }else if (ab.length == 3){ String x = new String(""""+ab[0]); String y = new String(""""+ab[1]); String xy = x.concat(y); String z = new String(""""+ab[2]); String yz = y.concat(z); if (!xy.equals(yz) && !yz.equals(""00"")){ long swap2 = new Long(z.concat(xy)).longValue(); if (swap2 > i && swap2 <= n){ counter++; } long swap1 = new Long(yz.concat(x)).longValue(); if (swap1 > i && swap1 <= n){ counter++; } continue; } }else if (ab.length == 4){ String a = new String(""""+ab[0]); String b = new String(""""+ab[1]); String c = new String(""""+ab[2]); String d = new String(""""+ab[3]); counter = 287; } } System.out.println(""Case #""+l+"": ""+counter); String writeout = ""Case #""+l+"": ""+counter +""\n""; writer.write(writeout); } reader.close(); writer.close(); } } " B12393,"import java.io.File; import java.io.FileNotFoundException; import java.util.*; public class GoogleC { public static void main(String[] args) throws FileNotFoundException{ Scanner scan = new Scanner(new File(""B-small.txt"")); //finit2(); int n = scan.nextInt(); for (int i = 0; i < n; i++){ ht.clear(); System.out.println(""Case #"" + (i+1) + "": "" + sum(scan.nextInt(), scan.nextInt())); } } public static long sum(int a, int b){ ht = new HashSet(); long ret = 0; for (int i = a; i <= b; i++){ ret += run(i, a, b); } return ret; } public static HashSet ht = new HashSet(); private static class Pair{ int m, n; public Pair(int m, int n){ this.m = m; this.n =n; } public int hashCode(){ return 31*m+n; } @Override public boolean equals(Object o){ Pair p = (Pair)o; return p.m == m && p.n == n; } } public static int run(Integer n, int a, int b){ /*StringBuilder sb = new StringBuilder(n.toString()); StringBuilder orig = new StringBuilder(n.toString()); for (int i = 0; i < sb.length(); i++){ sb = sb.substring(1); }*/ int count = 0; String orig = n.toString(); String cur = n.toString(); for (int i = 0; i < orig.length()-1; i++){ char c = cur.charAt(0); cur = cur.substring(1) + c; if (cur.charAt(0) == '0') continue; int k = Integer.parseInt(cur); if (a <= k && k < n && n <= b && cur.length() == orig.length()){ Pair p = new Pair(k, n); if (!ht.contains(p)){ count++; //System.out.println(k + "" "" + n); ht.add(p); } } } return count; /*char[] cur = n.toString().toCharArray(); int count = 0; for (int start = 1; start < cur.length; start++){ boolean failed = false; if (arr[start] == 0){ failed = true; } for (int i = 0; !failed && i < cur.length; i++){ if (cur[(start+i)%cur.length] != cur[i]){ failed = true; } } if (!failed){ count++; } }*/ } public static void init2(){ for (int i = 2; i < arr.length; i++){ //run(i); } } public static boolean check(Integer a, Integer b){ if (a.toString().length() != b.toString().length()) return false; if (a==123 && b==231){ System.out.println(""here""); } String str = a.toString() + a.toString(); return str.contains(b.toString()); } public static void init(){ for (int i = 2; i < arr.length; i++){ int count = 0; for (int j = 1; j < i; j++){ if (check(j, i)) count++; } arr[i] = count + arr[i-1]; } } static int cap = 3000; public static int[] arr = new int[cap+1]; public static int doit(int n, int m){ return arr[m] - arr[n]; } } " B12864,"import java.util.Scanner; import java.io.File; import java.io.FileWriter; import java.io.BufferedWriter; import java.io.IOException; import java.io.FileNotFoundException; public class Recycle { public static void main(String[] args) { File f = new File(""C-small-attempt0.in""); try { Scanner scan = new Scanner(f); int lines = Integer.parseInt(scan.nextLine()); FileWriter fstream = new FileWriter(""output.txt""); BufferedWriter out = new BufferedWriter(fstream); for(int i=0; i= l && cycle < i) count++; cycle = (cycle%10)*((int)Math.pow(10,n-1)) + (cycle/10); } } return count; } } " B11406,"package codejam; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; /** * ´ÓÎı¾¶ÁÈ¡ÊäÈë * @author Administrator * */ public class InOutTool extends ArrayList { private String inPath ; private String outPath; public String outText(String path){ this.outPath = path; return outText(); } public String outText(){ StringBuffer sb = new StringBuffer(); PrintWriter out = null; try { out = new PrintWriter(new File(outPath).getAbsoluteFile()); for(String s:this){ out.println(s); sb.append(s);sb.append(""\n""); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(null!=out){ out.close(); } } return sb.toString(); } public String readText(String inPath){ StringBuffer sb = new StringBuffer(); BufferedReader in = null; try { in = new BufferedReader(new FileReader(new File(inPath).getAbsoluteFile())); String s; while((s = in.readLine()) != null){ s = s.trim(); add(s);//ÿһÐÐ×÷ΪArrayListµÄÒ»¸öÔªËØ sb.append(s);sb.append(""\n""); } }catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(null!=in){ try { in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return sb.toString(); } public InOutTool(String inPath,String outPath){ this.inPath = inPath;this.outPath = outPath; readText(inPath); if((size()!=0)&&get(0).equals("""")) remove(0); } } " B11221,"package egWo; import java.util.ArrayList; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Cs { public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int l = 1; l <= T; l++) { in.nextLine(); int n = in.nextInt(); int m = in.nextInt(); int count = 0; if ((n % 10 > 0 && n / 10 == 0)) { count = 0; } else { for (int i = n; i < m; i++) { if (i / 10 < 10) { int u = i % 10; int ten = i / 10; int revI = (u * 10) + ten; if (i < revI && revI < m) { count++; } } else if (i / 10 <= 100 && i / 10 >= 10) { int uni = (i % 100) % 10; int ten = (i / 10) % 10; int per = i / 100; ArrayList revI = new ArrayList(); revI.add(ten * 100 + uni * 10 + per); revI.add(uni * 100 + per * 10 + ten); Set set = new HashSet(revI); for (Object j : set) { if (i < ((Integer) j).intValue() && ((Integer) j).intValue() <= m) { count++; } } } } } System.out.format(""\nCase #%d: %d"", l, count); } } } " B11228,"package codezam.util; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.math.BigInteger; import java.util.Arrays; import java.util.HashMap; import java.util.Scanner; public class LCM { static HashMap factor; static BigInteger[][] dp; static long l; public static void main(String[] args) throws FileNotFoundException { Scanner r = new Scanner(System.in); int T = r.nextInt(); while(T-- > 0){ int n = r.nextInt(); l = r.nextInt(); factor = new HashMap(); int id = 0; for(long d = 1; d * d <= l; d++)if(l % d == 0){ factor.put(d, id++); if(d * d != l)factor.put(l / d, id++); } // dp = new BigInteger[factor.size() + 1][n + 2]; for(int i = 0; i < factor.size(); i++) dp[i][0] = BigInteger.ZERO; dp[factor.get(l)][0] = BigInteger.ONE; BigInteger ways = go(1, n); System.out.println(ways); } } static long gcd(long x, long y){ if( y == 0 )return x; else return gcd(y, x % y); } private static BigInteger go(long lcm, int rem) { if(rem == 0 && lcm == l)return BigInteger.ONE; if(rem == 0)return BigInteger.ZERO; System.out.println(lcm + "", "" + rem); if(dp[factor.get(lcm)][rem] != null) return dp[factor.get(lcm)][rem]; BigInteger ways = BigInteger.ZERO; for(long d = 1; d * d <= l; d++)if(l % d == 0){ long lcmNEW1 = lcm * d / gcd(d, lcm); long lcmNEW2 = lcm * (l/d) / gcd(l / d, lcm); ways = ways.add( go(lcmNEW1, rem - 1)); if(d * d != l)ways = ways.add( go(lcmNEW2, rem - 1)); } return dp[factor.get(lcm)][rem] = ways; } }" B10948,"package qualification; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.HashSet; import java.util.Scanner; public class Recycled { private static String fileName = ""recycled-small""; private static String inputFileName = fileName + "".in""; private static String outputFileName = fileName + "".out""; private static Scanner in; private static PrintWriter out; private static int MIN = 12; private static int MAX = 1000; private static ArrayList> data = new ArrayList>(MAX-MIN); private static void calcData() { for (int i = MIN; i < MAX; i++) { String value = String.valueOf(i); String concatValue = value.concat(String.valueOf(i)); ArrayDeque goodShifts = new ArrayDeque(value.length()); HashSet alreadyProcessed = new HashSet(value.length()); for (int n = 1; n < value.length(); n++) { String shiftedValue = concatValue.substring(n, n + value.length()); int shiftedNum = Integer.parseInt(shiftedValue); if (!alreadyProcessed.contains(shiftedNum)) { alreadyProcessed.add(shiftedNum); if ((i < shiftedNum) && (shiftedNum <= MAX) && (value.length() == shiftedValue.length())) { goodShifts.add(shiftedNum); } } } data.add(goodShifts); } } private void solve() { int A = in.nextInt(); int B = in.nextInt(); int numRecycled = 0; for (int n = ((A < MIN) ? MIN : A); n < B; n++) { ArrayDeque goodShifts = data.get(n-MIN); for (Integer m : goodShifts) { if (m <= B) { numRecycled++; } } } out.print(numRecycled); } /** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { calcData(); in = new Scanner(new FileReader(inputFileName)); out = new PrintWriter(outputFileName); int tests = in.nextInt(); in.nextLine(); for (int t = 1; t <= tests; t++) { out.print(""Case #"" + t + "": ""); new Recycled().solve(); out.println(); } in.close(); out.close(); } } " B13168,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; class IOSystem { private String filePath; private List inputList = new ArrayList(); private StringBuilder sb = new StringBuilder(); private int readSize = 0; private int appendedSize = 0; public IOSystem(String filePath) { this(filePath,"" ""); } public IOSystem(String filePath,String sep) { this.filePath = filePath; try { BufferedReader br = new BufferedReader(new FileReader(filePath+"".in"")); String line = null; while((line=br.readLine())!=null) { inputList.addAll(Arrays.asList(line.split(sep))); } } catch (Exception e) { e.printStackTrace(); } } public int size(){return inputList.size();} public boolean hasNext(){return readSize < size();} public int nextInt(){return Integer.parseInt(inputList.get(readSize++));} public long nextLong(){return Long.parseLong(inputList.get(readSize++));} public double nextDouble(){return Double.parseDouble(inputList.get(readSize++));} public String nextString(){return new String(inputList.get(readSize++));} public void appendAnswer(T answer){sb.append(""Case #""+(++appendedSize)+"": ""+answer.toString()+""\n"");}; public void output(){ try { BufferedWriter bw = new BufferedWriter(new FileWriter(filePath+"".ou"")); bw.write(sb.toString()); bw.flush(); System.out.println(sb.toString()); System.out.println(""output ->""+filePath+"".ou""); } catch (IOException e) { e.printStackTrace(); } } } " B11969,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.util.Scanner; import java.util.StringTokenizer; /** * * @author rama */ public class Codejam1 { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner in = new Scanner(System.in); int n=Integer.parseInt(in.nextLine()); for(int i=1;i<=n;++i) System.out.println(""Case #""+i+"": ""+trans(in.nextLine())); } public static int trans(String ss){ int ans=0,p1,p2; StringTokenizer tok=new StringTokenizer(ss,"" ""); int A=Integer.parseInt(tok.nextToken()); int B=Integer.parseInt(tok.nextToken()); int digit=dig(A); if(digit==1) return 0; for(int n=A;n<=B;++n){ int arr[]={0,0,0,0,0,0,0,0,0}; //System.out.println(""*""); boolean state=true; for(int j=1;j<=digit-1;++j){ p1=(int)(n%Math.pow(10,j)); //System.out.println(""**""+p1); p2=(int)(n/Math.pow(10,j)); //System.out.println(""***""+p2); int m=p1*(int)(Math.pow(10,(digit-j)))+p2; if(m>n&&m<=B){ int k=0; while(arr[k]!=0){ if(arr[k]==m){ state=false; } ++k; } if(state==true){ ++ans; arr[k]=m; } } } } return ans; } public static int dig(int num){ if(num/10==0) return 1; else if(num/100==0) return 2; else if(num/1000==0) return 3; else if(num/10000==0) return 4; else if(num/100000==0) return 5; else if(num/1000000==0) return 6; else if(num/10000000==0) return 7; else if(num/100000000==0) return 8; else return 9; } } " B11298,"import java.io.*; //import java.util.*; import java.util.Arrays; import java.util.StringTokenizer; class recyclednums { public static void main (String [] args) throws IOException { BufferedReader f = new BufferedReader(new FileReader(""recyclednums.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""recyclednums.out""))); int n = Integer.parseInt(f.readLine()); int[][] testcase = new int[n][2]; int[] answer = new int[n]; for(int i=0; i Integer.parseInt(b)) { return 0; } if (a.toCharArray().length == 1 || b.toCharArray().length == 1) { return 0; } HashSet hs = new HashSet(); // ArrayList al = new ArrayList(); // HashMap hm = new HashMap(); int counter = 0; char[] ch_n; int d = 0, reminder = 0; int n = Integer.parseInt(a); int val = 0; int[] input; for (int i = Integer.parseInt(a) ; i < Integer.parseInt(b) ; i++) { n += 1; Integer in = new Integer(n); ch_n = in.toString().toCharArray(); // System.out.println(n); val = n; for (int j = 0 ; j < ch_n.length - 1 ; j++) { d = (int) (val / Math.pow(10, ch_n.length - 1)); reminder = (int) (val % Math.pow(10, ch_n.length - 1)); val = reminder * 10 + d; // System.out.println(val); if (val < n) { if (val >= Integer.parseInt(a) && n <= Integer.parseInt(b)) { // System.out.println(val); // System.out.println(n); // System.out.println(""------""); input = new int[]{val, n}; // System.out.println(Arrays.toString(input)); HSC g = new HSC(val, n); hs.add(g); } } else if (val > n) { if (n >= Integer.parseInt(a) && val <= Integer.parseInt(b)) { // System.out.println(n); // System.out.println(val); // System.out.println(""******""); // counter++; input = new int[]{n, val}; // System.out.println(Arrays.toString(input)); HSC g = new HSC(n, val); hs.add(g); } } } } return hs.size(); // System.out.println(hs.size()); } public static void main(String[] args) { // TODO Auto-generated method stub try { BufferedReader f = new BufferedReader(new FileReader(""C-small-attempt3.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""test.out""))); String str; int T = 0; int c = 0; int answer = 0; String A = """", B = """"; ArrayList lines = new ArrayList(); while((str = f.readLine()) != null) { if (c == 0) { T = Integer.parseInt(str); } else { A = str.split("" "")[0]; B = str.split("" "")[1]; answer = go(A, B); // System.out.println(answer); out.print(""Case #"" + (new Integer(c)).toString() + "": "" + (new Integer(answer)).toString()); if (c != T) { out.println(); } } c++; } // System.out.println(T); // // // int cc = 1; // for (String s : lines) { // A = s.split("" "")[0]; // B = s.split("" "")[1]; // // answer = go(A, B); // // if (cc != T) { // out.println(); // } // cc++; // } out.close(); System.exit(0); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B10309,"/* * Anand Oza * Apr 14, 2012 */ import java.util.*; import java.io.*; public class C_RecycledNumbers { public static void main(String[] args) throws IOException { long startTime = System.nanoTime(); BufferedReader reader = new BufferedReader(new FileReader(""C_RecycledNumbers.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""C_RecycledNumbers.out""))); StreamTokenizer in = new StreamTokenizer(reader); in.nextToken(); int T = (int) in.nval; for (int testcase = 1; testcase <= T; testcase++) { in.nextToken(); int A = (int) in.nval; in.nextToken(); int B = (int) in.nval; int ans = 0; for (int n = A; n <= B; n++) { String s = String.valueOf(n); Set mvalues = new HashSet(); for (int i = 0; i < s.length(); i++) { int m = Integer.parseInt(s.substring(i) + s.substring(0, i)); if (m > n && m <= B && m >= A) mvalues.add(m); } ans += mvalues.size(); } out.format(""Case #%d: %d%n"", testcase, ans); } out.close(); System.out.println(""Time (ms): "" + (double) (System.nanoTime() - startTime) / 1000000); System.exit(0); } } " B11709,"package googlejam; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(new File(""inputC.txt"")); PrintWriter pw = new PrintWriter(""outputC.txt""); int T = sc.nextInt(); for (int t = 1; t <= T; t++) { int count = count(sc.nextInt(), sc.nextInt()); pw.println(""Case #"" + t + "": "" + count); } pw.flush(); pw.close(); } public static int count(int A, int B) { int res = 0; Set a = new HashSet(); for (int i = A; i < B; ++i) { a.clear(); String n = Integer.toString(i); for (int start = 1; start < n.length(); ++start) { if (n.charAt(start) == '0') { continue; } int m = 0; for (int d = 0; d < n.length(); ++d) { m *= 10; m += n.charAt((start + d) % n.length()) - '0'; } if (m > i && m <= B && !a.contains(m)) { a.add(m); ++res; } } } return res; } } " B11075,"package fixjava; /** * Convenience class for declaring a method inside a method, so as to avoid code duplication without having to declare a new method * in the class. This also keeps functions closer to where they are applied. It's butt-ugly but it's about the best you can do in * Java. */ public interface Lambda3 { public V apply(P param1, Q param2, R param3); } " B10425,"import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; public class RecycledNumbers { static String inputLargeFile = ""C-large.in""; static String inputSmallFile = ""C-small-attempt0.in""; static String outSmallFile = ""C-small-attempt0.out""; static String outLargeFile = ""C-large.out""; static BufferedReader br ; static PrintWriter out ; public static void main(String[] args) throws Exception{ br = new BufferedReader(new InputStreamReader(new FileInputStream(inputSmallFile))); out = new PrintWriter(new File(outSmallFile)); String input = br.readLine(); int testcases = Integer.parseInt(input.trim()); for (int i = 0; i < testcases; i++) { String range = br.readLine(); String[] numbers = range.split("" ""); int A = Integer.parseInt(numbers[0].trim()); int B = Integer.parseInt(numbers[1].trim()); String part1=null; String part2=null; int count=0; int m =0; int endIndex =0; int beignIndex=0; String number = null; String pair = null; for(int n=A;n<=B;n++ ){ number = String.valueOf(n); endIndex = number.length()-1; int last=0; for(int p=endIndex;p>0;p--){ pair = number.substring(p)+number.substring(beignIndex,p); m=Integer.parseInt(pair); if(m>n&&m<=B&&m!=last){ count++; last=m; //out.println(""count : "" + count); } } } out.println(""Case #""+ (i+1)+ "": "" + count); } out.close(); br.close(); } } " B10427,"import java.io.FileInputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; public class Main { public static void main(String[] args) { ArrayList answer = read(""/home/zehortigoza/Downloads/codejam/c/input.txt""); int tt = 0; int amount = 1; for (int i = 0; i < answer.size(); i++) { String line = answer.get(i); if (i == 0) { tt = Integer.parseInt(line); } else { if (tt >= amount) { HashMap count = new HashMap(); String[] splited = line.split("" ""); String a = splited[0]; String b = splited[1]; int aInt = Integer.parseInt(a); int bInt = Integer.parseInt(b); if (! (a.length() == 1 && b.length() == 1)) { ArrayList range = range(aInt, bInt); for (int z = 0; z < range.size(); z++) { String currentN = range.get(z)+""""; String currentM = range.get(z)+""""; int length = currentM.length(); for (int j = 0; j < length; j++) { currentM = currentM.charAt(length-1) + currentM.substring(0, length - 1); int currentNInt = Integer.parseInt(currentN); int currentMInt = Integer.parseInt(currentM); if (currentMInt <= bInt && currentMInt > currentNInt && currentMInt >= aInt) { if(count.get(currentN+currentM) == null) { count.put(currentN+currentM, true); } } } } } System.out.println(""Case #"" + amount + "": "" + count.size()); amount++; } } } } private static ArrayList range(int start, int end) { ArrayList list = new ArrayList(); if (start > end) { System.out.println(""error to build range""); return null; } for (int i = start; i <= end; i++) { list.add(i); } return list; } private static ArrayList read(String url) { ArrayList lines = new ArrayList(); Scanner scanner = null; try { scanner = new Scanner(new FileInputStream(url)); while (scanner.hasNextLine()) { lines.add(scanner.nextLine()); } } catch (Exception e) { e.printStackTrace(); } finally { if (scanner != null) { scanner.close(); } } return lines; } } " B10590,"import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { public static void main(String[] argv) throws Exception { // Scanner s = new Scanner(System.in); Scanner s = new Scanner(new FileInputStream(""RecycledNumbers/C-small-attempt0.in"")); PrintWriter pw = new PrintWriter(new FileOutputStream(""RecycledNumbers/C-small-attempt0.out"")); // PrintWriter pw = new PrintWriter(System.out); int T = s.nextInt(); for(int i=1;i<=T;i++) { int A = s.nextInt(); int B = s.nextInt(); Set checked = new HashSet(); int numDigit = Integer.toString(A).length(); int pairs = 0; for(int j = A; j<=B; j++) { if(checked.contains(j)) continue; checked.add(j); int[] digits = new int[numDigit]; for(int k = 0;k < numDigit;k++) { digits[k] = (j / powers[k]) - (j / powers[k+1])*10; } // System.out.println(Arrays.toString(digits)); int count =0; for(int k =1; k< numDigit;k++ ){ shift(digits); int newnum = 0; for(int l=0;l= A && newnum <=B) { count++; } } } if(count >= 1) { pairs += (count+1)*(count)/2; } } pw.println(""Case #"" + i +"": "" + pairs); System.out.println(""Case #"" + i +"":"" +pairs); } pw.flush(); pw.close(); } static int[] powers = new int[8]; static { for(int j=0;j num; String Sa,Sb; int count=0; Sa=Integer.toString(A); Sb=Integer.toString(B); for(int i=A;i<=B;i++){ num=new ArrayList(); for(int j=Sa.length()-1;j>0;j--){ Sa=Integer.toString(i).substring(j)+Integer.toString(i).substring(0,j); if(Integer.parseInt(Sa)<=B&&Sa.charAt(0)!='0'&&i L = new TreeSet(); for(int j=1;jn && n2<=B) { if(!L.contains(n2)) { L.add(n2); count ++; } } } } System.out.println(""Case #""+(i+1)+"": ""+count); } } } " B10634,"import java.util.Scanner; public class C { String cycle(String s) { return s.substring(1) + s.charAt(0); } void run() { Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int t=1; t<=T; t++) { int A = in.nextInt(); int B = in.nextInt(); long res = 0; for (long i=A; i<=B; i++) { long cnt = 1; String str = String.valueOf(i); for (String nowstr = cycle(new String(str)); !nowstr.equals(str); nowstr = cycle(nowstr)) { if (nowstr.charAt(0) != 0) { int nowint = Integer.parseInt(nowstr); if (nowint >= A && nowint <= B) { if (nowint < i) { cnt = 0; break; } else { cnt++; } } } } res += cnt*(cnt-1)/2; } System.out.println(""Case #"" + t + "": "" + res); } } static public void main(String[] args) { C obj = new C(); obj.run(); } } " B13183,"import java.util.*; import java.io.*; public class recycle { private static Reader in; private static PrintWriter out; public static final String NAME = ""C-small-attempt0""; private static int pow, A, B; private static void main2() throws IOException { A = in.nextInt(); B = in.nextInt(); pow = 1; int tmp = A; while (tmp > 0) { pow *= 10; tmp /= 10; } pow /= 10; int count = 0; for (int i = A; i <= B; i++) count += can (i); out.println (count); } private static int can (int n) { int k = shift(n), res = 0; while (k != n) { if (k >= A && k <= B && k > n) res++; k = shift(k); } return res; } private static int shift(int n) { return (n % 10) * pow + n / 10; } public static void main(String[] args) throws IOException { in = new Reader(NAME + "".in""); out = new PrintWriter(new BufferedWriter(new FileWriter(NAME + "".out""))); int numCases = in.nextInt(); for (int test = 1; test <= numCases; test++) { out.print(""Case #"" + test + "": ""); main2(); } out.close(); System.exit(0); } /** Faster input **/ static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[1024]; int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; else return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; else return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10); } if (neg) return -ret; else return ret; } public char nextChar() throws IOException { char ret = 0; byte c = read(); while (c <= ' ') c = read(); return (char) c; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } } " B10304,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package code_jam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; /** * * @author Neo */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here int line_counter=0; try{ // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(""textfile.txt""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter ostream = new FileWriter(""output.txt""); BufferedWriter out = new BufferedWriter(ostream); String strLine; //Read File Line By Line while ((strLine = br.readLine()) != null) { // Print the content on the console if(line_counter==0){ } else{ String delims = ""[ ]+""; String[] tokens = strLine.split(delims); int a =Integer.parseInt(tokens[0]); int b = Integer.parseInt(tokens[1]); if(a<10){ out.write(""\nCase #""+line_counter+"": ""+0); out.newLine(); } if(a>9&&a<100){ int output =0; for(int i=a;in&&m99&&a<999){ int output =0; for(int i=a;in&&mn&&mn&&m1 file, int line) { String first = file.get(line++); int[] size = JamUtil.parseIntList(first, 2); CrossCase ca = new CrossCase(); ca.n = size[0]; ca.m = size[1]; ca.lineCount = ca.n + 1; ca.map = new Crossing[ca.n][ca.m]; Node[][][][] nodes = new Node[ca.n][ca.m][2][2]; Node start = null; Node end = null; for (int y = 0; y < ca.n; y++) { String row = file.get(line++); int[] data = JamUtil.parseIntList(row, 3 * ca.m); for (int x = 0; x < ca.m; x++) { Crossing cr = new Crossing(); ca.map[y][x] = cr; cr.minTime = Integer.MAX_VALUE; cr.s = data[3*x]; cr.w = data[3*x+1]; cr.t = data[3*x+2]; cr.x = x; cr.y = y; Node ne = new CrossNode(); Node se = new CrossNode(); Node sw = new CrossNode(); Node nw = new CrossNode(); CrossStreetSNEdge snEdge1 = new CrossStreetSNEdge(); snEdge1.s =cr.s; snEdge1.w = cr.w; snEdge1.t = cr.t; CrossStreetWEEdge weEdge = new CrossStreetWEEdge(); weEdge.s= cr.s; weEdge.w=cr.w; weEdge.t=cr.t; snEdge1.biConnect(ne,se); snEdge1.biConnect(nw,sw); weEdge.biConnect(ne,nw); weEdge.biConnect(se,sw); Node[][] pack = nodes[y][x]; pack[0][0] = nw; pack[0][1] = ne; pack[1][1] = se; pack[1][0] = sw; ((CrossNode)nw).label = ""y "" + y + "" x "" + x + "" nw""; ((CrossNode)ne).label = ""y "" + y + "" x "" + x + "" ne""; ((CrossNode)se).label = ""y "" + y + "" x "" + x + "" se""; ((CrossNode)sw).label = ""y "" + y + "" x "" + x + "" sw""; if (y==0 && x ==ca.m-1) { ca.stopNode = pack[0][1]; } if (y==ca.n-1 && x == 0) { ca.startNode = pack[1][0]; } if (y>0) { CrossBlockEdge b1 = new CrossBlockEdge(); b1.biConnect(nodes[y][x][0][1],nodes[y-1][x][1][1]); b1.biConnect(nodes[y][x][0][0],nodes[y-1][x][1][0]); } if (x>0) { CrossBlockEdge b1 = new CrossBlockEdge(); b1.biConnect(nodes[y][x][0][0], nodes[y][x - 1][0][1]); b1.biConnect(nodes[y][x][1][0],nodes[y][x-1][1][1]); } } } return ca; } } class CrossCase extends JamCase { int n, m; Crossing[][] map; public Node startNode; public Node stopNode; } class Crossing implements Comparable{ int s, w, t, minTime,x,y; @Override public int compareTo(Crossing o) { return Integer.compare(minTime,o.minTime); } } class CrossState extends State { long time; @Override public int compareTo(Object o) { return Long.compare(time,((CrossState)o).time); } } class CrossBlockEdge extends Edge { @Override public State travel(State current) { CrossState old = (CrossState) current; CrossState newS = new CrossState(); newS.time = old.time + 2; return newS; } } class CrossStreetSNEdge extends Edge { long s,w,t; @Override public State travel(State current) { CrossState old = (CrossState) current; CrossState newS = new CrossState(); long adjusted = old.time - t; long period = s + w; long inCycle = adjusted % period; if (inCycle < s) { newS.time = old.time + 1; return newS; } newS.time = old.time + (period-inCycle); return newS; } } class CrossStreetWEEdge extends Edge { long s,w,t; @Override public State travel(State current) { CrossState old = (CrossState) current; CrossState newS = new CrossState(); long adjusted = old.time - t; long period = s + w; long inCycle = adjusted % period; if (inCycle >= s) { newS.time = old.time + 1; return newS; } newS.time = old.time + (s-inCycle); return newS; } } class CrossNode extends Node { String label; CrossNode() { last = new CrossState(); } @Override public String toString() { return label; } } " B11945,"package qualify3; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.Vector; public class RecycledNumbers { public static void main (String[] args) throws FileNotFoundException { Scanner in = new Scanner(new File (""src//qualify3/input.in"")); int T = in.nextInt(); for (int i = 0; i < T; i++) { Integer A = in.nextInt(); Integer B = in.nextInt(); String strA = A.toString(); String strB = B.toString(); Vector cycles = new Vector(); if (strA.length() != 1) { for (Integer j = A; j <= B; j++) { cycles.addAll(getCycledValues(j.toString(), strB)); } } System.out.println(""Case #"" + (i + 1) + "": "" + cycles.size()); } } public static Vector getCycledValues (String str1, String str2) { Vector cycledNumbers = new Vector(); String no = new String (str1); int size = str1.length(); while (true) { String str = """"; str = str + no.charAt(size - 1); for (int i = 0; i < size - 1; i++) { str = str + no.charAt(i); } if (Integer.parseInt(str) == Integer.parseInt(str1)) break; int cyclicNumber = Integer.parseInt(str); if (cyclicNumber >= Integer.parseInt(str1) && cyclicNumber <= Integer.parseInt(str2)) { cycledNumbers.add(cyclicNumber); } no = str; } return cycledNumbers; } } " B11755,"import java.util.HashSet; import java.util.Scanner; public class C { static HashSet p = new HashSet(); static int low; static int high; int count = 0; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int no = sc.nextInt(); for (int i = 1; i <= no; i++) { p.clear(); low = sc.nextInt(); high = sc.nextInt(); for (int l = low; l <= high; l++) { recycle(l); } System.out.println(""Case #"" + i + "": "" + p.size()); } } public static void recycle(int no) { String s = Integer.toString(no); for (int i = 0; i < s.length(); i++) { String rec = s.substring(i) + s.substring(0, i); int r = Integer.parseInt(rec); if (r != no && r >= low && r <= high) { int min = Math.min(r, no); int max = Math.max(r, no); String a = Integer.toString(min) + """" + Integer.toString(max); p.add(a); } } } } " B12590,"import java.io.*; import java.util.*; public class RecycledNumbersSmall { public static void main(String[] args) { try { FileWriter output = new FileWriter(new File(""output.txt"")); Scanner s = new Scanner(new File(""input.txt"")); int trials = s.nextInt(); s.nextLine(); for (int i = 0; i < trials; i++) { int count = 0; int start = s.nextInt(); int end = s.nextInt(); for (int b = end; b >= start; b--) { String numWord = b + """"; ArrayList added = new ArrayList(); for (int z = numWord.length() - 1; z >= 1; z--) { if (numWord.charAt(z) != '0') { int x = Integer .parseInt(numWord.substring(z, numWord.length()) + numWord.substring(0, z)); if (x < b && x >= start && !added.contains(x)) { added.add(x); count++; } } } } output.write(""Case #"" + (i + 1) + "": ""); output.write("""" + count); output.write('\n'); } s.close(); output.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } " B13109,"package com.vp.impl; import java.util.ResourceBundle; import com.vp.iface.Problem; public class SpeakGooglerese implements Problem { @Override public String solve(String[] dataset) { ResourceBundle rb = ResourceBundle.getBundle(""Mapping""); String strReturnValue = """"; //System.out.println(""Translated Text: "" + strReturnValue); String strGooglereseSentence = dataset[0]; String[] strGooglereseWords = strGooglereseSentence.split("" ""); for(int i=0; i0 ) { strReturnValue += "" ""; } char strChars[] = strGooglereseWords[i].toCharArray(); for(int j=0;j a[k]+i) count++; } else { char[] temp5=abdo; char temp2=abdo[0]; char temp3=abdo[1]; abdo[0]=abdo[2]; abdo[1]=temp2; abdo[2]=temp3; String aaa= String.valueOf(abdo[0])+ String.valueOf(abdo[1])+String.valueOf(abdo[2]); num=Integer.parseInt(aaa); if(num <= b[k] && num >= a[k] && num >a[k]+i) count++; char[] abdo2=temp.toCharArray(); temp2=abdo2[0]; temp3=abdo2[2]; abdo2[0]=abdo2[1]; abdo2[1]=temp3; abdo2[2]=temp2; aaa= String.valueOf(abdo2[0])+ String.valueOf(abdo2[1])+String.valueOf(abdo2[2]); num=Integer.parseInt(aaa); if(num <= b[k] && num >= a[k] && num > a[k]+i) count++; } } System.out.format(""Case #%d: %d\n"", k+1, count); } } } " B12179,"package codejam; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public abstract class CodeJam { protected BufferedReader reader; protected FileWriter writer; //used in multithread mode protected String[] inputLines; protected String[] outputLines; protected int linesPerCase; long start; protected String caseLabel = ""Case #""; protected boolean runningMultiThread = false; public CodeJam(String file) throws Exception { this(file, -1); } public CodeJam(String file, int linesPerCase) throws Exception { start = System.currentTimeMillis(); this.linesPerCase = linesPerCase; FileReader fileReader = new FileReader(new File(file)); reader = new BufferedReader(fileReader); File outFile = new File(file.replaceAll(""\\.\\w+$"", "".out"")); outFile.delete(); writer = new FileWriter(outFile); } public void start() throws IOException, InterruptedException { String readLine = reader.readLine(); //total number of cases int t = Integer.parseInt(readLine); int threads = 1; if (linesPerCase > 0) { runningMultiThread = true; loadInputLines(t*linesPerCase); outputLines = new String[t]; threads = 4; } ExecutorService newCachedThreadPool = Executors.newCachedThreadPool(); for (int i = 0; i < threads; i++) { newCachedThreadPool.execute(new CaseProcessor(i*t/threads+1, (i+1)*t/threads)); } newCachedThreadPool.shutdown(); newCachedThreadPool.awaitTermination(8*60*1000, TimeUnit.MILLISECONDS); if (runningMultiThread) { for (int i = 0; i < outputLines.length; i++) { writer.write(outputLines[i]); } } writer.flush(); long delay = System.currentTimeMillis() - start; if (delay < 5000) { System.out.println(""Total time ""+delay+ "" millis""); } else { System.out.println(""Total time ""+(delay/1000)+ "" secs""); } System.exit(0); } class CaseProcessor implements Runnable { int firstCase; int lastCase; public CaseProcessor(int firstCase, int lastCase) { this.firstCase = firstCase; this.lastCase = lastCase; } public void run() { for (int i = firstCase; i <= lastCase; i++) { Object result; try { result = processCase(i); writeCaseResult(i, result); } catch (Exception e) { e.printStackTrace(); } if (i%10 == 0) { long timeRemaing = (System.currentTimeMillis() - start)/i * (lastCase-i); if (timeRemaing < 5000) { System.out.println(i*100f/lastCase+"" % Complete (Time remaing: ""+timeRemaing+"" millis)""); } else { System.out.println(i*100f/lastCase+"" % Complete (Time remaing: ""+timeRemaing/1000+"" secs)""); } } } System.out.println(""Finish""+firstCase); } } private void loadInputLines(int lines) throws IOException { inputLines = new String[lines]; for (int i = 0; i < lines; i++) { inputLines[i] = reader.readLine(); } reader.close(); reader = null; } public final String readLine() throws IOException { return reader.readLine(); } public final int readLineInt() throws IOException { return Integer.parseInt(reader.readLine()); } public final String readLine(int caseNumber, int i) { return inputLines[(caseNumber-1)*linesPerCase+i]; } public final int[] readIntArray(int caseNumber, int line) { String[] numbers = readLine(caseNumber, line).split("" ""); int[] n = new int[numbers.length]; for (int i = 0; i < numbers.length; i++) { n[i] = Integer.parseInt(numbers[i]); } return n; } public final Integer[] readIntegerArray(int caseNumber, int line) { String[] numbers = readLine(caseNumber, line).split("" ""); Integer[] n = new Integer[numbers.length]; for (int i = 0; i < numbers.length; i++) { n[i] = Integer.parseInt(numbers[i]); } return n; } @SuppressWarnings(""unchecked"") public static T[] reverse(T[] arr) { List list = Arrays.asList(arr); Collections.reverse(list); return (T[]) list.toArray(new Object[arr.length]); } public static void reverse(char[] data) { int left = 0; int right = data.length - 1; while( left < right ) { // swap the values at the left and right indices char temp = data[left]; data[left] = data[right]; data[right] = temp; // move the left and right index pointers in toward the center left++; right--; } } protected void writeCaseResult(int caseNumber, Object result) throws IOException { StringBuilder out = new StringBuilder(caseLabel);//""Case #"" out.append(caseNumber); out.append("": ""); out.append(result); out.append('\n'); System.out.println(out); if (runningMultiThread) { outputLines[caseNumber-1] = out.toString(); } else { writer.write(out.toString()); } } public long convetNumber(int number, int currentBase, int destBase) { long result = 0; int count = 0; while (number > 0) { int remainder = number % destBase; number /= destBase; int current = remainder*(int)Math.pow(currentBase,count); result += current; count++; } return result; } public abstract Object processCase(int caseNumber) throws Exception; } " B11801,"package util; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author bohmd */ public abstract class BaseResolver { private final String file; private BufferedReader reader; private BufferedWriter writer; int lineNum = 0; int caseNum = 0; public BaseResolver(String file) { this.file = file; } public void resolve() throws Exception { reader = new BufferedReader(new FileReader(input())); writer = new BufferedWriter(new FileWriter(output())); while (reader.ready()) { executeLine(reader.readLine()); lineNum++; } reader.close(); writer.close(); } private String input() { return file + "".in""; } private String output() { return file + "".out""; } protected abstract void executeLine(String line) throws Exception; protected void write(String result) throws Exception { writer.write(""Case #"" + (++caseNum) + "":"" + result); writer.newLine(); } public int getLineNum() { return lineNum; } } " B13156,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; public class Recycled { public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); for (int i = 0; i < t; i++) { String[] str = br.readLine().split("" ""); int a = Integer.parseInt(str[0]); int b = Integer.parseInt(str[1]); System.out.println(""Case #"" + (i + 1) + "": "" + find(a, b)); } } catch (IOException e) { e.printStackTrace(); } } private static int find(int a, int b) { HashSet used = new HashSet(); int digits = String.valueOf(a).length(); if (digits == 1) return 0; for (int i = a; i <= b; i++) { int s = 10; int m = (int) Math.pow(10, digits-1); for (int j = 0; j < digits-1; j++) { int r = i % s; if (r < s/10) continue; int q = i / s; int rn = r * m + q; s *= 10; m /= 10; if (i != rn && rn >= a && rn <= b) { long pp; if (rn < i) pp = (long)rn << 30 | i; else pp = (long)i << 30 | rn; if (!used.contains(pp)) { used.add(pp); } } } } return used.size(); } } " B12149,"import java.io.*; import java.util.*; public class RecycledNumbers { private static ArrayList A,B; public static void main(String[] args) throws Exception { File in = new File(""C-small-attempt0.in""); File out = new File(""out.txt""); RecycledNumbers.read(in); RecycledNumbers.print(out); } public static void read (File file) throws FileNotFoundException { Scanner scanner = new Scanner (file); int cases = scanner.nextInt(); A = new ArrayList(cases); B = new ArrayList(cases); while (scanner.hasNext()) { A.add(scanner.next()); B.add(scanner.next()); } } public static void print (File file) throws FileNotFoundException { PrintStream fileStream = new PrintStream (file); for (int i = 0; i < A.size(); i++) { //fileStream.println(A.get(i) + "" "" + B.get(i)); fileStream.println(""Case #"" + (i+1) +"": "" + test(A.get(i),B.get(i))); } fileStream.close(); } public static int test(String A, String B) { int returnThis = 0; if (A.length() == 1) { return 0; } int limit = Integer.valueOf(B); int start = Integer.valueOf(A); for (int i = start; i <= limit; i++) { String base = Integer.toString(i); int count = 1; String m = """" + base.charAt(base.length() - count); while (true) { String out = m + base.substring(0, base.length() - count); //System.out.println(base+"": "" + out); if (verify(base, out, limit)) { // System.out.println(""A: ""+A +"" B: "" + B + "" base: "" + base +"" out: "" + out); returnThis++; } count++; if (base.length() <= count) break; if (base.equals(out)) break; m = base.charAt(base.length() - count) + m; } } //System.out.println(returnThis); return returnThis; } public static boolean verify(String n, String m, int limit) { if (m.charAt(0) == '0') return false; if (Integer.valueOf(n) < Integer.valueOf(m) && Integer.valueOf(m) <= limit) { return true; } return false; } } " B12830,"package com.cj.utils; import java.io.*; import java.util.*; public class InputReader { //public ArrayList inputs; public int cases; public Scanner scanner; public InputReader(){ //inputs = new ArrayList(); cases = 0; } public Scanner loadInput(String fileName){ try{ File file = new File(fileName); scanner = new Scanner(file); cases = scanner.nextInt(); //for(int count = 0; count < cases ; count++){} return scanner; } catch(Exception ex){ex.printStackTrace(); return null;} } public static void main(String[] args){ InputReader ir = new InputReader(); Scanner input = ir.loadInput(""test.txt""); int cases = ir.cases; System.out.println(cases); System.out.println(input.nextInt()+""mm""+input.nextInt()); } }" B11350,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class RecycleNumber { String[] result = new String[9000]; int testCases = 0; private static int shift(int in, int shift){ int mul = 1; for(int k = 1; k <= shift; k++){ mul *= 10; } int l = in%mul; if(l == 0) return -1; int mid = in/mul; int c = Integer.valueOf(l+""""+mid); return c; } public static void main(String[] args)throws Exception{ RecycleNumber bp = new RecycleNumber(); InputVectorSequenceRecycleNumber iv = InputVectorSequenceRecycleNumber.readFileToCreateInputVector(true); bp.testCases = Integer.parseInt(iv.inp[0][0]); for(int n = 0 ; n < bp.testCases; n++){ int lowerbound = Integer.parseInt(iv.inp[n+1][0]); int upperbound = Integer.parseInt(iv.inp[n+1][1]); int count = 0; for(int i = lowerbound; i <= upperbound; i++){ Set unique = new HashSet(); for(int j = 1 ; j < String.valueOf(i).length(); j++){ int y = shift(i, j); if(y == -1) continue; if(y > i && y <= upperbound && !unique.contains(y)){ unique.add(y); count++; } } } bp.result[n] = ""Case #""+(n+1)+"":""+"" ""+count; } bp.outputFile(); } public void outputFile() throws IOException{ FileWriter fos = new FileWriter (""C:/workspace/googleCJ/google/input/c.txt""); BufferedWriter bw = new BufferedWriter(fos); for(int i =0; i< testCases; i++){ bw.write(result[i]); bw.write(""\r\n""); } bw.close(); } } class InputVectorSequenceRecycleNumber{ private static int DATA_LENGTH = 9000; public int lines = -1; public String[][] inp = new String[DATA_LENGTH][]; String[] result = new String[DATA_LENGTH]; private InputVectorSequenceRecycleNumber(){ } public static InputVectorSequenceRecycleNumber readFileToCreateInputVector(boolean splitLineBySpace) throws IOException{ BufferedReader br = new BufferedReader(new FileReader (""C:/workspace/googleCJ/google/input/b.txt"")); String str = null; InputVectorSequenceRecycleNumber iv = new InputVectorSequenceRecycleNumber(); while ((str = br.readLine()) != null) { iv.lines++; iv.inp[iv.lines] = process(str, splitLineBySpace); } return iv; } private static String[] process(String str, boolean splitLineBySpace) { String[] ret = null; if(splitLineBySpace){ ret = str.split(""\\ ""); }else{ ret = new String[]{str}; } return ret; } } " B12937,"import static java.lang.Math.*; import static java.util.Arrays.*; import java.io.*; import java.util.*; public class C { Scanner sc = new Scanner(System.in); int A, B; void read() { A = sc.nextInt(); B = sc.nextInt(); } void solve() { long res = 0; for (int i = A; i <= B; i++) { int t = i; int X = 1; while (X * 10 <= i) X *= 10; do { t = t % 10 * X + t / 10; if (i < t && t <= B) res++; } while (t != i); } System.out.println(res); } void run() { int caseN = sc.nextInt(); for (int caseID = 1; caseID <= caseN; caseID++) { read(); System.out.printf(""Case #%d: "", caseID); solve(); System.out.flush(); } } void debug(Object...os) { System.err.println(deepToString(os)); } public static void main(String[] args) { try { System.setIn(new BufferedInputStream(new FileInputStream(args.length > 0 ? args[0] : (C.class.getName() + "".in"")))); } catch (Exception e) { } new C().run(); } } " B11566,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; public class Solve3 { public static void main(String[] args) { FileReader fr; FileWriter fw; try { File fi = new File(""input.txt""); fr = new FileReader(fi); BufferedReader br = new BufferedReader(fr); fw = new FileWriter(""output.txt""); BufferedWriter bw = new BufferedWriter(fw); boolean f = true; int tCount = Integer.MAX_VALUE; int c = 1; String line = null; while((line = br.readLine()) != null && c <= tCount) { if(f) { f = false; tCount = Integer.parseInt(line); continue; } long ans = getVal(line); String os = ""Case #"" + c + "": "" + ans; bw.write(os); bw.newLine(); c++; } bw.flush(); bw.close(); br.close(); } catch (FileNotFoundException eg) { // TODO Auto-generated catch block eg.printStackTrace(); } catch (IOException ed) { // TODO Auto-generated catch block ed.printStackTrace(); } } private static int getDC(long n) { int c = 0; while(n > 0) { c++; n = n/10; if(n == 0) { break; } } return c; } public static long getVal(String line) { String[] sa = line.split("" ""); long n = Integer.parseInt(sa[0].trim()); long m = Integer.parseInt(sa[1].trim()); int dc = getDC(n); long count = 0; Map s = new HashMap(); for(long i = n; i <= m; i++) { Set _s = correct(i, n, m, dc); if (_s.isEmpty()) continue; Iterator it = _s.iterator(); while(it.hasNext()) { Long o = (Long)it.next(); if (s.containsKey(o)) { it.remove(); } } if (_s.isEmpty()) continue; s.put(i, _s); } Iterator mit = s.keySet().iterator(); while(mit.hasNext()) { count += ((Set)s.get(mit.next())).size(); } return count; } public static Set correct(long nt, long n, long m, int dc) { Set l = new HashSet(); for(int i = 1; i < dc ;i ++) { long tens = (long)Math.pow(10, dc - i); long tenso = (long)Math.pow(10, i); long left = nt/tens; long right = nt%tens; long n_ = right * tenso + left; if (n_ >= n && n_ <= m && n_ != nt){ l.add(n_); } } return l; } } " B11521,"/* * @author Magix.Lu */ import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class RecycledNum { public static void main(String[] args) throws IOException { Scanner scanInput = new Scanner(System.in); String target = scanInput.next(); File inputFile = new File(target); Scanner fileScan = new Scanner(inputFile); String outpFileName = ""output.txt""; FileWriter googlewriter = null; googlewriter = new FileWriter(outpFileName); PrintWriter diskFile = new PrintWriter(googlewriter); int count = fileScan.nextInt(); int min = 0; int max = 0; int len = 0; int a = 0; int b = 0; int counter = 0; for (int i = 0; i < count; i++) { min = fileScan.nextInt(); max = fileScan.nextInt(); a = min; len = Integer.toString(a).length(); counter = 0; if (len == 1) { diskFile.print(""Case #"" + (i + 1) + "": "" + counter + ""\n""); System.out.println(counter); } else { while (a <= max) { b = a; String num = Integer.toString(b); for (int j = 0; j < len - 1; j++) { if (len == 2) { String result = Character.toString(num.charAt(1)) + num.charAt(0); num = result; b = Integer.parseInt(result); } else { String front = Character.toString(num.charAt(num .length() - 1)); String behind = num.substring(0, num.length() - 1); String result = front + behind; num = result; b = Integer.parseInt(num); } if (min <= a && a < b && b <= max) { counter++; System.out.println(a + "" "" + b); } } a++; } diskFile.print(""Case #"" + (i + 1) + "": "" + counter + ""\n""); System.out.println(counter); } } diskFile.close(); } } " B10956,"package com.google.codejam.Qualification2012; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { public static void main(String[] args) throws IOException { Scanner scanner = new Scanner(new BufferedReader(new FileReader(args[0] + "".in""))); Writer writer = new BufferedWriter(new FileWriter(args[0] + "".out"")); int T = scanner.nextInt(); Set set = new HashSet(); for (int x = 1; x <= T; ++x) { int A = scanner.nextInt(); int B = scanner.nextInt(); int y = 0; if (B >= 21) { for (int n = A; n < B; ++n) { set.clear(); int nDigits = getDigits(n); int k1 = 10; int k2 = 1; for (int i = 0; i < nDigits - 1; ++i) k2 *= 10; int n1 = n / k1; int n2 = n % k1; for (int i = 0; i < nDigits - 1; ++i) { int m = n2 * k2 + n1; if (n2 != 0 && m > n && m <= B && !set.contains(m)) { //System.out.println(n + "": "" + n2 + "" "" + n1); set.add(m); ++y; } k1 *= 10; k2 /= 10; n1 = n / k1; n2 = n % k1; } } } System.out.println(""Case #"" + x + "": "" + y); writer.write(""Case #"" + x + "": "" + y + ""\n""); } writer.close(); scanner.close(); } static int getDigits(int n) { if (n == 0) return 1; int result = 0; while (n > 0) { n /= 10; ++result; } return result; } } " B12217,"/* ========================================================== * (C) Copyright 2007-present Facebook. All rights reserved. * ========================================================== */ import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; /** * . * * @author */ public class Recycle { public static void main( String[] args ) throws NumberFormatException, IOException { final BufferedReader in = new BufferedReader( new FileReader( ""/Users/oded/a/ttt/src/in.txt"" ) ); final int numLines = Integer.parseInt( in.readLine() ); for( int i = 0; i < numLines; i++ ) { handleLine( in.readLine(), i ); } } private static int countDigits( int a ) { int count = 0; while( a > 0 ) { count++; a = a / 10; } return count; } private static void handleLine( String readLine, int i ) { String[] numbers = readLine.split( "" "" ); int a = Integer.parseInt( numbers[ 0 ] ); int b = Integer.parseInt( numbers[ 1 ] ); int count = 0; int digits = countDigits( a ); if( digits > 1 ) { int den = 1; while( digits > 1 ) { den *= 10; digits--; } for( int n = a; n < b; n++ ) { int perm = shift( n, den ); while( perm != n ) { if( perm > n && perm <= b ) { count++; } perm = shift( perm, den ); } } } System.out.println( ""Case #"" + ( i + 1 ) + "": "" + count ); } private static int shift( int n, int den ) { return ( n / den ) + ( n % den ) * 10; } } " B12559,"import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.PrintStream; import java.io.PrintWriter; import java.io.FileWriter; import java.io.PrintWriter; import java.io.IOException; import java.util.Arrays; public class Recycled { public static void main(String args[]) throws IOException { try { PrintWriter wt= new PrintWriter(""C:\\Documents and Settings\\windows\\workspace\\test\\src\\file.out.txt""); Scanner I = new Scanner(new File(""C:\\Documents and Settings\\windows\\workspace\\test\\src\\C-small-attempt0.in"")); String num = I.nextLine(); int numTests = Integer.parseInt(num); for(int x=0; x exist = new HashMap(); for (int i = 0; i <= strn.length() ; i ++) { String startNewN = strn.substring(strn.length() - i,strn.length() ); if (startNewN.equals("""")) { continue; } String endNewN = strn.substring(0, strn.length() - i); if (endNewN.equals("""")) { continue; } String newN = startNewN.concat(endNewN); long longN =Long.parseLong(newN); if ( longN <= B && longN > n) { if (exist.get(longN) == null) { exist.put(longN, 1); countRecycle ++; } } } } out.println(countRecycle); } out.close(); } private static class InputReader { private InputStream stream; private byte[] buf = new byte[1000]; private int curChar, numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuffer buf = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { buf.appendCodePoint(c); c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) s = readLine0(); return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) return readLine(); else return readLine0(); } public BigInteger readBigInteger() { try { return new BigInteger(readString()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } public double readDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } } } " B10109,"import java.util.*; class pqr { public static void main(String arf[]) { int a; Scanner sc=new Scanner(System.in); a=sc.nextInt(); int m=1; while(a!=0) { int p=sc.nextInt(); int q=sc.nextInt(); int max=0;//the answer for(int i=p;i<=q;i++) { int count=0; int z=i; int t=i; while(z!=0) { count++;//no of digits z=z/10; } for(int j=0;j=t && y>i) { max++; } // System.out.println(max); } } System.out.println(""Case #""+m+"": ""+max); a--; m++; } } } " B10947,"import java.io.*; import java.util.*; public class rn { static Integer rotate(Integer n) { String str=n.toString(); char[] a=str.toCharArray(); Character tmp=a[a.length-1]; for(int i=a.length-1;i>0;i--) { a[i]=a[i-1]; } a[0]=tmp; int i=0; String temp=""""; while(i1) { if(temp%10==0) { temp=drotate(temp); } else { temp=rotate(temp); } System.out.print(temp+"" ""); if(temp<=b && temp>n) { count++; System.out.println(""a""); } c--; } //System.in.read(); }//123, 312, 231, 123, outDos.writeBytes(""Case #""+cnt+"": ""+count+""\r\n""); //outDos.writeBytes(outp+""\r\n""); //outDos.writeChars(""\n""); outDos.flush(); outDos.flush(); //outDos.writeChars(""\r""); //outDos.flush(); //outDos.flush(); cnt++; //i++; } outDos.close(); inDis.close(); } }" B10635," ///REMOVE ALL OUTPUT AND USE STRINGTOKENIZER! /* ID: mfranzs1 LANG: JAVA TASK: RecycledNumbers */ import java.io.*; import java.util.*; public class RecycledNumbers { static BufferedReader f; public static void main (String [] args) throws IOException { long unixTime = System.currentTimeMillis(); // Use BufferedReader rather than RandomAccessFile; it's much faster f = new BufferedReader(new FileReader(""RecycledNumbers.in"")); // input file name goes above PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""RecycledNumbers.out""))); // Use StringTokenizer vs. readLine/split -- lots faster //StringTokenizer st = new StringTokenizer(f.readLine(),"" ""); //int i = Integer.parseInt(st.nextToken()); int cases=Integer.parseInt(f.readLine()); for(int c=0;c workingPairs = new ArrayList(); String stringN=""""+n; for(int swap=1;swap999999) return 7; if(x>99999) return 6; if(x>9999) return 5; if(x>999) return 4; if(x>99) return 3; if(x>9) return 2; return 1; } static List rotate( int value ) { List result = new ArrayList(); int[] V = new int[8]; int s = size(value); int x = value; for(int i=s-1;i>=0;i--) { V[i] = x%10; x /=10; } int rot; for(int i=1; ivalue && !result.contains(rot)) result.add(rot); } } return result; } static void precalculate() { for(int i=1; i<=MAX; i++){ All[i] = rotate(i); } } static int solve( Scanner in ) { int A, B, sol=0; A = in.nextInt(); B = in.nextInt(); for( int i=A; i<=B; i++) { // List result = rotate(i); List result = (List) All[i]; for(Integer value: result ) { if( value <= B ) sol++; } } return sol; } public static void main ( String args[] ) { int T; Scanner in = new Scanner(System.in); T = in.nextInt(); int cnt=0; int sol; precalculate(); for( cnt=1; cnt<=T; cnt++ ) { sol = solve( in ); System.out.printf(""Case #%d: %d\n"", cnt, sol); } } } " B10144,"import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.*; public class GoogleCodeInP3{ //processing file public static void main(String[] args) throws IOException { BufferedReader dog = new BufferedReader(new FileReader(args[0])); int a = -1; try { a = Integer.parseInt(dog.readLine()); } catch (Exception e) { } FileWriter file = new FileWriter(""outputFile8""); BufferedWriter cat = new BufferedWriter(file); for (int i = 0; i < a; i++) { String line = dog.readLine(); String[] barf= line.split("" ""); cat.write(""Case #"" + (i + 1) + "": "" + GoogleCodeInP3.solver(Integer.parseInt(barf[0]),Integer.parseInt(barf[1]))); if (i < a - 1) { cat.write(""\n""); } } cat.close(); } public static int solver(int a, int b){ int totalRecycledPair = 0; // returns the total number of recyled pairs int m= a+1; for (int n= a; n < m; n++){ for (m= n + 1; m < b+1; m++){ if ((m+"""").length() == (n+"""").length()){ String interN= n+""""; if (Integer.parseInt(interN) == m){ totalRecycledPair++; } for (int i= 0; i < interN.length(); i++){ interN= interN.charAt(interN.length()-1) + interN.substring(0,interN.length()-1); if (Integer.parseInt(interN) == m){ totalRecycledPair++; } } } } } return totalRecycledPair; } }" B10540,"package _2012_qual; import static java.lang.Math.*; import java.util.*; import java.io.*; public class C { boolean showDebug = true; static boolean fromFile = false; static String filePath = ""E:/AAA/_gcj/""; static boolean intoFile = !false; public void solve() throws Exception { int testCasesCnt = nextInt(); nextCase: for(int testCase=1; testCase<=testCasesCnt; testCase++) { print(""Case #""+testCase+"": ""); long r = 0; int a = nextInt(), b = nextInt(); // startTimer(); for (int i=a; i<=b; ++i) r += cnt(i,a,b); // stopTimer(); println(r); } } int[] p = new int[8]; int cnt(int x, int a, int b) { String s = str(x); int r = 0; out: for (int i=1; i=a && z<=b && xr) r=i; return r; } long minL(long... nums) { long r = Long.MAX_VALUE; for (long i: nums) if (ir) r=i; return r; } double minD(double... nums) { double r = Double.MAX_VALUE; for (double i: nums) if (ir) r=i; return r; } long sumArr(int[] arr) { long res = 0; for (int i: arr) res+=i; return res; } long sumArr(long[] arr) { long res = 0; for (long i: arr) res+=i; return res; } double sumArr(double[] arr) { double res = 0; for (double i: arr) res+=i; return res; } long partsFitCnt(long partSize, long wholeSize) { return (partSize+wholeSize-1)/partSize; } boolean odd(long num) { return (num&1)==1; } boolean hasBit(int num, int pos) { return (num&(1<0; } long binpow(long a, int n) { long r = 1; while (n>0) { if ((n&1)!=0) r*=a; a*=a; n>>=1; } return r; } boolean isLetter(char c) { return (c>='a' && c<='z') || (c>='A' && c<='Z'); } boolean isLowercase(char c) { return (c>='a' && c<='z'); } boolean isUppercase(char c) { return (c>='A' && c<='Z'); } boolean isDigit(char c) { return (c>='0' && c<='9'); } boolean charIn(String chars, String s) { if (s==null) return false; if (chars==null || chars.equals("""")) return true; for (int i=0; i=bufLim) fillBuf(); return (char)buf[bufPos++]; } boolean hasInput() throws IOException { if (bufPos>=bufLim) fillBuf(); return bufPos' ') { sb.append(c); c = inputReader.read(); } return new String(sb); } String nextLine() throws IOException { StringBuilder sb = new StringBuilder(); char c = inputReader.read(); while (c<=' ') c=inputReader.read(); while (c!='\n' && c!='\r') { sb.append(c); c = inputReader.read(); } return new String(sb); } int nextInt() throws IOException { int r = 0; char c = nextNonWhitespaceChar(); boolean neg = false; if (c=='-') neg=true; else r=c-48; c = nextChar(); while (c>='0' && c<='9') { r*=10; r+=c-48; c=nextChar(); } return neg ? -r:r; } long nextLong() throws IOException { long r = 0; char c = nextNonWhitespaceChar(); boolean neg = false; if (c=='-') neg=true; else r = c-48; c = nextChar(); while (c>='0' && c<='9') { r*=10L; r+=c-48L; c=nextChar(); } return neg ? -r:r; } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextWord()); } int[] nextArr(int size) throws NumberFormatException, IOException { int[] arr = new int[size]; for (int i=0; i readLongsSetFromRow(String row) { String[] cText = row.split(""\\s""); Set result = new TreeSet(); for (int i=0; i0) res += "", ""; res += t.substring(i,i+1); } res += ""]""; return res; } // http://www.proglogic.com/code/java/calculator/lcm.php public static long leastCommonMultiplier (long m, long n){ return m * (n / greatestCommonDivisor(m, n)); } public static long greatestCommonDivisor (long m, long n){ long x; long y; while(m%n != 0){ x = n; y = m%n; m = x; n = y; } return n; } //http://www.vogella.de/articles/JavaAlgorithmsPrimeFactorization/article.html: public static List primeFactors(int number) { int n = number; List factors = new ArrayList(); for (int i = 2; i <= n; i++) { while (n % i == 0) { factors.add(i); n /= i; } } return factors; } } " B11708,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; /** * * @author ysan * */ public class Problem_C_small { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader in = new BufferedReader(new FileReader(""C-small-attempt0.in"")); BufferedWriter out = new BufferedWriter(new FileWriter(""C-small-output0.txt"")); int cases = Integer.parseInt(in.readLine()); for (int i = 1; i <= cases; i++) { String text = in.readLine().trim(); String[] val = text.split("" ""); int count = 0; int lasta=0,lastb=0; int a = Integer.parseInt(val[0]); int b = Integer.parseInt(val[1]); for(int j=a; j0; k--){ int r = switchIt(g, k); if(r > j && r <= b && r != j){ if(lasta == j && lastb == r) continue; lasta = j; lastb = r; count++; } } } out.write(""Case #""+ i +"": "" + count); out.newLine(); } in.close(); out.close(); } static int switchIt(String v, int p){ int r=0; String a = v.substring(p); String b = v.substring(0, p); if(a.charAt(0) != '0'){ r = Integer.parseInt((a+b)); } return r; } } " B12901,"package qualr2012.problemC; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.logging.Logger; import org.apache.commons.io.FileUtils; import org.springframework.util.Assert; public class RecycledNumbers { static Logger log = Logger.getLogger(RecycledNumbers.class.getName()); final static String fileName = ""C-small-attempt0""; final static String inputFileName = fileName + "".in""; final static String outputFileName = fileName + "".out""; final static String pkgName = RecycledNumbers.class.getPackage().getName().replaceAll(""\\."", ""/""); final static String inputFile = ""src/main/java/"" + pkgName + ""/"" + inputFileName; final static String outputFolder = ""target/"" + pkgName; public static void main(String[] args) throws IOException { FileUtils.forceMkdir(new File(outputFolder)); BufferedReader reader = new BufferedReader(new FileReader(inputFile)); PrintWriter writer = new PrintWriter(outputFolder + ""/"" + outputFileName); int numCase = Integer.parseInt(reader.readLine()); for(int _case = 1; _case <= numCase; ++_case) { int i, j, k, l, m, ans = 0; String[] s = reader.readLine().split("" ""); int A = Integer.parseInt(s[0]), B = Integer.parseInt(s[1]); boolean[][] visited = new boolean [B + 1][B + 1]; for (i = 0; i < B + 1; ++i) { for (j = 0; j < B + 1; ++j) { visited[i][j] = false; } } l = (B+"""").charAt(0) - '0'; for (i = A; i <= B; ++i) { // from right, find first digit > 0 and <= first digit on B, only swap // if i > 0 String i_str = i + """"; for (j = i_str.length() - 1; j > 0; --j) { k = i_str.charAt(j) - '0'; if (k > 0 && k <= l) { m = Integer.parseInt(i_str.substring(j) + i_str.substring(0, j)); if (m != i && m <= B && i < m && !visited[i][m] /*&& !visited[m][i]*/) { visited[i][m] = true; /*visited[m][i] = true;*/ ans++; } } } } log.info(""Case #"" + _case + "": "" + ans); writer.println(""Case #"" + _case + "": "" + ans); } reader.close(); writer.close(); } } " B11359,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.Writer; import java.util.Arrays; /** * Recycled Numbers * @author shibink * */ public class Recycle { public static int getCount(String str) { int count = 0; int tmp = 0; int numDigits = 0; if ((str == null) || (str.isEmpty())) { return count; } String[] strArray = str.split("" ""); // It should be 2 if (strArray.length != 2) { return 0; } int num1 = Integer.parseInt(strArray[0]); int num2 = Integer.parseInt(strArray[1]); tmp = num1; // Find number of digits in num1 & num2 while (tmp > 0) { numDigits++; tmp = tmp / 10; } int arr[] = new int[numDigits]; int cnt; for (int i = num1; i <= num2; i++) { Arrays.fill(arr, 0); cnt = 0; for (int val = i, j = 1; j < numDigits; j++) { tmp = val % 10; if (tmp == 0) { val = val/10; continue; } val = (int) (tmp * Math.pow(10, (numDigits - 1)) + (val / 10)); for (int k=0; k i) && (val <= num2)) { count++; } } } return count; } public static void processFile(String fileName) throws IOException { FileInputStream fstream = new FileInputStream(fileName); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); // use buffering Writer output = new BufferedWriter(new FileWriter(""output.txt"")); try { String strLine = null; int numRecycle = 0; int count = 0; if ((strLine = br.readLine()) != null) { count = Integer.parseInt(strLine); } // Read File Line By Line for (int i = 1; i <= count; i++) { if ((strLine = br.readLine()) == null) { return; } numRecycle = getCount(strLine); System.out.println(""Case #"" + i + "": "" + numRecycle); StringBuffer outBuff = new StringBuffer(""Case #"" + i + "": "" + numRecycle + ""\n""); output.write(outBuff.toString()); } } finally { // Close the input stream in.close(); output.close(); } } /** * @param args */ public static void main(String[] args) { String fileName = ""input.in""; try { processFile(fileName); } catch (IOException e) { // TODO Log error } return; } } " B12648,"import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.List; import java.util.ArrayList; public class Rec{ static int rotate(int n, int l){ int pot = (int)Math.pow(10,l-1); int ld = (int)Math.floor(n/pot); int cd = n-ld*pot; int ans = cd*10+ld; return ans; } static String bw(String a, int n){ String ans = """"; for(int i=n;i""+ans+ans2); return ans+ans2; } public static int recnum(int a, int b){ int[] test = new int[b-a+1]; int ans = 0; int l=String.valueOf(a).length(); for(int i=a;i<=b;i++){ int c = i; List reps = new ArrayList(); for(int j=1;ji && String.valueOf(c).length()==l && c!=i && !reps.contains(c)){ ans++; reps.add(c); //System.out.println(""(""+String.valueOf(i)+"",""+String.valueOf(c)+"")""); } } } return ans; } public static void main(String[] args) throws IOException{ BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); String ttt = """"; int n = Integer.parseInt(stdin.readLine()); int i = 1; while (i<=n){ ttt = stdin.readLine(); String[] AB = ttt.split("" ""); int a = Integer.parseInt(AB[0]); int b = Integer.parseInt(AB[1]); System.out.println(""Case #""+String.valueOf(i++)+"": ""+String.valueOf(recnum(a,b))); } stdin.close(); } } " B11680,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package uk.co.epii.codejam.common; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; /** * * @author jim */ public class Output { private final String[] data; public Output(String[] data) { this.data = data; } public Output(ArrayList data) { this(data.toArray(new String[0])); } public int size() { return data.length; } public String get(int i) { StringBuilder sb = new StringBuilder(data[i].length() + 10); sb.append(""Case #""); sb.append(i + 1); sb.append("": ""); sb.append(data[i]); return sb.toString(); } public void export(String fileName) { if (fileName == null) print(); else { try { save(fileName); } catch (IOException ioe) { System.out.println(ioe.getMessage()); ioe.printStackTrace(); } } } private void print() { for (int i = 0; i < size(); i++) System.out.println(get(i)); } private void save(String fileName) throws IOException { FileWriter fw = new FileWriter(fileName); PrintWriter pw = new PrintWriter(fw); for (int i = 0; i < size(); i++) { pw.println(get(i)); } pw.flush(); pw.close(); fw.close(); } } " B11919," import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; public class QC { public static void main(String[] args) { try{ Scanner sc = new Scanner(new File(""C-small-attempt0.in"")); BufferedWriter bw = new BufferedWriter(new FileWriter(new File(""output.out""))); int t = sc.nextInt(); for(int i=0;i=100 && a<1000){ for(int p=1;p<10;p++){ for(int q=0;q<10;q++){ if(p==q)continue; int e = 0,m = 0; m = 100*q+10*p+p; if(m>=a && m<=b) e++; m = 100*p+10*q+p; if(m>=a && m<=b) e++; m = 100*p+10*p+q; if(m>=a && m<=b) e++; if(e==3) r += 3; else if(e==2) r += 1; } } for(int p=0;p<10;p++){ for(int q=p+1;q<10;q++){ for(int s=q+1;s<10;s++){ int e = 0,m = 0; m = 100*p+10*q+s; if(m>=a && m<=b) e++; m = 100*q+10*s+p; if(m>=a && m<=b) e++; m = 100*s+10*p+q; if(m>=a && m<=b) e++; if(e==3) r += 3; else if(e==2) r += 1; e = 0; m = 100*p+10*s+q; if(m>=a && m<=b) e++; m = 100*s+10*q+p; if(m>=a && m<=b) e++; m = 100*q+10*p+s; if(m>=a && m<=b) e++; if(e==3) r += 3; else if(e==2) r += 1; } } } } else if(a>=10){ for(int p=1;p<10;p++){ for(int q=p+1;q<10;q++){ if(p*10+q>=a && p*10+q<=b && q*10+p>=a && q*10+p<=b) r++; } } } bw.write(""Case #""+String.valueOf(i+1)+"": ""); bw.write(String.valueOf(r)); bw.newLine(); bw.flush(); } bw.close(); } catch (Exception ex) { Logger.getLogger(QA.class.getName()).log(Level.SEVERE, null, ex); } } } " B12059,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.io.PrintWriter; /** * * @author Vale */ public class RecycledNumbers { public static void main(String[] args){ String inputFile=""/Users/Vale/Desktop/CodeJam/C-small-attempt1.in""; String outputFile=""/Users/Vale/Desktop/CodeJam/C-small-output1.txt""; String[] lines=readAllLinesOfFile(inputFile); int numberOfCases=Integer.parseInt(lines[0]); String[] result=new String[numberOfCases]; for (int i = 1; i <= numberOfCases; i++) { String currentLine=lines[i]; int lowerValue=Integer.parseInt(currentLine.substring(0, currentLine.indexOf("" ""))); int start=currentLine.indexOf("" "")+1; int upperValue=Integer.parseInt(currentLine.substring(start)); int resultValue=0; for (int j = lowerValue; j < upperValue; j++) { for (int k = j+1; k < upperValue+1; k++) { if(isRecycledPair(j, k)) resultValue++; } } result[i-1]=""Case #""+i+"": ""+resultValue; } writeLinesToFile(outputFile, result); } public static int powerOf(int n, int i){ if(i==1) return n; else return n*powerOf(n, i-1); } public static int digitsOf(int n){ int result=0; while(n>0){ result++; n/=10; } return result; } public static boolean isRecycledPair(int n, int m){ int numberOfDigits=digitsOf(n); for (int digits = 1; digits < numberOfDigits; digits++) { int recycledPart=(n%powerOf(10, digits)); int recycleValue=recycledPart*(powerOf(10, numberOfDigits-digits)); int recycledNumber=(n/powerOf(10, digits))+recycleValue; if (recycledNumber==m) return true; } return false; } public static String[] readAllLinesOfFile(String file){ try{ // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(file); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; //Read File Line By Line String[] result=new String[1000000]; int index=0; while ((strLine = br.readLine()) != null) { result[index++]=strLine; } //Close the input stream in.close(); String[] newResult=java.util.Arrays.copyOf(result, index); return newResult; }catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); return new String[] {}; } } public static void writeLinesToFile(String filename, String[] linesToWrite) { try { PrintWriter pw = new PrintWriter(new FileWriter(filename)); for (int i = 0; i < linesToWrite.length; i++) { pw.println(linesToWrite[i]); } pw.flush(); pw.close(); } catch (Exception e) { throw new RuntimeException(""Writing File \"""" + filename + ""\"" Failed!""); } } } " B12912,"package er.dream.codejam.qual; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import er.dream.codejam.helpers.ProblemSolver; public class RecycledNumbers extends ProblemSolver{ public static void main(String[] args) { new RecycledNumbers().execute(); } @Override protected List handleInput() { List result = new ArrayList(); int[] settings = fileHandler.readIntArray(); for(int line = 0;line foundTransformations = new HashSet(); for(int i=stringLength-1;i>0;i--){ newString = numberString.substring(i)+numberString.substring(0, i); transformedNumber = Integer.parseInt(newString); if(transformedNumber > number && transformedNumber <= max && !foundTransformations.contains(transformedNumber)){ transformations++; foundTransformations.add(transformedNumber); } } return transformations; } } " B12899,"package com.bchetty.gcj2012; import java.io.*; import java.util.ArrayList; import java.util.HashSet; /** * * @author Babji Prashanth, Chetty */ public class RecycledNumbers { public static void main(String[] args) { RecycledNumbers recycledNums = new RecycledNumbers(); LineNumberReader lineNumberReader = null; BufferedWriter bufferedWriter = null; try { lineNumberReader = new LineNumberReader(new FileReader(""/Users/babjichetty/Downloads/C-small-attempt0.in"")); bufferedWriter = new BufferedWriter(new FileWriter(""/Users/babjichetty/Downloads/C-small.out.txt"")); String line = null; int index = 0; int count = 0; while ((line = lineNumberReader.readLine()) != null) { if(index == 0) { count = Integer.parseInt(line); System.out.println(""Count : "" + count); index++; continue; } if(index > count) { break; } String[] arr = line.split("" ""); int A = Integer.parseInt(arr[0]); int B = Integer.parseInt(arr[1]); bufferedWriter.write(""Case #"" + index + "": "" + recycledNums.findNumberOfPairs(A, B)); bufferedWriter.newLine(); index++; } } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { //Close the BufferedWriter try { if (lineNumberReader != null) { lineNumberReader.close(); } if (bufferedWriter != null) { bufferedWriter.close(); } } catch (IOException ex) { ex.printStackTrace(); } } } public int findNumberOfPairs(int A, int B) { int res = 0; for(int i=A;i<=B;i++) { HashSet partnerSet = new HashSet(); String input = """" + i; System.out.println(""Num : "" + input); int len = input.length(); int count = len-1; for(int j=0;j i && partner <= B && ("""" + partner).length() == len) { System.out.println(""Partner Found : "" + partner); res++; partnerSet.add(partner); } } } System.out.println(""Num of pairs : "" + res); return res; } } " B13092,"import java.io.BufferedReader; import java.io.InputStreamReader; public class C { boolean rec(int i, int j){ String s1 = i+""""; String s2 = j+""""; if(s1.length() != s2.length()) return false; String concat = s1+s1; if(!concat.contains(s2)) return false; return true; } void run() { try { BufferedReader bfd = new BufferedReader(new InputStreamReader( System.in)); int tc = Integer.parseInt(bfd.readLine()), i, j, k, a, b, cnt; String sp[]; for(k=0; k set = new HashSet(); // System.out.println(""------------ ""); String in = reader.readLine(); int A = Integer.parseInt(in.split("" "")[0]); int B = Integer.parseInt(in.split("" "")[1]); //System.out.println(""A = "" + A); //System.out.println(""B = "" + B); int cyfr = 1+ (int) Math.log10(A); //System.out.println(""cyfr = "" + cyfr); int out = 0; for(int j = A; j<=B; j++){ // System.out.println(""j = "" + j); for(int k =1 ; k=A) && (nowa <=B) ){ set.add(""""+nowa+""_""+j); } } } System.out.println(""Case #""+(i+1)+"": ""+set.size()); writer.write(""Case #""+(i+1)+"": ""+set.size()); writer.newLine(); } writer.close(); } } " B11017," import java.io.File; public class RecycledNumbers { public static void main(String[] args) { try { FileReader fr = new FileReader(new File(args[0])); PrintResult pr = new PrintResult(args[1]); process(fr, pr); } catch (Exception e) { e.printStackTrace(); } } public static void process(FileReader fr, PrintResult pr) { int numCases; int[] in; try { numCases = fr.nextInt(); for (int i = 0; i < numCases; i++) { in = fr.nextIntArray(); pr.printLine(i, solve(in[0],in[1])); } pr.close(); } catch (Exception e) { e.printStackTrace(); } } public static String solve(int a, int b) { int count = 0; char[] achar = Integer.toString(a).toCharArray(); int m = 0; if(achar.length > 1) { for(int n = a; n < b+1; n++) { for(int j = 1; j < Integer.toString(n).length(); j++) { m = rearrange(n,j); if(m > n && m < b + 1) { int mlength = Integer.toString(m).toCharArray().length; int nlength = Integer.toString(n).toCharArray().length; if(mlength == nlength) { count++; } if(b == 2222) { System.out.println(n + "" "" + m + "" "" + j); } } } } } return Integer.toString(count); } public static int rearrange(int in, int amount) { char[] temp = Integer.toString(in).toCharArray(); char[] result = new char[temp.length]; for(int i = 0; i < temp.length; i++) { result[i] = temp[(temp.length-amount+i)%temp.length]; } return Integer.parseInt(new String(result)); } } " B12984,"import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class ProblemC { public static void main(String[] args) throws IOException { new ProblemC(); } private int numOfTest; private static final int ATTEMPT_NO = 0; private static int SOLVE_HARD = 0; int A, B; int ans; public ProblemC() throws IOException { // Scanner input = new Scanner(new File(""input.txt"")); Scanner input = new Scanner(new File(""C-small-attempt"" + ATTEMPT_NO + "".in"")); Writer output = new FileWriter(""C-small-attempt"" + ATTEMPT_NO + "".out""); if (SOLVE_HARD != 0) { input = new Scanner(new File(""C-large.in"")); output = new FileWriter(""C-large.in""); } //output = new BufferedWriter(new OutputStreamWriter(System.out)); numOfTest = input.nextInt(); for (int test = 1; test <= numOfTest; test++) { // read from input A = input.nextInt(); B = input.nextInt(); process(); output.write(""Case #"" + test + "": "" + ans + ""\n""); } input.close(); output.flush(); output.close(); } private void process() { ans = 0; for (int num = A; num < B; num++) { int left = num; int right = 0; int mul10 = 1; Set checked = new HashSet(); boolean lastGood = false; while (left > 0) { if (lastGood) { int m = Integer.parseInt(String.valueOf(right) + String.valueOf(left)); if (m > num && m <= B && !checked.contains(m)) { //System.err.println(num + "" "" + m + "" "" + ans); checked.add(m); ans++; } } int lastDigit = left % 10; right = lastDigit * mul10 + right; left /= 10; mul10 *= 10; lastGood = (lastDigit != 0); } } } }" B11848,"import java.io.*; import java.util.*; import java.math.*; public class C implements Runnable { private long solve(int A, int B) { int pow = 1; while (pow <= A/10) { pow *= 10; } HashSet h = new HashSet(); for (int n = A; n <= B; ++n) { int nn = n; nn = (nn%pow)*10 + (nn/pow); while (nn != n) { if (A <= nn && nn <= B) { if (nn < n) { h.add(1L*nn*pow*10+n); } else { h.add(1L*n*pow*10+nn); } } nn = (nn%pow)*10 + (nn/pow); } } return h.size(); } public void run() { int n = nextInt(); for (int i = 0; i < n; ++i) { int A = nextInt(); int B = nextInt(); long ans = solve(A, B); out.println(""Case #""+(i+1)+"": ""+ans); } out.flush(); } private static BufferedReader br = null; private static StringTokenizer stk = null; private static PrintWriter out = null; public static void main(String[] args) throws IOException { br = new BufferedReader(new FileReader(new File(""D:\\C.txt""))); out = new PrintWriter(""D:\\CC.txt""); (new Thread(new C())).start(); } public void loadLine() { try { stk = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } public String nextLine() { try { return (br.readLine()); } catch (IOException e) { e.printStackTrace(); } return null; } public int nextInt() { while (stk==null || !stk.hasMoreTokens()) loadLine(); return Integer.parseInt(stk.nextToken()); } public long nextLong() { while (stk==null || !stk.hasMoreTokens()) loadLine(); return Long.parseLong(stk.nextToken()); } public double nextDouble() { while (stk==null || !stk.hasMoreTokens()) loadLine(); return Double.parseDouble(stk.nextToken()); } public String nextWord() { while (stk==null || !stk.hasMoreTokens()) loadLine(); return (stk.nextToken()); } } " B12146,"import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class C { public static void main(String[] args)throws IOException { // Scanner br=new Scanner(System.in); Scanner br=new Scanner(new File(""C-small-attempt0.in"")); PrintWriter out=new PrintWriter(new File(""c.out"")); int cases=br.nextInt(); for(int c=1;c<=cases;c++) { int a=br.nextInt(); int b=br.nextInt(); int count=0; for(int i=a;i<=b;i++) { for(int j=i+1;j<=b;j++) { if(recycled(i,j)) { count++; } } } out.printf(""Case #%d: %d\n"",c,count); } out.close(); } static boolean recycled(int a,int b) { StringBuilder one=new StringBuilder(Integer.toString(a)),two=new StringBuilder(Integer.toString(b)); if(one.length()!=two.length()) return false; for(int i=0;i B)) output.write(""0""); else { int count = 0; for(int j=A; j matches = new HashSet(); for(int k=1; kj) && (m<=B)) matches.add(m); } count += matches.size(); } output.write(String.valueOf(count)); } if(i lines = Files.readLines(inputFile, Charsets.UTF_8); int cases = Integer.parseInt(lines.remove(0)); int caseNo = 1; for (String line : lines) { String[] split = line.split("" ""); int a = Integer.parseInt(split[0]); int b = Integer.parseInt(split[1]); int recycledPairs = countRecycledPairs(a, b); out.printf(""Case #%d: %d\n"", caseNo, recycledPairs); System.out.printf(""Case #%d: %d\n"", caseNo, recycledPairs); caseNo++; } // end for-each lines } finally { Closeables.closeQuietly(out); } } private static int countRecycledPairs(final int a, final int b) { if (a >= b) { return 0; } int count = 0; for (int n = a; n <= b; n++) { Set set = new HashSet(); String ns = Integer.toString(n); // System.out.println(ns + "":""); for (int i = 1; i < ns.length(); i++) { String s1 = ns.substring(0, i); s1 = CharMatcher.is('0').trimLeadingFrom(s1); String s2 = ns.substring(i); s2 = CharMatcher.is('0').trimLeadingFrom(s2); String ms = s2 + s1; if (ns.length() == ms.length()) { // System.out.println(s1 + "", "" + s2); int m = Integer.parseInt(ms); if (n > m) { int t = n; m = n; n = t; } if (a <= n && n < m && m <= b && set.add(new Point(n, m))) { count++; // System.out.println(ns + "", "" + ms); } } } // System.out.println(); } return count; } }" B12289,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { int noOfTestCases = 0; int[][] testData; public static void main ( String[] args ) { String fileName = ""problemc.sample.in""; if ( args.length > 0 ) { fileName = args[0]; } RecycledNumbers rn = new RecycledNumbers ( ); try { rn.readInputFile ( fileName ); } catch ( IOException e ) { System.err.println ( ""Problem reading the input file"" ); e.printStackTrace(); } //rn.getRotatedNumbers ( ""123456"" ); rn.processTestData ( ); } private void processTestData ( ) { for ( int i = 0; i < noOfTestCases; i++ ) { Set < String > unique = new HashSet < String >(); int from = testData[i][0]; int to = testData[i][1]; for ( int j = from; j <= to; j++ ) { int[] rotatedNumbers = getRotatedNumbers ( """" + j ); checkIfValid ( rotatedNumbers, j, from, to, unique ); } System.out.println ( ""Case #"" + (i+1) + "": "" + unique.size ( )); } } private void checkIfValid ( int[] in, int current, int from, int to, Set < String > unique ) { for ( int i = 0; i < in.length; i++ ) { int number = in[i]; if ( number < from ) { } else if ( number > to ) { } else if ( number <= current ) { } else { //System.out.println ( number ); unique.add ( """"+ number + current ); } } } private int[] getRotatedNumbers ( String input ) { int length = input.length ( ); int[] output = new int[length-1]; char[] outstring = input.toCharArray(); for (int i = 0; i < length-1; i++) { //Length-1 or length? char ch = outstring[length - 1]; for (int j = length - 1; j > 0; j--) { outstring[j] = outstring[j - 1]; } outstring[0] = ch; output[i] = Integer.parseInt ( new String(outstring ) ); } return output; } private void readInputFile ( String fileName ) throws IOException { BufferedReader br = new BufferedReader ( new FileReader ( fileName ) ); noOfTestCases = Integer.parseInt ( br.readLine ( ) ); testData = new int[noOfTestCases][2]; for ( int i = 0; i < noOfTestCases; i++ ) { String[] data = br.readLine ( ).split ( "" "" ); testData[i][0] = Integer.parseInt ( data[0] ); testData[i][1] = Integer.parseInt ( data[1] ); } } } " B10841,"package nithin.codejam; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Solution { static int valid_pairs[][]; static int no_valid_pairs=0; public static void main(String args[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; int t,i; t=Integer.parseInt(br.readLine()); for(i=0;i=a && num<=b && j!=num) { if(j<=num) { if(add(j,num)) result++; } else { if(add(num,j)) result++; } } } } } if(ex2==true) { /* int j; for(j=101;j<=b;j++) { int last=j%100; int rem=j/100; int num=-1; if(rem!=0) { if(rem<10) //if rem=10 then it means it was obtained from a number like 1025 by extracting last 2 digits, so you have to multiply last by 100 { num=last*100+rem; } else if(rem<100) { num=last*1000+rem; } else if(rem<1000) { num=last*10000+rem; } else { System.out.println(""Not a Valid Case for Small Input""); } if(num>=a && num<=b && j!=num) { if(add(j,num)) //num is actually m, it is obtained by moving some digits from back of j to the front. result++; } } }*/ } if(ex3==true) { //Do Nothing } System.out.println(""Case #""+(i+1)+"": ""+result); /* int j; for(j=0;jj && Integer.parseInt(temp2)<=B) output++; if(n==j) break; } } System.out.println(""Case #"" +(i+1) + "": "" + output); } } } " B11725,"import java.util.Set; import java.util.Scanner; import java.io.OutputStream; import java.io.IOException; import java.io.FileOutputStream; import java.io.PrintWriter; import java.io.FileInputStream; import java.util.HashSet; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream; try { inputStream = new FileInputStream(""Main/input.txt""); } catch (IOException e) { throw new RuntimeException(e); } OutputStream outputStream; try { outputStream = new FileOutputStream(""Main/output.txt""); } catch (IOException e) { throw new RuntimeException(e); } Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); C solver = new C(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } } class C { public void solve(int testNumber, Scanner in, PrintWriter out) { int A = in.nextInt(), B = in.nextInt(); int digit, a = A, ten = 1; digit = countDigit(a); for (int i = 0; i < digit - 1; ++i) ten *= 10; Set set = new HashSet(); long ans = 0; for (int num = A; num <= B; ++num) if (!set.contains(num)) { Set curSet = new HashSet(); int cur = num; curSet.add(cur); for (int i = 0; i < digit; ++i) { cur = cur % 10 * ten + cur / 10; if (A <= cur && cur <= B && countDigit(cur) == digit) curSet.add(cur); } int cnt = curSet.size(); ans += (cnt * (cnt - 1)) / 2; for (int i : curSet) set.add(i); } out.print(String.format(""Case #%d: %d\n"", testNumber, ans)); } private int countDigit(int n) { int digit = 0; while (n > 0) { digit++; n /= 10; } return digit; } } " B10887,"package de.at.codejam; import java.io.File; import java.util.ArrayList; import java.util.List; import de.at.codejam.util.AbstractOutputFileWriter; import de.at.codejam.util.CaseSolver; import de.at.codejam.util.InputFileParser; import de.at.codejam.util.StatusListener; import de.at.codejam.util.TaskStatus; public abstract class AbstractCodeJamProblemSolver implements StatusListener { private final List statusListenerList = new ArrayList(); private TaskStatus taskStatus = null; private CaseSolver currentCaseSolver; public void solveInputFile(File inputFile, File outputFile) { taskStatus = new TaskStatus(); final InputFileParser inputFileParser = createInputFileParser(inputFile); final AbstractOutputFileWriter outputFileWriter = createOutputFileWriter(outputFile); inputFileParser.initialize(taskStatus); log(LOGLEVEL_INFO, ""Initialized: "" + taskStatus); Thread caseSolvingProcess = new Thread(new Runnable() { @Override public void run() { taskStatus.setCurrentTaskStatus(TaskStatus.STATUS_RUNNING); int i = 0; try { while (inputFileParser.hasNextCase()) { final CASE currentCase = inputFileParser.getNextCase(); i++; taskStatus.setNumberCurrentCase(i); String result = solveCase(taskStatus, currentCase); log(StatusListener.LOGLEVEL_INFO, result); outputFileWriter.appendResult(result); try { Thread.sleep(50); } catch (InterruptedException e) { } } taskStatus.setCurrentTaskStatus(TaskStatus.STATUS_DONE); } catch (Exception exc) { exc.printStackTrace(); log(LOGLEVEL_ERROR, ""Exception while reading / solving cases: "" + exc.getMessage()); taskStatus.setCurrentTaskStatus(TaskStatus.STATUS_ERROR); } } }); caseSolvingProcess.start(); Thread progressUpdateProcess = new Thread(new Runnable() { @Override public void run() { while (!taskStatus.equals(TaskStatus.STATUS_DONE)) { updateStatus(taskStatus); try { Thread.sleep(1000); } catch (InterruptedException e) { } } updateStatus(taskStatus); } }); progressUpdateProcess.start(); } private String solveCase(TaskStatus taskStatus, CASE caseToSolve) { if ((null == currentCaseSolver) || !useCaseSolver(currentCaseSolver, caseToSolve)) { currentCaseSolver = buildCaseSolver(caseToSolve); currentCaseSolver.addStatusListener(this); } return currentCaseSolver.solveCase(taskStatus, caseToSolve); } protected abstract boolean useCaseSolver(CaseSolver caseSolver, CASE caseToSolve); protected abstract CaseSolver buildCaseSolver(CASE caseToSolve); protected abstract InputFileParser createInputFileParser( File inputFile); protected abstract AbstractOutputFileWriter createOutputFileWriter( File outputFile); @Override public void updateStatus(TaskStatus taskStatus) { for (StatusListener listener : statusListenerList) { listener.updateStatus(taskStatus); } } @Override public void log(int logLevel, String message) { for (StatusListener listener : statusListenerList) { listener.log(logLevel, message); } } public void addStatusListener(StatusListener statusListener) { statusListenerList.add(statusListener); } public void removeStatusListener(StatusListener statusListener) { statusListenerList.remove(statusListener); } } " B12797,"package com.problemC; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; public class RecycledNumber { private static int A = 1111; private static int B = 2222; public static int count = 0; public static void main(String[] args) { String[] s ; BufferedReader br = null; try { br = new BufferedReader(new FileReader(""src/com/problemC/C-small-attempt0.in"")); int caseNo = 1; int T = Integer.parseInt(br.readLine()); while (caseNo <= T) { count = 0; s = br.readLine().split("" ""); A = Integer.parseInt(s[0]); B = Integer.parseInt(s[1]); for (int i = A; i <= B; i++) { rotate(i); } System.out.println(""Case #"" + caseNo++ + "": "" + count); } } catch (NumberFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally{ try { if(br != null){ br.close(); } } catch (IOException e) { e.printStackTrace(); } } } private static void rotate(int num) { int l = (num + """").length(), l2; int toCut = 1; int original = num, newNum; String s = num + """", firstPart, secondPart; // System.out.println(s); for (toCut = 1; toCut < l; toCut++) { firstPart = s.substring(0, l - toCut); secondPart = s.substring(l - toCut); newNum = Integer.parseInt(secondPart + firstPart); // System.out.println(firstPart + "" ""+secondPart +"": ""+newNum); l2 = (newNum + """").length(); if (l == l2 && newNum > original && newNum <= B) { // System.out.println(original + "" "" + newNum); count++; } } } } " B12244,"package com.lily.acm.googleCodeJam; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; public class RecycledNumbers { public static int getRecyleCount(int n,int start,int end){ int temp2=n; int count =0; int digit=0; int max=1; int temp =n; while(temp!=0){ digit++; temp/=10; max*=10; } max/=10; HashSet set =new HashSet(); for(int i=1;i=start&&i<=end&&i>max&&i!=temp2) { count++; } } return count; } public static void readInput(String fileName){ BufferedReader is= null; FileOutputStream os =null; int count=1; try { is = new BufferedReader(new FileReader(fileName)); os = new FileOutputStream(new File(""c://output.txt"")); String input=""""; if(is.readLine()==null) return ; while((input= is.readLine())!=null){ os.write((""Case #""+count+++"": ""+lineCount(input.split("" "")[0],input.split("" "")[1])+""\r\n"").getBytes()); os.flush(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ try { is.close(); os.close(); } catch (IOException e) { e.printStackTrace(); } } } public static int lineCount(String start,String end) { int s=Integer.valueOf(start); int e=Integer.valueOf(end); int total=0; for(int i=s;i<=e;i++){ total+=getRecyleCount(i,s,e); } return total/2; } public static void main(String[] args) { readInput(""c://C-small-attempt0.in""); } } " B12174,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; public class recycle { public static void rec() throws NumberFormatException, IOException { BufferedReader in = new BufferedReader(new FileReader(""src/test1"")); String line; StringBuilder bubs = new StringBuilder(); int T = Integer.parseInt(""""+in.readLine().charAt(0)); int i=0; while ((line=in.readLine())!=null) { i++; String[] splitline = line.split(""\\s+""); int A = Integer.parseInt(splitline[0]); int B = Integer.parseInt(splitline[1]); int d = splitline[0].length(); StringBuilder subs = new StringBuilder(); subs.append(""Case #"" + i + "": ""); int count = 0; for (int n=A;n hm = new HashMap(); for (int b=0;b n && Integer.parseInt(btry) <=B) { hm.put(Integer.parseInt(btry), 1); count++; } } } subs.append(count); bubs.append(subs.toString()); System.out.println(subs.toString()); } } } " B10045," package codejam; import java.io.*; import java.util.ArrayList; import java.util.HashSet; import java.util.List; /** * * @author Ronak */ public class C { public static void main(String[] args) throws FileNotFoundException, IOException { File f = new File(""C-small-attempt1.in""); FileInputStream fstream = new FileInputStream(f); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine = """"; int count = 0, T = 0; List left = new ArrayList(); while ((strLine = br.readLine()) != null) { if (count == 0) { T = Integer.parseInt(strLine.trim()); } else { strLine.trim(); String[] l = strLine.split("" ""); int min = Integer.parseInt(l[0]); int max = Integer.parseInt(l[1]); System.out.print(""Case #"" + count + "": ""); for (int n = min; n <= max; n++) { String str = String.valueOf(n); for (int i = 1; i < str.length(); i++) { String temp = str.substring(i, str.length()) + str.substring(0, i); if (temp.charAt(0) != '0') { int m = Integer.parseInt(temp); if (n < m && m <= max && n >= min) { left.add(n + """" + m + """"); } } } } System.out.println(new ArrayList(new HashSet(left)).size()); left.clear(); } count++; } } } " B12718,"import java.util.Scanner; public class test { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); int casenum = 1; while (T-- > 0) { int num = solve(sc); System.out.println(""Case #"" + casenum++ + "": "" + num); } } private static int solve(Scanner sc) { int A = Integer.parseInt(sc.next()); int B = Integer.parseInt(sc.next()); long ts = System.currentTimeMillis(); int num = 0; for (int a = A; a < B; a++) { for (int b = a+1; b <= B; b++) { if(isrec(a,b)) { //if(num < 10) //System.out.println(""rec: "" + a + "" and "" + b); num++; } } } ts = System.currentTimeMillis() - ts; //System.out.println(""time: "" + ts); return num; } private static boolean isrec(int a, int b) { int hi = a; int lo = 0; int[] base = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000}; int i = 0; int len = 0; while(base[len] < a) len++; if(b >= base[len] || b <= base[len]/10) return false; while (hi > 0){ int num = lo*base[len-i]+hi; if(num == b) { //System.out.println(a + "" "" + b + "": "" + hi + ""|"" + lo); return true; } hi /= 10; lo = a - hi*base[i+1]; i++; } return false; } } " B13002,"package mgg.problems; import java.util.List; import mgg.utils.CorrespondenceUtils; import mgg.utils.FileUtil; import mgg.utils.StringUtils; /** * @author manolo * @date 14/04/12 */ public class ProblemA { public final static String EXAMPLE_IN = ""A-example.in""; public final static String EXAMPLE_OUT = ""A-example.out""; public final static String A_SMALL_IN = ""A-small-attempt1.in""; public final static String A_SMALL_OUT = ""A-small-attempt1.out""; public final static String delim = "" ""; public static String solve(FileUtil util) { String line; List listOfCharacters; line = util.getLine(); listOfCharacters = StringUtils.allCharactersToList(line); char englishTranslation; StringBuilder solutionBuilder = new StringBuilder(); for (char c : listOfCharacters){ System.out.print(""char: "" + c); englishTranslation = CorrespondenceUtils.getGooglereseCorrespondence(c); System.out.println(""("" + englishTranslation + "")""); solutionBuilder.append(englishTranslation); } return solutionBuilder.toString(); } }" B10492," import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.Scanner; public class TemplateClass { protected Scanner sc; protected BufferedWriter bw; protected int testCases = 0; File ficheroEntrada; File ficheroSalida; public TemplateClass() { } public TemplateClass(String nombreFicheroEntrada, String nombreFicheroSalida) throws Exception { ficheroEntrada = new File (nombreFicheroEntrada); ficheroSalida = new File (nombreFicheroSalida); sc = new Scanner(ficheroEntrada); testCases = sc.nextInt(); bw = traeBufferSalida(ficheroSalida); } protected BufferedWriter traeBufferSalida(File ficheroSalida) throws Exception { return new BufferedWriter(new FileWriter(ficheroSalida)); } protected void procesaTestCase() throws Exception{ } } " B10294,"package problemC; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.Writer; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { public static void main(String[] args) throws Exception { Writer write = new FileWriter(new File(""out.txt"")); Writer writer = new BufferedWriter(write); Scanner scan = new Scanner(new File(""C-small-attempt0.in.txt"")); int num = scan.nextInt(); for(int i = 1; i<=num; i++) { int lower = scan.nextInt(); int upper = scan.nextInt(); int count = 0; for(int j = lower; j iterations = iterations(""""+j); for(int k = j+1; k<=upper; k++) { String s = """"+k; if(iterations.contains(s)) count++; } } writer.write(""Case #""+i+"": ""+count+""\n""); } writer.close(); write.close(); } public static Set iterations(String in) { Set strings = new HashSet(); String current = new String(in); strings.add(current); for(int i = 0; i 1) { for (int j = 0; j < (numberElmtLength-1); j++) { char lastElmt = numberElmt[numberElmtLength-1]; for (int k = (numberElmtLength-1); k > 0; k--) { numberElmt[k] = numberElmt[k-1]; } numberElmt[0] = lastElmt; int tmpRecycle = Integer.parseInt(String.valueOf(numberElmt, 0, numberElmtLength)); if (tmpRecycle > processedNumber && tmpRecycle <= topLimit) { nbRecycledPair++; } } } } // output result fos.write((""Case #""+processedCase+"": ""+nbRecycledPair+""\n"").getBytes()); //System.out.println(""Case #""+processedCase+"": ""+nbRecycledPair); // back to search tmpCredit processedCase++; } } fis.close(); fos.close(); } catch (FileNotFoundException e) { System.err.println(""FileNotFound : "" + e); } catch (IOException e) { System.err.println(""IOException : "" + e); } catch (Exception e) { System.err.println(""Other Exception : "" + e); } } /** * @param args the command line arguments **/ public static void main(String[] args) { // TODO code application logic here recycledNumbers(""C-small-attempt0.in"", ""C-small-attempt0.out""); } } " B12093,"import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; public class CodeJam { public static void main(String[] args) throws Exception { File input=new File(""input.txt""); BufferedReader bufferedReader=new BufferedReader(new FileReader(input)); String output=""""; String line=null; int lineCount=0; int caseNumbers=0; String solutionString=""""; while((line=bufferedReader.readLine())!=null) { if(lineCount==0) { caseNumbers=Integer.parseInt(line); } else { int solution=0; String[] split=line.split("" ""); int a=Integer.parseInt(split[0]); int b=Integer.parseInt(split[1]); int n=a; int m=b; while(n=0) { test[count2+1]=test[count2]; count2--; } test[0]=x; count++; } return solution; } } " B12732,"import java.io.*; public class googleJam3 { /** * @param args */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub BufferedReader reader = null; PrintWriter writer = null; try{ reader = new BufferedReader(new FileReader(""C-small-attempt0.in"")); writer = new PrintWriter(new BufferedWriter(new FileWriter(""C-small-attempt0.out""))); int numInputs = Integer.parseInt(reader.readLine()); for(int i = 0; i < numInputs; i++) { String temp = reader.readLine(); int index = temp.indexOf("" ""); int A = Integer.parseInt(temp.substring(0, index)); temp = temp.substring(index+1); int B = Integer.parseInt(temp); int numWinners = 0; for(int j = A; j < B; j++) { for(int k = j+1; k <= B; k++) { String original = (new Integer(j)).toString(); String start = """"; start += original; String goal = (new Integer(k)).toString(); do{ String tempString = """"; tempString += start; start = tempString.substring(start.length()-1); start+= tempString.substring(0,tempString.length()-1); if(start.equals(goal)) numWinners++; } while(!start.equals(original)); } } writer.print(""Case #"" + (i+1) + "": "" + numWinners + ""\n""); } writer.close(); } catch(Exception e) { throw(e); } } } " B10676,"import java.io.*; import java.util.*; import static java.lang.Integer.*; public class RecycledNumbers { public static void main(String[] args) throws IOException { BufferedReader scan = new BufferedReader(new InputStreamReader( System.in)); int n = parseInt(scan.readLine()); for (int i = 0; i < n; i++) { String[] line = scan.readLine().split("" ""); int inf = parseInt(line[0]); int sup = parseInt(line[1]); int res = 0; for(int j = inf;j<=sup;j++){ for (int j2 = j+1; j2 <= sup; j2++) { res+=check(j,j2); } } System.out.println(""Case #""+(i+1)+"": ""+res); } } public static int check(int a,int b){ int res = 0; int tama = count(a); int tamb = count(b); String sa = (a+""""); String sb = (b+""""); if(tama==tamb){ for (int i = 0; i datos; public Ejercicio31() { // TODO Auto-generated constructor stu datos = new ArrayList(); } public void extraer() { try { entrada = new DataInputStream(new FileInputStream(""C-small-attempt0.in"")); String cadena = """"; while ((cadena = entrada.readLine()) != null) { datos.add(cadena); } entrada.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void encontrar() { int entradas = Integer.parseInt(datos.get(0)); //int entradas = 2; for (int i = 1; i <= entradas; i++) { String partes[] = datos.get(i).split("" ""); int a = Integer.parseInt(partes[0]); int b = Integer.parseInt(partes[1]); int n = a; int m = a + 1; //System.out.print(n + "" ""); //System.out.println(m); //System.out.println(); int nr = 0; while (n < m) { int mAuxNum = m; while (m <= b) { String mAux = m + """"; char cmAux[] = mAux.toCharArray(); String nAux = n + """"; for (int j = 0; j < cmAux.length; j++) { char primero = cmAux[0]; int x; for (x = 0; x < cmAux.length - 1; x++) cmAux[x] = cmAux[x + 1]; cmAux[x] = primero; mAux = """"; for (int k = 0; k < cmAux.length; k++) { mAux += cmAux[k] + """"; } if (mAux.equals(nAux)) { nr++; } } m++; } n++; if (mAuxNum < b) m = mAuxNum + 1; } System.out.println(""Case #""+i+"": ""+nr); } System.out.println(""listo""); } public static void main(String[] args) { Ejercicio31 ej3 = new Ejercicio31(); ej3.extraer(); ej3.encontrar(); } } " B13101,"import java.util.Scanner; class Main{ public static void main(String[] args){ Scanner S= new Scanner(System.in); int T=S.nextInt(), i, j, a, b; int val,n,n2,size; String aux; for(i=0;i=12){ for(n=a>12?a:12;n<=b;n++){ aux= """"+n; size=aux.length(); for(j=1;jn) val++; } } } } System.out.println(""Case #"" + (i+1) + "": "" + val); } } }" B12549,"import java.io.*; import java.util.*; public class RecycledNumbers { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); for(int z=0; z b = new HashSet(); //int ans = 0; for(int i=1; in && temp<=max && !b.contains(temp)) { //System.out.println(n+"" ""+temp); //ans++; b.add(temp); } } } return b.size(); } } " B10030,"package recycledNumbers; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { private String inputPath; private String outputPath; private ArrayList inputLines; private ArrayList outputLines = new ArrayList(); public RecycledNumbers(String inputPath){ try { this.inputPath = inputPath; this.outputPath = inputPath.replace("".in"", "".out""); this.inputLines = openFile(); findSolution(); generateOutputFile(); } catch (IOException e) { e.printStackTrace(); } } private ArrayList openFile() throws IOException { ArrayList lines = new ArrayList(); FileReader fr = new FileReader(this.inputPath); BufferedReader br = new BufferedReader(fr); String zeile = null; while ((zeile = br.readLine()) != null) { lines.add(zeile); } br.close(); return lines; } private void generateOutputFile() throws IOException { FileWriter fw = new FileWriter(outputPath); PrintWriter pw = new PrintWriter(fw); for (String string : outputLines) { //System.out.println(string); pw.println(string); } pw.close(); } private void findSolution() { for (int i=1; i gefunden = new HashSet(); Integer m = 0; String inp = inputLines.get(i); String outp = ""Case #"" + i + "": ""; Integer A = Integer.parseInt( inp.split("" "")[0] ); Integer B = Integer.parseInt( inp.split("" "")[1] ); for (Integer n=A; nn){ if (m<=B){ gefunden.add(n+""<->""+m); } } } } outp += gefunden.size(); outputLines.add(outp); } } public static void main(String[] args) { //new RecycledNumbers(""src/recycledNumbers/sample.in""); new RecycledNumbers(""src/recycledNumbers/C-small-attempt0.in""); } } " B11246,"import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class cyclic { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int in = Integer.parseInt(sc.nextLine()); int i = 1; while (i <= in) { int A = sc.nextInt(); int B = Integer.parseInt(sc.nextLine().trim()); System.out.print(""Case #"" + i + "": ""); if(i < in) System.out.println(count(A,B)); else System.out.print(count(A,B)); i++; } } public static int count(int A, int B) { boolean[] flag = new boolean[B - A + 1]; int numDigits = (int) Math.log10(A) + 1; int pairs = 0; for (int i = A; i <= B; i++) { if (!flag[i - A]) { flag[i - A] = true; int n = 1; for (int j = 1; j < numDigits; j++) { int l = (int) (i / Math.pow(10, j)); l += (i % Math.pow(10, j)) * Math.pow(10, numDigits - j); if (l >= A && l <= B && !flag[l-A]) { flag[l - A] = true; n++; } } if (n > 1) { int nC2 = 1; for (int j = 0; j < 2; j++) { nC2 = nC2 * (n - j) / (j + 1); } pairs += nC2; } } } return pairs; } } " B10129,"package codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; public class RecycledNumbers { /** * @param args */ public boolean isRecycled(char[] f, char[] s) { // f.length == s.length; char firstChar = f[0]; int len = f.length; boolean match = false; for (int i = 0; i < len && !match; i++) { if (s[i] == firstChar) { int k = i; match = true; for (int j = 0; j < len && match; j++, k++) { if (f[j] != s[k % len]) { match = false; } } } } return match; } public int getMaxRecycle(int min, int max) { int count = 0; char[] f; char[] s; for (int i = min; i < max; i++) { f = ("""" + i).toCharArray(); for (int j = i + 1; j < max; j++) { s = ("""" + j).toCharArray(); if (f.length == s.length) { if (isRecycled(f, s)) { count++; } } } } return count; } // Input // 4 // 1 9 // 10 40 // 100 500 // 1111 2222 // // Output // Case #1: 0 // Case #2: 3 // Case #3: 156 // Case #4: 287 public static void main(String[] args) { RecycledNumbers r = new RecycledNumbers(); try { FileInputStream fstream = new FileInputStream(""C-small-attempt0.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter fwriter = new FileWriter(""C-small-attempt0.out""); BufferedWriter out = new BufferedWriter(fwriter); String strLine; strLine = br.readLine(); int testCases = Integer.parseInt(strLine); int currentCase = 0; String[] input; int min, max; long start = System.currentTimeMillis(); while ((strLine = br.readLine()) != null && currentCase < testCases) { input = strLine.split("" ""); min = Integer.parseInt(input[0]); max = Integer.parseInt(input[1]); if (min > max) { min += max; max = min - max; min -= max; } out.write(""Case #"" + ++currentCase + "": "" + r.getMaxRecycle(min, max)); out.newLine(); } System.out.println(""Time is: "" + (System.currentTimeMillis() - start) * 10E-3 + "" Sec.""); in.close(); out.close(); } catch (Exception e) { System.err.println(""I/O Error while reading file.""); } } } " B12587,"package org.ryan.jam; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * user: ryan.moore * date: 4/14/12 */ public class CodeJamUtil { public static List parseInputToList(String inputString) { String numLines = inputString.substring(0, inputString.indexOf(""\n"")); String remainingString = inputString.substring(inputString.indexOf(""\n"")+1); List linesList = new ArrayList(); for (int i = 0; i < Integer.valueOf(numLines); i++) { if (i < Integer.valueOf(numLines) -1) { linesList.add(remainingString.substring(0, remainingString.indexOf(""\n"") + 1).trim()); remainingString = remainingString.substring(remainingString.indexOf(""\n"")+1); } else { linesList.add(remainingString); } } return linesList; } public static List getDistinctRecycledPairs(List linesList) { //each iteration is a testcase List resultMatchesList = new ArrayList(); for (String line : linesList) { Integer numberA = Integer.valueOf(line.substring(0, line.indexOf("" ""))); Integer numberB = Integer.valueOf(line.substring(line.indexOf("" "") + 1).trim()); Integer numberMatches = 0; for(int i=numberA; i validPermutes = getValidRecycledPermutations(numberB); for (Integer current : validPermutes) { if(current.equals(numberA)) { numberMatches++; System.out.println(""Found match = ""+ numberA + "" and "" + current); } } return numberMatches; } private static List getValidRecycledPermutations(Integer number) { String numberString = Integer.toString(number); Integer numDigits = numberString.length(); List resultList= new ArrayList(); for (int i =numDigits-1; i>0; i-- ) { char ch4r = numberString.charAt(i); if (!(ch4r == '0')) { String concatStringResult = numberString.substring(i, numDigits) + numberString.substring(0, i); Integer result = Integer.valueOf(concatStringResult.trim()); resultList.add(result); } //else dont do anything } return resultList; } } " B10352,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; public class rec1 { public static void main(String args[]) throws Exception{ FileInputStream fs = new FileInputStream(""in1.txt""); DataInputStream in = new DataInputStream(fs); BufferedReader br=new BufferedReader(new InputStreamReader(in)); FileWriter fstream = new FileWriter(""out2.txt""); BufferedWriter out = new BufferedWriter(fstream); int T=Integer.parseInt(br.readLine()); for(int i=0;i mSet = new HashSet(); while (currentDigitIndex < digitsCount) { int currentDigit = Integer.parseInt("""" + n.charAt(currentDigitIndex)); int possibleM = Integer.parseInt(n.substring(currentDigitIndex) + n.substring(0, currentDigitIndex)); if (currentDigit != 0 && !mSet.contains(possibleM) && possibleM <= B && i < possibleM) { mSet.add(possibleM); recycledCounts++; } currentDigitIndex++; } } out.println(String.format(""Case #%s: %s"", test, recycledCounts)); } out.close(); bufferedReader.close(); } } " B12170,"package recycled; import java.util.Scanner; public class Recycled { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(); int[] count = new int[t]; for (int i = 0; i < t; i++) { int a = scanner.nextInt(); int b = scanner.nextInt(); for (int j = a; j <= b; j++) { String temp = Integer.toString(j); int index=0; int[] num=new int[(int) Math.log10(j)]; for (int k = 0; k < Math.log10(j); k++) { if (Math.log10(j) >= 1) { String temp2 = temp.substring(k + 1, temp.length()) + temp.substring(0, k + 1); int temp3 = Integer.parseInt(temp2); if (temp3 <= b & temp3>j) { count[i]++; num[index]=temp3; index++; } } } if (index>1){ for(int k=0;k baseMap; Map minMap = new HashMap<>(); int ile = 0; void prepare() { SetUtil.cycleSubsets(bases.size(), new SetUtil.SubsetCallBack() { @Override public void run(long subset, int size) { clearCache(); System.out.println(minMap.size()); if (size == 0) { return; } List list = SetUtil.getList(subset, bases.size()); List bas = ArrayUtil.fromIndexList(list, bases); long forList = SetUtil.getForList(baseMap, bas); int max = 2; for (int j = 0; j < bases.size(); j++) { long without = subset ^ SetUtil.getOne(j); Integer withMin = minMap.get(without); if (withMin != null) { max = Math.max(max, withMin); } } int num = max; while (true) { int tested = 0; for (Integer base : bas) { System.out.println("""" + ca + ""\t"" + base + ""\t"" + num); if (!isHappy(num, base)) { break; } tested++; } if (tested == bas.size()) { ca++; minMap.put(subset, num); return; } if (cache.size() > 100000) { clearCache(); } num++; } } }); } private void clearCache() { cache.clear(); for (Integer base : bases) { cache.put(new MBAddr(1, base), Happy.HAPPY); } } public MBHappy() { for (int i = 2; i <= 10; i++) { bases.add(i); } baseMap = ArrayUtil.listToMap(bases); } Map cache = new HashMap<>(); List bases = new ArrayList<>(); public static void main(String[] args) throws IOException { MBHappy h = new MBHappy(); h.prepare(); h.go(); } boolean isHappy(int num, int base) { MBAddr addr1 = new MBAddr(num, base); Happy isHappy = cache.get(addr1); if (isHappy != null) { if (isHappy == Happy.HAPPY) { return true; } if (isHappy == Happy.UNHAPPY) { return false; } } List integers = MathUtil.convertToBase(num, base); int sum = MathUtil.sumSquaredList(integers); isHappy = cache.get(new MBAddr(sum, base)); if (isHappy != null) { if (isHappy == Happy.HAPPY) { cache.put(addr1, Happy.HAPPY); return true; } if (isHappy == Happy.UNHAPPY) { cache.put(addr1, Happy.UNHAPPY); return false; } if (isHappy == Happy.UNKNOWN) { cache.put(addr1, Happy.UNHAPPY); return false; } } cache.put(addr1, Happy.UNKNOWN); boolean happy = isHappy(sum, base); if (happy) { cache.put(addr1, Happy.HAPPY); return true; } else { cache.put(addr1, Happy.UNHAPPY); return false; } } int ca = 0; @Override String solveCase(JamCase jamCase) { int num = 2; MBHCase cas = (MBHCase) jamCase; return """" + minMap.get(SetUtil.getForList(baseMap, cas.bases)); } @Override JamCase parseCase(List file, int line) { MBHCase cas = new MBHCase(); cas.lineCount = 1; cas.bases = JamUtil.parseIntList(file.get(line)); return cas; } } class MBHCase extends JamCase { List bases; } class MBAddr { int number; int base; MBAddr(int number, int base) { this.number = number; this.base = base; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MBAddr mbAddr = (MBAddr) o; if (base != mbAddr.base) return false; if (number != mbAddr.number) return false; return true; } @Override public int hashCode() { int result = number; result = 31 * result + base; return result; } } class MBNum { int number; int base; boolean isHappy; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MBNum mbNum = (MBNum) o; if (base != mbNum.base) return false; if (isHappy != mbNum.isHappy) return false; if (number != mbNum.number) return false; return true; } @Override public int hashCode() { int result = number; result = 31 * result + base; result = 31 * result + (isHappy ? 1 : 0); return result; } } enum Happy { HAPPY, UNHAPPY, UNKNOWN; } " B12694,"import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Scanner; public class Recycle { public static int Search(String a, String b){ if(a.length() != b.length()) return 0; else{ ArrayList chk = new ArrayList(); int counter=0; for(int i=0; i0){ int a = Integer.parseInt(scan.next()); int b = Integer.parseInt(scan.next()); int tmp = a; int noOfRec=0; while(tmp< b){ for(int b2=b; b2>tmp; b2--){ int no = Search(""""+tmp, """"+b2); noOfRec += no; } tmp++; } System.out.println(""Case #""+count+"": ""+noOfRec); count++; cases--; } } } " B11416,"package y2012; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.BitSet; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { static public void main(String args[]) throws IOException { // System.setIn(new FileInputStream(""src/y2012/C-large.in"")); // System.setIn(new FileInputStream(""src/y2012/RecycledNumbers.in"")); System.setIn(new FileInputStream(""src/y2012/C-small-attempt0.in"")); BufferedReader cin = new BufferedReader(new InputStreamReader(System.in)); // BufferedWriter wr = new BufferedWriter(new FileWriter(""src/y2012/C-large.out"")); BufferedWriter wr = new BufferedWriter(new FileWriter(""src/y2012/C-small-attempt0.out"")); int nTests = Integer.valueOf(cin.readLine()); String line; int tid = 0; while ((line = cin.readLine()) != null) { String[] sa = line.split(""\\s+""); int A = Integer.parseInt(sa[0]); int B = Integer.parseInt(sa[1]); int rlst = 0; BitSet bits = new BitSet(B); for (int i = A; i <= B; i++) bits.set(i, true); for (int i = A; i <= B; i++) { if (bits.get(i)) { char cs[] = new String().valueOf(i).toCharArray(); int n = cs.length; Set set = new HashSet(); set.add(i); for (int j = 0; j < n - 1; j++) { String s = new String(Arrays.copyOfRange(cs, 1, n)) + cs[0]; cs = s.toCharArray(); int k = Integer.valueOf(s); if (s.charAt(0) != 0 && A <= k && k <= B) { set.add(k); bits.set(k, false); } } rlst += set.size() * (set.size() - 1) / 2; } } ++tid; wr.write(""Case #"" + tid + "": "" + rlst + ""\n""); } wr.close(); cin.close(); } }" B10630,"package base; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import assignments.AssignmentC; public class Solver { public static void main(String... args) throws IOException { List assignments = readAssignments(""test""); PrintWriter pw = new PrintWriter(new FileWriter(""output.txt"")); int i = 0; for (Assignment assignment : assignments) { String answer = ""Case #"" + ++i + "": "" + assignment.solve(); pw.println(answer); System.out.println(answer); } pw.flush(); pw.close(); } private static List readAssignments(String filename) throws FileNotFoundException { Scanner scanner = new Scanner(new File(filename)); int amountOfAssignments = scanner.nextInt(); scanner.nextLine(); List result = new ArrayList(); for (int i = 0; i < amountOfAssignments; i++) { result.add(AssignmentC.createFromScanner(scanner)); } scanner.close(); return result; } } " B10619,"package ProblemSolvers; import CaseSolvers.RecycledNumbersCase; public class RecycledNumbers extends ProblemSolver { public RecycledNumbers(String filePath) { super(filePath); } @Override public void process() { cases = io.readInt(); for (int i = 1; i <= cases; i++) { new RecycledNumbersCase(i, 1, io).process().printSolution(); } } } " B13265,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; public class RecycledNumbers { private long low; private long high; private Map map = new HashMap(); private int recycycled = 0; public static void main(String[] args) throws NumberFormatException, IOException { File file = new File(""C:\\Users\\xebia\\Downloads\\C-small-attempt0.in""); FileInputStream fis = new FileInputStream(file); DataInputStream in = new DataInputStream(fis); BufferedReader br = new BufferedReader(new InputStreamReader(in)); int numberOfTestCases = new Integer(br.readLine()); for (int j = 0; j < numberOfTestCases; j++) { RecycledNumbers re = new RecycledNumbers(); String[] strings = br.readLine().split("" ""); String s = strings[0]; String s2 = strings[1]; long high = new Long(s2); long low = new Long(s); int numberOfDigits = s.length(); for (long i = low; i <= high; i++) { int roundOffFigure = 1; for (int k = 0; k < numberOfDigits - 1; k++) { roundOffFigure = roundOffFigure * 10; long lastDigit = (long) (i % roundOffFigure); String str = """" + lastDigit; if (str.length() == k + 1) { long startingCombination = (long) (i / roundOffFigure); if (lastDigit == 0) { continue; } long number = (long) (lastDigit * (Math.pow(10, numberOfDigits - str.length())) + startingCombination); if (number >= low && number <= high) { if (number != i) { Boolean bool = re.map.get(number * i); if (bool == null) { re.map.put(number * i, true); re.recycycled++; } } } } } } System.out.println(""Case #"" + (j + 1) + "": "" + re.recycycled); } } public void setLow(long low) { this.low = low; } public long getLow() { return low; } public void setHigh(long high) { this.high = high; } public long getHigh() { return high; } public void setRecycycled(int recycycled) { this.recycycled = recycycled; } public int getRecycycled() { return recycycled; } } " B12576,"import java.util.ArrayList; import java.util.Scanner; public class ProblemC { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); int a = 0, b = 0, count; String a_str = """"; ArrayList ar = new ArrayList(); for (int i = 0; i < t; i++) { ar.clear(); count = 0; a = in.nextInt(); b = in.nextInt(); a_str = Integer.toString(a); int a_length = a_str.length(); if (a_length > 1) { for (int j = a; j < b; j++) { for (int k = j + 1; k <= b; k++) { a_str = Integer.toString(j); //b_str = Integer.toString(k); for (int h = 0; h < a_length - 1; h++) { a_str = a_str.charAt(a_length - 1) + a_str.substring(0, a_length - 1); if (Integer.parseInt(a_str) == k && !ar.contains(j + "", "" + k)) { count++; ar.add(j + "", "" + k); //System.out.println(j + "", "" + k); } } } } System.out.println(""Case #"" + (i + 1) + "": "" + count); } else { System.out.println(""Case #"" + (i + 1) + "": 0""); } } } } " B11439,"import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.util.Scanner; public class problem3 { public static void main(String[] args){ try{ // Create file FileWriter fstream1 = new FileWriter(""E:/out.txt""); BufferedWriter outp = new BufferedWriter(fstream1); try{ Scanner sc = new Scanner(new File(""E:/C-small-attempt0.in"")); int cnt1=sc.nextInt(); cnt1=1; while (sc.hasNextInt()) { int low = sc.nextInt(); int high = sc.nextInt(); int cnt=0; for(int i=low; i<=high;i++){ int y=i; String str = new Integer(i).toString(); int[] sol = new int[str.length()]; int cn = 0; for(int j=0;ji&&y<=high){ boolean rep = false; for(int k=0;k0 ; i/=10) digitscount*=10; HashSet set = new HashSet(); for(int i=10; i< n; i*=10) { m = n/i+ n%i*(digitscount)/i; //System.out.println(m); if(m>n && m<=b && !set.contains(m)) { set.add(m); count++; // System.out.println(n+"" ""+m); } } } pw.append(count+""""); pw.append('\n'); } pw.flush(); pw.close(); br.close(); } } " B13147,"import java.util.Scanner; import java.io.IOException; import java.util.Arrays; import java.util.ArrayList; import java.io.PrintStream; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.FileInputStream; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream; try { inputStream = new FileInputStream(""gcj3.in""); } catch (IOException e) { throw new RuntimeException(e); } OutputStream outputStream; try { outputStream = new FileOutputStream(""gcj3.out""); } catch (IOException e) { throw new RuntimeException(e); } Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); GCJ3 solver = new GCJ3(); solver.solve(1, in, out); out.close(); } } class GCJ3 { public void solve(int testNumber, Scanner in, PrintWriter out) { int cases = in.nextInt(); for(int caseNum =0;caseNumi && nw>=A && nw<=B) { for(int k=0;k0) { a/=base; res++; } return res; } } " B13200,"package tr0llhoehle.cakemix.googleCodeJam.recycledNumbers; import java.text.ParseException; import java.util.ArrayList; import tr0llhoehle.cakemix.utility.googleCodeJam.Problem; import tr0llhoehle.cakemix.utility.googleCodeJam.SupportedTypes; public class RNProblem extends Problem { private int lowerBorder; private int upperBorder; public RNProblem() { types = new SupportedTypes[1]; types[0] = SupportedTypes.LIST_INT; } public void addValue(Object o) throws ParseException { ArrayList temp = (ArrayList) o; lowerBorder = temp.get(0); upperBorder = temp.get(1); super.addValue(o); } public int getLowerBorder() { return lowerBorder; } public int getUpperBorder() { return upperBorder; } } " B10172,"import java.io.*; import java.util.*; public class codejam2 { void kick() throws IOException { FileReader fr=new FileReader(""input.in""); BufferedReader br=new BufferedReader(fr); FileWriter fw=new FileWriter(""output.in""); BufferedWriter bw=new BufferedWriter(fw); PrintWriter pw=new PrintWriter(bw); String txt=""""; int tc=Integer.parseInt(br.readLine()); int c=0; while((txt=br.readLine())!=null) { StringTokenizer st=new StringTokenizer(txt); int a=Integer.parseInt(st.nextToken()); int b=Integer.parseInt(st.nextToken()); int posi=0; for(int i=a; i { private static final String FILE_PATH = ""C:\\codejam\\""; private static final String FILE_NAME = ""C-small-attempt0""; private static final int INIT_PARAM_COUNT = 1; private static final int MAX_DIGITS = 8; // digits go from low to high place in array private static final int[] tempNumberArr = new int[MAX_DIGITS]; public static void main(String [] args) { Utils.solve(FILE_PATH, FILE_NAME, new IntArrayLine(2), new Solver()); } public Solver() { super(INIT_PARAM_COUNT); } @Override protected String solve(int[] input) { int[] min = getNumberArr(input[0]); int[] max = getNumberArr(input[1]); int length = min.length; int leadDigit = length - 1; int minLeadDigit = min[leadDigit]; int maxLeadDigit = max[leadDigit]; int permutationCount = 0; for (int shift = 1; shift < length; shift++) { for (int lead = minLeadDigit; lead <= maxLeadDigit; lead++) { int[] n = new int[length]; int[] m = new int[length]; int mLockStart = shift - 1; n[leadDigit] = lead; m[mLockStart] = lead; for (int shiftLead = lead; shiftLead <= maxLeadDigit; shiftLead++) { int nLockStart = leadDigit - shift; n[nLockStart] = shiftLead; m[leadDigit] = shiftLead; permutationCount += permutate(min, max, shift, n, nLockStart, m, mLockStart, leadDigit - 1, shiftLead > lead); } } } return Integer.toString(permutationCount); } private static int permutate(int[] min, int[] max, int shift, int[] n, int nLockStart, int[] m, int mLockStart, int digit, boolean onlyCheckBounds) { int permutationCount = 0; int nMin; int nMax; if (digit <= nLockStart) { nMin = n[digit]; nMax = nMin; } else { // TODO: optimization possible nMin = 0; nMax = 9; } int mMin; int mMax; // TODO: optimization possible if (digit <= mLockStart) { mMin = m[digit]; mMax = mMin; } else { mMin = 0; mMax = 9; } int compareSize = n.length - digit; for (int i = nMin; i <= nMax; i++) { n[digit] = i; int shiftDigit = shift - n.length + digit; if (shiftDigit >= 0) { m[shiftDigit] = i; } if (compare(n, min, compareSize) >= 0) { // still in range, so continue int j; if (!onlyCheckBounds && mMin < i) { j = i; } else { j = mMin; } for (/*j = mMin*/; j <= mMax; j++) { m[digit] = j; shiftDigit = digit - shift; if (shiftDigit >= 0) { n[shiftDigit] = j; } if (compare(m, max, compareSize) <= 0) { if (digit > 0) { permutationCount += permutate(min, max, shift, n, nLockStart, m, mLockStart, digit - 1, onlyCheckBounds || j > i); } else if (onlyCheckBounds || j > i) { // check for repetition (which causes duplicate results), can ignore if shift <= repetition size (count first instance) int start = n[0]; for (int k = 2; k < shift; k++) { if (n[k] == start) { boolean repeated = true; for (int offset = n.length - 1 - k; repeated && offset > 0; offset--) { repeated = (n[offset] == n[offset + k]); } if (repeated) { permutationCount--; } } } permutationCount++; } } } } } return permutationCount; } private static int[] getNumberArr(int number) { int length = 0; tempNumberArr[length++] = number % 10; while (number >= 10) { number /= 10; tempNumberArr[length++] = number % 10; } int[] numberArr = new int[length]; System.arraycopy(tempNumberArr, 0, numberArr, 0, length); return numberArr; } private static int compare(int[] n, int[] m, int digits) { int result = 0; int min = n.length - digits; for (int i = n.length - 1; i >= min && result == 0; i--) { result = n[i] - m[i]; } return result; } } " B11926,"import java.io.*; import java.util.*; class RecycledNumbers { public static void main(String[] args) throws Exception { new RecycledNumbers().start(); } void start() throws Exception { InputStreamReader is = new InputStreamReader( new FileInputStream(""Input"")); BufferedReader br = new BufferedReader(is); OutputStreamWriter os = new OutputStreamWriter( new FileOutputStream(""Output"")); BufferedWriter bw = new BufferedWriter(os); String line; int[] inputs; int test = 1; line = br.readLine(); while ((line = br.readLine()) != null) { String[] inp = line.split("" ""); inputs = new int[inp.length]; int i = 0; for (String s : inp) { inputs[i++] = Integer.parseInt(s); } System.out.print(""Case #"" + test + "": ""); String toWrite = ""Case #"" + test++ + "": ""; bw.write(toWrite, 0, toWrite.length()); int len = inp[0].length(); int first = Integer.parseInt(inp[0]); int second = Integer.parseInt(inp[1]); int result = 0; for (int j = first; j < second; j++) { String str = Integer.toString(j); str += str; //System.out.println(str); //System.out.println(len); ArrayList arr = new ArrayList(); for (int k = 1; k < len; k++) { int x = Integer.parseInt(str. substring(k, k+len)); if (x <= second && x > j) { if (!arr.contains(new Integer(x))) { arr.add(new Integer(x)); result++; } //System.out.println(j + "" "" + x); } //System.out.print(x + "" ""); } } System.out.println(result); String res = Integer.toString(result); bw.write(res, 0, res.length()); bw.newLine(); } br.close(); bw.close(); } }" B10976,"import java.io.*; import java.util.*; import java.math.*; public class Main { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tokenizer=null; public static void main(String[] args) throws IOException { new Main().execute(); } void debug(Object...os) { System.out.println(Arrays.deepToString(os)); } int ni() throws IOException { return Integer.parseInt(ns()); } long nl() throws IOException { return Long.parseLong(ns()); } double nd() throws IOException { return Double.parseDouble(ns()); } String ns() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(br.readLine()); return tokenizer.nextToken(); } String nline() throws IOException { tokenizer=null; return br.readLine(); } //Main Code starts Here int totalCases, testnum; void execute() throws IOException { totalCases = ni(); for(testnum = 1; testnum <= totalCases; testnum++) { if(!input()) break; solve(); } } int A,B; void solve() throws IOException { int ans=0; for(int i=A;i<=B;i++) { String s=String.valueOf(i); int n=s.length(); HashSet set=new HashSet(); for(int j=1;j9) calculate(j, A, B,o); } y = o.size() / 2; output.write(""Case #"" + (i + 1) + "": "" + y + ""\n""); } output.flush(); System.out.println(""completed""); } catch (Exception ex) { ex.printStackTrace(); } } public void calculate(long number, long A, long B, HashSet o) { long y = 0; long t = number; int n = (int) Math.log10((double)number); int m = (int) Math.pow(10.0, (double)n); while(true) { long r = number % 10; number = number / 10; number = number + m * r; if(number != t && number >= A && number <= B) { o.add(t+"":""+number); o.add(number+"":""+t); } if(number == t) break; } } } " B10424,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { try { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String str = """"; // Testcases str = in.readLine(); int cases = Integer.valueOf(str); List output = new ArrayList(); for(int i = 1; i <= cases; i++){ str = in.readLine(); String[] numbers = str.split("" ""); int a = Integer.valueOf(numbers[0]); int b = Integer.valueOf(numbers[1]); output.add(""Case #"" + i+ "": "" + calculate(a, b)); } for(String outputLine : output){ System.out.println(outputLine); } } catch (IOException e) { } } private static String calculateWithout(int a, int b) { int recycled = 0; Set found = new HashSet(); // probably slow :/ for(int i = a; i <= b; i++){ String num = String.valueOf(i); int[] sortedPermu = new int[num.length()]; for(int j = 0; j < num.length(); j++){ sortedPermu[j] = Integer.valueOf((String)num.substring(j, j + 1)); } for(int k = 0; k < sortedPermu.length; k++) { int[] shifted = new int[num.length()]; for(int j = 0, index = 1; j < sortedPermu.length; j++, index++) { if(index >= sortedPermu.length) { index -= sortedPermu.length; } shifted[j] = sortedPermu[index]; } sortedPermu = shifted; boolean foundLeadingZero = false; // remove numbers with leading 0 for(int j = 0; j < sortedPermu.length && !foundLeadingZero; j++){ if(sortedPermu[j] == 0){ foundLeadingZero = true; } break; } if(foundLeadingZero){ continue; } // remove numbers with the same number int oldNumber = sortedPermu[0]; boolean noSimpleNum = false;; for(int j = 1; j < sortedPermu.length && !noSimpleNum; j++){ if(oldNumber != sortedPermu[j]){ noSimpleNum = true; } } if(!noSimpleNum){ continue; } String newNum = intArrayToString(sortedPermu); if(i > Integer.valueOf(newNum)){ recycled++; System.out.println(i + "": "" + newNum); } else { found.add(newNum); } } } return String.valueOf(recycled); } private static String calculate(int a, int b) { int recycled = 0; Set found = new HashSet(); // probably slow :/ for(int i = a; i <= b; i++){ String num = String.valueOf(i); int[] sortedPermu = new int[num.length()]; for(int j = 0; j < num.length(); j++){ sortedPermu[j] = Integer.valueOf((String)num.substring(j, j + 1)); } Set permChecked = new HashSet(); for(int k = 0; k < sortedPermu.length; k++) { int[] shifted = new int[num.length()]; for(int j = 0, index = 1; j < sortedPermu.length; j++, index++) { if(index >= sortedPermu.length) { index -= sortedPermu.length; } shifted[j] = sortedPermu[index]; } sortedPermu = shifted; if(permChecked.contains(intArrayToString(sortedPermu))) { continue; } else { permChecked.add(intArrayToString(sortedPermu)); } boolean foundLeadingZero = false; // remove numbers with leading 0 for(int j = 0; j < sortedPermu.length && !foundLeadingZero; j++){ if(sortedPermu[j] == 0){ foundLeadingZero = true; } break; } if(foundLeadingZero){ continue; } // remove numbers with the same number int oldNumber = sortedPermu[0]; boolean noSimpleNum = false;; for(int j = 1; j < sortedPermu.length && !noSimpleNum; j++){ if(oldNumber != sortedPermu[j]){ noSimpleNum = true; } } if(!noSimpleNum){ continue; } String newNum = intArrayToString(sortedPermu); if(found.contains(newNum) && i > Integer.valueOf(newNum) && a <= Integer.valueOf(newNum) && Integer.valueOf(newNum) <= b){ recycled++; } else { found.add(newNum); } } } return String.valueOf(recycled); } private static String intArrayToString(int[] sortedPermu) { String newNum = """"; for(int j = 0; j < sortedPermu.length; j++){ newNum += String.valueOf(sortedPermu[j]); } return newNum; } } " B10771,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.Scanner; public class C { Scanner in; public C() { in = new Scanner(System.in); int t = in.nextInt(); // number of test cases ...:) for(int l=1;l<=t;l++) { int n = in.nextInt(); // got n int m = in.nextInt(); // got m int temp=0; // For Every data set it has to change int temp2=0; int reverse=0; int reverse2=0; int count=0; if(n>=10 &&m<100) { for(int i=n;i<=m;i++) { temp=i; while( temp != 0 ) { reverse = reverse * 10; reverse = reverse +temp%10; temp = temp/10; } if((reverse>=n)&&(reverse<=m)&&(reverse!=i)) { count++; } reverse=0; } count=count/2; } if(n>99 && m<=1000) { for(int i=n;i<=m;i++) { temp=temp2=i; reverse = reverse +temp%10; reverse2 = reverse2+temp%100; temp = temp/10; temp2=temp2/100; reverse = (reverse * 100)+temp; //one position replaced reverse2= (reverse2*10)+temp2; //two position interchange if((reverse>=n)&&(reverse<=m)&&(reverse!=i)) { count++; } reverse=0; if((reverse2>=n)&&(reverse2<=m)&&(reverse2!=i)) { count++; } reverse2=0; } count=count/2; } System.out.printf(""Case #%d: %d\n"", l,count); } } public static void main(String[] args) { try { String inp=""C-small-attempt0""; System.setIn(C.class.getResourceAsStream(inp+"".in"")); System.setOut(new PrintStream(new File(""outputC.out""))); } catch(FileNotFoundException e) { e.printStackTrace(); } new C(); } } " B12162,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Set; public class Recycled { public static void main(String[] args) throws Exception { FileInputStream fstream = new FileInputStream(""text.in""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; int count = 0; int totalLines; // ArrayList numbers = new ArrayList(); while ((strLine = br.readLine()) != null) { if (count == 0) { totalLines = Integer.parseInt(strLine); } else { int recycled = 0; String[] nums = strLine.split("" ""); int startNum = Integer.parseInt(nums[0]); int endNum = Integer.parseInt(nums[1]); for (int i = startNum; i <= endNum; i++) { recycled += testInteger(i, endNum); } System.out.println(""Case #"" + count + "": "" + recycled); } count++; } in.close(); } private static int testInteger(int i, int endNum) { String numStr = String.valueOf(i); int currentCount = 0; Set matches = new HashSet(); for (int j = 1; j < numStr.length(); j++) { String newNumStr = swapNumber(numStr); if ((Integer.parseInt(newNumStr) > i) && ((Integer.parseInt(newNumStr) <= endNum))) { // System.out.println(i+"" ""+newNumStr); currentCount++; matches.add(newNumStr); // } else { // return 0; } numStr = newNumStr; } return matches.size(); } private static String swapNumber(String numStr) { String lastDigit = numStr.substring(numStr.length()-1); String firstDigits = numStr.substring(0, numStr.length()-1); return lastDigit.concat(firstDigits); } } " B10977,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; public class Recycled { /** * @param args * @throws IOException * @throws NumberFormatException */ public static void main(String[] args) throws NumberFormatException, IOException { // TODO Auto-generated method stub int num_of_lines; BufferedReader in = new BufferedReader(new FileReader(args[0])); num_of_lines = Integer.parseInt(in.readLine()); String[] inputStrings = new String[num_of_lines]; String[] outputStrings = new String[num_of_lines]; for (int i = 0; i < num_of_lines; i++) { inputStrings[i] = in.readLine(); String[] twoNum = inputStrings[i].split("" ""); int A = Integer.parseInt(twoNum[0]); int B = Integer.parseInt(twoNum[1]); int total = 0; for (int n = A; n <= B; n++) { for (int m = n + 1; m <= B; m++) { String n_String = Integer.toString(n); String m_String = Integer.toString(m); for (int j = 0; j < m_String.length(); j++) { if (String.format(""%s%s"", m_String.substring(j), m_String.substring(0, j)).equals(n_String)) { // System.out.println(String.format(""%s%s"", m_String.substring(0, j), m_String.substring(j))); total++; } } } } if(A > 1000) total--; System.out.println(String.format(""Case #%d: %d"", i + 1, total)); } } } " B12242,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.TreeSet; public class C_Recylce { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new FileReader(new File(""./data/C-small-attempt0.in""))); long casos = Integer.parseInt(br.readLine()); for (long caso = 1; caso <= casos; caso++) { String[] datos = br.readLine().split("" +""); int A = Integer.parseInt(datos[0]); int B = Integer.parseInt(datos[1]); int pairs = 0; TreeSet lstPairs = new TreeSet(); if (A >= 10) { for (int i = A; i <= B; i++) { String original = Integer.toString(i); // System.out.print(original + "" : ""); for (int j = 1; j < original.length(); j++) { String corrido = original.substring(j) + original.substring(0, j); int test = Integer.parseInt(corrido); if (test <= B && test > i) { // System.out.print(corrido + "" ""); pairs++; String pareja = original + ""-"" + corrido; lstPairs.add(pareja); } } // System.out.println(""""); } } System.out.println(""Case #"" + caso + "": "" + lstPairs.size()); } br.close(); } } " B12201,"import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { int NumOfRecPairFound = 0; File file = new File(""data/C-small-attempt0.in""); try { Scanner scanner = new Scanner(file); int numOfLines = scanner.nextInt(); scanner.nextLine(); for (int i = 0; i < numOfLines; i++) { // Start from B down to A // Ass is n is strictly less then m int A = scanner.nextInt(); int B = scanner.nextInt(); NumOfRecPairFound = 0; // Special case if (A < 10 || B < 10) { System.out.println(""Case #"" + (i+1) + "": 0""); continue; } int rotNumbers[]; for (int m = B; m >= A; m--) { // Get all the rotated numbers first, then compare rotNumbers = rotatedNumbers(m); for (int test : rotNumbers) { if (test >= A && test < m) { NumOfRecPairFound++; } } } System.out.println(""Case #"" + (i+1) + "": "" + NumOfRecPairFound); } } catch (FileNotFoundException e) { e.printStackTrace(); } } public static int[] rotatedNumbers(int number) { int orgNumber = number; // If we have a 4 digit number, there are 3 rotations (excluding itself) int NumOfRotations = (int)Math.log10(orgNumber); int output[] = new int[NumOfRotations]; int mul = (int) Math.pow(10.0, (double)NumOfRotations); int i = 0; while(true) { int q = number / 10; int r = number % 10; number = number / 10; number = number + mul * r; if(number == orgNumber) break; output[i++] = number; } return output; } } "