//================================================================
// Enums

enum class FuelType
{
	GASOLINE
};

enum class EngineType
{
	V8
};

//================================================================
// Functions

const char* etos(const FuelType type)
{
	if (type == FuelType::GASOLINE)
	{
		return "FuelType";
	}
}
const char* etos(const EngineType type)
{
	if (type == EngineType::V8)
	{
		return "V8";
	}
}

//================================================================
// Classes

class Engine
{
public:
	Engine(uint32_t horsePower, FuelType fuelType, EngineType engineType)
		: mHorsePower(horsePower), mFuelType(fuelType), mEngineType(engineType)
	{

	}

	void Print()
	{
		cout << "Engine: " << mHorsePower << "HP | Fuel: " << etos(mFuelType) << " | Type: " << etos(mEngineType) << endl;
	}

private:
	uint32_t mHorsePower;
	FuelType mFuelType;
	EngineType mEngineType;
};

class Car
{
public:
	Car(const string& brand, const string& modelName, uint32_t modelYear, const Engine& engine)
		: mBrand(brand), mModelName(modelName), mModelYear(modelYear)
	{
		mEngine = new Engine(engine);
	}

	~Car()
	{
		if (mEngine == nullptr)
		{
			delete mEngine;
		}
	}

	void PrintCarInfo()
	{
		cout << "Car: " << mBrand << " " << mModelName << " (" << mModelYear << ")" << endl;
	}

	void PrintEngine()
	{
		mEngine->Print();
	}

private:
	string mBrand;
	string mModelName;
	uint32_t mModelYear;
	Engine* mEngine;
};


//================================================================
// Main
int main()
{
	Engine myEngine{ 450,FuelType::GASOLINE, EngineType::V8 };
	Car myCar("Ford", "Mustang", 2022, myEngine);

	myCar.PrintCarInfo();
	myCar.PrintEngine();

    return 0;
}

 
//================================================================
// Classes

 /**
  * @class Item
  * @brief 게임 내에서 사용되는 아이템 정보를 나타내는 클래스
  *
  * 아이템의 이름, 설명, 무게, 개수 등 정보를 담고 있음.
  * Inventory 및 ItemManager와 공유를 위해 shared_ptr로 관리됨.
  *
  * @note 아이템마다 고유 ID로 관리되면 더 빠른 탐색이 가능할듯!
  * 또한 ItemManager를 Inventory에서 delete시켜버릴 수 있는 문제가 있음.
  */

class Item
{
public:
    Item(const string& name, const string& desc, double weight, uint32_t quantity = 0)
        :mName(name), mDesc(desc), mWeight(weight), mQuantity(quantity) {
    }

    void Print()
    {
        cout << "Item: " << mName << " - " << mDesc << " (x" << mQuantity << ") | Weight: " << mWeight << endl;
    }

    const string& GetName() const
    {
        return mName;
    }

    void AddQuantity(uint32_t num)
    {
        mQuantity += num;
    }

private:

    string mName;
    string mDesc;
    double mWeight;
    uint32_t mQuantity;
};

/**
 * @class ItemManager
 * @brief 모든 아이템 정의를 관리하는 클래스
 *
 * 아이템의 기본 정보(템플릿)를 로딩하고, 이름으로 아이템을 찾아 반환하는 역할.
 * Inventory 등 다른 시스템에서 shared_ptr로 참조됨.
 *
 * @example
 * shared_ptr<Item> bomb = itemManager.GetItem("Bomb");
 */
class ItemManager
{
public:
    ItemManager()
    {
        LoadItem();
    }

    const shared_ptr<Item> GetItem(const string& itemName)
    {
        for (shared_ptr<Item> d : mItemList)
        {
            if (d->GetName() == itemName)
            {
                return d;
            }
        }

        return nullptr;
    }

private:
    void LoadItem()
    {
        shared_ptr<Item> Potion = make_shared<Item>("Potion", "Heals 50HP", 0.5);
        mItemList.push_back(Potion);
        shared_ptr<Item> Bomb = make_shared<Item>("Bomb", "Deals 100 Damage", 1.0);
        mItemList.push_back(Bomb);
    }

private:
    vector<shared_ptr<Item>> mItemList;
};

