function recursion

I'm trying to make a program that scrambles a sentence that the user inputs...

Here's what I've got this far...

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
38
39
40
#include <iostream>

using namespace std;

const int SIZE = 20;

void scramble(char [], int);
unsigned int factorial (int);

unsigned int f = 1;

int main()
{
    char ch[SIZE];
    
    cout << "Enter text: ";
    cin.getline(ch, SIZE);
    
    int length = 0;
    while (ch[length])
        length++;
    
    scramble(ch, length);
    
    return 0;
}

void scramble (char arr[], int n)
{    
}

unsigned int factorial(int n)//This function is to count the number of possible
{                            //combinations.
    if (n > 0)               //Also any other way to rewrite this without
    {                        //unsigned int f; as a global function?
        f *= n;
        f = factorial(n-1);
    }
    return f;
}


Can someone help me with the scramble function? I'm thinking of a for function that swaps the first character of the array with another one and then in a for loop using recursion like this : scramble(arr + 1, n);

Sample run:

1
2
3
4
5
6
7
Enter text: hey
hey
hye
yeh
yhe
ehy
eyh


//I've got a feeling that my thinking is completely wrong...
Thanks in advance :)
Last edited on
This almost seems too easy, but:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <algorithm>
#include <iostream>
#include <string>

int main()
{
  std::string sentence;
  std::cout << "Please enter a sentence: ";
  std::getline(std::cin,sentence);
  std::random_shuffle(sentence.begin(),sentence.end());
  std::cout << std::endl << "Shuffled: " << sentence << std::endl;
  return 0;
}
Last edited on
Can someone help me with the scramble function? I'm thinking of a for function that swaps the first character of the array with another one and then in a for loop using recursion like this : scramble(arr + 1, n);
You can do so but you need to decrease n as well: scramble(arr + 1, n - 1);

Check if n > 0 before you're doing anything in your scramble() function
You are looping senselessly here (does not do anything):
1
2
    while (ch[length])
        length++;

did you mean
1
2
3
    while (ch[length])
       { length++;
...}
?

Also your example changes the last character not your first as you mentioned:
hey
hye
while it should be
yhe


Anyway one (simple and not optimized) way to do it (and not use std functions) is to create a same size array and fill it with the correct sequence you wish.
eypros wrote:
You are looping senselessly here (does not do anything):
It's not senseless (strlen() would be better though). It just counts the chars
I'm thinking of a for function

unless you have a function named for it is actually a loop not a function
Topic archived. No new replies allowed.