How do I have multiple rand generators in one code? - c++

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

Related

binary search not returning the index

this is my c++ program for binary search and for some reason it is not returning the index of the element that I searched
#include <iostream>
//using namespace std;
struct array {
int A[10];
int size;
int length;
};
void displayArray(struct array arr) {
std::cout << "the elements are :-" << std:: endl << '\t';
for (int i = 0; i < arr.length; i++) {
std::cout << arr.A[i] << ',';
}
std::cout << std::endl;
}
int binarySearch(struct array arr, int element) {
int l, h;
l = 0;
h = arr.length;
for (int i = 0; l <= h; i++) {
int mid = (l + h) / 2;
if (arr.A[mid] == element)
return mid;
else if (arr.A[mid] < element)
h = mid -1;
else
l = mid+1;
std::cout << mid << std::endl;
}
return -1;
}
int main()
{
struct array arr = {{1,2,3,4,5,6,7}, 10, 7};
int* p;
displayArray(arr);
std::cout << binarySearch(arr, 6) << std::endl;
}
I tried everything and still, it is not working for some reason
am I missing something here?
change position of l, h. you need to growth mid value if you find bigger value, the other way around, too.
#include <iostream>
using namespace std;
struct array1 {
int A[10];
int size;
int length;
};
void displayArray(struct array1 arr) {
std::cout << "the elements are :-" << std::endl << '\t';
for (int i = 0; i < arr.length; i++) {
std::cout << arr.A[i] << ',';
}
std::cout << std::endl;
}
void binarySearch(struct array1 arr, int element) {
int l, h;
l = 0;
h = arr.length;
int mid = arr.length / 2;
if (arr.A[mid] == element)
cout << "i am on index number=" << mid;
else if ( element< arr.A[mid])
for (int i = 0; 1; i++)
{
if (arr.A[i] == element)
{
cout << "i am on index number=" << i;
break;
}
}
else
for (int i = mid; 1; i++)
{
if (arr.A[i] == element)
{
cout << "i am on index number=" << i;
break;
}
}
}
int main()
{
struct array1 arr = { {1,2,3,4,5,6,7}, 10, 7 };
displayArray(arr);
binarySearch(arr, 6);
return 0;

Run-Time Check Failure #2 - Stack around the variable 'board' was corrupted

I am running project called Horse Board Game. When it got almost done, it happened an error at the end of the execution part. The error is:
Run-Time Check Failure #2 - Stack around the variable 'board' was corrupted.
Where is the mistake here? Everything seems to work properly, only that error occurs.
#include <iostream>
#include <ctime>
#include <Windows.h>
using namespace std;
void printHorizontalLine(int size) {
for (int i = 0; i < size; i++) {
cout << " -----------";
}
cout << "\n";
}
void printVerticalLine(int size) {
cout << "|";
for (int i = 0; i < size; i++) {
cout << " |";
}
cout << "\n";
}
void displayBoard(int size, char board[50][50]) {
for (int i = 0; i < size; i++) {
printHorizontalLine(size);
printVerticalLine(size);
cout << "|";
if (i % 2 == 0) {
for (int j = 0; j < size; j++) {
cout << " " << board[i][j] << " |";
}
}
else {
for (int j = size - 1; j >= 0; j--) {
cout << " " << board[i][j] << " |";
}
}
cout << "\n";
printVerticalLine(size);
}
printHorizontalLine(size);
}
void init_board(char board[50][50], int size) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
board[i][j] = ' ';
}
}
}
void enteringPlayerName(char name[], int n) {
for (int i = 0; i < n; i++) {
cout << "Player " << i + 1 << " enter name: " << "\n";
cin >> name[i];
}
}
void beginningPos(int n, int pos[]) {
for (int i = 0; i < n; i++) {
pos[i] = -1;
}
}
void rollDice(int max, char board[50][50], int pos[], char name[], int size, int n, int cur) {
int step = rand() % max + 1;
cout << name[cur] << " roll " << step << "\n";
if (step + pos[cur] > size * size - 1) {
cout << "Cannot move forward\n";
}
else {
pos[cur] += step;
for (int i = 0; i < n; i++) {
if ((pos[cur] == pos[i]) && (i != cur)) {
pos[i] = -1;
cout << name[i] << " is kicked to the Start!!\n";
}
}
}
}
void updatingBoard(char board[50][50], char name[], int pos[], int n, int size) {
init_board(board, size);
for (int k = 0; k < n; k++)
{
int x, i, j;
x = pos[k];
i = x / size;
j = x % size;
board[i][j] = name[k];
}
}
char playGame(int max, int n, int size, char board[50][50], int pos[], char name[], int finish_point) {
char winner = ' ';
int cur_turn = 0;
while (winner == ' ') {
rollDice(max, board, pos, name, size, n, cur_turn % n);
updatingBoard(board, name, pos, n, size);
displayBoard(size, board);
if (pos[cur_turn % n] == finish_point) winner = name[cur_turn % n];
cur_turn++;
}
return winner;
}
int main() {
int size, n;
cin >> size;
cin >> n;
const int MAX = 50;
int max = 3;
int pos[200];
char name[10];
char winner = ' ';
char board[MAX][MAX];
int finish_point = size * size - 1;
srand(time(0));
enteringPlayerName(name, n);
init_board(board, size);
beginningPos(n, pos);
winner = playGame(max, n, size, board, pos, name, finish_point);
if (winner == ' ') cout << "Tie game";
else cout << winner << " is the winner";
return 0;
}```
When I set size to 4 and n to 2 as recommended in the comments section, then the line
board[i][j] = name[k];
in the function updatingBoard causes a buffer underflow.
The first time that line is executed, i has the value 0 and j has the value 0, which is ok, but the second time that line is executed, i has the value 0 but j has the value -1. This is obviously wrong, because board[0][-1] is accessing the array out of bounds.
That is the reason for the error message that you are receiving.
You can easily see this by running your program line by line in a debugger.

How to swap function value and array element in for loop?

How do I swap elements in the given code since I get message that expression must a modifiable lvalue?
I need to swap function value and array element in a for loop.
int niz[2] = { 2,1 };
int temp;
for (int i = 0;i < 1;i++)
{
temp = niz[i];
niz[i] = minimum(niz, 2, i);
minimum(niz, 2, i) = temp;
}
for (int i = 0;i < 2;i++)
{
cout << niz[i] << endl;
}
#include <iostream>
using namespace std;
void swap(int arr[], int size);
int main(void) {
int x[2] = {2, 1};
cout << "Before: ";
for (int i = 0; i <= 1; i++) {
cout << x[i] << ", ";
}
swap(x, 2);
cout << endl << "After: ";
for (int i = 0; i <= 1; i++) {
cout << x[i] << ", ";
}
return 0;
}
void swap(int arr[], int size) {
for (int i = 0; i < size / 2; i++) {
arr[i] ^= arr[size - 1 - i];
arr[size - 1 - i] ^= arr[i];
arr[i] ^= arr[size - 1 - i];
}
}
Hope it helps you.

Counting number of copying and comparisons in heapsort and insertation sort

I want to count how many times does algorithm makes comparisons and how many times algorithm makes copying.
#include <stdio.h>
#include <random>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <time.h>
void generuoti(int _N, const char *_file);
void nuskaityti(const char *_file);
int ps = 0;
int ks = 0;
void heapify(double arr[], int n, int i)
{
int largest = i; // Initialize largest as root
int l = 2 * i + 1; // left = 2*i + 1
int r = 2 * i + 2; // right = 2*i + 2
// If left child is larger than root
if (l < n && arr[l] > arr[largest])
largest = l;
ps+=1;
// If right child is larger than largest so far
if (r < n && arr[r] > arr[largest])
largest = r;
ps += 1;
// If largest is not root
if (largest != i)
{
std::swap(arr[i], arr[largest]);
ps += 1;
ks += 1;
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
// pagr funkcija haep sortui
void heapSort(double arr[], int n)
{
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// One by one extract an element from heap
for (int i = n - 1; i >= 0; i--)
{
// Move current root to end
std::swap(arr[0], arr[i]);
ks+=1;
// call max heapify on the reduced heap
heapify(arr, i, 0);
}
}
void insertion_sort(double arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i - 1;
ks+=1;
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
ks+=1;
ps+=1;
}
arr[j + 1] = key;
ks+=1;
}
}
using namespace std;
double *Data;
double* A;
double* B;
double N;
int main()
{
srand(time(NULL));
cout << "Generuojame atsitktinius duomenis" << endl;
generuoti(20000, "duom.txt");
cout << "Nuskaitome duomenis" << endl;
nuskaityti("duom.txt");
A = new double[(int)N];
B = new double[(int)N];//jeigu algoritmui reikia papildomo masyvo
for (int i = 0; i < N; i++) {
A[i] = Data[i];
}
cout << "Pradine skaiciu seka:" << endl;
for (int i = 0; i < N; i++)
cout << A[i] << " ";
cout << endl;
//
insertion_sort(A, N);
//heapSort(A, N);
//truksta veiksmu sk
cout << "Surusiuota skaiciu seka:" << endl;
for (int i = 0; i < N; i++)
cout << A[i] << " ";
cout << endl;
cout << "Kopijavimu skaicius " << ks << endl;
cout << "Palyginimu skaicius " << ps << endl;
system("pause");
return 0;
}
void generuoti(int _n, const char *_file) {
ofstream os(_file);
os << _n << endl;
for (int i = 0; i<_n; i++)
os << " " << 500+ (double)(rand() % 3001) ;
os.close();
}
void nuskaityti(const char *_file) {
ifstream is(_file);
if (is.fail()) {
cout << "Failo nera" << endl;
exit(1);
}
is >> N;
Data = new double[(int)N];
for (int i = 0; i < N; i++) {
is >> Data[i];
}
}
This is my code, and ps - is equal to a number of comparisons, and ks - is equal to number of copying. I want to ask if I counted all comparisons and all copying in the algorithms? Thanks for answers.
No
if (l < n && arr[l] > arr[largest])
largest = l;
ps+=1;
There are two problems here. Assuming you are talking about double comparisons (rather than integer), the comparison may or may not occur.
Secondly your indentation is deeply misleading. (You always increment.)
You need
if (l < n) {
ps++; // About to compare
if (arr[l] > arr[largest])
largest = l;
}
There are probably other errors, but it is impossible to tell because I can't read your language, so the printed text, comments, and names are meaningless.
Given you are writing in C++, I would write a class with operator <() and operator =, and a copy constructor, and instrument those. That way you cannot possibly get it wrong.

C++ Trying to sort an array of classes by their average then rank them in increasing order

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?