/**
 * @class Inventory
 * @brief Player가 Item을 보관하는 클래스
 */

 /**
  * @class Inventory
  * @brief 플레이어가 아이템을 보관하는 인벤토리 클래스
  *
  * 소유자의 이름과 아이템 목록을 포함.
  * ItemManager를 통해 아이템 정보를 받아오고, 수량을 관리함.
  *
  * @note Inventory는 ItemManager의 메모리를 소유하지 않음.
  */
class Inventory
{
public:
    Inventory(const string& owner, ItemManager* pim)
        : mOwner(owner), mPim(pim) {
    }
    ~Inventory() = default;

    void PrintIventoryInfo()
    {
        cout << "Inventory of : " << mOwner << endl;
    }
    void PrintItems()
    {
        for (auto& d : mItemList)
        {
            d->Print();
        }
    }

    /**
     * @brief 인벤토리에 아이템을 추가합니다.
     *
     * 이미 인벤토리에 존재하는 경우, 수량만 증가시킵니다.
     * 존재하지 않는 경우, ItemManager에서 아이템 정의를 가져와 추가합니다.
     *
     * @param name 추가할 아이템 이름
     * @param quantity 추가할 수량
     * @return 성공 여부 (true: 성공, false: 실패 또는 아이템 없음)
     */
    bool AddItem(const string& name, uint32_t quantity)
    {
        //------------------------------------------
        // 이미 인벤토리에 있는지 확인
        shared_ptr<Item> ptrFindItem = findItem(name);
        if (ptrFindItem != nullptr)
        {
            ptrFindItem->AddQuantity(quantity);
            return true;
        }

        //------------------------------------------
        // 인벤토리에 새로 추가 될 때

        // nullCheck
        {
            if (mPim == nullptr)
                return false;

            ptrFindItem = mPim->GetItem(name);
            if (ptrFindItem == nullptr)
                return false;
        }

        ptrFindItem->AddQuantity(quantity);
        mItemList.push_back(ptrFindItem);
        return true;
    }

private:

    shared_ptr<Item> findItem(const string& itemName)
    {
        for (auto& d : mItemList)
        {
            if (d->GetName() == itemName)
            {
                return d;
            }
        }
        return nullptr;
    }

private:
    string mOwner;
    vector<shared_ptr<Item>> mItemList;
    ItemManager* mPim; //
};

//================================================================
// Main
int main()
{
    ItemManager im;
    Inventory inven("Player1", &im);
    inven.AddItem("Potion", 3);
    inven.AddItem("Bomb", 2);

    inven.PrintIventoryInfo();
    inven.PrintItems();

    inven.AddItem("Potion", 2);
    inven.PrintItems();

    return 0;
}

//================================================================
// Enum
enum class Subject
{
    MATH = 0
};

//================================================================
// Function

const char* etos(Subject data)
{
    if (data == Subject::MATH)
    {
        return "Math";
    }

    return "NULL";
}

//================================================================
// Classes

class Student
{
public:
    Student(const string& name, uint32_t grade, char classNum, uint32_t score)
        :mName(name), mGrade(grade), mClass(classNum), mScore(score) { }

    void Print()
    {
        cout << " - " << mName << " (Grade " << mGrade << ", Class " << mClass << "): " << mScore << endl;
    }

private:

    string mName;
    uint32_t mGrade;
    char mClass;
    uint32_t mScore;
};


class Teacher
{  
public:
    Teacher(const string& name, const Subject& sub, uint32_t years)
        :mName(name), mSubject(sub), mYears(years){ }

    ~Teacher()
    {
        if (mStudents.empty() == false)
        {
            for (auto& d : mStudents)
            {
                delete d;
            }
            mStudents.clear();
        }
    }

