Tuesday, 5 September 2017

java - Find next greater number with same set of digits

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.util.Arrays;
import java.util.stream.IntStream;

import array._Array;

public class _Math2 {

    /**
     * Find next greater number with same set of digits
     * 
     * http://www.geeksforgeeks.org/find-next-greater-number-set-digits/
     * 
     */
    static int next_greater_number_with_same_set_of_digits(long num) {
        System.out.println(num);

        int zeroChar = (int)'0'; 
        int array[] = String.valueOf(num).chars().map(i -> i - zeroChar).toArray();

        int[] temp = Arrays.copyOf(array, array.length);
        Arrays.sort(temp);

        //check if array in increasing order
        if(Arrays.equals(array, temp)) {
            _Array.swap(array, array.length - 2, array.length - 1);
            return combineNumber(array);
        }

        _Array.reverse(temp);

        //check if num is max possible number is this set of digits
        if(Arrays.equals(array, temp))
            throw new Error("Not Possible");

        temp = Arrays.copyOf(array, array.length);

        //sort except first number
        Arrays.sort(temp, 1, array.length);

        //find first digit which does not match with original numbers digit in same index 
        int start = 1;
        while(array[start] == temp[start]) start++; 

        //swap it 
        _Array.swap(temp, start - 1, start);

        return combineNumber(temp);
    }

    public static int combineNumber(int[] array) {
        int sum = 0;
        for (int j = 0; j < array.length; j++) 
            sum += array[j]*Math.pow(10, array.length - j - 1);

        return sum;
    }
}

styled using hilite.me

No comments:

Post a Comment