locked
How to permute Tuple Items? RRS feed

  • Question

  • I've got a tuple containing 4 string items (Tuple<string, string, string, string>).

    How do I get all 24 permutations on it?

    Saturday, July 4, 2015 2:25 PM

Answers

  • If you are interested in non-recursive solutions too, try this one:

    var tuple = new Tuple<string, string, string, string>( "a", "b", "c", "d" );
    
    string[] array = new[] { tuple.Item1, tuple.Item2, tuple.Item3, tuple.Item4 };
    
    var solution = new List<Tuple<string, string, string, string>>();
    
    for( int i = 0; i < 4; ++i )
    {
         for( int j = 0; j < 4; ++j )
         {
               if( j == i ) continue;
    
               for( int k = 0; k < 4; ++k )
               {
                    if( k == i || k == j ) continue;
    
                    for( int m = 0; m < 4; ++m )
                    {
                         if( m == i || m == j || m == k ) continue;
    
                         solution.Add( new Tuple<string, string, string, string>( array[i], array[j], array[k], array[m] ) );
                    }
               }
         }
    }
    
    solution.ForEach( Console.WriteLine );
    
    

    • Marked as answer by Caillen Sunday, July 19, 2015 7:53 AM
    Saturday, July 4, 2015 3:51 PM