[go: up one dir, main page]

0% found this document useful (0 votes)
35 views5 pages

Dandy

The document outlines the implementation of two classes, MountainTrail and Mountain, in an object-oriented programming context. It specifies the attributes and methods for each class, including constructors, destructors, and methods for calculating difficulty and displaying information. Additionally, it includes a sorting function for mountains based on peak elevation and provides a main function for testing various functionalities.

Uploaded by

Zlatce Milenkow
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views5 pages

Dandy

The document outlines the implementation of two classes, MountainTrail and Mountain, in an object-oriented programming context. It specifies the attributes and methods for each class, including constructors, destructors, and methods for calculating difficulty and displaying information. Additionally, it includes a sorting function for mountains based on peak elevation and provides a main function for testing various functionalities.

Uploaded by

Zlatce Milenkow
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

COURSES   Златко Миленков

Објектно-ориентирано програмирање-2024/2025/L
Home / My courses / ОOП-2024/2025/L-46_42822 / 31 March - 6 April / Лабораториска вежба 3 за вежбање

Quiz navigation
Question 1
Да се дефинира класа MountainTrail за која се чуваат следните податоци:
1 2 3 4 5 Correct
name - име на патеката, низа од карактери
Marked out of
1.00 length - должина на патеката во километри, цел број
Finish attempt ... slope - наклон на патеката изразен во проценти, double
Flag question

За класата да се дефинира default конструктор, конструктор со аргументи и copy конструктор.


За класата да се дефинира метод double difficulty() кој ја пресметува тежината на патеката по следната формула: должина * наклон / 100. Да се дефинира и метод void display() кој
ги печати податоците за патеката во следниот формат: [име] [должина] [наклон].
Потоа да се дефинира класа Mountain за која се чува:
name - име на планината, низа од карактери
trails - низа од 5 патеки кои се наоѓаат на планината
peak_elevation - надморска височина на врвот, цел број
num_mountains - бр. на планини за кои водиме сметка во програмата (вредноста на ова поле треба да биде иста во сите објекти, треба да има и get метод)

За класата да се дефинира default конструктор, конструктор со аргументи, како и деструктор. Потребно е секој од овие методи да го ажурира вкупниот број на планини.

Во класата да се дефинира метод display() кој ќе печати податоци за планината во следниот формат: [име]: [н.в. на врвот]m

Надвор од класата да се дефинира метод void sortMountainsByPeakElevation(Mountain mountains[], int n) кој прима низа од планини и ги печати во опаѓачки редослед според
надморската висина на нивниот врв. Овој метод мора да пристапува директно до приватното поле за надморска висина.

Да не се менува main функцијата.

------------------------------------------------

Define a class MountainTrail for which the following data are stored:

name - name of the trail, string array


length - length of the trail in kilometers, integer
slope - slope of the trail expressed in percentages, double

For the class, define a default constructor, a constructor with arguments, and a copy constructor.

Additionally, define a method double difficulty() that calculates the difficulty of the trail using the following formula: length * slope / 100 and a void display() method which prints the data
for the trail in the following format: [name] [length] [slope].

Then, define a class Mountain for which the following data is stored:
name - name of the mountain, string array
trails - array of 5 trails located on the mountain
peak_elevation - elevation of the peak, integer
num_mountains - number of mountains tracked in the program (the value of this field should be the same in all objects, it should also have a get method)

For the class, define a default constructor, a constructor with arguments, a destructor (each of these methods needs to update the total number of mountains), and a display() method that
prints data for the mountain in the following format: [name]: [peak elevation]m

Outside the class, define a method void sortMountainsByPeakElevation(Mountain mountains[], int n) that takes an array of mountains and prints them in descending order according to the
elevation of their peak. This method must access the private field for peak elevation directly.

Do not change the main function.

Answer: (penalty regime: 0 %)

Reset answer

1 #include<iostream>
2
3 using namespace std;
4
5 #include <iostream>
6 #include <cstring>
7 using namespace std;
8
9 ▼ class MountainTrail {
10 private:
11 char name[100];
12 int length;
13 double slope;
14 public:
15 ▼ MountainTrail() {
16 strcpy(name, "");
17 length = 0;
18 slope = 0;
19 }
20
21 ▼ MountainTrail(const char* name, int length, double slope) {
22 strcpy(this->name, name);
23 this->length = length;
24 this->slope = slope;
25 }
26
27 ▼ MountainTrail(const MountainTrail& o) {
28 strcpy(this->name, o.name);
29 this->length = o.length;
30 this->slope = o.slope;
31 }
32
33 ▼ double difficulty() const {
34 return length * slope / 100;
35 }
36
37 ▼ void display() const {
38 cout << name << " " << length << " " << slope << endl;
39 }
40 };
41
42 ▼ class Mountain {
43 private:
44 char name[100];
45 MountainTrail trails[5];
46 int peak_elevation;
47 static int num_mountains;
48
49 friend void sortMountainsByPeakElevation(Mountain mountains[], int n);
50
51 public:
52 ▼ Mountain() {
53 strcpy(name, "");
54 peak_elevation = 0;
55 // No need to reset num_mountains here
56 }
57
58 ▼ Mountain(const char* name, MountainTrail trails[5], int peak_elevation) {
59 strcpy(this->name, name);
60 ▼ for (int i = 0; i < 5; ++i) {
61 this->trails[i] = trails[i];
62 }
63 this->peak_elevation = peak_elevation;
64 ++num_mountains;
65 }
66
67 ▼ Mountain(const Mountain& other) {
68 strcpy(this->name, other.name);
69 ▼ for (int i = 0; i < 5; ++i) {
70 this->trails[i] = other.trails[i];
71 }
72 this->peak_elevation = other.peak_elevation;
73 ++num_mountains;
74 }
75
76 ▼ ~Mountain() {
77 --num_mountains;
78 }
79
80 ▼ static int getNumMountains() {
81 return num_mountains;
82 }
83
84 ▼ void display() const {
85 cout << name << ": " << peak_elevation << "m" << endl;
86 }
87 };
88
89 ▼ void sortMountainsByPeakElevation(Mountain mountains[], int n) {
90 ▼ for (int i = 0; i < n - 1; ++i) {
91 ▼ for (int j = 0; j < n - i - 1; ++j) {
92 ▼ if (mountains[j].peak_elevation < mountains[j + 1].peak_elevation) {
93 Mountain temp = mountains[j];
94 mountains[j] = mountains[j + 1];
95 mountains[j + 1] = temp;
96 }
97 }
98 }
99
100 ▼ for (int i = 0; i < n; ++i) {
101 mountains[i].display();
102 }
103 }
104
105 int Mountain::num_mountains = 0;
106
107 ▼ int main() {
108
109 int test_case_n;
110
111 char trail_name[100];
112 int trail_length;
113 double trail_slope;
114
115 char mountain_name[100];
116 int mountain_peak_elevation;
117
118 cin>>test_case_n;
119 ▼ if (test_case_n == 0) {
120 cout << "Testing MountainTrail c-tors, display function:"<<endl;
121 cin >> trail_name >> trail_length >> trail_slope;
122 MountainTrail mt = MountainTrail(trail_name, trail_length, trail_slope);
123 MountainTrail mt2 = MountainTrail(mt);
124 mt.display();
125 mt2.display();
126 ▼ } else if (test_case_n == 1) {
127 cout << "Testing MountainTrail difficulty function:"<<endl;
128 ▼ for (int i = 0; i < 5; ++i) {
129 cin >> trail_name >> trail_length >> trail_slope;
130 MountainTrail mt = MountainTrail(trail_name, trail_length, trail_slope);
131 cout<<mt.difficulty()<<endl;
132 }
133 ▼ } else if (test_case_n == 2) {
134 cout << "Testing Mountain c-tor, display function:"<<endl;
135 MountainTrail trails[5];
136
137 cin>>mountain_name>>mountain_peak_elevation;
138
139 ▼ for (int i = 0; i < 5; ++i) {
140 cin >> trail_name >> trail_length >> trail_slope;
141 trails[i] = MountainTrail(trail_name, trail_length, trail_slope);
142 }
143
144 Mountain mountain = Mountain(mountain_name, trails, mountain_peak_elevation);
145 mountain.display();
146 ▼ } else if (test_case_n == 3) {
147 cout << "Testing static field in Mountain:" <<endl;
148 MountainTrail trails[5];
149
150 cin>>mountain_name>>mountain_peak_elevation;
151
152 ▼ for (int i = 0; i < 5; ++i) {
153 cin >> trail_name >> trail_length >> trail_slope;
154 trails[i] = MountainTrail(trail_name, trail_length, trail_slope);
155 }
156
157 ▼ for (int i = 0; i < 10; ++i) {
158 Mountain mountain = Mountain(mountain_name, trails, mountain_peak_elevation);
159 }
160
161 Mountain m1 = Mountain(mountain_name, trails, mountain_peak_elevation);
162 Mountain m2 = Mountain(mountain_name, trails, mountain_peak_elevation);
163 Mountain m3 = Mountain(mountain_name, trails, mountain_peak_elevation);
164 Mountain m4 = Mountain(mountain_name, trails, mountain_peak_elevation);
165 Mountain m5 = Mountain(mountain_name, trails, mountain_peak_elevation);
166
167 ▼ if(Mountain::getNumMountains() == 5) {
168 cout<<"OK";
169 ▼ } else {
170 cout<<"Missing mountain count increment/decrement";
171 }
172 ▼ } else if (test_case_n == 4) {
173 int M;
174 cin>>M;
175 cout<<"Testing order function:"<<endl;
176
177 Mountain mountains[M];
178
179 ▼ for (int i = 0; i < M; ++i) {
180 cin>>mountain_name>>mountain_peak_elevation;
181 MountainTrail trails[5];
182
183 ▼ for (int j = 0; j < 5; ++j) {
184 cin >> trail_name >> trail_length >> trail_slope;
185 trails[j] = MountainTrail(trail_name, trail_length, trail_slope);
186 }
187
188 mountains[i] = Mountain(mountain_name, trails, mountain_peak_elevation);
189 }
190
191 sortMountainsByPeakElevation(mountains, M);
192 }
193 }

Precheck Check

Input Expected Got

 0 Testing MountainTrail c-tors, display function: Testing MountainTrail c-tors, display function: 
RidgeRun 10 15.5 RidgeRun 10 15.5 RidgeRun 10 15.5
RidgeRun 10 15.5 RidgeRun 10 15.5

 1 Testing MountainTrail difficulty function: Testing MountainTrail difficulty function: 


RidgeRun 10 15.5 1.55 1.55
SummitLoop 8 12.8 1.024 1.024
ValleyView 12 18.2 2.184 2.184
CanyonTrail 6 20.0 1.2 1.2
PinePath 5 10.7 0.535 0.535

 2 Testing Mountain c-tor, display function: Testing Mountain c-tor, display function: 
Korab 2764 Korab: 2764m Korab: 2764m
RidgeRun 10 15.5
SummitLoop 8 12.8
ValleyView 12 18.2
CanyonTrail 6 20.0
PinePath 5 10.7

 3 Testing static field in Mountain: Testing static field in Mountain: 


Korab 2764 OK OK
RidgeRun 10 15.5
SummitLoop 8 12.8
ValleyView 12 18.2
CanyonTrail 6 20.0
PinePath 5 10.7

 4 Testing order function: Testing order function: 


2 Matterhorn: 4478m Matterhorn: 4478m
Matterhorn 4478 Fuji: 3776m Fuji: 3776m
ValleyWalk 6 12.2
PeakTrail 8 17.8
StonePath 5 11.5
FrostyRidge 9 13.6
Cliffside 7 10.4

Fuji 3776
BambooTrail 5 9.8
CherryBlossom 6 14.1
GoldenGate 7 11.9
MoonlitPath 8 16.5
RainbowRidge 9 13.2

 4 Testing order function: Testing order function: 


3 Everest: 8848m Everest: 8848m
Everest 8848 Denali: 6190m Denali: 6190m
RidgeRun 10 15.5 Kilimanjaro: 5895m Kilimanjaro: 5895m
SummitLoop 8 12.8
ValleyView 12 18.2
CanyonTrail 6 20.0
PinePath 5 10.7

Kilimanjaro 5895
ForestTrail 8 10.0
RockyRidge 6 14.5
WaterfallWay 7 11.2
SunrisePath 5 9.8
LakeView 9 13.7

Denali 6190
AlpineTrack 12 16.0
GlacierGorge 10 18.5
MistyMeadow 8 11.9
SnowySummit 11 14.3
SunsetTrail 7 9.6

 4 Testing order function: Testing order function: 


8 Everest: 8848m Everest: 8848m
Everest 8848 K2: 8611m K2: 8611m
RidgeRun 10 15.5 Aconcagua: 6962m Aconcagua: 6962m
SummitLoop 8 12.8 Denali: 6190m Denali: 6190m
ValleyView 12 18.2 Kilimanjaro: 5895m Kilimanjaro: 5895m
CanyonTrail 6 20.0 Elbrus: 5642m Elbrus: 5642m
PinePath 5 10.7 Matterhorn: 4478m Matterhorn: 4478m
Fuji: 3776m Fuji: 3776m
Kilimanjaro 5895
ForestTrail 8 10.0
RockyRidge 6 14.5
WaterfallWay 7 11.2
SunrisePath 5 9.8
LakeView 9 13.7

Denali 6190
AlpineTrack 12 16.0
GlacierGorge 10 18.5
MistyMeadow 8 11.9
SnowySummit 11 14.3
SunsetTrail 7 9.6

Matterhorn 4478
ValleyWalk 6 12.2
PeakTrail 8 17.8
StonePath 5 11.5
FrostyRidge 9 13.6
Cliffside 7 10.4

Fuji 3776
BambooTrail 5 9.8
CherryBlossom 6 14.1
GoldenGate 7 11.9
MoonlitPath 8 16.5
RainbowRidge 9 13.2

Elbrus 5642
IcePath 7 16.2
ValleyVista 9 13.5
CloudTrail 8 11.8
RockyPeak 10 18.4
MistCanyon 6 9.9

Aconcagua 6962
DesertTrail 11 14.5
SunsetSlope 8 12.3
HighlandHike 9 17.1
EchoValley 7 10.6
DiamondRidge 10 15.8

K2 8611
SnowySaddle 12 17.9
SkylineTrail 10 14.7
ForestFalls 8 11.2
MajesticMeadow 9 16.3
CrystalCreek 11 13.4

Passed all tests! 

Next page

◄ Предавање 6 - Оператори Jump to...

You are logged in as Златко Миленков (Log out)


ОOП-2024/2025/L-46_42822
Data retention summary
Get the mobile app
COURSES   Златко Миленков

Објектно-ориентирано програмирање-2024/2025/L
Home / My courses / ОOП-2024/2025/L-46_42822 / 31 March - 6 April / Лабораториска вежба 3 за вежбање

Quiz navigation
Question 2
Енда IT компанија во Македонија сака да додели стипендии на 3ца најдобри студенти на ФИНКИ. На огласот за стипендии може да конкурираат студенти и од други факултети, но
1 2 3 4 5 Correct
стипендиите се наменети исклучиво за студентите на ФИНКИ и тоа со проесек поголем од 9. За таа цел вие треба да и помогнете на оваа компанија за да ги најде најдобрите три
Marked out of студента.
1.00
Finish attempt ...
Flag question
Дефинирајте класа Student со следниве атрибути:
-име (низа од карактери)
-презиме (низа од карактери)
-факултет (низа од карактери)
-просек од оцени (float)
-вкупен број на студенти што аплицирале (статичка променлива)
-број на студенти што аплицирале од ФИНКИ (статичка променлива)
За самата класа да се дефинира: default конструктор, конструктор со аргументи, деструктор, како и метода bool finkiStudent() која ќе проверува дали некој студент е од ФИНКИ и има
просек поголем од 9.

Дефинирајте и класа Scholarship со следниве атрибути:


-име на компанијата која ја доделува стипендијата (низа од карактери)
-листа од студенти кои имаат аплицирано за стипендија
-средна вредност на просекот на студентите кои се од ФИНКИ со просек поголем од 9 (статичка променлива)
Дополнително во самата класа да се дефинира: default конструктор, конструктор со аргументи, деструктор, метод за додавање на нов студент и метод за печатење на името на
компанијата која ја издава стипендијата вклучувајќи го и бројот на студенти кои имале аплицирано за таа стипендија.

Надвор од оваа класа да се дефинира функција void studentsWithScholarship(Scholarship &scholarship, int num_students) која ќе биде пријател на двете класи и ќе ги прикаже 3-
цата добитници на овој тип стипендија. Освен тоа на крај оваа функција треба да ги испринта следниви основни статистички карактеристики за конкурсот:
- колку проценти од пријавените студенти (кои исполнуваат услови) се од ФИНКИ
- која е средната вредност на просекот на студентите кои го исполнувале условот за добивање на стипендија

Забелешка: Се претпоставува дека повеќе од 3ца студенти ќе го исполнат условот за добивање на стипендија. 
НЕ го менувајте main-от!
For example:

Input Result

0 --Testing finkiStudent method--


0

1 --Testing addStudent and print method--


Scholarship name: ITCompany, total applicants: 1

2 Scholarship name: ITCompany, total applicants: 5


ITCompany FINKI students with a scholarship
5 Pece Georgiev FINKI 9.93
Sandra Dimitrij Krstev FINKI 9.87
Georgiev Sandra Georgiev FINKI 9.25
FINKI Scholarship data shows that 60% of applicants are from FINKI, with an average grade of 9.68333
9.25
Dimitrij
Krstev
FINKI
9.87
Teodora
Mladenovska
FEIT
9.03
Aleksandar
Filipovski
FINKI
8.97
Pece
Georgiev
FINKI
9.93

2 Scholarship name: ITCompany, total applicants: 7


ITCompany FINKI students with a scholarship
7 Vlatko Spasev FINKI 9.92
Marija Marija Taneska FINKI 9.33
Taneska Pece Georgiev FINKI 9.1
FINKI Scholarship data shows that 57.1429% of applicants are from FINKI, with an average grade of 9.35
9.33
Sandra
Georgiev
BAS
9.25
Dimitrij
Krstev
FINKI
9.05
Teodora
Mladenovska
FEIT
9.03
Aleksandar
Filipovski
FINKI
8.97
Pece
Georgiev
FINKI
9.10
Vlatko
Spasev
FINKI
9.92

Answer: (penalty regime: 0 %)

Reset answer

1 #include <iostream>
2 #include <cstring>
3 #include <vector>
4 #include <algorithm>
5 using namespace std;
6
7 class Scholarship; // Forward declaration
8
9 ▼ class Student {
10 private:
11 char name[50];
12 char surname[50];
13 char faculty[50];
14 float average;
15 static int totalStudents;
16 static int finkiStudents;
17
18 public:
19 ▼ Student() {
20 strcpy(name, "");
21 strcpy(surname, "");
22 strcpy(faculty, "");
23 average = 0.0;
24 }
25
26 ▼ Student(const char* name, const char* surname, const char* faculty, float average) {
27 strcpy(this->name, name);
28 strcpy(this->surname, surname);
29 strcpy(this->faculty, faculty);
30 this->average = average;
31 totalStudents++;
32 ▼ if (finkiStudent()) {
33 finkiStudents++;
34 }
35 }
36
37 ▼ ~Student() {
38 totalStudents--;
39 ▼ if (finkiStudent()) {
40 finkiStudents--;
41 }
42 }
43
44 ▼ bool finkiStudent() const {
45 return strcmp(faculty, "FINKI") == 0 && average > 9.0;
46 }
47
48 ▼ float getAverage() const {
49 return average;
50 }
51
52 ▼ void print() const {
53 cout << name << " " << surname << " " << faculty << " " << average << endl;
54 }
55
56 ▼ static int getTotalStudents() {
57 return totalStudents;
58 }
59
60 ▼ static int getFinkiStudents() {
61 return finkiStudents;
62 }
63
64 friend class Scholarship;
65 friend void studentsWithScholarship(Scholarship&, int);
66 };
67
68 int Student::totalStudents = 0;
69 int Student::finkiStudents = 0;
70
71 ▼ class Scholarship {
72 private:
73 char company[50];
74 Student students[100];
75 int numStudents;
76 static float avgFinki;
77
78 public:
79 ▼ Scholarship() {
80 strcpy(company, "");
81 numStudents = 0;
82 }
83
84 ▼ Scholarship(const char* company) {
85 strcpy(this->company, company);
86 numStudents = 0;
87 }
88
89 ~Scholarship() {}
90
91 ▼ void addStudent(const Student& s) {
92 if (numStudents < 100)
93 students[numStudents++] = s;
94 }
95
96 ▼ void print() const {
97 cout << "Scholarship name: " << company << ", ";
98 cout << "total applicants: " << numStudents << endl;
99 }
100
101 friend void studentsWithScholarship(Scholarship&, int);
102 };
103
104 float Scholarship::avgFinki = 0.0;
105
106 ▼ void studentsWithScholarship(Scholarship& scholarship, int num_students) {
107 vector<Student> eligible;
108 float totalFinkiAverage = 0.0;
109 int countFinki = 0;
110
111 ▼ for (int i = 0; i < scholarship.numStudents; ++i) {
112 ▼ if (scholarship.students[i].finkiStudent()) {
113 eligible.push_back(scholarship.students[i]);
114 totalFinkiAverage += scholarship.students[i].getAverage();
115 countFinki++;
116 }
117 }
118
119 Scholarship::avgFinki = countFinki ? totalFinkiAverage / countFinki : 0.0;
120
121 ▼ sort(eligible.begin(), eligible.end(), [](Student a, Student b) {
122 return a.getAverage() > b.getAverage();
123 });
124
125 cout << "Scholarship name: " << scholarship.company << ", total applicants: " << scholarship.numStudents << endl;
126 cout << "FINKI students with a scholarship" << endl;
127 ▼ for (int i = 0; i < 3 && i < eligible.size(); ++i) {
128 eligible[i].print();
129 }
130
131 float percentFinki = (countFinki * 100.0) / num_students;
132 cout << "Scholarship data shows that " << percentFinki << "% of applicants are from FINKI, with an average grade of " << Scholarship::avgFin
133 }
134
135 //DO NOT CHANGE THE MAIN FUNCTION!
136 ▼ int main() {
137 char name[50], surname[50], faculty[50], scholarship_name[50];
138 float average_grade;
139 int n,case_;
140 cin>>case_;
141 if (case_ == 0)
142 //Testing Student constructor
143 ▼ {
144 cout<<"--Testing finkiStudent method--"<<endl;
145 Student s("Ana", "Denkova", "BAS", 9.89);
146 cout<<s.finkiStudent();
147 }
148 ▼ else if (case_==1){
149 //Testing addStudent and print method
150 cout<<"--Testing addStudent and print method--"<<endl;
151 Scholarship sc("ITCompany");
152 Student s("Ana", "Denkova", "BAS", 9.89);
153 sc.addStudent(s);
154 sc.print();
155 }
156 ▼ else if (case_ == 2){
157 cin>>scholarship_name;
158 Scholarship sc(scholarship_name);
159 cin>>n;
160 for(int i=0; i<n; i++)
161 ▼ {
162 cin>>name>>surname>>faculty>>average_grade;
163 Student s = Student(name, surname, faculty, average_grade);
164 sc.addStudent(s);
165 }
166 studentsWithScholarship(sc,n);
167 }
168 return 0;
169 }
170

Precheck Check

Input Expected Got

 1 --Testing addStudent and print method-- --Testing addStudent and print method--
Scholarship name: ITCompany, total applicants: 1 Scholarship name: ITCompany, total applicants: 1

 2 Scholarship name: ITCompany, total applicants: 5 Scholarship name: ITCompany, total applicants: 5
ITCompany FINKI students with a scholarship FINKI students with a scholarship
5 Pece Georgiev FINKI 9.93 Pece Georgiev FINKI 9.93
Sandra Dimitrij Krstev FINKI 9.87 Dimitrij Krstev FINKI 9.87
Georgiev Sandra Georgiev FINKI 9.25 Sandra Georgiev FINKI 9.25
FINKI Scholarship data shows that 60% of applicants are from FINKI, with an average grade of 9.68333 Scholarship data shows that 60% of applicants are from FINKI
9.25
Dimitrij
Krstev
FINKI
9.87
Teodora
Mladenovska
FEIT
9.03
Aleksandar
Filipovski
FINKI
8.97
Pece
Georgiev
FINKI
9.93

 2 Scholarship name: ITCompany, total applicants: 7 Scholarship name: ITCompany, total applicants: 7
ITCompany FINKI students with a scholarship FINKI students with a scholarship
7 Vlatko Spasev FINKI 9.92 Vlatko Spasev FINKI 9.92
Marija Marija Taneska FINKI 9.33 Marija Taneska FINKI 9.33
Taneska Pece Georgiev FINKI 9.1 Pece Georgiev FINKI 9.1
FINKI Scholarship data shows that 57.1429% of applicants are from FINKI, with an average grade of 9.35 Scholarship data shows that 57.1429% of applicants are from
9.33
Sandra
Georgiev
BAS
9.25
Dimitrij
Krstev
FINKI
9.05
Teodora
Mladenovska
FEIT
9.03
Aleksandar
Filipovski
FINKI
8.97
Pece
Georgiev
FINKI
9.10
Vlatko
Spasev
FINKI
9.92

Passed all tests! 

Previous page Next page

◄ Предавање 6 - Оператори Jump to...

You are logged in as Златко Миленков (Log out)


ОOП-2024/2025/L-46_42822
Data retention summary
Get the mobile app
COURSES   Златко Миленков

Објектно-ориентирано програмирање-2024/2025/L
Home / My courses / ОOП-2024/2025/L-46_42822 / 31 March - 6 April / Лабораториска вежба 3 за вежбање

Quiz navigation
Question 3 Да се направи класа County која ќе ги содржи следните променливи:
1 2 3 4 5 Correct
name, низа од карактери
Marked out of gdp, цел број
1.00
Finish attempt ...
Flag question За класата да се направи default конструктор, целосно параметризиран конструктор и get методи за двете променливи.
Да се направи класа State која ќе ги содржи следните променливи:
counties, низа од County објекти
name, низа од карактери
numCounties, цел број
federalTax, децимален број за процент на данок кој е заеднички за сите објекти од оваа класа и може да се пристапи без креирање на инстанца од истата. Иницијално да е
поставен на 15.5
redState, булеан вредност за дали државата е републиканска

За класата да се направи default конструктор, целосно параметризиран конструктор и следните функции:


get функции за променливите name, federalTax
set функција за променливата federalTax
increaseFederalTax(int increase) функција за зголемување на федералниот данок (моменталниот процент + додаток)
getFullGDP() функција која ќе го врати вкупниот ГДП на државата пресметан како збир на ГДП на сите окрузи (counties) на државата со одземен процент на федерален данок
print() метод што ќе печати во формат: "State of {име на држава} {во нов ред испечатени имињата на сите окрузи кои припаѓаат на државата}"

Дополнително да се дефинира функција friend void printStatesInGDPOrderByStateType(State states[], int numStates, bool redStates) која ќе ги печати сите држави во зависност
дали се републиканска или демократска држава (одредено со променливата redStates дадена како аргумент на функцијата) подредени според големината на ГДП што ја имаат. Оваа
функција треба да може директно да пристапува кон приватните членови на State класата

Create a County class that will contain the following variables:

name, a string of characters


gdp, integer

For the class, create a default constructor, a fully parameterized constructor and get methods for both variables.

Create a State class that will contain the following variables:

counties, an array of County objects


name, a string of characters
numCounties, integer
federalTax, a decimal number for the percentage of federal tax that is the same for all objects of this class and can be accessed without creating an instance of it. Initially set as 15.5
redState, boolean value for whether the state is Republican

For the class, make a default constructor, a fully parameterized constructor and the following functions:
get functions for the variables name, federalTax
set function for the federalTax variable
increaseFederalTax(int increase) function to increase the federal tax (current percentage + increase)
getFullGDP() function that will return the total GDP of the state calculated as the sum of the GDP of all counties of the state minus the percentage of federal tax
print() method that will print in the format: "State of {name of the state} {in a new line the names of all counties that belong to the state}"

Additionally define a function friend void printStatesInGDPOrderByStateType(State states[], int numStates, bool redStates) that will print all states depending on whether they are
Republican or Democrat (determined by the variable redStates given as an argument to the function) ordered by their GDP size. This function should be able to directly access the private
members of the State class.

For example:

Input Result

1 ---Testing constructors, getters, setters---


13.2 New York Federal tax: 13.2 Full GDP: 94.612

2 ---Testing print method---


Wayne State of New York
Richmond
Bronx
New York
Wayne

3 ---Testing increaseFederalTax static method---


2.1 15.5
17.6
89.816

4 ---Testing printStatesInGDPOrderByStateType---
0 Red states:
Blue states:
Ohio
New York

Answer: (penalty regime: 0 %)

Reset answer

