Created
April 27, 2017 09:00
-
-
Save Bambofy/66dbf94d7054038289d4d66d36fbd541 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
namespace CodeADay | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
string numberGiven = "1234"; | |
char[] numberGivenAsArray = numberGiven.ToCharArray(); | |
List<string> permutationsList = new List<string>(); | |
for (int i = 0; i < numberGivenAsArray.Length; i++) | |
{ | |
for (int j = 0; j < numberGivenAsArray.Length - 1; j++) | |
{ | |
// for each pass, | |
// swap the current index char with the char at the end of the array | |
char endChar = numberGivenAsArray[numberGivenAsArray.Length - 1]; | |
char currentChar = numberGivenAsArray[j]; | |
numberGivenAsArray[j] = endChar; | |
numberGivenAsArray[numberGivenAsArray.Length - 1] = currentChar; | |
// store the new swapped value. | |
permutationsList.Add(new string(numberGivenAsArray)); | |
} | |
} | |
// find the smallest distance between the given number and the permutations | |
// ensuring the permutation is greater than the given number. | |
int numberGivenAsInt = int.Parse(numberGiven); | |
int tempDistanceToNumber = -1, tempClosestNumber = -1; | |
foreach (var c in permutationsList) | |
{ | |
int thisPermutation = int.Parse(c); | |
int thisDistance = thisPermutation - numberGivenAsInt; | |
if (tempDistanceToNumber == -1 || tempClosestNumber == -1) | |
{ | |
tempDistanceToNumber = thisDistance; | |
tempClosestNumber = thisPermutation; | |
} | |
else | |
{ | |
// ensure this distance is positive as that means | |
// this permutation is larger than the given number. | |
if (thisDistance > 0) | |
{ | |
if (thisDistance < tempDistanceToNumber) | |
{ | |
tempDistanceToNumber = thisDistance; | |
tempClosestNumber = thisPermutation; | |
} | |
} | |
} | |
} | |
Console.WriteLine("Distance = {0}, Permutation = {1}", tempDistanceToNumber, tempClosestNumber); | |
Console.ReadLine(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment