Related
I am writing a code to sort an array of random integers using four sorting methods bubble, selection, shell and quick sort. I'm using the same code as a rand generator to create random integers which can be sorted by the sort functions. My issue is that when I run multiple sort methods at the same time; my rand generators create the same set of integers for the arrays. How do I fix this so I can have parallel rand generators in the same program? I cannot use c++11 array or STL vector.
main.cpp
#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "AssortedSorter.h"
using namespace std;
int main() {
AssortedSorter q, q2;
int UserNumOfNumbers;
int bchoice;
cout << " We pick array size (0) or you pick array size (1): ";
cin >> bchoice;
while (bchoice == 0) {
UserNumOfNumbers = 10000;
int array[UserNumOfNumbers];
srand(std::time(0));
for (int i = 0; i < UserNumOfNumbers; i++) {
array[i] = (rand() %200002) + 1;
}
cout << "\nArray Elements ::" << endl;
for (int i = 0; i < UserNumOfNumbers; i++) {
// long b = array[i];
q.quicksort(array, 0, UserNumOfNumbers);
q.bubbleSort(array, UserNumOfNumbers);
cout << " Number of Elements " << i + 1 << "::" << array[i] << endl;
// q.quicksort(array, 0, UserNumOfNumbers);
}
//q.bubbleSort(array, UserNumOfNumbers);}
// q.selectionSort(array, UserNumOfNumbers);}
return 0;
}
while (bchoice == 1) {
cout << "Enter a number between 10 and 20000: ";
cin >> UserNumOfNumbers;
while (UserNumOfNumbers < 10 || UserNumOfNumbers > 20000) {
cout << "Invalid entry! Please enter a valid value: ";
cin >> UserNumOfNumbers;
}
int array[UserNumOfNumbers];
srand(std::time(0));
for (int i = 0; i < UserNumOfNumbers; i++)
array[i] = (rand() %200002) + 1;
cout << "\nArray Elements ::" << endl;
for (int i = 0; i < UserNumOfNumbers; i++) {
q.bubbleSort(array, UserNumOfNumbers);
cout << " Number of Elements " << i + 1 << "::" << array[i] <</*(rand() %200002) + 1 */endl;
}
int arra[UserNumOfNumbers];
srand(std::time(NULL));
for (int j = 0; j < UserNumOfNumbers; j++)
arra[j] = (rand() %200002) + 1;
cout << "\nArray Elements ::" << endl;
for (int j = 0; j < UserNumOfNumbers; j++) {
q.quicksort(arra, 0, UserNumOfNumbers);
cout << " Number of Elements " << j + 1 << "::" << arra[j] << endl;
}
/*int arran[UserNumOfNumbers];
srand(std::time(0));
for (int k = 0; k < UserNumOfNumbers; k++)
arran[k] = (rand() %200002) + 1;
cout << "\nArray Elements ::" << endl;
for (int k = 0; k < UserNumOfNumbers; k++) {
q.selectionSort(arran, UserNumOfNumbers);
cout << " Number of Elements " << k + 1 << "::" <<(rand() %200001) + 1 << endl;}*/
break;
}
}
AssortedSorter.cpp
#include <iostream>
#include "AssortedSorter.h"
//long array;
using namespace std;
int AssortedSorter::partition(int array[], int start, int stop){
int up = start, down = stop - 1, part = array[stop];
long loopCountQ, swapCountQ;
if (stop <= start)
return start;
while (true)
{
while (array[up] < part){
/* loopCountQ++;
cout << " Loop Count++: " << loopCountQ << endl;*/
up++;}
while ((part < array[down]) && (up < down)){
/* loopCountQ++;
cout << " Loop Count--: " << loopCountQ << endl;*/
down--;}
if (up >= down)
break;
swap(array[up], array[down]);{
/* swapCountQ++;
cout << " Swap Count: " << swapCountQ << endl;*/
up++;
down--;}
}
swap(array[up], array[stop]);{
/* swapCountQ++;
cout << " Swap Count: " << swapCountQ << endl;*/
return up;}
}
int AssortedSorter ::getquicksort() const {
return *b;
}
void AssortedSorter :: quicksort(int a[], int start, int stop){
int i, s = 0, stack[20001];
// b = a;
//long * array = (a);
stack[s++] = start;
stack[s++] = stop;
while ( s > 0)
{
stop = stack[--s];
start = stack[--s];
if (start >= stop) continue;
i = partition(a, start, stop);
if
(i - start > stop - i)
{
stack[s++] = start; stack[s++] = i - 1;
stack[s++] = i + 1; stack[s++] = stop;
}
else {
stack[s++] = i + 1; stack[s++] = stop;
stack[s++] = start; stack[s++] = i - 1;
}
}
}
void AssortedSorter:: bubbleSort(int array[], int size) {
int maxElement;
int index;
//long loopcount = 0;
for (maxElement = size - 1; maxElement > 0; maxElement--) {
for (index = 0; index < maxElement; index++) {
if (array[index] > array[index + 1]) {/*loopcount++;
cout << " Loop count: " << loopcount << endl;*/
swap(array[index], array[index + 1]);
}
}
}
}
/*void AssortedSorter :: swap(int &a, int &b){
/* long int swapcount = 0;
{swapcount++;
cout << "Swap count: " << swapcount << endl;}
int temp = a;
a = b;
b = temp;
}*/
void AssortedSorter::selectionSort(int array[], int size)
{
int minIndex, minValue;
long int loopcountsel = 0;
for (int start = 0; start < (size - 1); start++)
{
minIndex = start;
minValue = array[start];
for (int index = start + 1; index < size; index++)
{
if(array[index] < minValue)
{
loopcountsel++;
// cout << "Loop count: " << loopcountsel << endl;
}
if(array[index] < minValue)
{
minValue = array[index];
minIndex = index;
}
}
swap(array[minIndex], array[start]);
}
}
void AssortedSorter :: swap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
AssortedSorter.h
#ifndef SORTER_ASSORTEDSORTER_H
#define SORTER_ASSORTEDSORTER_H
class AssortedSorter {
public:
void quicksort(int a[], int, int);
int getquicksort() const;
int partition(int [], int, int);
void bubbleSort(int[], int);
int getbubblesort() const;
//void swap(int & , int &);
int getswap() const;
void selectionSort(int[], int);
void swap(int &, int &);
private:
int* b;
};
#endif //SORTER_ASSORTEDSORTER_H
I have an admittedly very basic problem: I need to compare two numbers of type double for >=. For some reason, however, my code evaluates to true for values I know to be less than the threshold.
EDIT: My code (the error occurs in the countTrig() method of the Antenna class):
#define k 0.0000000000000000000000138064852 // Boltzmann's constant
class Antenna{
vector<vector<double> > output;
int channels, smplrate, smpldur, samples, timethld;
double resistance, temp, bandwidth, lnanoise, lnagain, RMS;
public:
Antenna(
const int _channels, const int _smplrate, const int _smpldur,
const double _resistance, const double _temp, const double _bandwidth,
const double _lnanoise, const double _lnagain
){
channels = _channels; smplrate = _smplrate; smpldur = _smpldur;
resistance = _resistance; temp = _temp; bandwidth = _bandwidth;
lnanoise = _lnanoise; lnagain = _lnagain;
RMS = 2 * sqrt(4 * k * resistance * temp * bandwidth);
RMS *= lnagain * pow(10,(lnanoise/10));
samples = smplrate/smpldur;
timethld = 508; //= (1/smplrate) * 0.127;
}
void genThrml(int units);
void plotTrig(int timethld, double voltsthld);
void plotThrml();
int countTrig(double snrthld, int iter);
};
double fabs(double val){ if(val < 0){ val *= -1; } return val; }
void Antenna::genThrml(int units){
output.resize(samples, vector<double>(channels));
samples *= units;
gRandom->SetSeed(time(NULL));
for(int i = 0; i < samples; ++i){
for(int j = 0; j < channels; ++j){
output[i][j] = gRandom->Gaus(0,RMS);
}
}
}
void Antenna::plotThrml(){
//Filler
}
int Antenna::countTrig(double snrthld, int iter){
int count = 0;
int high = iter + timethld;
int low = iter - timethld;
if(low < 0){ low = 0; }
if(high > samples){ high = samples; }
for(int i = low; i < high; ++i){
for(int j = 0; j < channels; ++j){
if(output[i][j] >= snrthld) count++; std::cout << output[i][j] << " " << snrthld << "\n";
}
}
if(iter >= 3) return 1;
else return 0;
}
void Antenna::plotTrig(int timethld, double voltsthld){
double snrthld = voltsthld / RMS;
for(int i = 0; i < samples; ++i){
for(int j = 0; j < channels; ++j){
countTrig(snrthld, i);
}
}
}
int main(){
Antenna test(20,4000,1,50,290,500000000,1.5,60);
test.genThrml(1);
test.plotTrig(400,0.0005);
return 0;
}
With a threshold of 0.147417, I get output like this:
0.0014238
-0.00187276
I believe I understand the problem (unless there's some obvious mistake I've made and not caught), and I understand the reasoning behind floating point errors, precision, etc. I don't, however, know, what the best practice is here. What is a good solution? How can I reliably compare values of type double? This will be used in an application where it is very important that values be precise and comparisons be reliable.
EDIT: A smaller example:
int countTrig(double snrthld, int iter, vector<vector<double> > output, int timethld){
int count = 0;
int high = iter + timethld;
int low = iter - timethld;
if(low < 0){ low = 0; }
if(high > 3){ high = 3; }
for(int i = low; i < high; ++i){
for(int j = 0; j < 3; ++j){
if(fabs(output[i][j]) >= snrthld) count++; std::cout << output[i][j] << " " << snrthld << "\n";
}
}
if(iter >= 3) return 1;
else return 0;
}
void plotTrig(int timethld, double snrthld){
vector<vector<double> > output = {{0.000028382, -0.0028348329, -0.00008573829},
{0.183849939, 0.9283829020, -0.92838200021},
{-0.00292889, 0.2399229929, -0.00081009189}};
for(int i = 0; i < 3; ++i){
for(int j = 0; j < 3; ++j){
countTrig(snrthld, i, output, timethld);
}
}
}
int main(){
plotTrig(1,0.1);
return 0;
}
You have a typo.
if(output[i][j] >= snrthld) count++; std::cout << output[i][j] << " " << snrthld << "\n";
this line means
if(output[i][j] >= snrthld)
count++;
std::cout << output[i][j] << " " << snrthld << "\n";
aka
if(output[i][j] >= snrthld)
{
count++;
}
std::cout << output[i][j] << " " << snrthld << "\n";
and you want:
if(output[i][j] >= snrthld)
{
count++;
std::cout << output[i][j] << " " << snrthld << "\n";
}
This is for a project in class and Ive been stuck for hours. The assignment is to open a text file containing a list of student names their ID numbers and their scores on different quizes, midterms, and finals then calculate the average. We have to make a class for each student then calculate the average for each student and give ranks to the student based on who got the best grade. So far I have created a class for each student and found the average and ranked the students averages from greatest to least but I cant figure out how to assign ranks. Here is a picture of the assignment if you want more information : http://imgur.com/Jetvj7O
And here is my code:
#include <iostream>
#include <cstring>
#include <string>
#include <fstream>
#include <algorithm>
#include <functional>
using namespace std;
int num_a = 0, num_b = 0, num_c = 0, num_d = 0, num_f = 0;
class Student {
private:
int rank;
string name;
int id;
double quiz_scores[5];
double midterm_scores[2];
double final_score;
double average;
double quiz_average;
double midterm_average;
char grade;
public:
Student();
void setRank(int num);
int getRank();
void setGrade(double average);
char getGrade();
void setName(string first);
string getName();
void setId(int num);
int getId();
void setMidterms(double nums[]);
double getMidterms();
void setQuizes(double nums[]);
double getQuizes();
void setFinal(double num);
double getFinal();
void setAverage();
double getAverage();
};
Student::Student()
{
name = "John Doe";
id = 0;
final_score = 0;
average = 0;
grade = 'F';
midterm_scores[2] = {};
quiz_scores[5] = {};
rank = 0;
}
void Student::setRank(int num)
{
rank = num;
}
int Student::getRank()
{
return rank;
}
void Student::setGrade(double average)
{
if (average <= 100 && average >= 90)
{
grade = 'A';
num_a++;
}
else if (average <= 89.99 && average >= 80)
{
grade = 'B';
num_b++;
}
else if (average <= 79.99 && average >= 70)
{
grade = 'C';
num_c++;
}
else if (average <= 69.99 && average >= 60)
{
grade = 'D';
num_d++;
}
else if (average < 60)
grade = 'F';
num_f++;
}
void Student::setName(string first)
{
name = first;
}
string Student::getName()
{
return name;
}
void Student::setId(int num)
{
id = num;
}
int Student::getId()
{
return id;
}
void Student::setMidterms(double nums[])
{
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(1);
double average, sum = 0;
for (int i = 0; i < 2; i++)
{
midterm_scores[i] = nums[i];
sum += midterm_scores[i];
}
average = sum / 2;
midterm_average = average * .40;
}
double Student::getMidterms()
{
return midterm_average;
}
void Student::setQuizes(double nums[])
{
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(1);
double score, sum = 0, average, min = nums[0];
for (int i = 0; i < 5; i++)
{
if (nums[i] < min)
{
min = nums[i];
}
score = nums[i];
quiz_scores[i] = score;
sum += quiz_scores[i];
}
sum = sum - min;
average = (sum / 40) * 100;
quiz_average = average * .20 ;
}
double Student::getQuizes()
{
return quiz_average;
}
void Student::setAverage()
{
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(1);
average = (quiz_average + midterm_average + final_score);
}
void Student::setFinal(double num)
{
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(1);
final_score = num * .40;
}
double Student::getFinal()
{
return final_score;
}
double Student::getAverage()
{
return average;
}
char Student::getGrade()
{
return grade;
}
//ranks the student by decreasing average grade
void rankStudents(double array[], int arraySize, Student scores[])
{
int m; // keep the index of current smallest value
double newArray[30], hold, finalArray[30];
bool isFound = false;
//stores the averages in an array then sorts array
for (int i = 0; i < arraySize; i++)
{
newArray[i] = array[i];
}
for (int k = 0; k <= arraySize - 2; k++)
{
m = k;
for (int j = k + 1; j <= arraySize - 1; j++)
{
if (newArray[j] > newArray[m])
m = j;
}
hold = newArray[m];
newArray[m] = newArray[k];
newArray[k] = hold;
}
//assigns rank to each student by comparing the array of averages to the students average by calling student.getAverage()
for (int i = 0; i < arraySize; i++)
{
double test = newArray[i];
int counter = i;
for (int k = 0; k < arraySize; k++)
{
int counter2 = i;
if (scores[k].getAverage() == test)
{
scores[k].setRank(counter+1);
}
else if (scores[k].getAverage() == scores[k - 1].getAverage() && scores[k].getAverage() == test)
{
scores[k].setRank(i + 1);
scores[k - 1].setRank(scores[k].getRank());
}
//cout << scores[k].getName() << ' ' << scores[k].getId() << ' ' << scores[k].getRank() << endl;
}
}
for (int i = 0; i < arraySize; i++)
{
//cout << scores[i].getName() << ' ' << scores[i].getId() << ' ' << scores[i].getAverage() << ' ' << scores[i].getGrade() << ' ' << scores[i].getRank() << endl;
}
//creates finalArray which stores the students ranks and sorts them
for (int i = 0; i < arraySize; i++)
{
finalArray[i] = scores[i].getRank();
}
for (int k = 0; k <= arraySize - 2; k++)
{
m = k;
for (int j = k + 1; j <= arraySize - 1; j++)
{
if (finalArray[j] < finalArray[m])
m = j;
}
hold = finalArray[m];
finalArray[m] = finalArray[k];
finalArray[k] = hold;
}
for (int i = 0; i < arraySize; i++)
{
//cout << scores[i].getRank() << endl;
}
//prints out the array
for (int i = 0; i < arraySize; i++)
{
double test = newArray[i];
int counter3 = i;
for (int k = 0; k < arraySize; k++)
{
if (scores[k].getAverage() == test)
{
cout << scores[k].getName() << ' ' << scores[k].getId() << ' ' << scores[k].getAverage() << ' ' <<scores[k].getGrade() << ' ' << scores[k].getRank() << endl;
}
if (scores[k].getAverage() == scores[k - 1].getAverage() && scores[k].getAverage() == test)
{
scores[k].setRank(i + 1);
scores[k - 1].setRank(scores[k].getRank());
cout << scores[k].getName() << ' ' << scores[k].getId() << ' ' << scores[k].getAverage() << ' ' << scores[k].getGrade() << ' ' << scores[k].getRank() << endl;
}
}
}
}
void readFile(Student people[])
{
//declares input file
ifstream in_file;
string user_file;
int number_of_students, id;
double quiz1, quiz2, quiz3, quiz4, quiz5, midterm1, midterm2, final_score, quizes[5], midterm[2], averages[30];
string name;
cout << "Enter an input file: ";
cin >> user_file;
in_file.open(user_file);
if (in_file.fail())
{
cout << "Error: file open failed \n" << endl;
exit(1);
}
//finds number of players in the array
in_file >> number_of_students;
//creates an array for scores then stores the id and scores of each player
for (int i = 0; i < number_of_students; i++)
{
in_file >> name >> id >> quiz1 >> quiz2 >> quiz3 >> quiz4 >> quiz5 >> midterm1 >> midterm2 >> final_score;
people[i].setName(name);
people[i].setId(id);
quizes[0] = quiz1;
quizes[1] = quiz2;
quizes[2] = quiz3;
quizes[3] = quiz4;
quizes[4] = quiz5;
midterm[0] = midterm1;
midterm[1] = midterm2;
people[i].setQuizes(quizes);
people[i].setMidterms(midterm);
people[i].setFinal(final_score);
//cout << array[i].getName() << " quiz average = " << array[i].getQuizes() << "midterm average = " << array[i].getMidterms() << "final = " << array[i].getFinal() << endl;
people[i].setAverage();
people[i].setGrade(people[i].getAverage());
//cout << array[i].getAverage() << endl;
averages[i] = people[i].getAverage();
//cout << averages[i] << endl;
//cout << "grade = " << array[i].getGrade() << endl;
//calls findAverage function to find average of each array then stores the result in player class
}
rankStudents(averages, number_of_students, people);
for (int i = 0; i < number_of_students; i++)
{
if (people[i].getAverage() == averages[i])
people[i].setRank(i);
}
for (int i = 0; i < number_of_students; i++)
{
cout << people[i].getRank();
}
}
int main()
{
Student students[30];
readFile(students);
return 0;
}
This is the part i need help on:
void rankStudents(double array[], int arraySize, Student scores[])
{
int m; // keep the index of current smallest value
double newArray[30], hold, finalArray[30];
bool isFound = false;
//stores the averages in an array then sorts array
for (int i = 0; i < arraySize; i++)
{
newArray[i] = array[i];
}
for (int k = 0; k <= arraySize - 2; k++)
{
m = k;
for (int j = k + 1; j <= arraySize - 1; j++)
{
if (newArray[j] > newArray[m])
m = j;
}
hold = newArray[m];
newArray[m] = newArray[k];
newArray[k] = hold;
}
//assigns rank to each student by comparing the array of averages to the students average by calling student.getAverage()
for (int i = 0; i < arraySize; i++)
{
double test = newArray[i];
int counter = i;
for (int k = 0; k < arraySize; k++)
{
int counter2 = i;
if (scores[k].getAverage() == test)
{
scores[k].setRank(counter+1);
}
else if (scores[k].getAverage() == scores[k - 1].getAverage() && scores[k].getAverage() == test)
{
scores[k].setRank(i + 1);
scores[k - 1].setRank(scores[k].getRank());
}
//cout << scores[k].getName() << ' ' << scores[k].getId() << ' ' << scores[k].getRank() << endl;
}
}
for (int i = 0; i < arraySize; i++)
{
//cout << scores[i].getName() << ' ' << scores[i].getId() << ' ' << scores[i].getAverage() << ' ' << scores[i].getGrade() << ' ' << scores[i].getRank() << endl;
}
//creates finalArray which stores the students ranks and sorts them
for (int i = 0; i < arraySize; i++)
{
finalArray[i] = scores[i].getRank();
}
for (int k = 0; k <= arraySize - 2; k++)
{
m = k;
for (int j = k + 1; j <= arraySize - 1; j++)
{
if (finalArray[j] < finalArray[m])
m = j;
}
hold = finalArray[m];
finalArray[m] = finalArray[k];
finalArray[k] = hold;
}
for (int i = 0; i < arraySize; i++)
{
//cout << scores[i].getRank() << endl;
}
//prints out the array
for (int i = 0; i < arraySize; i++)
{
double test = newArray[i];
int counter3 = i;
for (int k = 0; k < arraySize; k++)
{
if (scores[k].getAverage() == test)
{
cout << scores[k].getName() << ' ' << scores[k].getId() << ' ' << scores[k].getAverage() << ' ' <<scores[k].getGrade() << ' ' << scores[k].getRank() << endl;
}
if (scores[k].getAverage() == scores[k - 1].getAverage() && scores[k].getAverage() == test)
{
scores[k].setRank(i + 1);
scores[k - 1].setRank(scores[k].getRank());
cout << scores[k].getName() << ' ' << scores[k].getId() << ' ' << scores[k].getAverage() << ' ' << scores[k].getGrade() << ' ' << scores[k].getRank() << endl;
}
}
}
}
You can sort the scores by using the std sort() function by giving it an iterator to the beginning of the array as the first parameter and an iterator to the end of the array as the second parameter. More on sort.
Then, you can iterate through your sorted average scores and give a score based on a decrementing basis. For example, your highest score will be given rank 1. Go to the next score. Check if the score is the same as the previous. If it is, give the same rank, otherwise, increment your rank and then assign it.
Your ranking function is a bit convoluted. I suggest you separate this into three parts. Get the averages, sort, then rank. I'd use vectors to facilitate things further. I hope this helps :)
You say that you have done everything up to the last part, assigning grades ("Any average of 90 or more is an 'A',...").
I advise you to isolate this part of the problem. Write a function that takes a score and returns a letter. Once that's working perfectly, you can add that function to your code and fill in the grade field of each student.
The signature of the function should be something like this (until/unless you make it a member function or something):
char letterGrade(double score)
Is that enough to work with?
So the program gathers a number of scores specified, then displays them in ascending order, then is supposed to show the average score. But right now, it only takes the first score displayed, and is divided by the number of scores. How can I make it display correctly?
#include <iostream>
#include <iomanip>
using namespace std;
void sortArray(int*, int);
double getAverage(int*, int);
int main()
{
int *scores;
int num_Tests;
cout << "How many test scores would you like to enter?" << endl;
cin >> num_Tests;
scores = new int[num_Tests];
cout << "\nEnter score number (do not use negative numbers):\n";
for (int count = 0; count < num_Tests; count++)
{
cout << count + 1 << ". ";
cin >> scores[count];
}
sortArray(scores, num_Tests);
cout << "\n\n";
cout << "\n\n________________________________________________________________________________" << endl;
cout << "Test Score List (in ascending order)" << endl;
cout << "________________________________________________________________________________" << endl;
for (int count = 0; count < num_Tests; count++)
{
cout << count + 1 << ". ";
cout << scores[count] << endl;
}
cout << "\nAverage test score: " << getAverage(scores, num_Tests) << endl;
return 0;
}
double getAverage(int *scores, int size)
{
double ttlScore = 0.0;
double avgScore = 0.0;
ttlScore += *scores;
avgScore = ttlScore / size;
return avgScore;
}
void sortArray(int *scores, int size)
{
int temp;
bool swap;
do
{ swap = false;
for (int count = 0; count < (size - 1); count++)
{
if (scores[count] < scores[count + 1])
{
temp = scores[count];
scores[count] = scores[count + 1];
scores[count + 1] = temp;
swap = true;
}
}
} while (swap);
}
You need to loop through your scores array to add them, you cannot just do ttlScore += *scores, it needs to be ttlScore += scores[index]
Example:
double getAverage(int *scores, int size)
{
double ttlScore = 0.0;
for (int i = 0; i < size; i++)
{
ttlScore += scores[i];
}
return ttlScore / size;
}
getAverage logic is not correct. You are adding just first number. Add is as below:
double getAverage(int *scores, int size)
{
double ttlScore = 0.0;
double avgScore = 0.0;
for(int i=0;i<size;i++)
{
ttlScore += *(scores+i);
}
avgScore = ttlScore / size;
return avgScore;
}
*scores references the start of the array. You need to sum over all of the values of the array pointed to:
for (int i=0; i < size; i++)
{
ttlScore += scores[i];
}
avgScore = ttlScore / size;
return avgScore;
I think these will help you,
double getAverage(int *scores, int size){
int i, sum = 0;
double avg;
for (i = 0; i < size; ++i)
{
sum += scores[i];
}
avg = (double)sum / size;
return avg;
}
Try and let me know if any problem?
I'm new to programming but here is what I have.
//average function
double average(int* pnData)
{
double result;
int sum = 0; //declare and initialize our variables
int count = 0;
for (int i = 0; i < pnData[i]; i++)
{
sum += pnData[i]; //sum = sum + elements of our array
count++; //increment count
}//end of for loop
result = sum/(double)count;
return result;
}//end of function average
This way you do not have to know the length or count of the array.
I try to write the closest pair in n dimension, I use the divide and conquer.And I first split it into left and right part, and find their shortest path respectively and I have to find the distance accross them, when I do it , it comes to error. I have tried but cannot find the bug,where is the error in my method.
Please help me find it out!Thank in advance.
#include <vector>
#include <cmath>
#include <cfloat>
#include <iostream>
#include <algorithm>
using namespace std;
vector<int> ClosestPair(const vector< vector<double> >& points){
vector<int> closest_pair;
closest_pair.resize(2);
closest_pair[0] = 0;
closest_pair[1] = 1;
return closest_pair;
}
//utility function to calculate two point distance
double dist(vector<double> &p1, vector<double> &p2){
double sum = 0;
//n dimension point
for(int i = 0; i < p1.size(); i ++){
//cout << "i:" << i << endl;
//cout << "1:" << p1[i] << ",2:" << p2[i] << endl;
sum += (p1[i] - p2[i]) * (p1[i] - p2[i]);
}
//cout << "dist:" << sqrt(sum) << endl;
return sqrt(sum);
}
//direct calculate the distance
double bruteForce(vector<vector<double> > &p, int min_d, int max_d, int & a, int & b){
//set sum to the max_d value of double to test minimum
double sum = DBL_MAX;
//compare each distance
for(int i = min_d; i < max_d; i ++){
for(int j = i + 1; j < max_d + 1; j ++){
if(dist(p[i], p[j]) < sum){
a = i;
b = j;
sum = dist(p[i], p[j]);
}
}
}
cout << "brute:" << sum << endl;
return sum;
}
double closest(vector<vector<double> > &p, int min_d, int max_d, int& a, int& b){
//terminal condition
if(max_d - min_d <= 3){
//cout << "QQ" << endl;
return bruteForce(p, min_d, max_d, a, b);
}
//divide and conquer
else{
int a1 = 0, b1 = 0;
//cout << "haha" << endl;
int median = (max_d - min_d) / 2;
double left = closest(p, min_d, median, a1, b1);
double right = closest(p, median + 1, max_d, a, b);
if(left < right){
a = a1;
b = b1;
}
//minimun of left and right
double d = min(left, right);
//record index
int first = 0;
int last = 0;
int count = 0;
vector<vector<double> > temp;
for(int i = min_d; i < max_d; i ++){
//== d already exist
if(abs(p[i][0] - p[median][0]) < d){
if(count == 0)first = i;
count ++;
//cout << "inside:" << i << "count:" << count << endl;
temp.push_back(p[i]);
}
}
last = first + count - 1;
//cout << "first" << first << "last" << last << endl;
return min(d, closest(temp, first, last, a, b));
}
}
int main(){
int a = 0, b = 0;
//3 dimension
vector<vector<double> >test(7,vector<double>(3));
//(10,20,30)
test[0][0]= 10;
test[0][1]= 20;
test[0][2]= 30;
//(1,2,3)
test[1][0]= 1;
test[1][1]= 2;
test[1][2]= 3;
//(1000,2000,3000)
test[2][0]= 1000;
test[2][1]= 2000;
test[2][2]= 3000;
//(100,200,300)
test[3][0]= 100;
test[3][1]= 200;
test[3][2]= 300;
//(100,200,300)
test[4][0]= 100;
test[4][1]= 200;
test[4][2]= 301;
//(100,200,300)
test[5][1]= 200000;
test[5][0]= 100000;
test[5][2]= 300000;
//(100,200,300)
test[6][0]= 1000000;
test[6][1]= 2000000;
test[6][2]= 3000000;
//sort X
sort (test.begin(), test.end());
for (int i = 0; i < test.size(); i ++){
for(int j = 0; j < test[i].size(); j ++){
cout << test[i][j] << endl;
}
}
cout << "result:" << closest(test, 0, 6, a, b);
cout << "a" << a << "b" << b << endl;
return 0;
}
Change temp to something like:
vector<vector<double> > temp(7,vector<double>(3));