    void AddStudent(const Student& student)
    {
        Student* temp = new Student(student);
        mStudents.push_back(temp);
    }

    void PrintTeacher()
    {
        cout << "Teacher: " << mName << "(" << etos(mSubject) << ", " << mYears << " years)" << endl;
    }

    void PrintStudent()
    {
        for (auto& d : mStudents)
        {
            d->Print();
        }
    }

private:
    string mName;
    Subject mSubject;
    uint32_t mYears;
    vector<Student*> mStudents;
};


//================================================================
// Main
int main()
{
    Student Tom { "Tom", 2, 'A', 85 };
    Student Jane { "Jane", 2, 'A', 90 };
    Student Sam { "Sam", 2, 'A', 75 };

    Teacher Lee{ "Mr. Lee", Subject::MATH, 10 };
    Lee.AddStudent(Tom);
    Lee.AddStudent(Jane);
    Lee.AddStudent(Sam);

    Lee.PrintTeacher();
    Lee.PrintStudent();
    return 0;
}

//================================================================
// Struct
struct Date
{
    Date() = default;
    Date(uint32_t year, uint32_t month, uint32_t day)
        :year(year), month(month), day(day) { }

    uint32_t year;
    uint32_t month;
    uint32_t day;
};

//================================================================
// Classes

class Author
{
public:

    Author(const string& name, const string& email, const string& field)
        :mName(name), mEmail(email), mField(field) { }

    void Print()
    {
        cout << "Author : " << mName << " | Email: " << mEmail << " | Field: " << mField << endl;

    }

private:

    string mName;
    string mEmail;
    string mField;
};


class Article
{  
public:
    Article(const string& title, const Date& writeDate, uint32_t charNum, Author& author)
        : mTitle(title), mWriteDate(writeDate), mCharNum(charNum)
    {
        mAuthor = new Author(author);
    }

    ~Article()
    {
        if (mAuthor != nullptr)
        {
            delete mAuthor;
        }
    }

    void PrintArticle()
    {
        cout << "Article: " << "\"" << mTitle << "\" (" << mCharNum << " chars)" << endl;
    }

    void PrintAuthor()
    {
        mAuthor->Print();
    }

private:

    string mTitle;
    Date mWriteDate;
    uint32_t mCharNum;
    Author* mAuthor;
};


//================================================================
// Main
int main()
{
    Author alice{ "Alice Kim", "alice@domain.com", "Computer Science" };
    Article riseOfAI{ "Rise of AI", Date{2025,6,5}, 1240, alice };

    riseOfAI.PrintAuthor();
    riseOfAI.PrintArticle();
    return 0;
}

//================================================================
// Enum

/**
 * @enum Genre
 * @brief 책의 장르를 표현하는 열거형
 */
enum class Genre
{
    DYSTOPIA,
    SCI_FI
};

//================================================================
// Function

/**
 * @details Enum Genre의 값을 문자열로 변환한다.
 * 인식되지 않은 값에 대해서는 NULL을 반환한다.
 * @param e 변환할 Genre의 값
 * @return const char* Genre에 대응되는 문자열 값
 */
const char* etos(const Genre e)
{
    if (e == Genre::DYSTOPIA)
        return "Dystopia";

    if (e == Genre::SCI_FI)
        return "Sci-Fi";

    return "NULL";
}

//================================================================
// Struct & Classes

/**
 * @struct Book
 * @brief 책의 데이터를 가지고 있는 구조체
 */
struct Book
{
    Book(const string& name, const string& author, const Genre genre, uint32_t numPage)
        :name(name), author(author), genre(genre), numPage(numPage) { }

    string name;
    string author;
    Genre genre;
    uint32_t numPage;
};

/**
 * @class Library
 * @brief 도서관의 데이터를 가지고 있는 클래스, 구조체 Book의 리스트를 가지고 있음
 */
class Library
{
public:

    Library(const string& location, const string& managerName)
        : mLocation(location), mManagerName(managerName) { }