1 #include <iostream>
2 #include <cstring>
3 using namespace std;
4
5 class State;
6
7 ▼ class County {
8 private:
9 char name[20];
10 int gdp;
11 public:
12 County() {}
13
14 ▼ County(char *name, int gdp) {
15 strcpy(this->name, name);
16 this->gdp = gdp;
17 }
18
19 ▼ char* getName() {
20 return name;
21 }
22
23 ▼ int getGdp() {
24 return gdp;
25 }
26
27 friend class State;
28 friend void printStatesInGDPOrderByStateType(State states[], int numStates, bool redStates);
29 };
30
31 ▼ class State {
32 private:
33 County counties[10];
34 char name[20];
35 int numCounties;
36 static float federalTax;
37 bool redState;
38
39 public:
40 State() {}
41
42 ▼ State(County counties[], char *name, int numCounties, bool redState) {
43 strcpy(this->name, name);
44 this->numCounties = numCounties;
45 this->redState = redState;
46 ▼ for (int i = 0; i < numCounties; i++) {
47 this->counties[i] = counties[i];
48 }
49 }
50
51 ▼ char* getName() {
52 return name;
53 }
54
55 ▼ static float getFederalTax() {
56 return federalTax;
57 }
58
59 ▼ static void setFederalTax(float fed) {
60 federalTax = fed;
61 }
62
63 ▼ static void increaseFederalTax(float increase) {
64 federalTax += increase;
65 }
66
67
68 ▼ double getFullGDP() {
69 double total = 0;
70 ▼ for (int i = 0; i < numCounties; i++) {
71 total += counties[i].getGdp() * (1 - federalTax / 100);
72 }
73 return total;
74 }
75
76 ▼ void print() {
77 cout << "State of " << name << endl;
78 ▼ for (int i = 0; i < numCounties; i++) {
79 cout << counties[i].getName() << endl;
80 }
81 }
82
83 friend void printStatesInGDPOrderByStateType(State states[], int numStates, bool redStates);
84 };
85
86 ▼ void printStatesInGDPOrderByStateType(State states[], int numStates, bool redStates) {
87 State filtered[100];
88 int count = 0;
89 ▼ for (int i = 0; i < numStates; i++) {
90 ▼ if (states[i].redState == redStates) {
91 filtered[count++] = states[i];
92 }
93 }
94
95 ▼ for (int i = 0; i < count - 1; i++) {
96 ▼ for (int j = 0; j < count - i - 1; j++) {
97 ▼ if (filtered[j].getFullGDP() < filtered[j + 1].getFullGDP()) {
98 State temp = filtered[j];
99 filtered[j] = filtered[j + 1];
100 filtered[j + 1] = temp;
101 }
102 }
103 }
104
105 ▼ for (int i = 0; i < count; i++) {
106 cout << filtered[i].getName() << endl;
107 }
108
109 }
110
111 //main should remain unchanged!
112 float State::federalTax = 15.5;
113
114 ▼ int main() {
115 int n;
116 cin >> n;
117 char name[30] = "Richmond";
118 County counties[3];
119 counties[0] = County(name, 20);
120 strcpy(name, "Bronx");
121 counties[1] = County(name, 57);
122 strcpy(name, "New York");
123 counties[2] = County(name, 32);
124 State state(counties, name, 3, false);
125 ▼ switch(n){
126 ▼ case 1: {
127 cout << "---Testing constructors, getters, setters---" << endl;
128 float fed;
129 cin >> fed;
130 State::setFederalTax(fed);
131 ▼ if (State::getFederalTax() == 15.5) {
132 cout << "State federal tax setter not OK!";
133 break;
134 }
135 cout << counties[2].getName() << " Federal tax: " << State::getFederalTax() << " Full GDP: "
136 << state.getFullGDP();
137 break;
138 }
139 ▼ case 2: {
140 cout << "---Testing print method---" << endl;
141 char name2[50];
142 cin >> name2;
143 County counties2[4];
144 ▼ for (int i = 0; i < 3; ++i) {
145 counties2[i] = counties[i];
146 }
147 counties2[3] = County(name2, 27);
148 State state2(counties2, name, 4, false);
149 state2.print();
150 break;
151 }
152 ▼ case 3: {
153 cout << "---Testing increaseFederalTax static method---" << endl;
154 float increase;
155 cin >> increase;
156 cout << State::getFederalTax() << endl;
157 State::increaseFederalTax(increase);
158 cout << State::getFederalTax() << endl;
159 cout << state.getFullGDP();
160 break;
161 }
162 default:
163 cout << "---Testing printStatesInGDPOrderByStateType---" << endl;
164 County counties2[4];
165 ▼ for (int i = 0; i < 3; ++i) {
166 counties2[i] = counties[i];
167 }
168 strcpy(name, "Wayme");
169 counties2[3] = County(name, 27);
170 strcpy(name, "Ohio");
171 State state2(counties2, name, 4, false);
172 int numStates;
173 cin >> numStates;
174 numStates = numStates + 2;
175 State states[numStates];
176 states[0] = state;
177 states[1] = state2;
178 bool redStateSType;
179 ▼ for (int i = 2; i < numStates; ++i) {
180 char stateName[30];
181 int numCounties;
182 cin >> stateName >> numCounties >> redStateSType;
183 County county[numCounties];
184 ▼ for (int j = 0; j < numCounties; ++j) {
185 char ime[30];
186 int GDP;
187 cin >> ime >> GDP;
188 county[j] = County(ime, GDP);
189 }
190 states[i] = State(county, stateName, numCounties, redStateSType);
191 }
192 cout << "Red states: "<<endl;
193 printStatesInGDPOrderByStateType(states, numStates, true);
194 cout << "Blue states: "<<endl;
195 printStatesInGDPOrderByStateType(states, numStates, false);
196
197 }
198 return 0;
199 }

Precheck Check

Input Expected Got

 1 ---Testing constructors, getters, setters--- ---Testing constructors, getters, setters--- 


13.2 New York Federal tax: 13.2 Full GDP: 94.612 New York Federal tax: 13.2 Full GDP: 94.612

 2 ---Testing print method--- ---Testing print method--- 


Wayne State of New York State of New York
Richmond Richmond
Bronx Bronx
New York New York
Wayne Wayne

 3 ---Testing increaseFederalTax static method--- ---Testing increaseFederalTax static method--- 


2.1 15.5 15.5
17.6 17.6
89.816 89.816

 4 ---Testing printStatesInGDPOrderByStateType--- ---Testing printStatesInGDPOrderByStateType--- 


0 Red states: Red states:
Blue states: Blue states:
Ohio Ohio
New York New York

 4 ---Testing printStatesInGDPOrderByStateType--- ---Testing printStatesInGDPOrderByStateType--- 


4 Red states: Red states:
California Texas Texas
5 Arizona Arizona
0 Blue states: Blue states:
Los-Angeles California California
100 Florida Florida
San-Francisco Ohio Ohio
55 New York New York
San-Diego
82
Orange
62
Riverside
43
Texas
4
1
Dallas
70
Austin
60
Houston
81
San-Antonio
55
Florida
3
0
Miami-Dade
90
Orange
62
Broward
71
Arizona
5
1
Nassau
51
Suffolk
55
Westchester
60
Erie
40
Monroe
45

Passed all tests! 

Previous page Next page

◄ Предавање 6 - Оператори Jump to...

You are logged in as Златко Миленков (Log out)


ОOП-2024/2025/L-46_42822
Data retention summary
Get the mobile app
COURSES   Златко Миленков

Објектно-ориентирано програмирање-2024/2025/L
Home / My courses / ОOП-2024/2025/L-46_42822 / 31 March - 6 April / Лабораториска вежба 3 за вежбање

Quiz navigation
Question 4
Да се дефинира класа Tour за која се чуваат слецните податоци:
1 2 3 4 5 Correct
destination - char[]
Marked out of
1.00 duration - int
Finish attempt ... price - double
Flag question
totalTours - static варијабла која брои колку вкупно тури се креирани, бројот да се инкрементира во конструкторот со аргумрнти
passengers - int

За класата да се дефинира default конструктор, конструктор со аргументи и copy конструктор.


За класата да се дефинира метод double profitByTour() со која се пресметува остварениот профит од дадената тура. (бројот на патници * цената на турата)
Да се креира и display метода во следниот формат:
Destination: [destination], Duration: [duration] days, Price: [price], Passengers: [passengers]

Потоа да се дефинира класа Agency за која се чува:

name - char[]
tours - низа од Tour која нема да има повеќе од 10 елементи
numTours - int

За класата да се дефинира default конструктор, конструктор со аргументи.


Да се креира и display метода во следниот формат:

Travel Agency: [name]


[tour1 display]
[tour2 display]
...

Исто така да се дефинира метода void addTour(Tour tour) со која ќе се додаваат тури во агенцијата.

Надвор од класата да се дефинира метод void findBestAgency(Agency *agencies, int numAgencies) кој прима низа од агении и ја печати онаа агенција која остварила најмногу
профит од сите тури. Овој метод мора да пристапува до самите приватни полиња од класите.

-----------------------------------------------
Define a class Tour that stores the following data:

destination - char[]
duration - int
price - double
totalTours - static variable that counts the total number of tours created, incremented in the constructor with arguments
passengers - int

For the class, define a default constructor, constructor with arguments, and copy constructor.
Define a method double profitByTour() for the class to calculate the profit made from the given tour. (number of passengers * tour price)

