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

3 Comments INTERVIEW JOB CODING TASKS – Calculate permutations1 min read

  1. Brianmuh

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

    Reply

Leave a Reply

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