Skip to content

Instantly share code, notes, and snippets.

@Gumball12
Last active March 19, 2019 10:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gumball12/740266820861ba994e6cd5a3169f0ec9 to your computer and use it in GitHub Desktop.
Save Gumball12/740266820861ba994e6cd5a3169f0ec9 to your computer and use it in GitHub Desktop.
c# assignments 2

Windows Programming (C#) assignments - 2

윈도우즈 프로그래밍 실습문제 2번입니다.

Problem 1

문제는 다음과 같습니다.

> 구구단을 저장할 배열을 구성하고, 배열 안의 멤버들을 foreach 문을 통해 탐색하라

/* example */
단을 입력하세요: 5

5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
/* example */

코드는 다음과 같습니다.

// Mono C# compiler v4.6.2.0

using System;
using System.Collections.Generic;

namespace ConsoleApp3
{
    class Assignment1
    {
        static void Main(string[] args)
        {
            // variables
            List<string> ss = new List<string>(); // define array
            int n;

            // user input
            Console.Write("단을 입력하세요: ");
            n = Convert.ToInt32(Console.ReadLine());

            // insert elements
            for (var i = 1; i < 10; i++)
            {
                ss.Add($"{n} * {i} = {n * i}");
            }

            // print elements
            foreach(string s in ss)
            {
                Console.WriteLine($"{s}");
            }
        }
    }
}

간단히, 어렵지 않게 구구단의 배열을 선언하고, 단을 입력받은 뒤 그대로 출력해주면 되는 문제였습니다.

여기서 list에 element를 push하기 위해 Add() 메서드를 사용하였습니다.

Problem 2

문제는 다음과 같습니다.

> 배열에 저장 단어를 foreach문을 하여 탐색하고 대, 소문자에 상관없이 검색하는 프로그램을 작성하여라
> 저장된 배열은 다음과 같음
> 배열 = "computer", "science", "ENGINEERING", "android", "VISUALSTUDIO"

/* example */
<단어가 없을 시>
검색할 단어를 입력하세요: AppLe
검색한 단어 'AppLe'(이)가 배열에 없습니다.

<단어가 있을 시>
검색할 단어를 입력하세요: ComPuTer
검색한 단어 'ComPuTer'(이)가 배열에 있습니다.

코드는 다음과 같습니다.

// Mono C# compiler v4.6.2.0

using System;

namespace ConsoleApp3
{
    class Assigmnet2
    {
        static void Main(string[] args)
        {
            // define variables
            String[] str = { "computer", "science", "ENGINEERING", "android", "VISUALSTUDIO" };

            string q;
            Boolean find = false;
            
            // input
            Console.Write("검색할 단어를 입력하세요: ");
            q = Console.ReadLine();

            // iteration
            foreach (string s in str)
            {
                if (q.ToLower() == s.ToLower())
                {
                    find = true;
                }
            }

            Console.Write($"검색한 단어 '{q}'(이)가 배열에 ");
            Console.WriteLine(find ? "있습니다." : "없습니다.");
        }
    }
}

ToLower()을 사용하여 처음부터 모두 소문자로 비교하면 간단히 해결 가능한 문제입니다.

여기서는 find boolean 변수를 사용하였는데, 이는 가장 마지막에 배열에 단어가 있는지 확인하기 위해 사용한 것입니다.

Problem 3

문제는 다음과 같습니다.

> 도서관 장서 관리 시스템을 만들어 보자. 2차원 배열을 이용하여 도서의 이름과 저자를 저장하고, Do while문을 통해 반복한다. 도서는 최대 10개까지 입력 받을 수 있다.

/* example */
**********
1: 도서 추가    2: 도서 검색    3: 도서 리스트 출력    0: 종료
********** >>> 1

입력할 도서(책이름, 저자)를 입력하시오. 최대 10개까지 입력 가능: ex) 무라카미 하루키, 상실의 시대
무라카미 하루키, 상실의 시대
>>> 입력 값: 1. 무라카미 하루키 상실의 시대

**********
1: 도서 추가    2: 도서 검색    3: 도서 리스트 출력    0: 종료
********** >>> 1

입력할 도서(책이름, 저자)를 입력하시오. 최대 10개까지 입력 가능: ex) 무라카미 하루키, 상실의 시대
베르나르 베르베르,개미
>>> 입력 값: 1. 베르나르 베르베르 개미

