Эта программа предназначена для создания двух массивов: библиотеки глубиной 1024 строки и списка глубиной 128 строк. Содержимое каждой строки для обоих массивов будет иметь длину от 2 до 3 МБ (случайным образом назначается программой). Пользователю будет предложено ввести случайное слово, и программа выполнит поиск всех экземпляров этого слова в списке. Строки, содержащие слово, останутся в списке, а те, которые не содержат слова, будут извлечены из списка и повторно инициализированы в нижней части библиотеки. Одновременно список будет усечен, а самые верхние строки библиотеки будут добавлены к пустым строкам списка. Я добавил комментарии, где у меня проблемы с моим кодом.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cstring>
using namespace std;
// Constants used to create depth and width of recent_list and Library
const int recentList_Size = 128, library_Size = 1024; // Number of 'lines' in the
// recent_list and Library
// Used to create variable sizes of chars
const int btm = 2000000, top = 3000000;
// Was told to use power of 2s, but a quick cout of 2^21 gives 23 not 2M
// Create pointers for recent_list and Library
struct Arrays {
char* recent[recentList_Size];
char* library[library_Size];
};
// Method to generate 26 CAPITAL letters using ascii value
inline char random_letter() {
return char('A' + rand() % 26);
}
// Build the array
// Was told to check memory?
void initArrays(Arrays& o) {
for (int i = 0; i < recentList_Size; i++) // Build recent_list vertically
{
int sz = rand() % (top - btm + 1) + btm; // Used to randomly generate array sized between 2MB and 3MB
o.recent[i] = new char[sz + 1]; // Dynamically allocate memory to a pointer based on list size
for (int j = 0; j < sz; j++)
o.recent[i][j] = random_letter(); // Fill horizontal array with randomly generated alphabet characters
o.recent[i][sz] = '\0';
}
for (int i = 0; i < library_Size; i++) // Build Library (simialr method as the above)
{
int sz = rand() % (top - btm + 1) + btm;
o.library[i] = new char[sz + 1];
for (int j = 0; j < sz; j++)
o.library[i][j] = random_letter();
o.library[i][sz] = '\0';
}
}
int main() {
srand(time(0));
Arrays a;
initArrays(a);
int input;
// Prompt for user
cout << "----------------------------------------------" << endl;
cout << " Press 1 to search the Recent List for a word " << endl;
cout << " Press 2 to exit the program" << endl;
cout << "----------------------------------------------" << endl;
cin >> input;
// catch if input not within bounds
while (input != 1 && input != 2)
{
cout << "-------- Please ONLY press 1 or 2 ---------" << endl;
cout << " Press 1 to search the Recent List for a word " << endl;
cout << " Press 2 to exit the program" << endl;
cout << "---------------------------------------------" << endl;
cin >> input;
}
while (input != 2)
{
cout << "Enter a word to search for in the recent_list: ";
char* search_word = new(char[16]); // 15 letter word, 16 character of \0 to mark the end of the string
// Dynamic memory needed for comparison
cin >> search_word;
while (cin.get() != '\n') continue; // FLush buffer
// Array of booleans that will match the recent_List length, where we are going to mark if the array has
// the word we are looking for.
bool words_found_at[recentList_Size] = { false };
// Go through each array of letters and find the matching word
// Keep count of instances where word is and is not found in each array of letters
int words_found = 0;
int words_not_found = 0;
for (int i = 0; i < recentList_Size; i++) {
// C++ function strstr used to compare chars of array to char inputted
if (strstr(a.recent[i], search_word) != NULL) {
words_found++; // Increment counter
words_found_at[i] = true; // Tab when word is found (original code)
}
}
words_not_found = recentList_Size - words_found;
cout << search_word << " found in " << words_found << " arrays " << endl;
cout << words_not_found << " arrays were ejected " << endl;
if (words_found != 0) {
// "Move" the arrays where the word was not found to a recent_list temp
char** recent_list_move = new char* [words_not_found];
for (int i = 0, j = 0; i < recentList_Size; i++) {
// instances in char array where word was not found
if (words_found_at[i] == false) {
recent_list_move[j] = a.recent[i]; // create temp array of chars w/o word(s) based on position
j++;
}
}
// Based on the num of words not found, "move" the arrays from the contents from the Library
// to another temp array in FIFO order
char** library_list_move = new char* [words_not_found];
for (int i = 0; i < words_not_found; i++) {
library_list_move[i] = a.library[i];
}
// Shift Library up to maintain the FIFO order
// j is used for the position of array after the top 'n' array(s) have been moved to the recent_list
for (int i = 0, j = words_not_found; i < library_Size; i++, j++) {
if (j < 15)
{
a.library[i] = a.library[j];
}
else
{
a.library[i] = NULL; // j goes out of bounds of array when i = 12
}
}
// "Move" arrays of words from recent_list temp to the Library
// (library_Size - words_not_found) used to place recent_list temp contents at the bottom of Library
for (int i = library_Size - words_not_found, j = 0; i < library_Size; i++, j++) {
a.library[i] = recent_list_move[j];
}
// Find first index where word(s) have not been found, since that is the index
// Keeps count of how many spaces need to be filled
int shift_starts_at = 0;
for (int i = 0; i < recentList_Size; i++) {
if (words_found_at[i] == false) {
shift_starts_at = i;
break;
}
}
// Truncate recent_list up
for (int i = shift_starts_at, j = shift_starts_at; i < recentList_Size; i++) {
if (words_found_at[i] == true) {
a.recent[j] = a.recent[i];
j++;
}
}
// Fill in the recent_list with contents from library based on count
// 'i' will be the starting position of the recent_list after truncation
for (int i = recentList_Size - words_not_found, j = 0; i < recentList_Size; i++, j++) {
a.recent[i] = library_list_move[j];
}
}
// Prompt for user
cout << "---------------------------------------------" << endl;
cout << " Press 1 to search the Recent List for a word " << endl;
cout << " Press 2 to exit the program" << endl;
cout << "---------------------------------------------" << endl;
cin >> input;
while (input != 1 && input != 2 && input != 3)
{
cout << "---------Please press only 1, 2 or 3---------" << endl;
cout << " Press 1 to search the Recent List for a word" << endl;
cout << " Press 2 to exit the program" << endl;
cout << "---------------------------------------------" << endl;
cin >> input;
}
}
// Recommended to de-allocate memory before exiting but unsure how to do so
return 0;
}