반응형

8.8> 다음 그림과 같은 상속 구조를 갖는 클래스를 설계한다. 모든 프린터는 모델명(model), 제조사(manufacturer), 인쇄 매수(printedCount), 인쇄 종이 잔량(availableCount)을 나타내는 정보와 print(int pages) 멤버 함수를 가지며, print()가 호출할 때마다 pages 매의 용지를 사용한다. 잉크젯 프린터는 잉크 잔량(availableInk) 정보와 printInkJet(int pages) 멤버 함수를 추가적으로 가지며, 레이저 프린터는 토너 잔량(availableToner) 정보와 역시 printLaser(int pages) 멤버 함수를 추가적으로 가진다. 각 클래스에 적절한 접근 지정으로 멤버 변수와 함수, 생성자, 소멸자를 작성하고, 다음과 같이 실행되도록 전체 프로그램을 완성하라. 잉크젯 프린터 객체와 레이저 프린터 객체를 각각 하나만 동적 생성하여 시작한다.

<코드>

#include <iostream>

#include <string>

 

using namespace std;

 

class Printer { //프린터 클래스

protected:

        string model; //모델명 스트링

        string manufacturer; //제조사명 스트링

        int printedcount; // 출력된 매수

        int availableCount; // 앞으로 출력 가능한 매수

        int print(int pages); //프린트 원형 함수

        Printer(string model, string manufacturer, int availableCount); //생성자

        void show(); // 화면 출력 함수

};

class InkjetPrinter : public Printer { //프린터를 상속받은 잉크젯 프린터 클래스

private:

        int availableInk; //잉크잔량

public:

        InkjetPrinter(string model, string manufacturer, int availableCount,int availableInk); //생성자

        void printInkJet(int pages); //잉크젯 프린트 함수

        void inkjetshow(); //잉크젯 화면 출력 함수

};

class LaserPrinter : public Printer { //프린터를 상속받은 레이저 프린터 클래스

private:

        float availableToner; //토너잔량

public:

        LaserPrinter(string model, string manufacturer, int availableCount, float availableToner); //생성자

        void printLaser(int pages); //레이저 프린트 함수

        void lasershow(); //레이저 화면 출력 함수

};

Printer::Printer(string model, string manufacturer, int availableCount) {

        this->model = model;

        this->manufacturer = manufacturer;

        this->printedcount = 0; //객체 생성시 한장도 안뽑았으므로 0

        this->availableCount = availableCount;

}

int Printer::print(int pages) {

        if (availableCount - pages < 0) { cout << "용지가 부족하여 프린트 없습니다." << endl; return 0; }

        else { availableCount -= pages; printedcount += pages;  return 1; }

} //사용가능한 용지보다 뽑아야하는 용지 수가 많으면 fail, 아니면 success 이때는 사용가능 페이지를 사용한 만큼 - 해준다. 그리고 사용한 페이지를 +해준다.

        //리턴 타입을 정해준 이유는 아래 프린트잉크젯이나 프린트레이저에서 프린트가 가능 때만 if문이 실행되게 하기 위해서 그렇다.

 

void Printer::show() {

        cout << this->model << ", " << this->manufacturer << ", " << "남은 종이" << this->availableCount << "";

} //모델명, 제조사명, 남은종이 출력

 

InkjetPrinter::InkjetPrinter(string model, string manufacturer, int availableCount, int availableInk) : Printer(model, manufacturer, availableCount) {

        this->availableInk = availableInk;} //프린터 생성자와 동시에 사용가능잉크 입력

void InkjetPrinter::printInkJet(int pages) {if (print(pages)) {

        if(availableInk-pages<0){ cout << "잉크가 부족하여 프린트 없습니다." << endl; availableCount+=pages;} //잉크 부족시 에러

        else {cout << "프린트하였습니다." << endl; availableInk -= pages;} }} //페이지 수만큼 출력가능하면 잉크 그만큼 -해줌.

void InkjetPrinter::inkjetshow() {

        show(); cout << ", 남은 잉크 " << this->availableInk << endl;} //print show 실행 남은 잉크 출력

 

LaserPrinter::LaserPrinter(string model, string manufacturer, int availableCount, float availableToner) : Printer(model, manufacturer, availableCount) {

        (this->availableToner) = (float)availableToner; } //프린터 생성자와 동시에 사용가능토너 입력

 

void LaserPrinter::printLaser(int pages) { if (print(pages)) {

        if((float)(availableToner*2)-(float)pages<0){ cout << "토너가 부족하여 프린트 없습니다." << endl; availableCount+=pages;} //토너 부족시 에러

        else {cout << "프린트하였습니다." << endl; (float)availableToner -= ((float)pages/2);} } } // 페이지 수만큼 출력가능하면 토너 그것의 1/2만큼 - 해줌.

