1. 程式人生 > >《程式設計珠璣》程式碼之路4:變位詞集合完整程式碼

《程式設計珠璣》程式碼之路4:變位詞集合完整程式碼

字典的變位詞集合:變位詞就是由相同的字母的不同順序組成的單詞,例如pots和stop就是變位詞,按構成字母順序排序的opst就是他兩的標誌。

現在給一個字典,把變位詞一起輸出:

例如一個字典:

pans
pots
opt
snap
stop
tops

那麼對應的標誌分別是:

anps pans
opst pots
opt opt
anps snap
opst stop
opst tops

最後輸出:

anps: pans snap 
opst: pots stop tops 
opt: opt 

#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;

class Word{
public:
	string word;//單詞
	string sign;//標誌

	Word(){
		word = "";
		sign = "";
	}

	bool operator < (const Word &b) const {
		return sign < b.sign;
	}
}dict[10000];

int nWord = 0;

//讀取資料
int readData(Word dict[]);
//計算每個單詞的標誌sign
int Sign(Word dict[]);
//按標誌sign給字典排序
int Sort(Word dict[]);
//按照標誌輸出單詞
int Squash(Word dict[]);

int main(){
	freopen("in.txt", "r", stdin);
	freopen("out.txt", "w", stdout);

	readData(dict);
	Sign(dict);
	Sort(dict);
	Squash(dict);

	return 0;
}

int readData(Word dict[]){
	char word[100];
	
	while (scanf("%s", &word) != EOF){
		dict[nWord].word = dict[nWord].sign = word;
		cout << dict[nWord].word << endl;
		nWord++;
	}
	return 0;
}

int Sign(Word dict[]){

	freopen("sign.txt", "w", stdout);
	for (int i = 0; i < nWord; ++i){
		sort(dict[i].sign.begin(), dict[i].sign.end());
		cout << dict[i].sign << ' ' << dict[i].word << endl;
	}
	return 0;
}

int Sort(Word dict[]){
	freopen("sort.txt", "w", stdout);
	sort(dict, dict + nWord);

	for (int i = 0; i < nWord; ++i){
		cout << dict[i].sign << ' ' << dict[i].word << endl;
	}
	return 0;
}

int Squash(Word dict[]){
	freopen("out.txt", "w", stdout);

	string oldSign = "";
	int curWord = 0;

	cout << dict[0].sign << ": ";
	for (int i = 0; i < nWord; ++i){
		if (oldSign != dict[i].sign && curWord > 0){
			cout << endl;
			cout << dict[i].sign << ": ";
		}

		curWord++;
		oldSign = dict[i].sign;
		cout << dict[i].word << ' ';
	}

	return 0;
}