Reputation: 6230
I am not sure if this question is for Maths section or for this one but I need a programmatic solution (in .NET) hence I am placing the question here.
I have an array with variable length which outputs as shown in below example.
for int[] arr = {1,2} it would be as follows:
[1 , 2],[1],[2]
for int[] arr = {1,2,3} it would be as follows:
[1 , 2],[2 , 3],[3 , 1],[1],[2],[3],[1 , 2 , 3]
for int[] arr = {1,2,3,4} it would be like
[1 , 2],[2 , 3],[3 , 4],[4 , 1],[1],[2],[3],[4],[1,2,3],[2,3,4],[3,4,1],[4,1,2],[1,2,3,4]
for int[] arr = {1,2,3,4,5} .....
I think you should be able to see the pattern by now
Any pointers or hints how to solve this programmatically or any if there a related mathematical formula that anyone can think of?
Thanks,
Upvotes: 0
Views: 72
Reputation: 111860
I think it's quite useless as a program, and as an exercise if you don't do it yourself then it's useless. But I give everyone what they ask...
int[] arr = new int[] { 1, 2, 3 };
// How much elements in each permutation
for (int i = 1; i <= arr.Length; i++)
{
// Starting point of the permutation
for (int j = 0; j < arr.Length; j++)
{
Console.Write("[");
// Single element of the permutation
for (int k = 0; k < i; k++)
{
if (k != 0)
{
Console.Write(", ");
}
Console.Write("{0}", arr[(j + k) % arr.Length]);
}
Console.WriteLine("]");
// Single cycle for last permutation of length arr.Length
if (i == arr.Length)
{
break;
}
}
}
Upvotes: 2