본문 바로가기
<ALGORITHM>/NOTE

20210203(수)

by CodeGrimie 2021. 2. 3.

구조체 복습

#include <cstdio>
#include <cstring>
#include <clocale>

typedef struct {
    wchar_t name[20];
    wchar_t address[100];
    unsigned int age;
} Person;

void PersonSwap(Person* a, Person* b)
{
    Person temp = *a;
    *a = *b;
    *b = temp;
}

int main()
{
    Person GildongHong;
    wcscpy(GildongHong.name, L"홍길동");
    wcscpy(GildongHong.name, L"서울시 관악구 조원중앙로");
    GildongHong.age = 18;

    Person* He = &GildongHong;
    wprintf(L"%s", *(He).name);
    wprintf(L"%s", He->name);

    return (0);
}

큐와 구조체를 사용한 예시

#include <cstdio>
#include <clocale>
#include <ctime>
#include <cstdlib>
#include <queue>

#define USE_ARRAY 1

typedef struct {
    int a;
    int b;
    int c;
    int d;
}Node;

const static unsigned int NODE_SIZE = 5;

#if (USE_ARRAY)

Node nodeArray[NODE_SIZE];

int front = -1;
int end = -1;
int length = 0;

bool IsEmpty()
{
    if (front == -1 && end == -1)
        return true;
    else
        return false;
}


void Enqueue(Node value)
{
    //queue is full
    if ((end + 1) % NODE_SIZE == front)
        printf("Queue is full \n");
    else
    {
        //first element inserted
        if (front == -1)
            front = 0;
        //insert element at rear
        end = (end + 1) % NODE_SIZE;
        nodeArray[end] = value;
        length++;
    }
}

void Dequeue()
{
    if (IsEmpty())
        printf("Queue is empty\n");
    else
    {
        //only one element
        if (front == end)
            front = end = -1;
        else
            front = (front + 1) % NODE_SIZE;
        length--;
    }
}

#else

std::queue<Node> nodeQueue;

#endif

bool CompareNode(Node& a, Node& b)
{
    if (a.a != b.a)
        return (false);
    if (a.b != b.b)
        return (false);
    if (a.c != b.c)
        return (false);
    if (a.d != b.d)
        return (false);

    return (true);
}

void PrintNode(Node node)
{
    printf("{ %d, %d, %d, %d }", node.a, node.b, node.c, node.d);
}

int main()
{
    _wsetlocale(LC_ALL, L"Korean");
    srand(time(nullptr));

    for (int i = 0; i < NODE_SIZE; i++)
    {
        Node temp;
        temp.a = rand() % 10;
        temp.b = rand() % 10;
        temp.c = rand() % 10;
        temp.d = rand() % 10;
#if (USE_ARRAY)
        Enqueue(temp);
#else
        nodeQueue.push(temp);
#endif
    }

    while (1)
    {
#if (USE_ARRAY)
        if (IsEmpty())
        {
            break;
        }
#else
        if (nodeQueue.empty())
        {
            break;
        }
#endif
        Node playerAnswer = { 0 };
        wprintf(L"플레이어 값 : ");
        scanf_s("%d %d %d %d", &playerAnswer.a, &playerAnswer.b, &playerAnswer.c, &playerAnswer.d);

#if (USE_ARRAY)
        if (!CompareNode(nodeArray[front], playerAnswer))
#else
        if (!CompareNode(nodeQueue.front(), playerAnswer))
#endif
        {
            printf("> FAILED\n");
            printf("CPU    NODE : ");
#if (USE_ARRAY)
            PrintNode(nodeArray[front]);
#else
            PrintNode(nodeQueue.front());
#endif
            printf("\n");
            printf("PLAYER NODE : ");
            PrintNode(playerAnswer);
            printf("\n");
        }
        else
        {
            printf("> SUCCESS\n");
            printf("CPU NODE : ");
#if (USE_ARRAY)
            PrintNode(nodeArray[front]);
#else
            PrintNode(nodeQueue.front());
#endif
            printf("\n");
            printf("PLAYER NODE : ");
            PrintNode(playerAnswer);
            printf("\n");
        }
#if (USE_ARRAY)
        Dequeue();
        printf("REMAIN QUEUE : %d\n", length);
#else
        nodeQueue.pop();
        printf("REMAIN QUEUE : %d\n", nodeQueue.size());
#endif
    }

    return (0);
}

쓰레드(Thread)

#include <cstdio>
#include <ctime>
#include <clocale>
#include <thread>
#include "Windows.h"

#define FRAME   60
#define FPS     (1000/60)

using std::thread;

void func1(int cycle)
{
    for (int i = 0; i < cycle; i++)
    {
        wprintf(L"쓰레드 1 동작 중..\n");
        Sleep(1000);
    }
}

void func2()
{
    for (int i = 0; i < 10; i++)
    {
        wprintf(L"쓰레드 2 동작 중..\n");
        Sleep(1000);
    }
}