Create a display method in the following format:


Destination: [destination], Duration: [duration] days, Price: [price], Passengers: [passengers]
Then, define a class Agency that holds:
name - char[]
tours - an array of Tour with no more than 10 elements
numTours - int

For the class, define a default constructor and constructor with arguments.
Create a display method in the following format:
Travel Agency: [name]
[tour1 display]
[tour2 display]
...
Also, define a method void addTour(Tour tour) to add tours to the agency.
Outside the classes, define a method void findBestAgency(Agency *agencies, int numAgencies) which takes an array of agencies and prints the agency that has generated the most profit from
all tours. This method must access the private fields of the classes.

For example:

Input Result

0 Testing Tour c-tors, display function:


Rome 7 2000.0 70 Destination: Rome, Duration: 7 days, Price: 2000, Passengers: 70
Destination: Rome, Duration: 7 days, Price: 2000, Passengers: 70

1 Testing Tour profitByTour function:


Rome 7 2000.0 70 140000

2 Testing Agency c-tor, display function:


Agency3 Travel Agency: Agency3
3 Destination: Budapest, Duration: 3 days, Price: 1200, Passengers: 40
Budapest 3 1200.0 40 Destination: London, Duration: 8 days, Price: 2200, Passengers: 60
London 8 2200.0 60 Destination: Sydney, Duration: 14 days, Price: 4000, Passengers: 90
Sydney 14 4000.0 90

3 Testing static field in Tour:


3 Total number of tours: 6
Agency1
2
Paris 5 1500.0 50
Rome 7 2000.0 70
Agency2
1
Tokyo 10 3000.0 80
Agency3
3
Budapest 3 1200.0 40
London 8 2200.0 60
Sydney 14 4000.0 90

4 Travel Agency: Agency3


3 Destination: Budapest, Duration: 3 days, Price: 1200, Passengers: 40
Agency1 Destination: London, Duration: 8 days, Price: 2200, Passengers: 60
2 Destination: Sydney, Duration: 14 days, Price: 4000, Passengers: 90
Paris 5 1500.0 50
Rome 7 2000.0 70
Agency2
1
Tokyo 10 3000.0 80
Agency3
3
Budapest 3 1200.0 40
London 8 2200.0 60
Sydney 14 4000.0 90

Answer: (penalty regime: 0 %)

Reset answer

1 #include <iostream>
2 #include <cstring>
3 using namespace std;
4
5 class Agency;
6
7 ▼ class Tour {
8 private:
9 char destination[50];
10 int duration;
11 double price;
12 static int totalTours;
13 int passengers;
14 public:
15 Tour(){}
16 ▼ Tour(char *destination, int duration, double price, int passengers) {
17 strcpy(this->destination, destination);
18 this->duration = duration;
19 this->price = price;
20 this->passengers = passengers;
21 totalTours++;
22 }
23 ▼ Tour(const Tour &t) {
24 strcpy(destination, t.destination);
25 this->duration = t.duration;
26 this->price = t.price;
27 this->passengers = t.passengers;
28 }
29 ▼ double profitByTour() {
30 return passengers * price;
31 }
32 ▼ static int getNumTours() {
33 return totalTours;
34 }
35 ▼ void display() {
36 cout<<"Destination: "<<destination<<", Duration: "<<duration<<" days, Price: "<<price<<", Passengers: "<<passengers<<endl;
37 }
38 friend class Agency;
39 friend void findBestAgency(Agency *agencies, int numAgencies);
40 };
41
42 ▼ class Agency {
43 private:
44 char name[20];
45 Tour tours[10];
46 int numTours;
47 public:
48 Agency(){}
49 ▼ Agency(char *name, Tour tours[], int numTours) {
50 strcpy(this->name, name);
51 this->numTours = numTours;
52 ▼ for (int i = 0; i<numTours; i++) {
53 this->tours[i] = tours[i];
54 }
55 }
56 ▼ void setName(char n[20]) {
57 strcpy(name, n);
58 }
59
60 ▼ void display() {
61 cout<<"Travel Agency: "<<name<<endl;
62 ▼ for (int i = 0; i<numTours; i++) {
63 tours[i].display();
64 }
65 }
66 ▼ void addTour(const Tour& tour) {
67 ▼ if (numTours < 10) {
68 tours[numTours++] = tour;
69 }
70 }
71 ▼ double getVkupenProfit() {
72 double vkupenProfit = 0;
73 ▼ for (int i = 0; i<numTours; i++) {
74 vkupenProfit = vkupenProfit + tours[i].profitByTour();
75 }
76 return vkupenProfit;
77 }
78 friend void findBestAgency(Agency *agencies, int numAgencies);
79 };
80
81 // ostream operator<<(const ostream & lhs, const Agency & rhs);
82
83 ▼ void findBestAgency(Agency *agencies, int numAgencies) {
84 double maxProfit = agencies[0].getVkupenProfit();
85 int ind = 0;
86 ▼ for (int i = 1; i<numAgencies; i++) {
87 ▼ if (agencies[i].getVkupenProfit() > maxProfit) {
88 maxProfit = agencies[i].getVkupenProfit();
89 ind = i;
90 }
91 }
92 agencies[ind].display();
93 }
94 int Tour::totalTours = 0;
95 ▼ int main() {
96
97
98 int test_case_n;
99
100 char name[50];
101 char dest[50];
102 int dur;
103 double pr;
104 int pass;
105
106 cin>>test_case_n;
107
108 ▼ if (test_case_n == 0) {
109 cout << "Testing Tour c-tors, display function:"<<endl;
110 cin >> dest >> dur >> pr >> pass;
111 Tour t1 = Tour(dest, dur, pr, pass);
112 Tour t2 = Tour(t1);
113 t1.display();
114 t2.display();
115 ▼ } else if (test_case_n == 1) {
116 cout << "Testing Tour profitByTour function:"<<endl;
117 cin >> dest >> dur >> pr >> pass;
118 Tour t1 = Tour(dest, dur, pr, pass);
119 cout<<t1.profitByTour()<<endl;
120 ▼ } else if (test_case_n == 2) {
121 cout << "Testing Agency c-tor, display function:"<<endl;
122
123 Agency agency;
124
125 cin>>name;
126 agency.setName(name);
127 int numTours;
128 cin>>numTours;
129 ▼ for (int j = 0; j < numTours; ++j) {
130 cin>>dest>>dur>>pr>>pass;
131 agency.addTour(Tour(dest, dur, pr, pass));
132 }
133
134 agency.display();
135
136
137 ▼ } else if (test_case_n == 3) {
138 cout << "Testing static field in Tour:" <<endl;
139
140 Agency agency [10];
141 int n;
142 cin >> n;
143
144 ▼ for (int i = 0; i < n ; ++i) {
145 cin>>name;
146 agency[i].setName(name);
147 int numTours;
148 cin>>numTours;
149 ▼ for (int j = 0; j < numTours; ++j) {
150 cin>>dest>>dur>>pr>>pass;
151 agency[i].addTour(Tour(dest, dur, pr, pass));
152
153
154 }
155
156 }
157
158 cout<<"Total number of tours: "<<Tour::getNumTours()<<endl;
159
160
161
162 ▼ } else if (test_case_n == 4) {
163 Agency agency [10];
164 int n;
165 cin >> n;
166
167 ▼ for (int i = 0; i < n ; ++i) {
168 cin>>name;
169 agency[i].setName(name);
170 int numTours;
171 cin>>numTours;
172 ▼ for (int j = 0; j < numTours; ++j) {
173 cin>>dest>>dur>>pr>>pass;
174 agency[i].addTour(Tour(dest, dur, pr, pass));
175 }
176 }
177
178 findBestAgency(agency, n);
179 }
180
181
182 return 0;
183
184 }

