INTERVIEW JOB CODING TASKS – Calculate permutations1 min read

Today we are going to continue with interview coding tasks.

I really do hope this, solved, coding task is going to help you during your interview.

Task: Depending on input value i.e. (123) create all permutations i.e:(123,213,231,132,312,321)

Solution:


private static void Main(string[] args)
{
WritePermutations();
Console.ReadLine();
}
public static void WritePermutations()
{
var permutations = GetPermutations("123");
foreach (var permutation in permutations)
{
Console.WriteLine(permutation);
}
}
public static List<string> GetPermutations(string inputString)
{
return IsPermutated(inputString, out var permutations, out var list) ? list : ListOfPermutations(inputString, permutations);
}
private static bool IsPermutated(string inputString, out List<string> permutations, out List<string> list)
{
permutations = new List<string>();
list = null;
if (inputString == null) return true;
if (inputString.Length != 0) return false;
permutations.Add("");
{
list = permutations;
return true;
}
}

private static List<string> ListOfPermutations(string inputString, List<string> permutations)
{
var firstCharacter = inputString[0];
var remainder = inputString.Substring(1);
var words = GetPermutations(remainder);
foreach (var word in words)
{
for (var i = 0; i <= word.Length; i++)
{
permutations.Add(InsertCharacterAt(word, firstCharacter, i));
}
}
return permutations;
}
public static string InsertCharacterAt(string word, char character, int i)
{
var start = word.Substring(0, i);
var end = word.Substring(i);
return $"{start}{character}{end}";
}

Cheers

(Visited 32 times, 1 visits today)

4 Comments

  1. Brianmuh 24 March 2020 at 22:08

    Great looking internet site. Presume you did a lot of your very own html coding.

  2. Brianmuh 04 April 2020 at 11:19

    Sustain the excellent work and delivering in the crowd!

  3. Jamesjus 24 April 2020 at 06:20

    Keep up the excellent work and generating the group!

  4. 파라오카지노 16 October 2020 at 12:35

    Hello There. I found your weblog the use of msn. This is a very smartly
    written article. I will make sure to bookmark it and come back to learn more of
    your helpful info. Thanks for the post. I will definitely return.

Leave a comment

Your email address will not be published. Required fields are marked *