2022-11-21

Finding the largest combination given a list/array of integers

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



No comments:

Post a Comment