Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# String permutation

I have 5 strings, such as: "one", "two", "three", "four", and "five". I need to get all permutations of these strings. I've explored all internet resources, but all solutions are so bulky and it's hard for me to understand it and integrate it to my program.
So, maybe you know any easy solution how to get permutations.

like image 950
Frankie Drake Avatar asked Dec 02 '22 03:12

Frankie Drake


2 Answers

Permutations are very easy to do.

/// <summary>
/// Returns all permutations of the input <see cref="IEnumerable{T}"/>.
/// </summary>
/// <param name="source">The list of items to permute.</param>
/// <returns>A collection containing all permutations of the input <see cref="IEnumerable&lt;T&gt;"/>.</returns>
public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> source)
{
    if (source == null)
        throw new ArgumentNullException("source");
    // Ensure that the source IEnumerable is evaluated only once
    return permutations(source.ToArray());
}

private static IEnumerable<IEnumerable<T>> permutations<T>(IEnumerable<T> source)
{
    var c = source.Count();
    if (c == 1)
        yield return source;
    else
        for (int i = 0; i < c; i++)
            foreach (var p in permutations(source.Take(i).Concat(source.Skip(i + 1))))
                yield return source.Skip(i).Take(1).Concat(p);
}
like image 181
Timwi Avatar answered Dec 19 '22 04:12

Timwi


Here's a class that works in .Net 2.0. First, sort your array. Then use it by looping over while(Permute.Next(array)). When there are no more permutations, Permute.Next returns false.

using System;
using System.Collections.Generic;
using System.Text;

public class Permute
{
    public static bool Next(IList<IComparable> list)
    {
        int k = FindSmallestK(list);
        if (k < 0) return false;
        int l = FindLargestL(list, k);
        Swap(list, k, l);
        Reverse(list, k + 1);
        return true;
    }

    private static void Reverse(IList<IComparable> list, int p)
    {
        for (int i = p, j = list.Count - 1; i < j; i++, j--)
        {
            Swap(list, i, j);
        }
    }

    private static void Swap(IList<IComparable> list, int k, int l)
    {
        IComparable temp = list[k];
        list[k] = list[l];
        list[l] = temp;
    }

    private static int FindLargestL(IList<IComparable> list, int k)
    {
        for (int i = list.Count - 1; i > k; i--)
        {
            if (list[k].CompareTo(list[i]) < 0) return i;
        }
        return -1;
    }

    private static int FindSmallestK(IList<IComparable> list)
    {
        for (int i = 0; i < list.Count - 1; i++)
        {
            if (list[i].CompareTo(list[i + 1]) < 0) return i;
        }
        return -1;
    }
}
like image 38
neural Avatar answered Dec 19 '22 06:12

neural