1. Linked List를 이용해서 실행시 파라미터 숫자(argc, argv) 만큼 랜덤하게 0 ~100 사이의 숫자 생성후 최소, 최대, 평균 값 찾기
2. vector를 이용해서 같은 문제 풀기
#include <iostream>
#include <cstdlib>
#include <stdlib.h>
#include <ctime>
using namespace std;
typedef struct Node {
int data;
struct Node *next;
}Node;
int main(int argc, char *argv[]){
Node *head = NULL;
Node *tail = NULL;
Node *cur = NULL;
Node *newNode = NULL;
int count = atoi(argv[1]);
int randomNum = 0;
cout << "Input Node Count : " << count << endl;
srand((unsigned int)time(NULL));
for(int i=0; i<count; i++){
randomNum = rand() % 101;
newNode = new Node();
newNode->data = randomNum;
newNode->next = NULL;
if(head == NULL)
head = newNode;
else
tail->next = newNode;
tail = newNode;
}
int node_sum = 0;
int node_max = 0;
int node_min = head->data;
cout << "Output Node : " << endl;
if(head == NULL){
return 0;
}
else{
cur = head;
cout << cur->data << " ";
node_sum += cur->data;
while(cur->next != NULL){
cur = cur->next;
cout << cur->data << " ";
node_sum += cur->data;
if(node_max < cur->data)
node_max = cur->data;
if(node_min > cur->data)
node_min = cur->data;
}
}
cout << "\nTotal : " << node_sum << "\n";
cout << "Mean : " << node_sum / count << "\n";
cout << "Min : " << node_min << "\n";
cout << "Max : " << node_max << "\n";
return 0;
}
Vector를 이용하여 풀기
#include <iostream>
#include <cstdlib>
#include <stdlib.h>
#include <ctime>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, char *argv[]){
int count = atoi(argv[1]);
int node_sum = 0;
vector<int> v;
cout << "Input Node Count : " << count << endl;
cout << "Output Node : " << endl;
srand((unsigned int)time(NULL));
for(int i=0; i<count; i++){
v.push_back(rand() % 101);
node_sum += v[i];
cout << v[i] << " ";
}
cout << "\nTotal : " << node_sum << "\n";
cout << "Mean : " << node_sum / count << "\n";
cout << "Max : " << *max_element(v.begin(), v.end()) << "\n";
cout << "Min : " << *min_element(v.begin(), v.end()) << "\n";
return 0;
}
훨씬 간단하게 풀 수 있습니다.
반응형
'알고리즘' 카테고리의 다른 글
[알고리즘 C++] 백준 2655 - 가장높은탑쌓기 (0) | 2021.12.17 |
---|---|
[알고리즘 C++] 프로그래머스 - 등굣길 (0) | 2021.12.17 |
[알고리즘 C++] 백준 1912 - 연속합 (0) | 2021.12.17 |
[알고리즘 C++] 백준 4963 - 섬의 개수 (0) | 2021.12.17 |
[알고리즘 C++] 백준 14496 - 그대, 그머가 되어 (0) | 2021.12.17 |