flying3615
8/10/2017 - 10:58 AM

LongestNumber.java

import java.util.*;
import java.util.stream.Collectors;

/*
Task
Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer.

Use the following two sets of integers as tests   and   show your program output here.

  {1, 34, 3, 98, 9, 76, 45, 4}
  {54, 546, 548, 60}

  Another way to solve this is to note that in the best arrangement, for any two adjacent original integers X and Y, the concatenation X followed by Y will be numerically greater than or equal to the concatenation Y followed by X.
 */


public class Test {

    public static void main(String[] args) {
        Integer [] input = {1, 2, 3};
        List<Integer> inputList = Arrays.asList(input);
        Comparator<Integer> sorter = (o1, o2) -> (o2 + "" + o1).compareTo(o1 + "" + o2);
        String result = inputList.stream().sorted(sorter).map(num -> num.toString()).collect(Collectors.joining(""));
        System.out.println(result);


        System.out.println(permutation(Arrays.asList(input)));

    }


    public static String permutation(List<Integer> nums) {
        List<List<Integer>> accum = new ArrayList<>();
        permutation(accum, Arrays.asList(), nums);
        List<String> toBeSorted = accum.stream().map(l->l.stream().map(i->i.toString()).collect(Collectors.joining())).collect(Collectors.toList());
        Comparator<String> sorter = Comparator.reverseOrder();
        Collections.sort(toBeSorted,sorter);
        return toBeSorted.get(0);
    }

    private static void permutation(List<List<Integer>> accum, List<Integer> prefix, List<Integer> nums) {
        int n = nums.size();
        if (n == 0) {
            accum.add(prefix);
        } else {
            for (int i = 0; i < n; ++i) {
                List<Integer> newPrefix = new ArrayList<>();
                newPrefix.addAll(prefix);
                newPrefix.add(nums.get(i));

                List<Integer> numsLeft = new ArrayList<>();
                numsLeft.addAll(nums);
                numsLeft.remove(i);

                permutation(accum, newPrefix, numsLeft);
            }
        }
    }
}