**********
1: 도서 추가    2: 도서 검색    3: 도서 리스트 출력    0: 종료
********** >>> 2

찾고자 하는 도서의 이름이나 저자의 이름을 입력하시오
개미
>>> 찾고자 하는 도서가 존재함

**********
1: 도서 추가    2: 도서 검색    3: 도서 리스트 출력    0: 종료
********** >>> 2

찾고자 하는 도서의 이름이나 저자의 이름을 입력하시오
해리포터
>>> 찾고자 하는 도서가 존재하지 않음

**********
1: 도서 추가    2: 도서 검색    3: 도서 리스트 출력    0: 종료
********** >>> 3

전체 도서 목록
1. 무라카미 하루키 상실의 시대
2. 베르나르 베르베르 개미

**********
1: 도서 추가    2: 도서 검색    3: 도서 리스트 출력    0: 종료
********** >>> 0

종료
계속하려면 아무 키나 누르십시오 . . .

코드는 다음과 같습니다.

// Mono C# compiler v4.6.2.0

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp3
{
    class Assigmnet2_3
    {
        static void Main(string[] args)
        {
            // declare, define variables
            List<List<string>> books = new List<List<string>>(); // 2-d list
            string input;
            byte command;
            Boolean find;
            int size;

            // tools
            Func<string, string> trim = s => s.Trim();
            Func<string[], string, string> join = (sa, sep) => String.Join(sep, sa);

            // user input
            do
            {
                Console.Write("**********\n1: 도서 추가 \t 2: 도서 검색 \t 3: 도서 리스트 출력 \t 0: 종료\n********** \t >>> ");
                command = Convert.ToByte(Console.ReadLine());

                switch (command)
                {
                    case 1:
                        if (books.ToArray().Length > 9)
                        {
                            Console.WriteLine("도서는 열 개 이하만 등록할 수 있습니다.");
                            break;
                        }

                        Console.WriteLine("\n입력할 도서(책 이름, 저자)를 입력하시오. 최대 10개 입력이 가능: ex) 무라카미 하루키, 상실의 시대");
                        input = Console.ReadLine();

                        books.Add(input.Split(',').Select(trim).ToList());
                        
                        size = books.ToArray().Length;
                        
                        Console.WriteLine($">>> 입력 값: {size}. {books[size - 1][0]} {books[size - 1][1]}");

                        break;
                    case 2:
                        Console.WriteLine("찾고자 하는 도서의 이름이나 저자의 이름을 입력하시오.");
                        input = Console.ReadLine();

                        /*
                        find = books.Aggregate(false, (r, book) => r || book.Contains(input));
                        */

                        find = false;

                        foreach (List<string> book in books)
                        {
                            find = find || book.Contains(input);
                        }

                        Console.WriteLine(
                            find ?
                            "찾고자 하는 도서가 존재함" :
                            "찾고자 하는 도서가 없음"
                        );

                        break;
                    case 3:
                        /*
                        books.ForEach(book =>
                            Console.WriteLine(
                                join(book.ToArray(), " \t ")
                            )
                        );
                        */

                        for (var i = 0; i < books.ToArray().Length; i++)
                        {
                            List<string> book = books[i];
                            Console.WriteLine(join(book.ToArray(), " \t "));
                        }

                        break;
                    default:
                    case 0:
                        // nothing
                        Console.WriteLine("종료");
                        break;
                }
            } while (command != 0);
        }
    }
}

System.Collections.Generic.List 클래스를 이용해 배열을 생성하고, 이를 그냥 문제에서 주어진 것과 같이 구현해주면 되는 문제였습니다.

Find books

검색할 때 문제에서는 foreach 문을 사용하라고 했었지만, 다음과 같은 코드로도 구현이 가능합니다.

boolean find = books.Aggregate(false, (r, book) => r || book.Contains(input)); // input = book name

Aggregate() 라는 메서드를 사용하여 구현하였는데, 이 메서드는 배열의 요소를 하나씩 순회하며 하나의 값으로 만드는 동작을 합니다. 이를 이용하면 foreach 문을 사용할 필요 없이 한 줄의 코드로 바로 책이 리스트에 포함되었는지 구해낼 수 있다는 장점이 있습니다.

