C++/C++로 쉽게 풀어쓴 자료구조

C++로 쉽게 풀어쓴 자료구조 프로그래밍 프로젝트 4

꾸준함. 2017. 9. 27. 00:13

[문제 1, 2]


CircularStudent.h

/*

가장 간단한 방법의 미팅 주선 프로그램을 만들려고 한다.

남학생과 여학생의 큐를 각각 만들어 학생이 등록하면 큐에 넣는다.

가장 먼저 등록한 남학생과 여학생을 뽑아 미팅을 주선하는 일을 반복한다.

만약 여학생 큐가 비었거나 남학생 큐가 비었으면 한쪽 큐에 있는 학생들은 기다려야 한다.

 

조건

(1) 등록한 학생 정보를 수동으로 입력하도록 사용자 인터페이스를 완성하라

(2) 원형 큐를 사용하여 남학생 큐와 여학생 큐를 구현해보라

*/

#include <iostream>

#include <cstdlib>

#include <cstring>

using namespace std;

 

#define MAX_QUEUE_SIZE 100

 

inline void error(char *str)

{

        cout << str << endl;

        exit(1);

}

 

class CircularStudent

{

protected:

        int front; //첫 번째 요소 앞의 위치

        int rear; //마지막 요소 위치

        char **data;

public:

        CircularStudent()

        {

               front = rear = 0;

               data = new char*[MAX_QUEUE_SIZE];

               for (int i = 0; i < MAX_QUEUE_SIZE; i++)

                       data[i] = new char[20];

        }

        ~CircularStudent()

        {

               for (int i = 0; i < MAX_QUEUE_SIZE; i++)

                       delete[]data[i];

               delete[]data;

        }

        bool isEmpty()

        {

               return front == rear;

        }

        bool isFull()

        {

               return (rear + 1) % MAX_QUEUE_SIZE == front;

        }

        void enqueue(char *name) //큐에 삽입

        {

               if (isFull())

                       error("error:큐가 포화상태입니다\n");

               else

               {

                       rear = (rear + 1) % MAX_QUEUE_SIZE;

                       strcpy(data[rear], name);

               }

        }

        char *dequeue() //첫 항목을 큐에서 빼서 반환

        {

               if (isEmpty())

                       error("Error: 큐가 공백상태입니다\n");

               else

               {

                       front = (front + 1) % MAX_QUEUE_SIZE;

                       return data[front];

               }

        }

        char *peek() //첫 항목을 큐에서 빼지 않고 반환

        {

               if (isEmpty())

                       error("Error: 큐가 공백상태입니다\n");

               else

                       return data[(front + 1) % MAX_QUEUE_SIZE];

        }

        void display() //큐의 모든 내용을 순서대로 출력

        {

               cout << "학생 : ";

               if (!isEmpty())

               {

                       int maxi = (front < rear) ? rear : rear + MAX_QUEUE_SIZE;

                       for (int i = front + 1; i <= maxi; i++)

                              cout << data[i%MAX_QUEUE_SIZE] << " ";

               }

               else

                       cout << "학생이 아직 없습니다";

               cout << endl;

        }

};


CircularStudentMeeting.cpp

#include "CircularStudent.h"

 

int main(void)

{

        CircularStudent male, female; //남자 여자

        char name[20];

        char gender; //성별

        cout << "미팅 주선 프로그램입니다" << endl;

        cout << "프로그램 종료 원하시면 이름에 '그만'을 입력해주세요" << endl << endl;

        while (1)

        {

               cout << "고객이름: ";

               cin >> name;

               if (!strcmp(name, "그만"))

                       break;

               cout << "성별을 입력하세요(f or m) ";

               cin >> gender;

               if (gender == 'm')

                       male.enqueue(name);

               else if (gender == 'f')

                       female.enqueue(name);

 

               if (!male.isEmpty() && !female.isEmpty()) //여자 남자 한쌍을 이룰 경우

               {

                       char boyfriend[20], girlfriend[20];

                       strcpy(boyfriend, male.dequeue());

                       strcpy(girlfriend, female.dequeue());

 

                       cout << "커플이 탄생했습니다! " << boyfriend << " " << girlfriend << endl << endl;

               }

               else

                       cout << "아직 대상자가 없습니다. 기다려주십시요." << endl << endl;

        }

        return 0;

}

[문제 3]


CircularStudentDeque.h

/*

(3)덱을 이용하여 남학생 큐와 여학생 큐를 구현하고 큐에 입력될 때 즉시 원하는지를

물어보고 즉시 원한다고 하면 큐의 맨 처음에 삽입한다.

*/