void LaserPrinter::lasershow() {

        show(); cout << ", 남은 잉크 " << (float)(this->availableToner) << endl;} //print show 실행 남은 토너 출력

 

int main(void) {

        char check = 0; // check y/n 나타낸다.

        InkjetPrinter ip("Officejet V40", "HP", 20, 10); // 잉크젯프린터 ip 생성

        LaserPrinter lp("SCX-6x45", "삼성전자", 30, 10.0); // 레이저프린터 lp 생성

        cout << "현재 작동 중인 2 대의 프린터는 아래와 같다." << endl;

        cout << "잉크젯 : "; ip.inkjetshow(); cout << "레이저 : "; lp.lasershow(); //화면 출력

        while (1) {

               cout << "프린터(1:잉크젯, 2:레이저) 매수 입력>> ";

               int which = 0; int pg = 0; //which 잉크젯과 레이저를 구분

               cin >> which >> pg; cin.ignore(100, '\n'); //개행문자 삭제를 위하여 ignore 사용

               if (which == 1) { //잉크젯이면

                       ip.printInkJet(pg); //pg만큼 출력한다.

                       cout << "잉크젯 : "; ip.inkjetshow(); cout << "레이저 : "; lp.lasershow(); //화면 출력

                      

                      

                       while (1) {

                              cout << "계속 프린트 하시겠습니까?(y/n)>>";

                              check=cin.get(); cin.ignore(100, '\n'); //'y','n' 받고 개행문자 없애기 위함.

                              if (check == 'y'||check=='n') { break; } //'y' 'n'이면 브레이크

                              else { cout << "잘못된 입력입니다." << endl; continue; } //이상한 들어오면 다시 실행

                       }

                       if (check=='y') continue; else if (check=='n') break//y 루프 처음으로 n이면 브레이크

               }

               else if (which == 2) { //레이저면

                       lp.printLaser(pg); //pg만큼 출력한다.

                       cout << "잉크젯 : "; ip.inkjetshow(); cout << "레이저 : "; lp.lasershow(); //화면 출력

                       while (1) {

                              cout << "계속 프린트 하시겠습니까?(y/n)>>";

                              check = cin.get(); cin.ignore(100, '\n'); //'y','n' 받고 개행문자 없애기 위함.

                              if (check == 'y' || check == 'n') { break; }  //'y' 'n'이면 브레이크

                              else { cout << "잘못된 입력입니다." << endl; continue; } //이상한 들어오면 다시 실행

                       }

                       if (check == 'y') continue; else if (check == 'n') break; //y 루프 처음으로 n이면 브레이크

               }

               else { cout << "잘못된 입력입니다." << endl; continue; } //which 1이나 2가아니면 출력되는 에러

        }

        return 0;

}

 

 

 

<결과창>


반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글

KmToMile class  (0) 2017.12.31
WonToDollar Class  (0) 2017.12.31
ROM RAM class  (0) 2017.12.31
MyStack Class  (0) 2017.12.31
MyQueue Class  (0) 2017.12.31
반응형

8.7> 아래와 같은 BaseMemory 클래스를 상속받는 ROM(Read Only Memory), RAM 클래스를 작성하라. BaseMemory에 필요한 코드를 수정 추가하여 적절히 완성하라.

<코드>

#include <iostream>

 

using namespace std;

 

class BaseMemory { //베이스메모리 클래스

private:

        char *mem; //캐릭터 동적 배열을 가리킬 포인터 mem

protected:

        BaseMemory(int size) { mem = new char[size]; } //생성자 mem size만큼의 캐릭터 동적 배열 할당

        void burn(int index, char value);

public:

        char read(int index);

 

};

class ROM : public BaseMemory { //베이스메모리를 상속받은 롬 클래스

public:

        ROM(int memsize, char *arr, int arrsize);

};

 

class RAM : public BaseMemory { //베이스메모리를 상속받은 램 클래스

public:

        RAM(int memsize);

        void write(int i, char value);

};

 

void BaseMemory::burn(int index, char value) { mem[index] = value; } //mem 배열의 해당 index value 삽입

 

char BaseMemory::read(int index) { return mem[index]; } //mem 배열의 해당 index 원소 리턴

 

ROM::ROM(int memsize, char *arr, int arrsize) : BaseMemory(memsize) { //롬 생성자, 베이스 메모리 생성자 실행하고

        for (int i = 0; i < arrsize; i++) { burn(i, arr[i]); } //arr이 가리키는 배열의 원소 ROM에 굽는다.

}

RAM::RAM(int memsize) : BaseMemory(memsize) {} //단순히 memsize의 캐릭터 동적 배열만 할당한다.(베이스메모리 컨스트럭터와 동일)

 

void RAM::write(int i, char value) { burn(i, value); } //램에 존재하는 캐릭터 배열 인덱스 i value값을 삽입한다.

 