Print book list

배열 내 요소를 출력할 때 문제에서는 for 문을 사용하여 출력하라고 했엇으나, 다음과 같은 코드로도 구현이 가능합니다.

Func<string[], string, string> join = (sa, sep) => String.Join(sep, sa);

books.ForEach(book => Console.WriteLine(join(book.ToArray(), " \t ")));

이 방법을 사용하면 index 변수의 생성 없이도 배열 내 모든 원소를 출력할 수 있다는 장점이 있습니다.

/**
* Windows programming (c#) assignment 2.1
*
* @author HaeJun Seo
* @since Mar 18, 2019
*/
// Mono C# compiler v4.6.2.0
using System;
using System.Collections.Generic;
namespace ConsoleApp3
{
class Assignment2_1
{
static void Main(string[] args)
{
// variables
List<string> ss = new List<string>(); // define array
int n;
// user input
Console.Write("단을 입력하세요: ");
n = Convert.ToInt32(Console.ReadLine());
// insert elements
for (var i = 1; i < 10; i++)
{
ss.Add($"{n} * {i} = {n * i}");
}
// print elements
foreach(string s in ss)
{
Console.WriteLine($"{s}");
}
}
}
}
/**
* Windows programming (c#) assignment 2.2
*
* @author HaeJun Seo
* @since Mar 18, 2019
*/
// Mono C# compiler v4.6.2.0
using System;
namespace ConsoleApp3
{
class Assigmnet2_2
{
static void Main(string[] args)
{
// define variables
String[] str = { "computer", "science", "ENGINEERING", "android", "VISUALSTUDIO" };
string q;
Boolean find = false;
// input
Console.Write("검색할 단어를 입력하세요: ");
q = Console.ReadLine();
// iteration
foreach (string s in str)
{
if (q.ToLower() == s.ToLower())
{
find = true;
break;
}
}
Console.Write($"검색한 단어 '{q}'(이)가 배열에 ");
Console.WriteLine(find ? "있습니다." : "없습니다.");
}
}
}
/**
* Windows programming (c#) assignment 2.3
*
* @author HaeJun Seo
* @since Mar 18, 2019
*/
// Mono C# compiler v4.6.2.0
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp3
{
class Assigmnet2_3
{
static void Main(string[] args)
{
// declare, define variables
List<List<string>> books = new List<List<string>>(); // 2-d list
string input;
byte command;
Boolean find;
int size;
// tools
Func<string, string> trim = s => s.Trim();
Func<string[], string, string> join = (sa, sep) => String.Join(sep, sa);
// user input
do
{
Console.Write("**********\n1: 도서 추가 \t 2: 도서 검색 \t 3: 도서 리스트 출력 \t 0: 종료\n********** \t >>> ");
command = Convert.ToByte(Console.ReadLine());
switch (command)
{
case 1:
if (books.ToArray().Length > 9)
{
Console.WriteLine("도서는 열 개 이하만 등록할 수 있습니다.");
break;
}
Console.WriteLine("\n입력할 도서(책 이름, 저자)를 입력하시오. 최대 10개 입력이 가능: ex) 무라카미 하루키, 상실의 시대");
input = Console.ReadLine();
books.Add(input.Split(',').Select(trim).ToList());
size = books.ToArray().Length;
Console.WriteLine($">>> 입력 값: {size}. {books[size - 1][0]} {books[size - 1][1]}");
break;
case 2:
Console.WriteLine("찾고자 하는 도서의 이름이나 저자의 이름을 입력하시오.");
input = Console.ReadLine();
/*
find = books.Aggregate(false, (r, book) => r || book.Contains(input));
*/
find = false;
foreach (List<string> book in books)
{
find = find || book.Contains(input);
}
Console.WriteLine(
find ?
"찾고자 하는 도서가 존재함" :
"찾고자 하는 도서가 없음"
);
break;
case 3:
/*
books.ForEach(book =>
Console.WriteLine(
join(book.ToArray(), " \t ")
)
);
*/
for (var i = 0; i < books.ToArray().Length; i++)
{
List<string> book = books[i];
Console.WriteLine(join(book.ToArray(), " \t "));
}
break;
default:
case 0:
// nothing
Console.WriteLine("종료");
break;
}
} while (command != 0);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment