Skip to content

Instantly share code, notes, and snippets.

@4toblerone
Last active September 8, 2021 20:25
Show Gist options
  • Save 4toblerone/d2f6b8fe3176f22129c2642c02d13355 to your computer and use it in GitHub Desktop.
Save 4toblerone/d2f6b8fe3176f22129c2642c02d13355 to your computer and use it in GitHub Desktop.
Solution to the next smallest number
import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
/*
* Given a Long number N, write a function that calculates the highest number lower than N obtained by permute only one digit of N.
* If no permutation exists to return a lower value, return N.
* Example:
* N = 153
* permuteToPrevious(N) = 135
* N = 12345
* permuteToPrevious(N) = 12345
*
* Please note:
* Use Long as type. Digits can repeat
*/
class Data {
static final List<Long> exampleData = new ArrayList<>();
static {
exampleData.add(153L);
exampleData.add(12345L);
exampleData.add(92145112L);
exampleData.add(54321L);
exampleData.add(295468L);
/*
* Example output for this data:
135
12345
92142115
54312
294568
*/
}
}
class Solution {
public static List<Integer> splitIntoDigits(Long number){
List<Integer> listOfDigits = new ArrayList<>();
while(number > 0){
Long remainder = number % 10;
listOfDigits.add(remainder.intValue());
number = number / 10;
}
return listOfDigits;
}
public static Long combineDigitsIntoNumber(Integer [] listOfDigits){
Long temp = 0L;
for(int i = listOfDigits.length-1; i >= 0; i--){
Long localTemp = listOfDigits[i] * (long)Math.pow(10L,i);
temp += localTemp;
}
return temp;
}
/**
* When traversing an array of digits to the right
* it can happen that the fist occurrence of a smaller
* number is not the one closest to the original one
* thus we are essentially collecting all the numbers
* smaller than the original one and in the last step
* we are sorting them and using the largest one
* */
private static Long permuteToPrevious(Long input) {
List<Integer> listOfDigits = splitIntoDigits(input);
Integer [] arrayOfInts = listOfDigits.toArray(new Integer[listOfDigits.size()]);
List<Long> candidates = new ArrayList<>();
for(int j = 0 ; j < arrayOfInts.length; j++){
Integer first = arrayOfInts[j];
for(int i = j; i < arrayOfInts.length; i++){
if(arrayOfInts[i] > first){
Integer [] copyArray = Arrays.copyOf(arrayOfInts, arrayOfInts.length);
copyArray[j] = copyArray[i];
copyArray[i] = first;
candidates.add(combineDigitsIntoNumber(copyArray));
}
}
}
Collections.sort(candidates);
return candidates.size() == 0 ? input : candidates.get(candidates.size()-1);
}
public static void main(final String[] args) {
for (final Long input : Data.exampleData) {
System.out.println(permuteToPrevious(input));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment