where to go from here

im solving a programming challenge where you have to devise a program to print out every possible combination of the letters in a string. the mini algorithm i have for the program will essentially switch every letter with every other letter, and is written rougly like so (copyarray is a copy of the original string)

1
2
array[0] = array[0 + 1];
array[0 + 1] = copyarray[0]


all of the constants in this will be replaced by variables of course :)

however when im going through each character eventually adding numbers will cause it to go out of bounds of the array and give me some random crap when i output the string. how might i go about avoiding this?
do %string_length.
Though I'm not sure I understand the problem. Do you need to find every permutation of a given string? Now you're just rotating it..
trying to find every permutation, and ive already used strlen.
what do you mean by just rotating it? if i have the word dog for example replacing the numbers with the letters of the word it would end up like this
1
2
array[d] = array[o]
array[o] = array[d]

so the word would end up as odg
right..?
Last edited on
Oh. I guess it;s fine then.
I meant
1
2
3
int len = strlen(array);
array[i] = array[ (i + 1)%len];
array[(i + 1)%len] = copyarray[i]

That way i+1 won't be out of bounds. It there something else? Post the whole loop in that case.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <cstring>
using std::cout;
using std::endl;
using std::cin;

int main(void)
{
	const int max = 10;
	char str[max] = {0};
	char copystr[max] = {0};
	cout << "String: ";
	cin >> str;
	int length = strlen(str);

	//make a copy of the string
	for (int i = 0; i < length; i++)
		copystr[i] = str[i];

	for (int i = 0; i < length; i++)
	{	
		//swap characters
		for (int y = 0; y < length; y++)
		{
			str[i] = str[(i + y) % length];
			str[(i + y) % length] = copystr[i];
		}

		cout << str << endl;
		//reset the string
		for (int i = 0; i < length; i++)
			str[i] = copystr[i];
	}

	cout << str << endl;
	return 0;
}


obviously it doesnt work so help please :)
Last edited on
doesn't work, as in doesn't permute correctly, or keeps going out of bounds?

Either way, there is http://www.cplusplus.com/reference/algorithm/next_permutation/

Also, in case you haven't tried, google should give you plenty of solutions. It's a rather popular task..
well the point is that im trying to do it without googling it because i dont really see how ill get better if i just copy some code..?

and doesnt work as in doesnt permute correctly
Last edited on
Hey! This was one of my favorite problems to work on!! Did you see my blog post on it?
didnt know you had ablog lol, but im near giving up on this and just working on my bubble sortting program instead anyhow :o
Topic archived. No new replies allowed.