void func3()
{
    for (int i = 0; i < 10; i++)
    {
        wprintf(L"쓰레드 3 동작 중..\n");
        Sleep(1000);
    }
}

int main()
{
    _wsetlocale(LC_ALL, L"Korean");

    thread t1(func1, 10);
    thread t2(func2);
    thread t3(func3);

    t1.join();
    t2.join();
    t3.join();

    return (0);
}

쓰레드를 이용한 큐 게임

#include <cstdio>
#include <clocale>
#include <ctime>
#include <cstdlib>
#include <queue>
#include <thread>
#include "Windows.h"

using std::thread;

#define FRAME   60
#define FPS     (1000/60)
#define SECOND  1000

typedef struct {
    int a;
    int b;
    int c;
    int d;
}Node;

const static unsigned int NODE_SIZE = 5;

std::queue<Node> nodeQueue;
Node aiAnswer = { 0 };

bool CompareNode(Node& a, Node& b)
{
    if (a.a != b.a)
        return (false);
    if (a.b != b.b)
        return (false);
    if (a.c != b.c)
        return (false);
    if (a.d != b.d)
        return (false);

    return (true);
}

void PrintNode(Node node)
{
    printf("{ %d, %d, %d, %d }", node.a, node.b, node.c, node.d);
}

void ThreadEnqueue()
{
    while (1)
    {
        Node temp;
        temp.a = rand() % 10;
        temp.b = rand() % 10;
        temp.c = rand() % 10;
        temp.d = rand() % 10;

        nodeQueue.push(temp);
        wprintf(L"CPU QUEUE: %d %d %d %d\n", nodeQueue.back().a, nodeQueue.back().b, nodeQueue.back().c, nodeQueue.back().d);
        Sleep(1.5f * SECOND);
    }
}

void ThreadInput()
{
    while (1)
    {
        Node temp;
        temp.a = rand() % 10;
        temp.b = rand() % 10;
        temp.c = rand() % 10;
        temp.d = rand() % 10;
        aiAnswer = temp;

        wprintf(L"CPU NODE : %d %d %d %d\n", aiAnswer.a, aiAnswer.b, aiAnswer.c, aiAnswer.d);
        Sleep(2 * SECOND);
    }
}

void ThreadRoop()
{
    while (1)
    {
        if (nodeQueue.empty())
        {
            break;
        }

        wprintf(L"############\n");
        if (!CompareNode(nodeQueue.front(), aiAnswer))
        {
            printf("> FAILED\n");
            printf("CPU QUEUE : ");

            PrintNode(nodeQueue.front());

            printf("\n");
            printf("CPU NODE : ");
            PrintNode(aiAnswer);
            printf("\n");
        }
        else
        {
            printf("> SUCCESS\n");
            printf("CPU QUEUE : ");

            PrintNode(nodeQueue.front());

            printf("\n");
            printf("CPU NODE : ");
            PrintNode(aiAnswer);
            printf("\n");
        }
        nodeQueue.pop();
        printf("REMAIN QUEUE : %d\n", nodeQueue.size());
        wprintf(L"############\n");
        Sleep(2 * SECOND);
    }
}

int main()
{
    _wsetlocale(LC_ALL, L"Korean");
    time_t startTime = time(nullptr);
    srand((int)startTime);

    thread enqueueThread(ThreadEnqueue);
    thread roopThread(ThreadRoop);
    thread inputThread(ThreadInput);

    enqueueThread.join();
    inputThread.join();
    roopThread.join();


    return (0);
}

쓰레드를 사용한 토이 프로젝트

#include <cstdio>
#include <clocale>
#include <ctime>
#include <cstdlib>
#include <thread>
#include "Windows.h"

using std::thread;

#define FRAME   60
#define FPS     (1000/60)
#define SECOND  1000

typedef struct {
    wchar_t name[20];
    int hp;
    int attack;
}Actor;

static bool isSimulationRunning = true;
static unsigned int roundCount = 0;

const static wchar_t ACTOR_NAME_ARRAY[5][20] = {
    L"당나귀",
    L"쿼카",
    L"고양이",
    L"토끼",
    L"햄스터"
};

Actor Player = { (wchar_t)nullptr, 0, 0 };
Actor Monster = { (wchar_t)nullptr, 0, 0 };

void SetActor(Actor& actor)
{
    wcscpy_s(actor.name, ACTOR_NAME_ARRAY[rand() % 5]);
    actor.hp = (rand() % 5 + 1) * 100;
    actor.attack = (rand() % 5 + 1) * 10;
}