int main(void) {

        char x[5] = { 'h','e','l','l','o' }; //캐릭터배열 크기 5

        ROM biosROM(1024 * 10, x, 5); //10KB ROM 메모리, 배열 x로 초기화됨.

        RAM mainMemory(1024 * 1024); //1MB RAM 메모리

 

                                                              //0번지에서 4번지까지 biosROM에서 읽어 mainMemory에 복사

        for (int i = 0; i < 5; i++) { mainMemory.write(i, biosROM.read(i)); }

        //램 메인메모리에 있는 캐릭터 배열의 i인덱스에 롬 바이오스롬에 들어있는 캐릭터 배열의 i인덱스 원소를 삽입한다.

        for (int i = 0; i < 5; i++) { cout << mainMemory.read(i); } //메인메모리에 있는 캐릭터배열 0~4인덱스 원소를 순회하고 출력한다.

 

        return 0;

}

<결과창>

 


반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글

WonToDollar Class  (0) 2017.12.31
Printer Class  (0) 2017.12.31
MyStack Class  (0) 2017.12.31
MyQueue Class  (0) 2017.12.31
Stack class  (0) 2017.12.25
반응형

8.6> BaseArray 클래스를 상속받아 스택으로 작동하는 MyStack 클래스를 작성하라.

<코드>

#include <iostream>

 

using namespace std;

 

class BaseArray{

private:

        int capacity;//배열의 크기

        int *mem;//정수 배열을 만들기 위한 메모리의 포인터

protected:

        BaseArray(int capacity=100){ //디폴트 매개변수 100

               this->capacity=capacity;

               mem=new int[capacity]; //캐패시티 크기로 동적 배열 형성

        }

        ~BaseArray(){delete []mem;} //동적 메모리 힙으로 반환

        void put(int index, int val){mem[index]=val;} //인덱스에 매개변수 삽입

        int get(int index){return mem[index];} //해당 인덱스에서 정수 가져옴

        int getCapacity(){return capacity;} //용량 리턴

};

 

class MyStack : public BaseArray{

private:

        int rear; //마지막 인덱스 리어

public:

        MyStack(int capacity,int rear);

        void push(int arg); //마지막에 원소 추가

        int capacity(); //스택 용량

        int length(); //스택 길이

        int pop(); //마지막 원소 꺼내옴

};

MyStack::MyStack(int capacity=100,int rear=-1):BaseArray(capacity) {this->rear=rear;}

void MyStack::push(int arg) {rear++; put(rear,arg);}

int MyStack::capacity() {int cap=getCapacity(); return cap;}

int MyStack::length(){return rear+1;}

int MyStack::pop(){int out=get(rear); rear--; return out;}

 

int main(void){

MyStack mStack(100);

        int n;

        cout << "스택에 삽입할 5개의 정수를 입력하라>> ";

        for(int i=0;i<5;i++){

               cin >> n;

               mStack.push(n); //큐에 삽입

        }

        cout<<"스택 용량: " <<mStack.capacity()<<", 스택 크기:"<<mStack.length()<<endl;

        cout<<"스택의 모든 원소를 팝하여 출력한다>> ";

        while(mStack.length()!=0){

               cout<<mStack.pop()<<' '; //큐에서 제거하여 출력

        }

        cout<<endl<<"큐의 현재 크기 : "<<mStack.length()<<endl;

        return 0;

}

 

<결과창>

  

 

반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글

Printer Class  (0) 2017.12.31
ROM RAM class  (0) 2017.12.31
MyQueue Class  (0) 2017.12.31
Stack class  (0) 2017.12.25
Statistics class  (0) 2017.12.25
반응형

8.5> BaseArray를 상속받아 큐처럼 작동하는 MyQueue 클래스를 작성하라. MyQueue를 활용하는 사례는 다음과 같다.

<코드>

#include <iostream>

 

using namespace std;

 

class BaseArray{

private:

        int capacity;//배열의 크기

        int *mem;//정수 배열을 만들기 위한 메모리의 포인터

protected:

        BaseArray(int capacity=100){ //디폴트 매개변수 100

               this->capacity=capacity;

               mem=new int[capacity]; //캐패시티 크기로 동적 배열 형성

        }

        ~BaseArray(){delete []mem;} //동적 메모리 힙으로 반환

        void put(int index, int val){mem[index]=val;} //인덱스에 매개변수 삽입

        int get(int index){return mem[index];} //해당 인덱스에서 정수 가져옴

        int getCapacity(){return capacity;} //용량 리턴

};

class MyQueue : public BaseArray{

private:

        int rear; //마지막 인덱스

        int front; // 첫번째 인덱스 -1

public:

        MyQueue(int capacity,int front,int rear); // 생성자

        void enqueue(int arg); //마지막에 원소 추가

        int capacity(); //용량

        int length(); //현재 길이

        int dequeue(); //첫번째 원소 리턴

};

MyQueue::MyQueue(int capacity=100,int front=-1,int rear=-1):BaseArray(capacity){

        this->front=front;

        this->rear=rear;

}

void MyQueue::enqueue(int arg){

        rear++;

        put(rear,arg);

}

int MyQueue::capacity(){int cap=getCapacity(); return cap;}

int MyQueue::length(){

        return rear-front;

}

int MyQueue::dequeue(){

        int out=get(front+1);

        front++;

        return out;

        }

int main(void){

        MyQueue mQ(100);

        int n;

        cout << "큐에 삽입할 5개의 정수를 입력하라>> ";

        for(int i=0;i<5;i++){

               cin >> n;

               mQ.enqueue(n); //큐에 삽입

        }

        cout<<"큐의 용량: " <<mQ.capacity()<<", 큐의 크기:"<<mQ.length()<<endl;

        cout<<"큐의 원소를 순서대로 제거하여 출력한다>> ";

        while(mQ.length()!=0){

               cout<<mQ.dequeue()<<' '; //큐에서 제거하여 출력

        }

        cout<<endl<<"큐의 현재 크기 : "<<mQ.length()<<endl;

        return 0;

}

 

<결과창>

  

                                 


반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글

ROM RAM class  (0) 2017.12.31
MyStack Class  (0) 2017.12.31
Stack class  (0) 2017.12.25
Statistics class  (0) 2017.12.25
Circle class 오퍼레이터 오버로딩  (0) 2017.12.25
반응형

7.10> 스택 클래스 Stack을 만들고 푸시(push)용으로 <<연산자를, (pop)을 위해 >> 연산자를, 비어 있는 스택인지를 알기 위해 ! 연산자를 작성하라. 다음 코드를 main()으로 작성하라.

<코드>

#include <iostream>

 

using namespace std;

class Stack{

private:

        int stk[5]; //크기 5짜리 스택

        int index;

public:

        Stack(int index=-1); //디폴트 매개변수 인덱스 = -1(empty)

        Stack& operator<<(int op); //푸시

        friend bool operator!(Stack op);

        void operator>>(int &op); //

};

Stack::Stack(int index){this->index=index;} //index 초기화

Stack& Stack::operator<<(int op){ //푸시 구현

        index++; //인덱스 증가

        stk[index]=op; //오퍼랜드를 해당 인덱스에 넣어줌

        return *this; //현재 객체의 참조 반환

}

bool operator!(Stack op){ //비어있는지 확인

        if(op.index==-1)

               return true; //비었으면 true 리턴

        else

               return false;

}

void Stack::operator>>(int &op){

        index--; //인덱스 감소

        op= stk[index+1]; //제일 위의 원소 pop

}

int main(void){

        Stack stack;

        stack<<3<<5<<10; //3,5,10 순서의 스택

        while(true){

               if(!stack) break;

               int x;

               stack>>x; //제일 위의 원소부터 나옴

               cout<<x<<" ";

        }

        cout << endl;

        return 0;

}

 

<결과창>

               

                    


반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글

MyStack Class  (0) 2017.12.31
MyQueue Class  (0) 2017.12.31
Statistics class  (0) 2017.12.25
Circle class 오퍼레이터 오버로딩  (0) 2017.12.25
Circle class  (0) 2017.12.25
반응형

인하대학교 전자공학과 데이터 구조 포인터, 어레이 과제 (pointer, array)


인하대학교 전자공학과 데이터 구조 하노이의 탑, 이진 탐색(binary search, tir, recursive)


인하대학교 전자공학과 데이터 구조 시스템 스택, 선형 리스트 (system stack, linear list)


인하대학교 전자공학과 데이터 구조 preorder, postorder, max heap


인하대학교 전자공학과 데이터 구조 dfs, bfs, 프림, 크루스칼 (prim, kruskal)


소스코드, 수도코드, 플로우차트(순서도), 분석 및 고찰, 결과창 등이 들어있는 보고서입니다.


전부 만점받은 보고서입니다. 

반응형
반응형

1. Figure 1 and 2 show the recursive traversal algorithms(or programs) of preorder and postorder, respectively. Write the respectively corresponding iterative traversal algorithms(or programs) of preorder and postorder.

<Figure 2. Postorder traversal algorithm>


<Figure 1. Preorder traversal algorithm>


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <stdio.h>
#include <stdlib.h> //exit 함수 사용때문에 넣음
 
#define MAX_STACK_SIZE 10 //스택 최대 크기
 
typedef struct node* treepointer;  //node 자료형 포인터의 새로운 이름 treepointer
typedef struct node{
    char data;
    treepointer leftchild, rightchild;
}node; //node 구조체 자료형의 새로운 이름 node, 안에는 char형 data와 treepointer형 leftchild, rightchild가 들어있다.
 
void push(treepointer stack[],treepointer item,int *top);
treepointer pop(treepointer stack[],int *top);
void iterpreorder(treepointer node);
void iterpostorder(treepointer node);
 
 
int main(void)
{
    int i; // int형 변수 i
    treepointer root; //treepointer 형 포인터 변수 root
    node tree[MAX_STACK_SIZE]; // node 배열 tree 크기는 10
    for(i=0;i<MAX_STACK_SIZE;i++//i=0부터 10보다 작을때까지 반복
    {tree[i].leftchild=0; tree[i].rightchild=0;tree[i].data=0;} //배열의 원소 초기화
    tree[0].data='+'; tree[0].leftchild=&tree[1]; tree[0].rightchild=&tree[2]; 
    tree[1].data='*'; tree[1].leftchild=&tree[3]; tree[1].rightchild=&tree[4]; 
    tree[2].data='E'
    tree[3].data='*'; tree[3].leftchild=&tree[5]; tree[3].rightchild=&tree[6]; 
    tree[4].data='D';
    tree[5].data='/'; tree[5].leftchild=&tree[7]; tree[5].rightchild=&tree[8]; 
    tree[6].data='C';
    tree[7].data='A';
    tree[8].data='B'//문제에서와 같이 바이너리 트리 형성
    root=&tree[0];  //root에 tree[0]의 주소 대입 (첫번째 노드)
    printf("preorder : ");iterpreorder(root); //preorder를 itr로 구현한 함수 호출
    printf("postorder : ");iterpostorder(root);//postorder를 itr로 구현한 함수 호출
    return 0;
}
 
void push(treepointer stack[],treepointer item,int *top)
{
    if(*top>=MAX_STACK_SIZE-1//만약에 top이가리키는주소의 값이 9이상이라면 
        {fprintf(stderr,"스택 과부하 원소 추가 불가능\n"); // 문장 출력하고
    exit(EXIT_FAILURE);} //프로그램 종료
    stack[++(*top)]=item; //stack의 맨 위에 item 삽입
}
treepointer pop(treepointer stack[],int *top)
{
    if((*top)==-1//top이 가리키는 주소의 값이 -1 이라면
    {fprintf(stderr,"스택 비어있음\n"); //문장 출력하고
    exit(EXIT_FAILURE);} //프로그램 종료
    return stack[(*top)--]; //제일 위에 있는 원소 return
}
 
void iterpreorder(treepointer node)
{
    int top=-1//int 형 변수 top을 -1로 초기화
    treepointer stack[MAX_STACK_SIZE]; //treepointer 형 포인터배열 stack 크기는 10
    push(stack,node,&top); //node를 stack에 쌓는다.
    while(1){
        if(top==-1break//top이 -1이면 루프 탈출 어차피 마지막이 아니면 top이 -1이 될 일이 없다.
        node=stack[top]; //node에 stack의 top 원소 삽입
        printf("%c", node->data); //node의 data 출력
        pop(stack,&top); //stack의 top원소 pop
        if(node->rightchild) //node가 가리키는 구조체node에 rightchild가 있으면
            push(stack,node->rightchild,&top); //stack에 쌓는다.
        if(node->leftchild) //node가 가리키는 구조체node에 leftchild가 있으면
            push(stack,node->leftchild,&top); //stack에 쌓는다.
        }
    printf("\n"); //개행문자 출력
    }
void iterpostorder(treepointer node)
{
    int top1=-1//int 형 변수 top1을 -1로 초기화
    int top2=-1//int 형 변수 top2을 -1로 초기화
    treepointer stack1[MAX_STACK_SIZE]; //treepointer 형 포인터배열 stack1 크기는 10
    treepointer stack2[MAX_STACK_SIZE]; //treepointer 형 포인터배열 stack2 크기는 10
    push(stack1,node,&top1); //node를 stack1에 쌓는다.
    while(1)
    {
        if(top1==-1)break//top1이 -1이면 루프 탈출  어차피 마지막이 아니면 top1이 -1이 될 일이 없다.
        node=pop(stack1,&top1); //node에 stack에서 pop한 원소를 대입
        push(stack2,node,&top2); // stack2에 node를 삽입
        if(node->leftchild) //node가 가리키는 구조체node에 leftchild가 있으면
            push(stack1,node->leftchild,&top1); //stack1에 쌓는다.
        if(node->rightchild) //node가 가리키는 구조체node에 rightchild가 있으면
            push(stack1,node->rightchild,&top1); //stack1에 쌓는다.
    }
    while(1)
    {
        if(top2==-1)break;  //top2가 -1이면 루프 탈출  어차피 마지막이 아니면 top2가 -1이 될 일이 없다.
        node=pop(stack2,&top2); //node에 stack2에서 pop한 원소 대입
        printf("%c", node->data); //character type으로 출력 
    }
    printf("\n"); //개행문자 출력
    }
 
cs



2. Write a C function that searches for an arbitrary element in a max heap. What is the computing time of your function?

<Figure 3. Max heap>



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <stdio.h>
 
#define MAX_SIZE 8 //스택 최대 크기
 
typedef struct node* treepointer;  //node 자료형 포인터의 새로운 이름 treepointer
typedef struct node{
    int data;
    treepointer leftchild, rightchild;
}node; //node 구조체 자료형의 새로운 이름 node, 안에는 char형 data와 treepointer형 leftchild, rightchild가 들어있다.
 
void search_max_heap(treepointer ptr,treepointer *res,int value);
 
int main(void)
{
    int i; // int형 변수 i
    treepointer root; //treepointer 형 포인터 변수 root
    treepointer res=0//결과 값을 저장할 treepointer res
    node tree[MAX_SIZE]; // node 배열 tree 크기는 10
    for(i=0;i<MAX_SIZE;i++//i=0부터 10보다 작을때까지 반복
    {tree[i].leftchild=0; tree[i].rightchild=0;tree[i].data=0;} //배열의 원소 초기화
    tree[0].data=14; tree[0].leftchild=&tree[1]; tree[0].rightchild=&tree[2]; 
    tree[1].data=12; tree[1].leftchild=&tree[3]; tree[1].rightchild=&tree[4]; 
    tree[2].data=7;  tree[2].leftchild=&tree[5];
    tree[3].data=10
    tree[4].data=8;
    tree[5].data=6;  //교과서와 같이 트리 생성
    root=&tree[0];  //root에 tree[0]의 주소 대입 (첫번째 노드)
    printf("번호    값    주소\n");
    for(i=0;i<MAX_SIZE;i++)
    {printf("[%d]번 노드 : %d    %d\n",i,tree[i].data,&tree[i]);} //트리의 각 노드 값과 주소 출력
    search_max_heap(root,&res,10); //서치 펑션 호출, 10을 찾음
    printf("찾은값    해당주소\n"); 
    printf("%d    %d\n",res->data,res); //찾고싶은 값의 주소와 값을 가리키는 res 출력
    
    return 0;
}
 
void search_max_heap(treepointer ptr,treepointer *res,int value)
{
    if(ptr){ //ptr이 NULL이 아니면
    if(ptr->data==value)  //ptr이 가리키는 data가 value와 같으면
        *res=ptr; //res가 가리키는 포인터에 ptr의 주소 대입
    else if(((ptr->data)>value)){ //ptr->data가 value보다 크면
        search_max_heap(ptr->leftchild,res,value); //ptr->leftchild로 서치 펑션 재귀적 호출
        search_max_heap(ptr->rightchild,res,value);} //ptr->rightchild로 서치 펑션 재귀적 호출
    else if((ptr->data)<value){ //ptr->data가 value보다 작으면
        printf("%d는 %d보다 작다.\n",ptr->data,value); //아무것도 안해도 되지만 디버깅 위해 문장 출력
    }}
    
}
cs



3. Write the swapTree function of C that swap left child and right child of all nodes.

<Figure 4. swapTree>



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <stdio.h>
#define MAX_SIZE 10 //스택 최대 크기
 
typedef struct node* treepointer;  //node 자료형 포인터의 새로운 이름 treepointer
typedef struct node{
    char data;
    treepointer leftchild, rightchild;
}node; //node 구조체 자료형의 새로운 이름 node, 안에는 char형 data와 treepointer형 leftchild, rightchild가 들어있다.
 
 
void swap_bin_tree(treepointer ptr);
void print(treepointer ptr);
 
int main(void)
{
    int i; // int형 변수 i
    treepointer root; //treepointer 형 포인터 변수 root
    node tree[MAX_SIZE]; // node 배열 tree 크기는 10
    for(i=0;i<MAX_SIZE;i++//i=0부터 10보다 작을때까지 반복
    {tree[i].leftchild=0; tree[i].rightchild=0;tree[i].data=0;} //배열의 원소 초기화
    tree[0].data='A'; tree[0].leftchild=&tree[1]; tree[0].rightchild=&tree[2]; 
    tree[1].data='B'; tree[1].leftchild=&tree[3]; tree[1].rightchild=&tree[4]; 
    tree[2].data='C'; tree[2].leftchild=&tree[5];
    tree[3].data='D';                              tree[3].rightchild=&tree[6]; 
    tree[4].data='E';
    tree[5].data='F';                              tree[5].rightchild=&tree[7]; 
    tree[6].data='G';
    tree[7].data='H'//교과서와 같이 이진 트리 구현
    root=&tree[0];  //root에 tree[0]의 주소 대입 (첫번째 노드)
    printf("번호    값    주소\n");
    for(i=0;i<MAX_SIZE;i++)
    {printf("[%d]번 노드 : %c    %d\n",i,tree[i].data,&tree[i]);} //각 노드의 값과 주소 출력
    swap_bin_tree(root); //트리 스왑
    print(root); //스왑된 트리 확인
    return 0;
}
 
void swap_bin_tree(treepointer ptr)
{
    treepointer temp; //treepointer 즉 node의 포인터 temp
    if(ptr){ //ptr이 NULL이아니면 
        temp=ptr->leftchild;  
        ptr->leftchild=ptr->rightchild;
        ptr->rightchild=temp; //temp라는 빈 물 컵을 이용해 left와 right의 스왑
        
        if(ptr->leftchild) //leftchild가 null이 아니면 (불필요한 반복 줄이기 위해 한번 더 검사)
    swap_bin_tree(ptr->leftchild); //스왑
        if(ptr->rightchild) //rightchild가 null이 아니면 (불필요한 반복 줄이기 위해 한번 더 검사)
    swap_bin_tree(ptr->rightchild); //스왑
    }}
void print(treepointer ptr)
{
    if(ptr){
    printf("노드             : %c    %d\n",ptr->data,ptr); //노드 값, 주소 출력
    if(ptr->leftchild) //ptr->leftchild가 NULL이 아니면 (불필요한 반복 줄이기 위해 한번 더 검사)
    printf("노드 왼쪽 자식   : %c    %d\n",(ptr->leftchild)->data,ptr->leftchild); //노드 왼쪽 자식 값, 주소 출력
    if(ptr->rightchild) //ptr->rightchild가 NULL이 아니면 (불필요한 반복 줄이기 위해 한번 더 검사)
    printf("노드 오른쪽 자식 : %c    %d\n",(ptr->rightchild)->data,ptr->rightchild); //노드 오른쪽 자식 값, 주소 출력
    if(ptr->leftchild) //ptr->leftchild가 NULL이 아니면
    print(ptr->leftchild); // 재귀호출 프린트
        if(ptr->rightchild) //ptr->rightchild가 NULL이 아니면
    print(ptr->rightchild); //재귀호출 프린트
    }
}
cs







반응형
반응형

7.5>하나의 학생 정보를 Student 클래스로 표현한다. Student 클래스에는 이름, 학과, 학번, 학점 평균을 나타내는 필드가 있다. 키보드로 학생 정보를 5개 입력 받아  ArrayList<Student>에 저장한 후에 ArrayList<Student>의 모든 학생 정보를 출력하는 프로그램을 작성하라.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package SecondHW;
import java.util.*//Arraylist와 스캐너 사용 위한 임포트
class Student{ //Student 클래스, 스트링형 name, department, 정수형 number, double형 score 포함
    String name;
    String department;
    int number;
    double score;
    public Student(String name, String department, int number, Double score){
        this.name=name; //Studnet 클래스의 생성자 인자를 객체의 각 원소에 대입한다.
        this.department=department;
        this.number=number;
        this.score=score;
    }}
public class Roaster {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);  //스캐너 객체
        ArrayList<Student> st = new ArrayList<Student>(); //Student를 원소로 갖는 어레이리스트
        System.out.println("학생 정보를 입력하세요: ");
        for(int i=0;i<5;i++//5번 반복
        {
                System.out.print((i+1)+"이름>>");
                String name=s.nextLine();
                System.out.print((i+1)+"학과>>");
                String department=s.nextLine();
                System.out.print((i+1)+"학번>>");
                int number=s.nextInt();
                System.out.print((i+1)+"학점평균>>");
                double score=s.nextDouble();  //이름, 학과, 학번, 학점평균을 Scanner객체 s를 이용하여 받는다.
                Student tmp = new Student(name,department,number,score); //Student 객체 tmp 생성 
                st.add(tmp); //tmp를 st의 원소로 추가
                s.nextLine(); //버퍼에서 개행문자를 비워주기 위함
        }
        for(int i=0;i<st.size();i++){ //st.size=5이므로 5번 반복
            Student res = st.get(i); //어레이리스트 st에서 i번째 인덱스 원소를 res에 대입
            System.out.println("=============================");
            System.out.println("이름: "+res.name);
            System.out.println("학과: "+res.department);
            System.out.println("학번: "+res.number);
            System.out.println("학점평균: "+res.score);
            System.out.println("=============================");//각 원소 출력
        }}}
 
cs




반응형

'컴퓨터 & 프로그래밍 & 전자공학 > JAVA' 카테고리의 다른 글

제네릭 클래스  (0) 2017.06.19
학점 계산  (0) 2017.06.19
가장 큰 수  (0) 2017.06.19
겜블링 게임  (0) 2017.06.19
가위바위보  (0) 2017.06.19
반응형

7.2>Scanner 클래스를 사용하여 5개 학점(‘A’, ‘B’, ‘C’, ‘D’, ‘F’)을 문자로 입력 받아 ArrayList에 저장한다. 그리고 ArrayList를 검색하여 학점을 점수(A=4.0, B=3.0, C=2.0, D=1.0, F=0)로 변환하고 평균을 계산하여 그 결과를 출력하는 프로그램을 작성하라.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package SecondHW;
import java.util.*//scanner와 vector 사용을 위한 임포트
public class Grades {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in); //스캐너 객체와 레퍼런스 변수 생성
        ArrayList<Character> grade= new ArrayList<Character>(); //ArrayList 객체와 레퍼런스 변수 생성, 스레드 동기화 지원 안함
        double sum=0//실수 변수 sum 초기화 0
        int count=0//정수 변수 count 초기화 0
        double score[]=new double[5]; //실수형 배열 크기 5 score
        System.out.print("5개의 학점을 빈 칸으로 분리하여 입력하세요. (A/B/C/D/F)");
        while(count!=5//count가 5가 아닐때까지 반복, for를 쓰지 않은 이유는 A,B,C,D,F 이외의 것을 걸러내야해서 continue써야하는데
            //for 에서 continue 쓰면 증감식은 그대로 실행되어버리니까
        {
            String st = s.next(); //String에 문자열 입력
            char c = st.charAt(0); //지정된 index에 있는 문자 리턴해서 c에 대입
            if((c>='A'&&c<='D')||c=='F'//c가 A~D 혹은 F이면
            {grade.add(c); count++;} //grade에 c를 추가하고 count 증가
            else continue//아니면 continue;
        }
        for(int i=0;i<grade.size();i++//i=0부터 grade.size보다 작을때까지 반복, size는 5
        {
            if(grade.get(i)=='A')   //grade의 index에 해당하는 값이 A일때
            {score[i]=4.0;} //score[i]에 4.0 대입
            else if(grade.get(i)=='B'//grade의 index에 해당하는 값이 B일때
            {score[i]=3.0;} //score[i]에 3.0 대입
            else if(grade.get(i)=='C'//grade의 index에 해당하는 값이 C일때
            {score[i]=2.0;} //score[i]에 2.0 대입
            else if(grade.get(i)=='D'//grade의 index에 해당하는 값이 D일때
            {score[i]=1.0;} //score[i]에 1.0 대입
            else if(grade.get(i)=='F'//grade의 index에 해당하는 값이 F일때
            {score[i]=0.0;} //score[i]에 0.0 대입
            System.out.print(score[i]+" "); //socre[i]와 공백문자 출력
            sum+=score[i]; //sum에 sum과 score[i] 더한 값 대입
        }
        System.out.println(); //개행문자 출력
        System.out.print("평균 : "+sum/grade.size() ); //평균 출력}}
 
cs



반응형

'컴퓨터 & 프로그래밍 & 전자공학 > JAVA' 카테고리의 다른 글

제네릭 클래스  (0) 2017.06.19
학생 정보  (0) 2017.06.19
가장 큰 수  (0) 2017.06.19
겜블링 게임  (0) 2017.06.19
가위바위보  (0) 2017.06.19
반응형

7.1>Scanner 클래스를 사용하여 10개의 실수 값을 키보드로부터 읽어 벡터에 저장한 후, 벡터를 검색하여 가장 큰 수를 출력하는 프로그램을 작성하라.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package SecondHW;
import java.util.*//scanner와 vector 사용을 위한 임포트
public class Biggest {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);  //스캐너 객체와 레퍼런스 변수 생성
        Vector<Double>v=new Vector<Double>(10); //벡터 객체와 레퍼런스 변수 생성 초기 cap이 10
        for(int i=0;i<v.capacity();i++//i=0부터 v.cap (즉 10) 미만일때까지 반복 즉 10번 반복
        {
            double a = s.nextDouble(); //double형 변수 a 에 키보드 입력 double로 받음
            v.add(a); //자동 박싱 v.add(new Double(a))와 같음 , 벡터 v에 a 삽입
        }
        double biggest = v.get(0); //가장 큰 숫자를 넣을 double형 변수 biggest에 초기값 v의
 //첫번째 원소 대입
        for(int i=1;i<v.size();i++//0은 비교할필요 없으니 1부터 size(10) 미만, 
//즉 1~9의 인덱스에 해당하는 원소 비교
        {
            if(biggest<v.get(i)) //biggest보다 해당 인덱스 원소가 크면
                biggest=v.get(i); //biggest에 그 원소 대입
        }
        System.out.println("가장 큰 수는 "+biggest+" 입니다."); //제일 큰 것 출력
    }}
 
cs




반응형

'컴퓨터 & 프로그래밍 & 전자공학 > JAVA' 카테고리의 다른 글

학생 정보  (0) 2017.06.19
학점 계산  (0) 2017.06.19
겜블링 게임  (0) 2017.06.19
가위바위보  (0) 2017.06.19
대문자 개수 세기  (0) 2017.06.19

+ Recent posts