1

I am trying to make a program that, with a given word, can calculate and print every letter combination. To be more specific, I am asked to use a recursive function and what I should get is something like this:

Given word: HOME

EHOM

EMOH

MEHO

The approach I am taking in to swap the content #x with #x+1 like this

string[0]->string[1]

string[0]->string[2]

This is what I came up with

void anagram(char * s, int len, int y)
{
char temp; //used to store the content to swap betwen the two 

if (len < 0) //when the total lenght of the array gets to 0 it means that every single swap has been made
    return;

temp = s[len]; //swapping
s[len] = s[y];
s[y] = temp;

puts(s); //prints the string

if (y == 0)                     
    return anagram(s, len-1, y - 1);

return anagram(s, len, y - 1);

}

What I get is just a huge mess and a Break Point from VS (if not a crash).

Can somebody help me please?

OmG
  • 18,337
  • 10
  • 57
  • 90
parmigiano
  • 95
  • 1
  • 14
  • Possible duplicate of [How to generate all permutations of an array in sorted order?](http://stackoverflow.com/questions/17396222/how-to-generate-all-permutations-of-an-array-in-sorted-order) – Lorenzo Belli Oct 01 '15 at 15:08
  • How are you making the initial call to your function? `anagram("HOME", ?, ?);` What goes in place of the question marks? – pcarter Oct 01 '15 at 16:07
  • @pcarter anagram("HOME", stringlen(s), stringlen(s)) where s is the string – parmigiano Oct 01 '15 at 16:29
  • `anagram("HOME", stringlen(s), stringlen(s))` Assuming that `stringlen(s)` is going to return the length of your string (i.e. 4 in this example), then you are going to have a problem when you index into the string with `s[len]`. Remember that C++ arrays are 0-based, so the maximum valid index is length - 1. – atkins Oct 01 '15 at 16:34
  • I really enjoyed going back to this question and asking myself what the heck I was trying to accomplish... – parmigiano May 16 '18 at 09:27

0 Answers0