    ~Library()
    {
        if (mBookList.empty() == false)
        {
            for (auto& d : mBookList)
            {
                delete d;
            }
            mBookList.clear();
        }
    }

    void AddBook(const string& bookName, const string& author, const Genre genre, uint32_t numPage)
    {
        Book* temp = new Book(bookName, author, genre, numPage);
        mBookList.push_back(temp);
    }

    void ShowInfo()
    {
        cout << "Library: " << mLocation << " | ";
        cout << "Manager: " << mManagerName << endl;

        cout << "Books :" << endl;
        for (auto& d : mBookList)
        {
            cout << " - \"" << d->name << "\" by " << d->author << " (" << etos(d->genre) << ", " << d->numPage << "p)" << endl;
        }
    }

private:

    vector<Book*> mBookList;
    string mLocation;
    string mManagerName;
};


//================================================================
// Main
int main()
{
    Library lib = { "Central Library", "Ms. Kim" };
    lib.AddBook("1984", "Orwell", Genre::DYSTOPIA, 320);
    lib.AddBook("Dune", "Herbert", Genre::SCI_FI, 500);

    lib.ShowInfo();
    return 0;
}

//================================================================
// Struct & Classes


/**
 * @struct Player
 * @brief 플레이어의 기본적인 정보를 가지고 있는 구조체
 */
struct Player
{
    Player() = default;
    Player(string name, string team, uint32_t score, uint32_t id)
        :name(name), team(team), score(score), id(id) { }

    string name;
    string team;
    uint32_t score;
    uint32_t id;
};


/**
 * @class PlayerManager
 * @brief 플레이어를 관리하는 클래스, 플레이어의 생성과 플레이어의 점수를 관리함
 */
class PlayerManager
{
public:

    PlayerManager() = default;
    ~PlayerManager()
    {
        if (mPlayers.empty() == false)
        {
            for (Player* d : mPlayers)
            {
                delete d;
            }
            mPlayers.clear();
        }
    }

    void AddPlayer(const string& name, const string& team)
    {
        Player* tempPlayer = new Player(name, team, 0, mPlayerCnt);
        mPlayers.push_back(tempPlayer);
        ++mPlayerCnt;
    }

    void AdjustScore(const string& name, const uint32_t score)
    {
        // 플레이어 찾기
        for (const auto& d : mPlayers)
        {
            if (d->name == name)
            {
                d->score += score;
                return;
            }
        }
        return;
    }

    const vector<Player*>& GetPlayers() const
    {
        return mPlayers;
    }

private:
    vector<Player*> mPlayers;
    static uint32_t mPlayerCnt; // Player의 고유 ID = 여태 만들어진 Player수
};
uint32_t PlayerManager::mPlayerCnt = 0;


/**
 * @class ScoreBoard
 * @brief 플레이어의 데이터 출력용 UI클래스
 */
class ScoreBoard
{
public:
    
    void PrintPlayerRecord(const vector<Player*> players) const
    {
        cout << "[ScoreBoard]" << endl;
        for (auto& d : players)
        {
            cout << "- Player: " << d->name << " (Team " << d->team << ")";
            cout << "Scroe: " << d->score << endl;
        }

        cout << "Average: " << GetAverage(players) << endl;
    }

private:

    uint32_t GetAverage(const vector<Player*> players) const
    {
        uint32_t ret = 0;
        for (auto& d : players)
        {
            ret += d->score;
        }
        return (ret / players.size());
    }
};

//================================================================
// Main
int main()
{
    PlayerManager pm;
    ScoreBoard sb;

    pm.AddPlayer("John", "A");
    pm.AdjustScore("John", 80);
    pm.AddPlayer("Mary", "B");
    pm.AdjustScore("Mary", 90);

    sb.PrintPlayerRecord(pm.GetPlayers());
    return 0;
}

struct PCI
{
	char c;
	int i;
};

