// ** Puzzle; // http://www.reddit.com/r/dailyprogrammer/comments/230m05/4142014_challenge_158_easy_the_torn_number/ // ** Algorithm; // [3025] = (30+25)^2 // [abcd] = (ab+cd)^2 // 1000a + 100b + 10c + d = ( (10a + b) + (10c + d) )^2 // ** Diff check; // a!=b & a!=c & a!=d & b!=c & b!=d & c!=d // ** Output; // Against the rule 'composed of four figures, all different': 2025 // Valid number found: 3025 // Valid number found: 9801 public class RedditChallenge { public static void main(String[] args) { try { //System.out.println("checkMonday(3025) : " + checkMonday(3025)); challengeMonday(); } catch (Exception e) { e.printStackTrace(); } } private static void challengeMonday() { try { for (int i = 1000; i < 9999; i++) { if (checkMonday(i)) { System.out.println("Valid number found: " + i); } } } catch (Exception e) { e.printStackTrace(); } } private static boolean checkMonday(int number) { try { String str = Integer.toString(number); if (str == null || str.isEmpty() || str.length() != 4) { return false; } // ABCD int digitA = Integer.parseInt("" + str.charAt(0)); // (number / 1000); int digitB = Integer.parseInt("" + str.charAt(1)); // (number / 100) % 10; int digitC = Integer.parseInt("" + str.charAt(2)); // (number / 10) % 10; int digitD = Integer.parseInt("" + str.charAt(3)); // (number % 10); int check = (1000 * digitA) + (100 * digitB) + (10 * digitC) + digitD; if (number != check) { System.out.println("Check number:" + number); } int result = ((10 * digitA + digitB) + (10 * digitC + digitD)) * ((10 * digitA + digitB) + (10 * digitC + digitD)); if (result == number) { if (digitA == digitB || digitA == digitC || digitA == digitD || digitB == digitC || digitB == digitD || digitC == digitD) { System.out.println("Against the rule 'composed of four figures, all different': " + number); } else { return true; } } } catch (Exception e) { e.printStackTrace(); } return false; } }