void ThreadAttack()
{
    while (isSimulationRunning)
    {
        wprintf(L"□□□□□□□□□□□□□□□□□□\n");
        wprintf(L"           ROUND %d\n", roundCount);
        wprintf(L"NAME   :   %s       %s\n", Player.name, Monster.name);
        wprintf(L"HP     :   %d       %d\n", Player.hp, Monster.hp);
        wprintf(L"ATTACK :   %d       %d\n", Player.hp, Monster.hp);


        bool isFront = (rand() % 2);

        if (isFront)
        {
            wprintf(L"[몬스터 선공]\n");
            Player.hp -= Monster.attack;
            wprintf(L"\'%s\'가 \'%s\'에게 \'%d\'만큼 데미지를 가했다.\n", Monster.name, Player.name, Monster.attack);
            Monster.hp -= Player.attack;
            wprintf(L"\'%s\'가 \'%s\'에게 \'%d\'만큼 데미지를 가했다.\n", Player.name, Monster.name, Monster.attack);
        }
        else
        {
            wprintf(L"[플레이어 선공]\n");
            Monster.hp -= Player.attack;
            wprintf(L"\'%s\'가 \'%s\'에게 \'%d\'만큼 데미지를 가했다.\n", Monster.name, Player.name, Monster.attack);
            Player.hp -= Monster.attack;
            wprintf(L"\'%s\'가 \'%s\'에게 \'%d\'만큼 데미지를 가했다.\n", Player.name, Monster.name, Monster.attack);
        }

        if (Player.hp <= 0 || Monster.hp <= 0)
        {
            isSimulationRunning = false;

            wprintf(L"□□□□□□□□□□□□□□□□□□\n");
            if (Player.hp > Monster.hp)
            {
                wprintf(L"플레이어가 승리했습니다.\n");
            }
            else if (Player.hp < Monster.hp)
            {
                wprintf(L"몬스터가 승리했습니다.\n");
            }
            else
            {
                wprintf(L"무승부입니다.\n");
            }
        }

        roundCount++;
        Sleep(SECOND);
    }
}

int main()
{
    _wsetlocale(LC_ALL, L"Korean");
    srand((unsigned int)time(nullptr));
    SetActor(Player);
    SetActor(Monster);

    thread attackThread(ThreadAttack);
    attackThread.join();


    return (0);
}

리스트 예시

#include <cstdio>
#include <list>

using namespace std;

int main()
{
    list<int> a;

    a.push_back(0);
    a.push_back(1);
    a.push_front(2);
    a.push_front(3);

    list<int>::iterator index = a.begin();
    a.insert(index, 4);

    for (auto i = a.begin(); i != a.end(); i++)
    {
        printf("%d ", *i);
    }

    return (0);
}

리스트를 사용한 도서 관리 프로그램

#include <cstdio>
#include <clocale>
#include <list>

using namespace std;

enum class BOOK_TYPE {
    MODERN = 1,
    FANTASY,
    HISTORY,
    CHILDREN
};

typedef struct {
    BOOK_TYPE type;
    wchar_t title[20];
}Book;

char todo = 0;

int main()
{
    _wsetlocale(LC_ALL, L"Korean");

    list<Book>bookList;

    while (1)
    {
        wprintf(L"< 현재 책 목록 >\n");
        for (auto i = bookList.begin(); i != bookList.end(); i++)
        {
            wchar_t bookType[20];
            switch ((*i).type)
            {
            case BOOK_TYPE::MODERN:
                wcscpy_s(bookType, L"현대문학");
                break;
            case BOOK_TYPE::FANTASY:
                wcscpy_s(bookType, L"판타지");
                break;
            case BOOK_TYPE::HISTORY:
                wcscpy_s(bookType, L"역사");
                break;
            case BOOK_TYPE::CHILDREN:
                wcscpy_s(bookType, L"아동문학");
                break;
            default:
                wcscpy_s(bookType, L"잘못된 책 코드입니다.");
                break;
            }
            wprintf(L"[%s : %s]\n", bookType, (*i).title);
        }
        wprintf(L"\n");

        wprintf(L"A : 도서추가 D : 도서제거\n");
        wprintf(L"업무 선택 : ");
        todo = 0;
        scanf_s("%c", &todo, sizeof(todo));

        Book temp;
        wprintf(L"책을 입력하세요 : ");
        wscanf_s(L"%d %s", &(temp.type), temp.title, sizeof(temp.title));
        wprintf(L"\n");

        if (todo == 'A' || todo == 'a')
        {
            list<Book>::iterator index = bookList.begin();
            for (index = bookList.begin(); index != bookList.end(); index++)
            {
                if ((*index).type == temp.type)
                {
                    bookList.insert(index, temp);
                    break;
                }
            }
            if (index == bookList.end())
            {
                bookList.push_back(temp);
            }
        }
        else
        {
            list<Book>::iterator index = bookList.begin();
            for (index = bookList.begin(); index != bookList.end(); index++)
            {
                if ((*index).type == temp.type)
                {
                    bookList.erase(index);
                    break;
                }
            }
        }
    }

    return (0);
}

 

'<ALGORITHM> > NOTE' 카테고리의 다른 글

20210208(월)  (0) 2021.02.08
20210201(월)  (0) 2021.02.01
20210127(수)  (0) 2021.01.27
20210121(목)  (0) 2021.01.21
20210120(수)  (0) 2021.01.20

댓글