bool cmp(PCI& a, PCI& b)
{
	// 1. 문자 우선
	if (a.c != b.c)
		return a.c < b.c;

	// 2. 문자가 같다면 숫자 정렬
	return a.i < b.i;
}

int main()
{
	PCI input[100] = { 0 };

	int n;
	cin >> n;

	for (int i = 0; i < n; ++i)
	{
		cin >> input[i].c >> input[i].i;
	}

	sort(input, input + n, cmp);

	for (int i = 0; i < n; ++i)
	{
		cout << input[i].c << " " << input[i].i << endl;
	}


	return 0;
}

 


int depthMax, branchCnt;
char path[100] = { 0 };

void DFS(int lev)
{
	// Base case:
	if (lev == depthMax)
	{
		cout << path << endl;
		return;
	}

	// Recursive step:
	for (int i = 0; i < branchCnt; ++i)
	{
		path[lev] = '0' + i;
		DFS(lev + 1);
		path[lev] = 0;
	}
	return;
}


int main()
{
	cin >> depthMax >> branchCnt;
	DFS(0);

	return 0;
}

 


int arr1[6] = { 0 };
int arr2[6] = { 0 };

int main()
{
	// 1. Get inputs
	for (int i = 0; i < 6; ++i)
	{
		cin >> arr1[i];
	}

	for (int i = 0; i < 6; ++i)
	{
		cin >> arr2[i];
	}


	// 2. Solve
	stack<int> buff;

	int btn = 0;
	for (int i = 5; 0 <= i; --i)
	{
		const int t = arr1[i] + arr2[i] + btn;
		
		if (10 <= t)
			btn = 1;
		else
			btn = 0;

		buff.push(t % 10);
	}
	if (btn == 1)
		buff.push(1);
	

	// 3. Print
	while (buff.empty() == false)
	{
		cout << buff.top() << " ";
		buff.pop();
	}

	return 0;
}

 


int input[5] = { 0 };

int main()
{
	for (auto& d : input)
	{
		cin >> d;
	}

	int prv = input[0];
	for (int i = 1; i < 5; ++i)
	{
		if (input[i] <= prv)
		{
			cout << "증가안됨";
			return 0;
		}

		prv = input[i];
	}

	cout << "증가됨";
	return 0;
}

 


int main()
{
	// Get input
	int input = 0;
	cin >> input;

	// Solve
	int arr[100] = { 0 };
	int idx, btn = 0;
	for (idx = 0; idx < 5; ++idx)
	{
		const int t = (input % 10) + 1 + btn;

		if (10 <= t)
			btn = 1;
		else
			btn = 0;

		arr[idx] = t % 10;
		input /= 10;
	}
	if (btn == 1)
		arr[idx++] = 1;

	// Print
	for (int i = 0; i < idx; ++i)
	{
		cout << arr[i];
	}

	return 0;
}

 


int main()
{
	string input;
	cin >> input;
	
	vector<char> ret;
	char DAT[256] = { 0 };
	for (char& d : input)
	{
		DAT[d]++;
		if (DAT[d] == 2)
			ret.push_back(d);
	}

	std::sort(ret.begin(), ret.end());

	for (auto d : ret)
	{
		cout << d;
	}

	return 0;
}

 


int main()
{
	// GetInput
	int arr[4][3] = {
		3,5,1,
		3,1,2,
		3,4,6,
		5,4,6
	};

	// Solve
	char DAT[15] = { 0 };
	for (int i = 0; i < 4; ++i)
	{
		for (int j = 0; j < 3; ++j)
		{
			DAT[arr[i][j]]++;
		}
	}

	// Print
	for (int i = 1; i <= 6; ++i)
	{
		cout << i;
		for (int j = 0; j < DAT[i]; ++j)
		{
			cout << " *";
		}
		cout << endl;
	}

	return 0;
}

'코딩 테스트 > 알고리즘 풀이' 카테고리의 다른 글

