1
0

interating avg

This commit is contained in:
Captain ALM 2022-10-28 10:11:47 +01:00
parent 52edc7807a
commit 77fdbf36dc
3 changed files with 38 additions and 55 deletions

View File

@ -1,4 +1,5 @@
#include <iostream>
#include <list>
#include <iomanip>
using string = std::string;
@ -15,66 +16,24 @@ void printlm(T m){
printm("\n");
}
class Heap {
int pos {0};
int length {0};
int size;
int* storage;
public:
Heap(int sz) {
size = sz;
storage = new int[sz];
}
~Heap() {
delete[] storage;
}
bool isEmpty() {
return length == 0;
}
void add(int item) {
if (length + 1 > size) return;
pos = length;
while (pos > 0 && storage[(pos-1)/2] < item) {
storage[pos] = storage[(pos-1)/2];
pos = (pos-1)/2;
}
storage[pos] = item;
++length;
}
int extractMax() {
int max {storage[0]};
storage[0] = storage[--length];
int first {0};
while ((2*first)+1 <= length - 1) {
int largest {(2*first)+1};
if ((2*first)+2 <= length - 1 && storage[largest] < storage[(2*first)+2]) largest = (2*first)+2;
if (storage[first] >= storage[largest]) break;
int swap = storage[first];
storage[first] = storage[largest];
storage[largest] = swap;
first = largest;
}
return max;
}
};
int prompti(string,bool*);
double promptd(string,bool*);
double avgitr(std::list<double>*);
double avgfor(std::list<double>*);
int main() {
printlm("Create Heap:");
Heap h{16};
printlm("Average of:");
bool s {};
int i {0};
std::list<double> lst {};
do {
auto d = prompti("Enter a number: ",&s);
if (s) {
h.add(d);
++i;
}
}
while(s && i < 16);
printlm("Output Heap:");
while (!h.isEmpty()) printlm(h.extractMax());
auto v = promptd("Enter a double value: ", &s);
if (s) lst.push_back(v);
} while (s);
printm("avgitr: ");
printlm(avgitr(&lst));
printm("avgfor: ");
printlm(avgfor(&lst));
return 0;
}
@ -91,3 +50,27 @@ int prompti(string message, bool *status) {
return tr;
}
double promptd(string message, bool *status) {
double tr {};
*status = false;
std::cout << message;
if (!(std::cin >> tr)){
std::cin.clear();
std::cin.ignore();
return 0.0;
}
*status = true;
return tr;
}
double avgitr(std::list<double> *values) {
double sum {};
for (auto itr = values->cbegin(); itr != values->cend(); ++itr) sum += *itr;
return sum / values->size();
}
double avgfor(std::list<double> *values) {
double sum {};
for (auto c : *values) sum += c;
return sum / values->size();
}

BIN
main.o

Binary file not shown.

BIN
t

Binary file not shown.