Groovy web console

subscribe to the feed Subscribe
to this
site

Find Second Largest Integer

Published 3 weeks ago by Jay Wei
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
def integers = [2338                
                ,46
                ,21
                ,14
                ,56
                ,493
                ,22]

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

println 'secondLargestIntegerAmongAllCombinations: ' + secondLargestIntegerAmongAllCombinations

def findSecondLargestIntegerAmongAllCombinations(integers) {
    def maxCombo = findMaxIntegerAmongAllCombinations(integers)
    swap(maxCombo, 1, 2)
    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
    }
}