public
anonymous / gist:3837129
Created

  • Download Gist
gistfile1.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
static long nextPermutation(long x)
{
string s = x.ToString();
string t;
long temp;
for (int i = s.Length - 1; i >= 1; i--)
{
if (long.Parse(s.Substring(i, 1)) > long.Parse(s.Substring(i - 1, 1)))
{
t = s.Substring(i, s.Length - i);
temp = long.Parse(s.Substring(i - 1, 1));
return long.Parse(s.Substring(0, i - 1) + permutate(temp, t));
}
}
return long.Parse(reverseString(s));
}
static string permutate(long temp, string s)
{
string result;
int nextStart = 10;
int nextStartIndex = 0;
for (int i = 0; i < s.Length; i++)
{
if (long.Parse(s.Substring(i, 1)) < nextStart && long.Parse(s.Substring(i, 1)) > temp)
{
nextStart = int.Parse(s.Substring(i, 1));
nextStartIndex = i;
}
}
result = nextStart.ToString();
s = s.Substring(0, nextStartIndex) + s.Substring(nextStartIndex + 1, s.Length - nextStartIndex - 1);
s = reverseString(s);
int sLength = s.Length;
for (int i = 0; i < s.Length; i++)
{
if (temp < int.Parse(s.Substring(i, 1)))
{
s = s.Substring(0, i) + temp.ToString() + s.Substring(i, s.Length - i);
i = s.Length;
}
}
if (sLength == s.Length) return result + s + temp.ToString();
return result + s;
}
static int[] lexPerm(int[] originalArray)
{
int max1;
int max2;
int temp;
int[] reverseTemp;
max1 = -1;
for (int i = 0; i < originalArray.Length - 1; i++)
{
if (originalArray[i] < originalArray[i + 1])
{
max1 = i;
}
}
if (max1 != -1)
{
max2 = originalArray.Length - 1;
for (int i = max1 + 1; i < originalArray.Length; i++)
{
if (originalArray[max1] < originalArray[i])
{
max2 = i;
}
}
temp = originalArray[max1];
originalArray[max1] = originalArray[max2];
originalArray[max2] = temp;
}
reverseTemp = new int[originalArray.Length - max1 - 1];
for (int i = 0; i < reverseTemp.Length; i++)
{
reverseTemp[reverseTemp.Length - 1 - i] = originalArray[max1 + 1 + i];
}
for (int i = 0; i < reverseTemp.Length; i++)
{
originalArray[max1 + 1 + i] = reverseTemp[i];
}
return originalArray;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.