Skip to content

Instantly share code, notes, and snippets.

@lavantien
Created September 16, 2019 17:43
Show Gist options
  • Save lavantien/0cdc043a0171a5efd005c1c5c9b00010 to your computer and use it in GitHub Desktop.
Save lavantien/0cdc043a0171a5efd005c1c5c9b00010 to your computer and use it in GitHub Desktop.
Combine whole integer array into a number called 'x'. Sort the given array so that 'x' is maximum value. This solution using brute-force approach O(n!).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
namespace TestCS
{
class Program
{
static void Main(string[] args) {
#region Main Block
int n = int.Parse(Console.ReadLine());
if (n > 10 || n < 0) {
n = 10;
}
string tstr = Console.ReadLine();
List<int> list = tstr.Split(' ').Select(Int32.Parse).ToList();
List<int> resList = Solve(list.ToArray());
foreach (var x in resList) {
Console.Write("{0} ", x);
}
Console.WriteLine();
#endregion
Console.ReadKey();
}
private static List<int> Solve(int[] arr) {
List<int> res = new List<int>();
Array.Sort(arr);
BigInteger max = -1;
while (NextPermutation(arr)) {
BigInteger t = ToNumber(arr);
if (max < t) {
max = t;
res.Clear();
res = arr.ToList();
}
}
return res;
}
private static BigInteger ToNumber(int[] arr) {
return BigInteger.Parse(string.Join(string.Empty, arr));
}
private static bool NextPermutation(int[] numList) {
/*
Knuths
1. Find the largest index j such that a[j] < a[j + 1]. If no such index exists, the permutation is the last permutation.
2. Find the largest index l such that a[j] < a[l]. Since j + 1 is such an index, l is well defined and satisfies j < l.
3. Swap a[j] with a[l].
4. Reverse the sequence from a[j + 1] up to and including the final element a[n].
*/
#region STEP 1
var largestIndex = -1;
for (var i = numList.Length - 2; i >= 0; i--) {
if (numList[i] < numList[i + 1]) {
largestIndex = i;
break;
}
}
if (largestIndex < 0) return false;
#endregion
#region STEP 2
var largestIndex2 = -1;
for (var i = numList.Length - 1; i >= 0; i--) {
if (numList[largestIndex] < numList[i]) {
largestIndex2 = i;
break;
}
}
#endregion
#region STEP 3
var tmp = numList[largestIndex];
numList[largestIndex] = numList[largestIndex2];
numList[largestIndex2] = tmp;
#endregion
#region STEP 4
for (int i = largestIndex + 1, j = numList.Length - 1; i < j; i++, j--) {
tmp = numList[i];
numList[i] = numList[j];
numList[j] = tmp;
}
#endregion
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment