A problem given by my lab professor, as the title reads: Find the largest combination given a list/array of integers. ie:
input: {10, 68, 75, 7, 21, 12}
stdout: 77568211210
my output : 75768211210
The current code:
import java.util.*;
import java.lang.*;
public class classwork6
{
static Scanner in = new Scanner(System.in);
static void sort(String[] arr)
{
for(int i=0;i<arr.length;i )
{
for(int j=i 1;j<arr.length;j )
{
if(arr[i].compareTo(arr[j])<0)
{
String temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
public static void main(String[] args)
{
int[] list = {10, 68, 75, 7, 21, 12};
String[] arr = new String[list.length];
for(int i=0;i<list.length;i )
{
arr[i] = String.valueOf(list[i]);
}
sort(arr);
System.out.print(Arrays.toString(arr).replaceAll("[\\[\\], ]",""));
}
}
My first attempt was simply sorting the array, after which I quickly found out that 777568211210>75682112107
My latest attempt was to lexicographically compare the string values of the integers. Yet the output is still incorrect 777568211210>75768211210
CodePudding user response:
You're on the right track. But think about it, which number will "give" more to the final result: 91 or 911.
It should be obvious that the shorter number gives more "possibilities" to get higher number. So your sort should prioritize shorter numbers if two numbers begin with same characters
CodePudding user response:
Just lexically
compare each pair of integers as strings, concatenated back to back. Consider 77
and 234
. "77243"
is lexically
greater than "23477"
. So 77
would come first, then 234
.
List<Integer> list = new ArrayList<>(List.of(92, 101, 79, 42, 2002, 22));
Comparator<Integer> comp = (b,a)-> (a "" b).compareTo(b "" a);
list.sort(comp);
System.out.println(list);
String result = list.stream().map(i->Integer.toString(i)).reduce("",String::concat);
System.out.println(result);
prints
[92, 79, 42, 22, 2002, 101]
927942222002101