Precheck Check

Input Expected Got

 0 Testing Tour c-tors, display function: Testing Tour c-tors, display function: 
Rome 7 2000.0 70 Destination: Rome, Duration: 7 days, Price: 2000, Passengers: 70 Destination: Rome, Duration: 7 days, Price: 2000, Passengers: 70
Destination: Rome, Duration: 7 days, Price: 2000, Passengers: 70 Destination: Rome, Duration: 7 days, Price: 2000, Passengers: 70

 1 Testing Tour profitByTour function: Testing Tour profitByTour function: 


Rome 7 2000.0 70 140000 140000

 2 Testing Agency c-tor, display function: Testing Agency c-tor, display function: 
Agency3 Travel Agency: Agency3 Travel Agency: Agency3
3 Destination: Budapest, Duration: 3 days, Price: 1200, Passengers: 40 Destination: Budapest, Duration: 3 days, Price: 1200, Passengers: 40
Budapest 3 1200.0 40 Destination: London, Duration: 8 days, Price: 2200, Passengers: 60 Destination: London, Duration: 8 days, Price: 2200, Passengers: 60
London 8 2200.0 60 Destination: Sydney, Duration: 14 days, Price: 4000, Passengers: 90 Destination: Sydney, Duration: 14 days, Price: 4000, Passengers: 90
Sydney 14 4000.0 90

 3 Testing static field in Tour: Testing static field in Tour: 


3 Total number of tours: 6 Total number of tours: 6
Agency1
2
Paris 5 1500.0 50
Rome 7 2000.0 70
Agency2
1
Tokyo 10 3000.0 80
Agency3
3
Budapest 3 1200.0 40
London 8 2200.0 60
Sydney 14 4000.0 90

 4 Travel Agency: Agency3 Travel Agency: Agency3 


3 Destination: Budapest, Duration: 3 days, Price: 1200, Passengers: 40 Destination: Budapest, Duration: 3 days, Price: 1200, Passengers: 40
Agency1 Destination: London, Duration: 8 days, Price: 2200, Passengers: 60 Destination: London, Duration: 8 days, Price: 2200, Passengers: 60
2 Destination: Sydney, Duration: 14 days, Price: 4000, Passengers: 90 Destination: Sydney, Duration: 14 days, Price: 4000, Passengers: 90
Paris 5 1500.0 50
Rome 7 2000.0 70
Agency2
1
Tokyo 10 3000.0 80
Agency3
3
Budapest 3 1200.0 40
London 8 2200.0 60
Sydney 14 4000.0 90

Passed all tests! 

Previous page Next page

◄ Предавање 6 - Оператори Jump to...

You are logged in as Златко Миленков (Log out)


ОOП-2024/2025/L-46_42822
Data retention summary
Get the mobile app
COURSES   Златко Миленков

Објектно-ориентирано програмирање-2024/2025/L
Home / My courses / ОOП-2024/2025/L-46_42822 / 31 March - 6 April / Лабораториска вежба 3 за вежбање

Quiz navigation
Question 5
Во рамките на една видео игра се чуваат податоци за кориснички профили (UserProfile) и нивните достигнувања во играта (Achievement). Вие треба да ги дефинирате класите и
1 2 3 4 5 Correct
функциите за коректна имплементација на системот. Не го менувајте дадениот код.
Marked out of
1.00
Finish attempt ... За таа цел, дефинирајте класа Achievement со приватни податочни членки:
Flag question
name - име на достигнувањето (низа од знаци);
description - опис на достигнувањето (низа од знаци);
totalUserAchievements - вкупен број на достигнувања на сите кориснички профили (static int).

Дополнете ја класата со default конструктор, конструктор со аргументи и copy конструктор како и следните функции:
print - функција која ги печати името и описот на достигнувањето во нов ред;
incrementTotalUserAchievements - функција која ја зголемува вредноста на totalUserAchievements за 1.

Потребно е да работите без get/set методи.

Понатаму, дефинирајте класа UserProfile со приватни податочни членки:

name - име на профилот (низа од знаци);


achievements - низа од добиени достигнувања на корисникот за дадената игра (максимална големина е 50);
n - број на добиени достигнувања на корисникот за дадената игра (иницијално поставен на 0).

Дополнете ја класата со default конструктор и конструктор со аргумент name.


Напишете ги функциите:
print - функција која го печати името на корисникот и неговите добиени достигнувања во играта во формат даден во тест примерите.
void addAchievement(const Achievement& achievement) - функција која во низата од достигнувања achievements го додава достигнувањето achievement и ја зголемува вредноста
на totalUserAchievements.

На крај, да се напише функција void showAchievementsProgress(UserProfile profiles[], int n, Achievement achievements[], int m) која директно пристапува до приватните членки на 
класите Achievement и UserProfile, и за секое достигнување во играта на екран ќе ги испечати името и описот на достигнувањето, како и процентот на корисници кои го добиле тоа
достигнување. На крај да се испечати просечниот број на добиени достигнувања со формулата totalUserAchievements * 100.0 / (n * m). Форматот на печатењето е даден во тест
примерите.

---------------------------------------
For each video game, data about user profiles (UserProfile) and their achievements in the game (Achievement) are stored. You need to define the classes and functions for the correct
implementation of the system. Do not modify the given code.

For this purpose, define the Achievement class with private data members:
name - name of the achievement (char array);
description - description of the achievement (char array);
totalUserAchievements - total number of achievements across all user profiles (static int).

Supplement the class with a default constructor, a constructor with arguments, and a copy constructor as well as the following functions:

print - a function that prints the name and description of the achievement on a new line;
incrementTotalUserAchievements - a function that increments the value of totalUserAchievements by 1.

You are required to work without get/set methods.

Furthermore, define the UserProfile class with private data members:


name - name of the profile (char array);
achievements - an array of achievements obtained by the user for the given game (maximum size is 50);
n - number of achievements obtained by the user for the given game (initially set to 0).

Supplement the class with a default constructor and a constructor with an argument name. Write the functions:
print - a function that prints the name of the user and their obtained achievements in the game in the format given in the test examples.
void addAchievement(const Achievement& achievement) - a function that adds the achievement achievement to the array of achievements achievements and increments the value of
totalUserAchievements.

Finally, write a function void showAchievementsProgress(UserProfile profiles[], int n, Achievement achievements[], int m) which directly accesses the private members of the Achievement and
UserProfile classes, and for each achievement in the game, it will print on the screen the name and description of the achievement, as well as the percentage of users who have obtained that
achievement. At the end, print the average number of obtained achievements with the formula totalUserAchievements * 100.0 / (n * m). The printing format is given in the test examples.

For example:

Input Result

Testing Achievement methods. Secret Achievement 1


1 "Description is hidden for this achievement."
ALL USERS: Final boss
Anonymous31 "Reach the final stage."
2
ALL ACHIEVEMENTS:
Secret Achievement 1
"Description is hidden for this achievement."
Final boss
"Reach the final stage."
2
LIST OF NUMBERS where user [num1] has achievement [num2]:
1 1
1 2

Testing UserProfile methods. User: Anonymous31


2 Achievements:
ALL USERS: Secret Achievement 1
Anonymous31 "Description is hidden for this achievement."
UltimateGamer Final boss
2 "Reach the final stage."
ALL ACHIEVEMENTS: User: UltimateGamer
Secret Achievement 1 Achievements:
"Description is hidden for this achievement." Final boss
Final boss "Reach the final stage."
"Reach the final stage."
3
LIST OF NUMBERS where user [num1] has achievement [num2]:
1 1
1 2
2 2

Testing showAchievementsProgress function. Secret Achievement 1


