C++ Primer 16 프로그래밍 연습
01
// palindrome.cpp
#include <iostream>
#include <string>
using namespace std;
bool is_palindrome(string & str);
int main()
{
string str;
cout << "문자열을 입력하세요 : ";
cin >> str;
if (is_palindrome(str))
cout << "화문입니다.\n";
else
cout << "화문이 아닙니다.\n";
return 0;
}
bool is_palindrome(string & str)
{
for (auto f = str.begin(), r = str.end(); f < r; )
{
if (*f++ != *--r)
return false;
}
return true;
}
02
// palindrome2.cpp
#include <iostream>
#include <string>
using namespace std;
bool is_palindrome(string & str);
int main()
{
string str;
cout << "문자열을 입력하세요 : ";
getline(cin, str);
if (is_palindrome(str))
cout << "화문입니다.\n";
else
cout << "화문이 아닙니다.\n";
return 0;
}
bool is_palindrome(string & str)
{
for (auto i = str.begin(); i != str.end(); ++i)
{
if (!isalpha(*i))
str.erase(i--);
else
*i = tolower(*i);
}
for (auto f = str.begin(), r = str.end(); f < r; )
{
if (*f++ != *--r)
return false;
}
return true;
}
03
// hangman_fromfile.cpp
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <cctype>
using namespace std;
int main()
{
vector<string> wordlist;
ifstream openFile("word.txt");
string temp;
while (openFile >> temp)
{
wordlist.push_back(temp);
}
const int NUM = wordlist.size();
std::srand(std::time(0));
char play;
cout << "영어 단어 게임을 하시겠습니까? <y/n> ";
cin >> play;
play = tolower(play);
while (play == 'y')
{
string target = wordlist[std::rand() % NUM];
int length = target.length();
string attempt(length, '-');
string badchars;
int guesses = 6;
cout << "수수께끼 단어를 추측해 보십시오.\n"
<< length << "개의 문자로 이루어져있습니다.\n"
<< "한 번에 한 문자씩 추측하십시오.\n"
<< "틀릴 수 있는 기회 : " << guesses << "번\n";
cout << "추측하는 단어 : " << attempt << endl;
while (guesses > 0 && attempt != target)
{
char letter;
cout << "문자를 추측하십시오 : ";
cin >> letter;
if (badchars.find(letter) != string::npos
|| attempt.find(letter) != string::npos)
{
cout << "이미 추측한 문자입니다. 다시 하십시오. \n";
continue;
}
int loc = target.find(letter);
if (loc == string::npos)
{
cout << "땡! 틀렸습니다.\n";
--guesses;
badchars += letter;
}
else
{
cout << "딩동댕! 맞았습니다. \n";
attempt[loc] = letter;
loc = target.find(letter, loc + 1);
while (loc != string::npos)
{
attempt[loc] = letter;
loc = target.find(letter, loc + 1);
}
}
cout << "추측하는 단어 : " << attempt << endl;
if (attempt != target)
{
if (badchars.length() > 0)
cout << "틀리게 추측한 문자들 : " << badchars << endl;
cout << "틀릴 수 있는 기회 : " << guesses << "번\n";
}
}
if (guesses > 0)
cout << "그렇습니다. 그것이 수수께끼 단어입니다.\n";
else
cout << "안타깝습니다. 수수께끼 단어는 " << target << "입니다.\n";
cout << "게임을 다시 하시겠습니까? <y/n> ";
cin >> play;
play = tolower(play);
}
cout << "프로그램을 종료합니다.\n";
return 0;
}
04
// reduce1.cpp
#include <iostream>
#include <algorithm>
#include <list>
using namespace std;
int reduce(long ar[], int n);
int main()
{
long ar[6] = {1, 2, 3, 1, 1, 1};
cout << reduce(ar, 6) << endl;
return 0;
}
int reduce(long ar[], int n)
{
list<long> ar_set(ar, ar + n);
ar_set.sort();
ar_set.unique();
for(list<long>::iterator i = ar_set.begin(); i != ar_set.end(); ++i)
cout << (*i) << endl;
return ar_set.size();
}
05
// reduce2.cpp
#include <iostream>
#include <algorithm>
#include <list>
using namespace std;
template<class T>
int reduce(T ar[], int n);
const int NUM = 6;
int main()
{
long ar[NUM] = {1, 2, 3, 1, 1, 1};
string ar_str[NUM] = {"abc", "wofi", "abc", "xvas", "fewfwe", "as"};
cout << reduce(ar, NUM) << endl;
cout << reduce(ar_str, NUM) << endl;
return 0;
}
template<class T>
int reduce(T ar[], int n)
{
list<T> ar_set(ar, ar + n);
ar_set.sort();
ar_set.unique();
for(typename list<T>::iterator i = ar_set.begin(); i != ar_set.end(); ++i)
cout << (*i) << endl;
return ar_set.size();
}
06
// bank_STL.cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <queue>
#include "xxx.h"
const int MIN_PER_HR = 60;
bool newcustomer(double x);
int main()
{
using std::cin;
using std::cout;
using std::endl;
using std::ios_base;
using std::queue;
std::srand(std::time(0));
cout << "사례 연구 : 히서 은행의 ATM\n";
cout << "큐의 최대 길이를 입력하십시오 : ";
int qs;
cin >> qs;
queue<Item> line;
cout << "시뮬레이션 시간 수를 입력하십시오 : ";
int hours;
cin >> hours;
long cyclelimit = MIN_PER_HR * hours;
cout << "시간당 평균 고객 수를 입력하십시오 : ";
double perhour;
cin >> perhour;
double min_per_cust;
min_per_cust = MIN_PER_HR / perhour;
Item temp;
long turnaways = 0;
long customers = 0;
long served = 0;
long sum_line = 0;
int wait_time = 0;
long line_wait = 0;
for (int cycle = 0; cycle < cyclelimit; cycle++)
{
if (newcustomer(min_per_cust))
{
if (line.size() == qs)
turnaways++;
else
{
customers++;
temp.set(cycle);
line.push(temp);
}
}
if (wait_time <= 0 && !line.empty())
{
temp = line.back();
line.pop();
wait_time = temp.ptime();
line_wait += cycle - temp.when();
served++;
}
if (wait_time > 0)
wait_time--;
sum_line += line.size();
}
if (customers > 0)
{
cout << " 큐에 줄을 선 고객 수 : " << customers << endl;
cout << "거래를 처리한 고객 수 : " << served << endl;
cout << " 발길을 돌린 고객 수 : " << turnaways << endl;
cout << " 평균 큐의 길이 : ";
cout.precision(2);
cout.setf(ios_base::fixed, ios_base::floatfield);
cout.setf(ios_base::showpoint);
cout << (double) sum_line / cyclelimit << endl;
cout << " 평균 대기 시간 : "
<< (double) line_wait / served << "분\n";
}
else
cout << "고객이 한 명도 없습니다!\n";
cout << "완료!\n";
return 0;
}
bool newcustomer(double x)
{
return (std::rand() * x / RAND_MAX < 1);
}
void Customer::set(long when)
{
processtime = std::rand() % 3 + 1;
arrive = when;
}
07
// Lotto.cpp
#include <iostream>
#include <algorithm>
#include <vector>
#include <random>
using namespace std;
vector<int> Lotto(int max, int n);
int main()
{
vector<int> winners;
winners = Lotto(51, 6);
for (int i = 0; i < 6; ++i)
cout << winners[i] << endl;
return 0;
}
vector<int> Lotto(int max, int n)
{
vector<int> temp;
vector<int> ret;
for (int i = 0; i < max; ++i)
temp.push_back(i + 1);
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
shuffle(temp.begin(), temp.end(), default_random_engine(seed));
vector<int>::iterator it;
it = temp.begin();
for (int i = 0; i < n; ++i)
{
ret.push_back((*it));
++it;
}
return ret;
}
08
// Pat&Mat.cpp
#include <iostream>
#include <list>
using namespace std;
int main()
{
list<string> Pat;
list<string> Mat;
list<string> PatandMat;
cout << "Mat의 친구들을 입력하세요 (끝내려면 quit) : \n";
string temp;
while (cin >> temp && temp != "quit")
Mat.push_back(temp);
Mat.sort();
cout << "Mat의 친구들 목록입니다.\n";
for (list<string>::iterator i = Mat.begin(); i != Mat.end(); ++i)
cout << (*i) << endl;
cout << "Pat의 친구들을 입력하세요 (끝내려면 quit) : \n";
while (cin >> temp && temp != "quit")
Pat.push_back(temp);
Pat.sort();
cout << "Pat의 친구들 목록입니다.\n";
for (list<string>::iterator i = Pat.begin(); i != Pat.end(); ++i)
cout << (*i) << endl;
PatandMat = Mat;
PatandMat.merge(Pat);
PatandMat.unique();
cout << "Pat&Mat의 친구들 목록입니다.\n";
for (list<string>::iterator i = PatandMat.begin(); i != PatandMat.end(); ++i)
cout << (*i) << endl;
return 0;
}
09
// sorttime.cpp
#include <iostream>
#include <vector>
#include <list>
#include <ctime>
#include <algorithm>
using namespace std;
const int NUM = 10000;
void show(const int i);
int main()
{
srand(time(nullptr));
vector<int> vi0;
for (int i = 0; i < NUM; i++)
vi0.push_back(rand() % NUM);
vector<int> vi = vi0;
list<int> li(vi0.begin(), vi0.end());
clock_t start, end;
double duration1, duration2, duration3;
start = clock();
sort(vi.begin(), vi.end());
end = clock();
duration1 = static_cast<double>(end - start);
cout << "vi 정렬 시간 : " << duration1 << endl;
start = clock();
li.sort();
end = clock();
duration2 = static_cast<double>(end - start);
cout << "li 정렬 시간 : " << duration2 << endl;
li.clear();
li.assign(vi0.begin(), vi0.end());
vi.clear();
vi.assign(li.begin(), li.end());
start = clock();
sort(vi.begin(), vi.end());
end = clock();
li.assign(vi.begin(), vi.end());
duration3 = static_cast<double>(end - start);
cout << "복사 -> 정렬 -> 재복사 시간 : " << duration3 << endl;
return 0;
}
10
// vect3_shared_ptr.cpp
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
struct Review {
std::string title;
int rating;
int price;
};
bool operator<(const std::shared_ptr<Review> & r1, const std::shared_ptr<Review> & r2);
bool worseThan(const std::shared_ptr<Review> & r1, const std::shared_ptr<Review> & r2);
bool worseprice(const std::shared_ptr<Review> & r1, const std::shared_ptr<Review> & r2);
bool FillReview(Review & rr);
void ShowReview(const std::shared_ptr<Review> & rr);
int main()
{
using namespace std;
vector<shared_ptr<Review>> books;
Review temp;
while (FillReview(temp))
{
shared_ptr<Review> pt (new Review(temp));
books.push_back(pt);
}
if (books.size() > 0)
{
cout << "감사합니다. 당신은 다음과 같이 "
<< books.size() << "개의 책 등급을 입력하셨습니다.\n"
<< "등급\t제목\n";
for_each(books.begin(), books.end(), ShowReview);
vector<shared_ptr<Review>> books_origin = books;
while (true)
{
cout << "어느 정렬 방식을 선택하시겠습니까?\n";
cout << "1.원래 순서\t2.알파벳 순서\t3.등급 오름차순\n";
cout << "4.등급 내림차순\t5.가격 오름차순\t6.가격 내림차순\n";
cout << "주어진 방식 이외의 입력을 받을시 프로그램이 종료됩니다.\n";
int n;
cin >> n;
if (n < 1 || n > 6)
{
cout << "프로그램을 종료합니다.\n";
return 0;
}
switch(n)
{
case 1:
cout << "원래 순서 : \n등급\t제목\t가격\n";
for_each(books_origin.begin(), books_origin.end(), ShowReview);
break;
case 2:
sort(books.begin(), books.end());
cout << "책 제목을 기준으로 정렬 : \n등급\t제목\t가격\n";
for_each(books.begin(), books.end(), ShowReview);
break;
case 3:
sort(books.begin(), books.end(), worseThan);
cout << "등급 오름차순 정렬 : \n등급\t제목\t가격\n";
for_each(books.begin(), books.end(), ShowReview);
break;
case 4:
sort(books.rbegin(), books.rend(), worseThan);
cout << "등급 오름차순 정렬 : \n등급\t제목\t가격\n";
for_each(books.begin(), books.end(), ShowReview);
break;
case 5:
sort(books.begin(), books.end(), worseprice);
cout << "가격 오름차순 정렬 : \n등급\t제목\t가격\n";
for_each(books.begin(), books.end(), ShowReview);
break;
case 6:
sort(books.rbegin(), books.rend(), worseprice);
cout << "가격 오름차순 정렬 : \n등급\t제목\t가격\n";
for_each(books.begin(), books.end(), ShowReview);
break;
}
}
}
else
cout << "프로그램을 종료합니다.\n";
return 0;
}
bool operator<(const std::shared_ptr<Review> & r1, const std::shared_ptr<Review> & r2)
{
if (r1->title < r2->title)
return true;
else if (r1->title == r2->title && r1->rating < r2->rating)
return true;
else
return false;
}
bool worseThan(const std::shared_ptr<Review> & r1, const std::shared_ptr<Review> & r2)
{
if (r1->rating < r2->rating)
return true;
else
return false;
}
bool worseprice(const std::shared_ptr<Review> & r1, const std::shared_ptr<Review> & r2)
{
if (r1->price < r2->price)
return true;
else
return false;
}
bool FillReview(Review & rr)
{
std::cout << "책 제목을 입력하십시오(끝내려면 quit를 입력) : ";
std::getline(std::cin, rr.title);
if (rr.title == "quit")
return false;
std::cout << "책 등급(0-10)을 입력하십시오 : ";
std::cin >> rr.rating;
if (!std::cin)
return false;
std::cout << "책 가격을 입력하십시오 : ";
std::cin >> rr.price;
if (!std::cin)
return false;
while (std::cin.get() != '\n')
continue;
return true;
}
void ShowReview(const std::shared_ptr<Review> & rr)
{
std::cout << rr->rating << "\t" << rr->title << "\t" << rr->price << std::endl;
}