#include "CircularStudent.h"

 

class CircularStudentDeque :public CircularStudent

{

public:

        CircularStudentDeque()

        {

               front = rear = 0;

               data = new char*[MAX_QUEUE_SIZE];

               for (int i = 0; i < MAX_QUEUE_SIZE; i++)

                       data[i] = new char[20];

        }

        ~CircularStudentDeque()

        {

               for (int i = 0; i < MAX_QUEUE_SIZE; i++)

                       delete[]data[i];

               delete[]data;

        }

        void addRear(char *name)

        {

               enqueue(name);

        }

        char *deleteFront()

        {

               return dequeue();

        }

        char *getFront()

        {

               return peek();

        }

        void addFront(char *name) //전단에 삽입

        {

               if (isFull())

                       error("Error: 덱이 포화상태입니다\n");

               else

               {

                       strcpy(data[front], name);

                       front = (front - 1 + MAX_QUEUE_SIZE) % MAX_QUEUE_SIZE; //front 감소

               }

        }

        char *deleteRear() //후단에서 삭제

        {

               if (isEmpty())

                       error("Error: 덱이 공백상태입니다\n");

               else

               {

                       char *ret;

                       strcpy(ret, data[rear]);

                       rear = (rear - 1 + MAX_QUEUE_SIZE) % MAX_QUEUE_SIZE;

                       return ret;

               }

        }

        char *getRear() //후단에서 peek

        {

               if (isEmpty())

                       error("Error: 덱이 공백상태이빈다\n");

               else

                       return data[rear];

        }

        void display() //CircularQueue::display() 오버라이딩

        {

               cout << "덱의 내용: ";

               if (!isEmpty())

               {

                       int maxi = (front < rear) ? rear : rear + MAX_QUEUE_SIZE;

                       for (int i = front + 1; i <= maxi; i++)

                              cout << data[i%MAX_QUEUE_SIZE] << " ";

               }

               else

                       cout<<"학생이 아직 없습니다";

               cout << endl;

        }

};


DequeStudentMeeting.cpp

#include "CircularStudentDeque.h"

 

int main(void)

{

        CircularStudentDeque male, female; //남자 여자

        char answer; //답변

        char gender; //성별

        char name[20];

        cout << "미팅 주선 프로그램입니다" << endl;

        cout << "프로그램 종료 원하시면 이름에 'stop'을 입력해주세요" << endl << endl;

        while (1)

        {

               cout << "고객이름: ";

               cin >> name;

               if (!strcmp(name, "그만"))

                       break;

               cout << "성별을 입력하세요(f or m) ";

               cin >> gender;

               cout << "주선을 즉시 원하십니까?";

               cin >> answer;

               if (gender == 'm' && answer == 'y')

                       male.addFront(name);

               else if (answer == 'n')

                       male.addRear(name);

               else if (gender == 'f' && answer == 'y')

                       female.addFront(name);

               else if (answer == 'n')

                       female.addRear(name);

 

               if (!male.isEmpty() && !female.isEmpty()) //여자 남자 한쌍을 이룰 경우

               {

                       char boyfriend[20], girlfriend[20];

                       strcpy(boyfriend, male.deleteFront());

                       strcpy(girlfriend, female.deleteFront());

 

                       cout << "커플이 탄생했습니다! " << boyfriend << " " << girlfriend << endl << endl;

               }

               else

                       cout << "아직 대상자가 없습니다. 기다려주십시요." << endl << endl;

        }

        return 0;

}


[문제 4]


CircularIntQueue.h

/*

(4)은행 서비스 시뮬레이션 프로그램을 참고하여 자동으로 시뮬레이션 할 수 있는 프로그램을 설계하고 구현하라

*/

#include <iostream>

#include <cstdlib>

#include <cstring>

using namespace std;

 

#define MAX_QUEUE_SIZE 100

 

inline void error(char *str)

{

        cout << str << endl;

        exit(1);

}

 

class CircularIntQueue

{

protected:

        int front; //첫 번째 요소 앞의 위치

        int rear; //마지막 요소 위치

        int data[MAX_QUEUE_SIZE];

public:

        CircularIntQueue()

        {

               front = rear = 0;

        }

        bool isEmpty()

        {

               return front == rear;

        }

        bool isFull()

        {

               return (rear + 1) % MAX_QUEUE_SIZE == front;

        }

        void enqueue(int val) //큐에 삽입