2 "Description is hidden for this achievement."
ALL USERS: ---Percentage of users who have this achievement: 50%
Anonymous31 Final boss
UltimateGamer "Reach the final stage."
2 ---Percentage of users who have this achievement: 100%
ALL ACHIEVEMENTS: ------Average completion rate of the game: 75%
Secret Achievement 1
"Description is hidden for this achievement."
Final boss
"Reach the final stage."
3
LIST OF NUMBERS where user [num1] has achievement [num2]:
1 1
1 2
2 2

Answer: (penalty regime: 0 %)

Reset answer

1 #include <iostream>
2 #include <cstring>
3 using namespace std;
4
5 class UserProfile;
6
7 ▼ class Achievement {
8 private:
9 char name[100];
10 char description[300];
11 static int totalUserAchievements;
12
13 public:
14 ▼ Achievement() {
15 strcpy(this->name, "");
16 strcpy(this->description, "");
17 }
18
19 ▼ Achievement(char* name, char* description) {
20 strcpy(this->name, name);
21 strcpy(this->description, description);
22 }
23
24 ▼ Achievement(const Achievement& a) {
25 strcpy(this->name, a.name);
26 strcpy(this->description, a.description);
27 }
28
29 ▼ void print() const {
30 cout << name << endl;
31 cout << description << endl;
32 }
33
34 ▼ static void incrementTotalUserAchievements() {
35 totalUserAchievements++;
36 }
37
38 friend class UserProfile;
39 friend void showAchievementsProgress(UserProfile profiles[], int n, Achievement achievements[], int m);
40 };
41
42 int Achievement::totalUserAchievements = 0;
43
44 ▼ class UserProfile {
45 private:
46 char name[100];
47 Achievement achievements[50];
48 int n;
49
50 public:
51 ▼ UserProfile() {
52 strcpy(this->name, "");
53 n = 0;
54 }
55
56 ▼ UserProfile(char* name) {
57 strcpy(this->name, name);
58 n = 0;
59 }
60
61 ▼ void print() const {
62 cout << "User: " << name << endl;
63 cout << "Achievements: " << endl;
64 ▼ for (int i = 0; i < n; i++) {
65 achievements[i].print();
66 }
67 }
68
69 ▼ void addAchievement(const Achievement& achievement) {
70 ▼ if (n < 50) {
71 achievements[n++] = achievement;
72 Achievement::incrementTotalUserAchievements();
73 }
74 }
75
76 friend void showAchievementsProgress(UserProfile profiles[], int n, Achievement achievements[], int m);
77 };
78
79 ▼ void showAchievementsProgress(UserProfile profiles[], int n, Achievement achievements[], int m) {
80 ▼ for (int i = 0; i < m; i++) {
81 int count = 0;
82 ▼ for (int j = 0; j < n; j++) {
83 ▼ for (int k = 0; k < profiles[j].n; k++) {
84 ▼ if (strcmp(profiles[j].achievements[k].name, achievements[i].name) == 0) {
85 count++;
86 break;
87 }
88 }
89 }
90 achievements[i].print();
91 cout << "---Percentage of users who have this achievement: " << (count * 100.0 / n) << "%" << endl;
92 }
93
94 cout << "------Average completion rate of the game: " << (Achievement::totalUserAchievements * 100.0 / (n * m)) << "%" << endl;
95 }
96
97
98 // Don't modify
99 ▼ int main() {
100 char testcase[100];
101 cin.getline(testcase, 100);
102
103 int n;
104 cin >> n;
105 cin.ignore();
106
107 char ignore[100];
108 cin.getline(ignore, 100);
109 UserProfile users[100];
110 ▼ for (int i = 0; i < n; ++i) {
111 char name[100];
112 cin >> name;
113 users[i] = UserProfile(name);
114 }
115
116 int m;
117 cin >> m;
118 cin.ignore();
119
120 cin.getline(ignore, 100);
121 Achievement achievements[100];
122 ▼ for (int i = 0; i < m; ++i) {
123 char name[100], description[100];
124 cin.getline(name, 100);
125 cin.getline(description, 100);
126 achievements[i] = Achievement(name, description);
127 }
128
129 int k;
130 cin >> k;
131 cin.ignore();
132
133 cin.getline(ignore, 100);
134 ▼ for (int i = 0; i < k; ++i) {
135 int numUser, numAchievement;
136 cin >> numUser >> numAchievement;
137 numUser -= 1;
138 numAchievement -= 1;
139 users[numUser].addAchievement(achievements[numAchievement]);
140 }
141
142 ▼ if (testcase[8] == 'A') { // Testing Achievement methods.
143 ▼ for (int i = 0; i < m; ++i) {
144 achievements[i].print();
145 }
146 Achievement::incrementTotalUserAchievements();
147 ▼ } else if (testcase[8] == 'U') { // Testing UserProfile methods.
148 ▼ for (int i = 0; i < n; ++i) {
149 users[i].print();
150 }
151 ▼ } else { // Testing showAchievementsProgress function.
152 showAchievementsProgress(users, n, achievements, m);
153 }
154
155 return 0;
156 }
157

Check

Input Expected

 Testing Achievement methods. Secret Achievement 1


1 "Description is hidden for this achievement."
ALL USERS: Final boss
Anonymous31 "Reach the final stage."
2
ALL ACHIEVEMENTS:
Secret Achievement 1
"Description is hidden for this achievement."
Final boss
"Reach the final stage."
2
LIST OF NUMBERS where user [num1] has achievement [num2]:
1 1
1 2

 Testing UserProfile methods. User: Anonymous31


2 Achievements:
ALL USERS: Secret Achievement 1
Anonymous31 "Description is hidden for this achievement."
UltimateGamer Final boss
2 "Reach the final stage."
ALL ACHIEVEMENTS: User: UltimateGamer
Secret Achievement 1 Achievements:
"Description is hidden for this achievement." Final boss
Final boss "Reach the final stage."
"Reach the final stage."
3
LIST OF NUMBERS where user [num1] has achievement [num2]:
1 1
1 2
2 2

 Testing showAchievementsProgress function. Timber!!


5 “Chop down your first tree.”
ALL USERS: ---Percentage of users who have this achievement: 100%
Dimitrij1234 Ooo! Shiny!
ItsMeTeodora “Mine your first nugget of ore with a pickaxe.”
xX_Sandra_Xx ---Percentage of users who have this achievement: 60%
Al3ksandarrr I Am Loot!
PeceWasHere “Discover a golden chest underground and take a peek at its contents.”
6 ---Percentage of users who have this achievement: 20%
ALL ACHIEVEMENTS: Mastermind
Timber!! “Defeat the Brain of Cthulhu, an enormous demon brain which haunts the creeping
“Chop down your first tree.” ---Percentage of users who have this achievement: 60%
Ooo! Shiny! Like a Boss
“Mine your first nugget of ore with a pickaxe.” “Obtain a boss-summoning item.”
I Am Loot! ---Percentage of users who have this achievement: 20%
“Discover a golden chest underground and take a peek at its contents.” Sword of the Hero
Mastermind “Obtain a Terra Blade, forged from the finest blades of light and darkness.”
“Defeat the Brain of Cthulhu, an enormous demon brain which haunts the creeping crimson.” ---Percentage of users who have this achievement: 40%
Like a Boss ------Average completion rate of the game: 50%
“Obtain a boss-summoning item.”
Sword of the Hero
“Obtain a Terra Blade, forged from the finest blades of light and darkness.”
15
LIST OF NUMBERS where user [num1] has achievement [num2]:
1 1
1 2
1 3
1 4
2 1
2 4
2 5
2 6
3 1
3 2
3 6
4 1
4 2
4 4
5 1

Passed all tests! 

Previous page Finish attempt ...

◄ Предавање 6 - Оператори Jump to...

You are logged in as Златко Миленков (Log out)


ОOП-2024/2025/L-46_42822
Data retention summary
Get the mobile app

You might also like