2011-12-03 36 views
2

ユーザーが入力した4文字の文字列をスクランブルするプログラムを作成する必要があります。 (例TESTはtset、ttseなどのようにスクランブルすることができます。)うまく動作するプログラムがありますが、それは4要素のchar配列に限られています。それを作る方法があるかどうかを知りたいのですが、あらかじめ決められたサイズを持つ必要があります。シャッフル文字列

//4 letter word scrambler (ex. test tets tset...) 
int counter=0; 
int main(int argc, char* argv[]) 
{ 
    char str[4]; 
    cout << "Please enter a word: "; //ask for input 
    cin >> str; 
    counter+=1; // set counter to 1 
    cout << counter << " " << str << endl; 
    for (int i=0;i<3;i++){// iteration through one full loop in array 
     swap(str[i], str[i+1]); //swap two elements as iterates through array 
     counter+=1;//add 1 to counter each time 
     cout <<counter<<" "<< str << endl; 
    } 
    for (int i=0;i<3;i++){ 
     swap(str[i], str[i+1]); 
     counter+=1; 
     cout << counter<< " " << str << endl; 
    } 
    for (int i=0;i<3;i++){ 
      swap(str[i], str[i+1]); 
     counter+=1; 
     cout << counter << " " << str << endl; 
    } 
    for (int i=0;i<2;i++){ 
      swap(str[i], str[i+1]); 
     counter+=1; 
     cout << counter << " " << str << endl; 
    } 

    system("PAUSE"); 
    return 0; 
} 
+0

だけで行う簡単な[フィッシャーイエーツ](のhttp:/ /en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle)シャッフル。私はC++を使用していないので、すでにこれを行うには素晴らしいものがあるかもしれませんが、wikiの記事はかなりいいですし、単純なアルゴリズムです。 shuffleが* array *全体をどのように実行するかに注目してください(これが任意のサイズのコレクションに拡張可能にしています)。このインプリメンテーションを使用して、「インプレース出力」を行うことができます(シャッフルされた配列結果を保存する必要はありません)。 –

+1

あなたはすべての順列を探しますか、それともランダムにしたいですか? – Dani

+0

あなたの初期のソリューションは、何が起きても正確に12のソリューションを提供しますので、多くの場合間違っていると思います。異なった位置にある同じ文字を区別したいのですか?だから、反復の有無にかかわらず順列が欲しいですか? _(** TTTT **の結果は** 4!**または** 1 **?)_ – ch0kee

答えて

9

を一度文字列をシャッフルしたい場合:

string str; 
cout << "Please enter a word: "; //ask for input 
cin >> str; 
counter+=1; // set counter to 1 
cout << counter << " " << str << endl; 
for (int i=0;i<str.size();i++){ 
    // iteration through one full loop in array 

とチェックアウトの文字列をシャッフルするより良い方法について

単語の文字のすべての順列を印刷します。両方とも、C++標準ライブラリを使用するとかなりシンプルです。

このコードの最初のビットは、単一のランダムシャッフルを行います。

#include <algorithm> 
#include <iostream> 
#include <string> 
using namespace std; 

int main() 
{ 
    string str; 
    cout << "Please enter a word: "; //ask for input 
    cin >> str; 
    random_shuffle(str.begin(), str.end()); 
    cout << str << '\n'; 
} 

印刷物に文字列のすべての順列を次

#include <algorithm> 
#include <iostream> 
#include <string> 
using namespace std; 

int main() 
{ 
    string str; 
    cout << "Please enter a word: "; //ask for input 
    cin >> str; 
    sort(str.begin(), str.end()); 
    do { 
     cout << str << '\n'; 
    } while (next_permutation(str.begin(), str.end())); 
} 
0

文字0 -> n-1から文字列によって長さN
反復の文字列をスクランブルする簡単な方法があります。
各繰り返しで2つのランダムなインデックスi,jrandom(n)経由)を選択し、これらの2つのインデックスを入れ替えます。 これは、一様ランダムスクランブリングであることを証明できます。

+0

srand()とrand()を使用しますか?それらは私が知っている唯一のランダム関数です。 –

0

char [4]の代わりにstd :: stringを使用できます。 (文字列は常にchar []に優先します)。あなたのコードは次のようになりますか、私はよく分からない

std::next_permutation 
関連する問題