-1

I have to find the greatest even number possible using the digits of given number

Input : 7876541
Desired output : 8776514

Can anyone help me with the logic?

Rao
  • 20,781
  • 11
  • 57
  • 77
Rita R
  • 23
  • 4

2 Answers2

2

How about this?

  • convert it into string
  • sort the numbers in reverse order
  • join them and convert it as number
def n = 7876541
def newN = (n.toString().split('').findAll{it}.sort().reverse().join()) as Integer
println newN

You can quickly try it on-line demo

EDIT: Based on the OP comments, updating the answer.

Here is what you can do -
- find the permutations of the number
- find the even number
- filter it by maximum number.

There is already found a thread for finding the permutations, so re-using it with little changes. Credits to JavaHopper.

Of course, it can be simplified by groovified.

class Permutations {
  static def list = []
  public static void printPermutation(char[] a, int startIndex, int endIndex) {
    if (startIndex == endIndex)
        list << ((new String(a)) as Integer)
    else {
        for (int x = startIndex; x < endIndex; x++) {
            swap(a, startIndex, x)
            printPermutation(a, startIndex + 1, endIndex)
            swap(a, startIndex, x)
        }
    }
  }
  private static void swap(char[] a, int i, int x) {
    char t = a[i]
    a[i] = a[x]
    a[x] = t
  }

}
def n = 7876541
def cArray = n.toString().toCharArray()
Permutations.printPermutation(cArray, 0, cArray.size())
println Permutations.list.findAll { it.mod(2) == 0}?.max()

Quickly try online demo

Rao
  • 20,781
  • 11
  • 57
  • 77
0

There is no need to create permutations. Try this solution:

  • convert the source number into a string.
  • split the string into an array,
  • sort the numbers, for the time being, in ascending order,
  • find the index of the first even digit,
  • remove this number from the array (storing it in a variable),
  • reverse the array and add the removed number,
  • join the digits from the array and convert them into integer.

So the whole script looks like below:

def inp = 7876541
def chars1 = inp.toString().split('')
// findAll{it} drops an empty starting element from the split result
def chars2 = chars1.findAll{it}.sort()
// Find index of the 1st even digit
def n = chars2.findIndexOf{it.toInteger() % 2 == 0}
def dig = chars2[n]     // Store this digit
chars2.remove(n)        // Remove from the array
def chars3 = chars2.reverse()   // Descending order
chars3.add(dig)         // Add the temporarily deleted number
def out = (chars3.join()) as Integer    // result
println out
Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41