algorithm - Mysterious number 6174 [Kaprekar Theorem] in Java -
in 1949 mathematician d. r. kaprekar, devised process known kaprekar's operation. first choose 4 digit number digits not same (that not 1111, 2222,...). rearrange digits largest , smallest numbers these digits can make. finally, subtract smallest number largest new number, , carry on repeating operation each new number.
let's try out, starting number 2005, digits of last year. maximum number can make these digits 5200, , minimum 0025 or 25 (if 1 or more of digits zero, embed these in left hand side of minimum number)
5200 - 0025 = 5175 7551 - 1557 = 5994 9954 - 4599 = 5355 5553 - 3555 = 1998 9981 - 1899 = 8082 8820 - 0288 = 8532 8532 - 2358 = 6174
now objective verify theorem & find number of iteration take reach 6174.
can give better algorithm? here code.
public int verifykaprekartheorem(int m) { if (m <= 1000 || m > 9999) { return -1; } string orginal = string.valueof(m); int count = 0; while (true) { int max = integer.parseint(sortstring(orginal, false)); int min = integer.parseint(sortstring(orginal, true)); count++; int diff = max - min; if (diff == 6174) { break; } orginal = string.valueof(diff); } return count; } public static string sortstring(string source, boolean assendingorder) { char[] original = string.valueof(source).tochararray(); arrays.sort(original); if (assendingorder) { return new string(original); } char[] dessending = new char[original.length]; (int = original.length - 1; >= 0; i--) { dessending[i] = original[(original.length - 1) - i]; } return new string(dessending); }
and testcase
public void testcase01() { int actual = verifykaprekartheorem(4321); assertequals(3, actual); }
i have change integer string char array sorting again integer conversion.
public int verifykaprekartheorem(int m) { if (m <= 1000 || m > 9999) { return -1; } int count = 0; while (true) { int max = largestnumber(m); int min = smallestnumber(m); count++; m = max - min; if (m == 6174) { break; } } return count; } private static int largestnumber(int input) { int[] numbers = new int[10]; (int = input; != 0; /= 10) { numbers[i % 10]++; } int counter = 0; int result = 0; (int = 0; < 10; counter += numbers[i++]) { result += (int) ((math.pow(10, numbers[i]) * - 1) / 9) * math.pow(10, counter); } return result; } private static int smallestnumber(int input) { int[] numbers = new int[10]; (int = input; != 0; /= 10) { numbers[i % 10]++; } int counter = 0; int result = 0; (int = 9; >= 0; counter += numbers[i--]) { result += (int) ((math.pow(10, numbers[i]) * - 1) / 9) * math.pow(10, counter); } return result; }
Comments
Post a Comment