# Groovy web console

## 找到通过组合一组整数后得到的最大的数，比如输入{1，3，2}，则321是最大的数

Published 2 months ago by Anonymous
```def integers = [2, 3, 5, 0]

println 'input: ' + integers
Long secondLargestIntegerAmongAllCombinations = findSecondLargestIntegerAmongAllCombinations(integers)
println 'secondLargestIntegerAmongAllCombinations: ' + secondLargestIntegerAmongAllCombinations

def findSecondLargestIntegerAmongAllCombinations(integers) {
def maxCombo = findMaxIntegerAmongAllCombinations(integers)
def zeroIndex = maxCombo.indexOf(0)
def indexA = 1
def indexB = 2

if (zeroIndex > -1) {
indexA = zeroIndex
indexB = zeroIndex - 1
}

swap(maxCombo, indexA, indexB)
return Long.valueOf(integers.join().toString())
}

def findMaxIntegerAmongAllCombinations(integers) {
int i = 0
for (; i < integers.size(); i++) {
if (i > 0) {
def firstSwapIndex = -1

for (int j = i; j > 0; j--) {
def prevInd = j - 1
def previousChars = integers[prevInd].toString().chars
def currentChars = integers[j].toString().chars
def needSwapping = compare(currentChars, previousChars, 0)
if (needSwapping > 0) {
swap(integers, prevInd, j)
firstSwapIndex = j
}
}

if (firstSwapIndex > 0) {
i = firstSwapIndex + 1
}
}
}

return integers
}

def swap(input, indexA, indexB) {
def temp = input[indexA]
input[indexA] = input[indexB]
input[indexB] = temp

return input
}

def compare(currentChars, previousChars, comparingIndex) {

char currentChar = currentChars[comparingIndex]

def lenOfPrev = previousChars.size()
def lastIndexOfPrev = lenOfPrev - 1
def charIndexComparedWith = comparingIndex
if (comparingIndex > lastIndexOfPrev) {
charIndexComparedWith = lastIndexOfPrev
}

char prevChar = previousChars[charIndexComparedWith]
int intForCurChar = Integer.parseInt(String.valueOf(currentChar))
int intForPrevChar = Integer.parseInt(String.valueOf(prevChar))
if (intForCurChar == intForPrevChar) {

if (comparingIndex >= currentChars.size() - 1) {
return -1
}

compare(currentChars, previousChars, comparingIndex+1)
} else if (currentChar > prevChar) {
return 1
} else {
return -1
}
}
```