-1

Possible Duplicate:
How to type sets for a given string

I'm trying to type the permutation for a string for example the string "123" should give me 123 132 213 231 321 312 I need help to fix my code

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

namespace TestAAD
{
class Program
{
    static int len = 0;
    static int lenPerm = 0;
    private static void Permutations(string str, string perm , int i)
    {
        if (i == len) Console.WriteLine(perm);
        for (int k = 0; k < len; k++)
        {
             lenPerm = perm.Length;
            for (int j = 0; j < lenPerm; j++)
            {
                if ((perm[j] == str[(len - 1) - k]) && (len-1-k>0))
                    k++;
            }
            if((len-1-k) >=0)
            Permutations(str, perm + str[(len - 1) - k], i++);
        }
    }
    static void Main(string[] args)
    {
        string st = "123";
        len = st.Length;
        Permutations(st, "",0);
    }
}
}

Please if anyone can help me , Please thanks all

Community
  • 1
  • 1
user1816808
  • 13
  • 1
  • 2
  • 2
    It'd help to show where exactly your code fails. What does it already do, where doesn't it work? What specifically is the problem? And: What have you tried solving the problem? – slhck Dec 08 '12 at 15:48
  • it gives me stackOverFlowException – user1816808 Dec 08 '12 at 15:49
  • If you need help with why your code doesn't work, then don't ask 3 questions in a row how to achieve the desired behavior. Instead try finding out what goes wrong, report what you don't understand about what is going wrong, point to the relevant part of the code, and perhaps _then_ we could help you out. I'm flagging this post. 3 exact same questions in a row without putting any effort into improving your question at all is just wasting everybody's time. – Steven Jeuris Dec 08 '12 at 16:20

2 Answers2

1

Permutations calls Permutations again in a loop len times. This second Permutations call calls Permutations again in a loop len times. This happens again and again endlessly, or at least until you get a stack overflow.

When you use recursive calls, you always must make sure that the recursion stops somewhere.

If (job not done) {
    make recursive call
}

The recursive call must make a step towards the completion of the job, otherwise it will never finish.


UPDATE 1 (only addressing the exception problem)

The method is difficult to read. Instead of repeating the expression len-1-k several times, reverse the loop! for (int k = str.Length - 1; k >= 0; k--) and decrease k with k-- instead in the inner loop. I also got rid of the variable len which is superfluous.

In your implementation len-1-k is always >= 0. Therefore the recursive calls will never end. Therefore I changed the condition for decreasing k. It will decrease k even if it is already 0. In order not the get an index out of bounds error in str[k] the condition k >= 0 must be checked first.

private static void Permutations(string str, string perm, int i)
{
    if (i == str.Length)
        Console.WriteLine(perm);
    for (int k = str.Length - 1; k >= 0; k--) {
        int lenPerm = perm.Length;
        for (int j = 0; j < lenPerm; j++) {
            if (k >= 0 && perm[j] == str[k])
                k--;
        }
        if (k >= 0)
            Permutations(str, perm + str[k], i++);
    }
}

public static void Start()
{
    string st = "123";
    Permutations(st, "", 0);
}

This doesn't produce an endless recursion any more but the result is still not correct. I let you figure out how to improve the code further.


UPDATE 2 (creating correct permutations)

Finally here is my working implementation

public static class PermutationBuilder
{
    private static char[] _characters;
    private static List<string> _list;

    public static IEnumerable<string> GetPermutations(string characters)
    {
        _characters = characters.ToCharArray();
        _list = new List<string>();
        AddPermutations("", 0);
        return _list;
    }

    private static void AddPermutations(string permutation, int level)
    {
        if (level >= _characters.Length) {
            _list.Add(permutation);
        } else {
            for (int i = 0; i < _characters.Length; i++) {
                char ch = _characters[i];
                if (ch != ' ') {
                    _characters[i] = ' ';
                    AddPermutations(permutation + ch, level + 1);
                    _characters[i] = ch;
                }
            }
        }
    }
}

Note that I temporarily mark the characters that have been used with a space character.

You call it like this

foreach (string permutation in PermutationBuilder.GetPermutations("123")) {
    Console.WriteLine(permutation);
}
Olivier Jacot-Descombes
  • 86,431
  • 10
  • 121
  • 160
1

Permutations are very easy to do.

public string[] FindPermutations(string word)
{
    if (word.Length == 2)
    {
        char[] c = word.ToCharArray();
        string s = new string(new[] { c[1], c[0] });
        return new[]
            {
                word,
                s
            };
    }

    List<string> result = new List<string>();

    string[] subsetPermutations = FindPermutations(word.Substring(1));
    char firstChar = word[0];
    foreach (string temp in subsetPermutations
                    .Select(s => firstChar.ToString(CultureInfo.InvariantCulture) + s))
    {
        result.Add(temp);
        char[] chars = temp.ToCharArray();
        for (int i = 0; i < temp.Length - 1; i++)
        {
            char t = chars[i];
            chars[i] = chars[i + 1];
            chars[i + 1] = t;
            string s2 = new string(chars);
            result.Add(s2);
        }
    }
    return result.ToArray();
}
Olivier Jacot-Descombes
  • 86,431
  • 10
  • 121
  • 160
Parimal Raj
  • 19,121
  • 9
  • 66
  • 105