Sort an integer array in such a manner that upon concatenating the elements it the result yields maximum value
package personal.puzzles;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Max value array sorter
*
* @author madhuc
*
*/
public class MaxValueArraySorter {
public static int getMaxValueFromArray(int[] input) {
List<String> inputAsString = new ArrayList<String>(input.length);
for (int i = 0; i < input.length; ++i) {
inputAsString.add(String.valueOf(input[i]));
}
Collections.sort(inputAsString,
Collections.reverseOrder(new MyComparator()));
StringBuilder outputBuilder = new StringBuilder();
for (int i = 0; i < inputAsString.size(); ++i) {
outputBuilder.append(inputAsString.get(i));
}
return Integer.valueOf(outputBuilder.toString());
}
public static class MyComparator implements Comparator<String> {
public int compare(String paramT1, String paramT2) {
if (paramT1.length() <= paramT2.length()) {
return findLargest(paramT1, paramT2);
} else {
return -1 * findLargest(paramT2, paramT1);
}
}
private int findLargest(String t1, String t2) {
for (int i = 0; i < t1.length(); ++i) {
if (t1.charAt(i) < t2.charAt(i)) {
return -1;
} else if (t1.charAt(i) > t2.charAt(i)) {
return 1;
}
}
return 1;
}
}
public static void main(String[] args) {
int[] test = {989, 91};
System.out.println(MaxValueArraySorter.getMaxValueFromArray(test));
}
}
2 Comments:
sorted(a, lambda x, y: cmp(str(y)+str(x), str(x)+str(y))) Python variant
sorted(a, lambda x, y: cmp(str(y)+str(x), str(x)+str(y)))
Post a Comment
Subscribe to Post Comments [Atom]
<< Home