        {

               if (isFull())

                       error("error:큐가 포화상태입니다\n");

               else

               {

                       rear = (rear + 1) % MAX_QUEUE_SIZE;

                       data[rear] = val;

               }

        }

        int dequeue() //첫 항목을 큐에서 빼서 반환

        {

               if (isEmpty())

                       error("Error: 큐가 공백상태입니다\n");

               else

               {

                       front = (front + 1) % MAX_QUEUE_SIZE;

                       return data[front];

               }

        }

        int peek() //첫 항목을 큐에서 빼지 않고 반환

        {

               if (isEmpty())

                       error("Error: 큐가 공백상태입니다\n");

               else

                       return data[(front + 1) % MAX_QUEUE_SIZE];

        }

        void display() //큐의 모든 내용을 순서대로 출력

        {

               cout << "학생 : ";

               if (!isEmpty())

               {

                       int maxi = (front < rear) ? rear : rear + MAX_QUEUE_SIZE;

                       for (int i = front + 1; i <= maxi; i++)

                              cout << data[i%MAX_QUEUE_SIZE] << " ";

               }

               else

                       cout << "학생이 아직 없습니다";

               cout << endl;

        }

};


CircularSimulator.h

#include "CircularIntQueue.h"

#include <ctime>

 

class CircularSimulator

{

private:

        int maxStudent; //참여한 총 인원 수

        double perticipate; //단위시간에 등록하는 학생 수

        int couple; //미팅 주선에 성공한 커플의 쌍의 번호

        int count; //학생 번호

        int student; //참여한 학생 수

        double probArrival; //단위시간 당 미팅에 나오는 평균 학생 수

        int m;

        int f;

        int random; //성별 무작위

        CircularIntQueue que;

 

        //랜덤 숫자를 생성하여 고객 도착 여부와 서비스 시간 자동 생성 코드

        double Random()

        {

               return rand() / (double)RAND_MAX;

        }

        bool IsNewStudent()

        {

               return (Random() > probArrival);

        }

public:

        CircularSimulator()

        {

               count = couple = m = f = student = 0;

        }

        void readSimulationParameters()

        {

               cout << "시뮬레이션 할 최대 인원(:100) = ";

               cin >> maxStudent;

               cout << "단위시간에 나오는 학생 수(:0.5) = ";

               cin >> probArrival;

        }

        void run()

        {

               CircularIntQueue male, female; //남학생 여학생

               while (count < maxStudent)

               {

                       cout << count + 1 << "번째 시도" << endl;

                       if (IsNewStudent())

                       {

                              student++;

                              random = rand() % 2;

                              if (!random)

                              {

                                      male.enqueue(count);

                                      m++;

                                      cout << "남학생이 참석했습니다" << endl;

                              }

                              else

                              {

                                      female.enqueue(count);

                                      f++;

                                      cout << "여학생이 참석했습니다" << endl;

                              }

                       }

                       else

                       {

                              cout << "아쉽게도 " << count << " 학생은 바빠서 참석하지 못했습니다" << endl;

                       }

 

                       if (!male.isEmpty() && !female.isEmpty())

                       {

                              int boyfriend, girlfriend;

                              boyfriend = male.dequeue();

                              girlfriend = female.dequeue();

                              cout << "미팅 성공! " << boyfriend << "" << girlfriend << "가 커플이 되었습니다" << endl << endl;

                              couple++;

                       }

                       else

                              cout << "아직 대상자가 없습니다. 기다려주십시오" << endl << endl;

                       count++;

               }

        }

        void printStat()

        {

               cout << "=================================================================" << endl;

               cout << "미팅에 지원한 총 학생 수= " << maxStudent << endl;

               cout << "미팅에 참여한 학생 수= " << student << endl;

               cout << "성비(남학생:여학생) = " << m << " : " << f << endl;

               cout << "성사된 커플 수= " << couple << endl;

               cout << "안타까운 솔로들= " << maxStudent - 2 * (couple) << endl;

        }

};


SimulationMeeting.cpp

/*

은행 서비스 시뮬레이션 프로그램을 참고하여 자동으로 시뮬레이션 할 수 있는 프로그램을 설계하고 구현하라

*/

#include "CircularSimulator.h"

 

int main(void)

{

        srand((unsigned)time(NULL));

        CircularSimulator sim;

        sim.readSimulationParameters();

        sim.run();

        sim.printStat();

        return 0;

}



개발환경:Visual Studio 2017


지적, 조언, 질문 환영입니다! 댓글 남겨주세요~


[참고] C++로 쉽게 풀어쓴 자료구조


*4번 문제(Simulator)는 9/27 수정했습니다

반응형