0

I'm trying to write a program that can output written words in every possible way.

e.g.

Input:

I am coding

Output:

I am coding

I coding am

am I coding

am coding I

coding I am

coding am I

here's my code:

#include <iostream>
using namespace std;

int main()
{
    string data;
    cout << "enter data: "; getline(cin, data);
    
    // counting amount of the words //
    int size = 1, word = 0;
    for(int i=0; i<data.size(); i++)
    {
        if(data[i] == ' ') size++;
    }
    
    string msg[size];
    
    // each index is one word //
    for(int i=0; i<data.size(); i++)
    {
        if(data[i] == ' ') { word++; continue; }
        
        msg[word] += data[i];
    }
    
    // output words in every possible way //
    for(int i=0; i<size; i++)
    {
        for(int j=0; j<size; j++)
        {
            for(int k=0; k<size; k++)
            {
                if(i==j || i==k || j==k) continue;
                
                cout << msg[i] << ' ' << msg[j] << ' ' << msg[k] << endl;
            }
        }
    }
}

Is there a way to make it work on N nested loops for any other amount of words?

I also tried to do it using factorials but it didn't work.

  • Look up "recursion" to see how to nest as many loops as you would like. – Sergey Kalinichenko Aug 22 '22 at 16:15
  • `string msg[size];` is a variable-length array, and [C++ doesn't have variable-length arrays](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard). – Some programmer dude Aug 22 '22 at 16:18
  • 4
    As for your problem, what you seem to want is [`std::next_permutation`](https://en.cppreference.com/w/cpp/algorithm/next_permutation). And if you're not allowed to use it, then the term you need to research is *permutation*. – Some programmer dude Aug 22 '22 at 16:20

1 Answers1

0

Write less loops based on indices, use more standard library code. Like this :

#include <algorithm>
#include <numeric>
#include <string>
#include <vector>
#include <iostream>

void output_sentence(const std::vector<std::string>& words, const std::vector<std::size_t>& indices)
{
    bool space{ false };

    for (const auto index : indices)
    {
        if (space) std::cout << " ";
        std::cout << words[index];
        space = true;
    }

    std::cout << "\n";
}

int main()
{
    
    std::vector<std::string> words{ "I","Am","Coding" };    // vector with words;
    std::vector<std::size_t> indices(words.size());         // vector of indices to permutate
    std::iota(indices.begin(), indices.end(), 0ul);         // fill indices from 0 to words.size()-1

    do
    {
        output_sentence(words, indices);
    } while (std::next_permutation(indices.begin(),indices.end())); // permutate indices

    return 0;
}

Live demo here : https://onlinegdb.com/706nqY0gy

Pepijn Kramer
  • 9,356
  • 2
  • 8
  • 19