All pastes #2077278 Raw Edit

Someone

public text v1 · immutable
#2077278 ·published 2011-06-09 12:29 UTC
rendered paste body
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

void get_course_list();
void organize_popular_courses();
int get_course_students(vector<string>, int);
void print_vector(vector<string>, int);
vector<string> global_list;

int main()
{
	get_course_list(); // Display original course information
	organize_popular_courses(); // Display organized course information

	print_vector(global_list, 5);

	system("pause");
	return 0;
}

/**
 * Prints the specified vector.
 *
 * @param vector v - The vector you want to print.
 * @param int length - how much of the vector you want to print.
 */
void print_vector(vector<string> v, int length)
{
	for (int i = 0; i < length - 1; i++)
		cout << v.at(i) << endl;
}

/**
 * Loads the course list into a vector. Each course is in its
 * own index of the vector.
 *
 * Prints the vector before ending.
 */
void get_course_list()
{
	ifstream fin;
	fin.open( "Course.txt" );

	while ( !fin.eof() )
	{
		string s;
		getline(fin, s);
		global_list.push_back(s);
	}
	fin.close();
}

/**
 * Swap strings in vector according to the number of students in each course.
 * Uses the get_course_students() method to compare the number of students
 * in one course to the number of students in another course.
 *
 * Prints the vector before ending.
 */
void organize_popular_courses()
{
	int first, second, swap;
	bool unorganized = true;

	while (unorganized)
	{
		first = 0, second = first + 1;
		swap = 0;

		/*
		 * Iterate through the list once
		 */
		for(int i = 0; i < global_list.size(); i++)
		{
			if (second > global_list.size() - 1) // Wrap second back to beginning of the vector
				second = 0;
			if (second == 0)
				break;
			if (first > global_list.size() - 1) // Wrap first back to beginning of the vector
				first = 0;

			if (get_course_students(global_list, first) < get_course_students(global_list, second))
			{
				global_list.at(first).swap(global_list.at(second)); // Swap the two strings
				swap++;
			}
			first++;
			second++;
		}

		// If no swaps take place, the vector must be organized.
		if (swap > 0)
		{
			unorganized = true;
		} else
			unorganized = false;

	}
}

/**
 * Counts the numbers of students in each course by counting
 * the number of words on each line in the text file, then subtracts
 * 3 from the final answer to eliminate the course number, course name,
 * and professors name.
 */
int get_course_students(vector<string> v, int m)
{
	int wordsInString = 1;
	char nextChar;
	string course = v.at(m); // get the line we want to count

	for (int i = 0; i < course.length(); i++)
	{
		nextChar = course.at(i);
		if (isspace(course[i]))
			wordsInString++;
	}

	return wordsInString - 3; // remove 3 from total words in the string
}