[LV17] 복습 문제  (0) 2025.06.07
[LV17] 연습 문제  (0) 2025.06.07
[LV16] 연습 문제  (0) 2025.05.27
[LV15] 연습 문제  (0) 2025.05.24
[설계편] 코테 준비 문제  (0) 2025.05.24

////////////////////////////////////////////////
// Globals
enum class AccountType
{
    Saving = 0
};

// AccountType을 string으로 변환하는 함수
const char* toString(AccountType type) noexcept
{
    if (type == AccountType::Saving)
        return "Saving";

    return "NULL";
}

////////////////////////////////////////////////
// Classes

class BankAccount
{
public:

    BankAccount(uint32_t balance, const string& accNum, const string& bankName, AccountType accountType)
        :balance(balance), accNum(accNum), bankName(bankName), accountType(accountType) { }

    // 입금
    bool Deposit(uint32_t money)
    {
        const uint32_t before = balance;
        balance += money;

        writeStatement(before, money, balance, statementOption::DEPOSIT);
        return true;
    }

    // 출금
    bool WithDrawal(uint32_t money)
    {
        if (balance < money)
            return false;

        const uint32_t before = balance;
        balance -= money;

        writeStatement(before, money, balance, statementOption::WITHDRAWAL);
        return true;
    }

    // 계좌 정보 출력
    void Print()
    {
        cout << "Account: " << accNum
            << " | Bank: " << bankName
            << " | Type: " << toString(accountType) << endl;

        for (auto d : statement)
        {
            cout << d << endl;
        }
    }

private:

    enum statementOption
    {
        DEPOSIT,
        WITHDRAWAL
    };

    // 계좌 내역 저장
    void writeStatement(uint32_t before, uint32_t money, uint32_t after, statementOption option)
    {
        string t = "Balance: $" + std::to_string(before) + " -> ";

        if (option == statementOption::DEPOSIT)
            t += "Deposit $" + std::to_string(money) + " -> ";

        if (option == statementOption::WITHDRAWAL)
            t += "Withdrawal $" + std::to_string(money) + " -> ";

        t += "Balance: $" + std::to_string(after);
        statement.push_back(t);
    }

private:

    uint32_t balance;
    string accNum;
    string bankName;
    AccountType accountType;
    vector<string> statement; // 거래 내역 저장
};

// Class: Customer
class Customer
{
public:

    Customer(const string& name, const string& phoneNum, const string& address, size_t age)
        :name(name), phoneNum(phoneNum), address(address), age(age), acc(nullptr) {
    }

    ~Customer()
    {
        if (acc != nullptr)
            delete acc;
    }

    // 계좌 생성
    bool AddAccount(uint32_t balance, string accNum, string bankName, AccountType accountType)
    {
        if (acc != nullptr)
            return false;

        acc = new BankAccount(balance, accNum, bankName, accountType);
        return true;
    }

    // 입금
    bool Deposit(uint32_t money)
    {
        if (acc == nullptr)
            return false;

        return acc->Deposit(money);
    }

    // 출금
    bool WithDrawal(uint32_t money)
    {
        if (acc == nullptr)
            return false;

        return acc->WithDrawal(money);
    }

    // 고객 정보 출력
    void PrintCustomer()
    {
        cout << "Customer: " << name
            << " | Phone: " << phoneNum
            << " | Age: " << age << endl;
    }

    // 고객 계좌 정보 출력
    void PrintAccount()
    {
        if (acc == nullptr)
            cout << "No Account" << endl;
        else
            acc->Print();
    }

private:

    string name;
    string phoneNum;
    string address;
    size_t age;
    BankAccount* acc;
};

////////////////////////////////////////////////
// Main
int main()
{
    Customer alice = { "Alice", "010-1234-5678", "Korea", 27 };
    alice.AddAccount(1500, "123-456", "Hana", AccountType::Saving);
    alice.Deposit(200);
    alice.WithDrawal(500);
    alice.PrintCustomer();
    alice.PrintAccount();

    return 0;
}

 

+ Recent posts