/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author cteam042 */ import java.util.Scanner; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; public class collatz { public static class Trida{ public int number; public int index; public Trida(int v, int i) { number = v; index = i; } public int getValue() { return number; } @Override public String toString() { String toRet = String.valueOf(number); return toRet; } } public static final Comparator comp = new DefaultComparator(); public static class DefaultComparator implements Comparator { public int compare(Trida arg0, Trida arg1) { int a = Integer.parseInt(arg0.toString()); int b = Integer.parseInt(arg1.toString()); if (a one = new ArrayList(); ArrayList two = new ArrayList(); int backupX = x; int backupY = y; for (int i = 0;; i++) { one.add(new Trida(x,i)); if (x == 1) { break; } if (x % 2 == 0) { x = x / 2; } else { x = 3 * x + 1; } } for (int i = 0;; i++) { two.add(new Trida(y,i)); if (y == 1) { break; } if (y % 2 == 0) { y = y / 2; } else { y = 3 * y + 1; } } Trida[] oneArray = new Trida[one.size()]; for (int i = 0; i < one.size(); i++) oneArray[i] = (Trida)one.get(i); Trida[] twoArray = new Trida[two.size()]; for (int i = 0; i < two.size(); i++) twoArray[i] = (Trida)two.get(i); Arrays.sort(oneArray, comp); Arrays.sort(twoArray, comp); /*for (int i = 0; i < oneArray.length; i++) System.out.println(oneArray[i].number+" * "+oneArray[i].index); System.out.println(); for (int i = 0; i < twoArray.length; i++) System.out.println(twoArray[i].number+" * "+twoArray[i].index);*/ int limit = Math.min(oneArray.length,twoArray.length); int indexOne = 0; int indexTwo = 0; int lowestForOne = Integer.MAX_VALUE; int lowestForSecond = Integer.MAX_VALUE; int whereMet = 0; while(1==1) { if (indexOne == oneArray.length && indexTwo == twoArray.length) break; if (indexOne == oneArray.length && indexTwo != twoArray.length) indexOne--; if (indexOne != oneArray.length && indexTwo == twoArray.length) indexTwo--; int first = oneArray[indexOne].number; int second = twoArray[indexTwo].number; if (first == second) { int actualOne = oneArray[indexOne].index; int actualTwo = twoArray[indexTwo].index; if (actualOne < lowestForOne){ lowestForOne = actualOne; lowestForSecond = actualTwo; whereMet = oneArray[indexOne].number; } if (actualTwo < lowestForSecond){ lowestForSecond = actualTwo; lowestForOne = actualOne; whereMet = oneArray[indexOne].number; } indexOne++; indexTwo++; } if (first > second) { indexOne++; //System.out.println("indexOne++"); } else if (second > first) { indexTwo++; //System.out.println("indexTwo++"); } } System.out.println(backupX+" needs "+ lowestForOne + " steps, "+ backupY + " needs "+ lowestForSecond + " steps, they meet at "+whereMet); } } }