i think ive done everything correctly but i dont know to the bonus part my teacher gave me
Note that some of the numbers
in LSTest appear more than once
in LSStandard. The Linear
Search algorithm as we discussed in class will return th
e first found instance, and that’s
perfectly
okay for the basic assignment. However, you can get 5 bonus points if your program can find
and report
the indices
of all instances of a num
ber that were
found in LSStandard. In this case,
your output could lo
ok something like:
number 1 (79) was located at index(es) 44, 47.
#include<iostream>
#include<fstream>
#include<time.h>
#include <cstdlib>
usingnamespace std;
int searchList(int stdList1[], int noelem, int value); // prototype function
int main() // start main function
{
ofstream file1("LSStandard.txt", ios::out);
ofstream file2("LSTest.txt", ios::out);
constint sizeValue = 100; //100 size for first array
int stdList1[sizeValue];
constint sizeValue2 = 50; //50 size for secend array
int stdTest[sizeValue2];
for (int ind = 0; ind<100; ind++)
file1 << rand() % 100 + 1 << endl;
//write 100 random NUMs file 2
for (int ind = 0; ind<50; ind++)
file2 << rand() % 100 + 1 << endl;
//close
file1.close();
file2.close();
//open files
ifstream fileone("LSStandard.txt", ios::in); //read ls standard text
ifstream INFILE2("LSTest.txt", ios::in); // read ls test
int NUM;
for (int ind = 0; ind<100; ind++)
{
fileone >> NUM;
stdList1[ind] = NUM;
}
for (int ind = 0; ind<50; ind++)
{
INFILE2 >> NUM;
stdTest[ind] = NUM;
}
fileone.close(); // close file
INFILE2.close(); //close file 2
int noelem = sizeValue;
for (int ind = 0; ind<50; ind++)
{
int position = searchList(stdList1, noelem, stdTest[ind]); //call searchlist function
if (position != -1) // if number found
cout << "NUM" << ind + 1 << "(" << stdList1[ind] << ")" <<
"was located in position " << position << endl;
else // if number not found
cout << "NUM" << ind + 1 << "(" << stdList1[ind] << ")" <<
"not in the file" << endl;
}
system("pause");
return 0;
} // end function
int searchList(int stdList1[], int noelem, int value) // search list function
{
int position = -1;
bool found = false;
for (int ind = 0; ind<noelem && !found; ind++)
{
if (stdList1[ind] == value)
{
position = ind;
found = true;
}
}
return position;
} //end function
¿why so much whitespace in the code and why the random line breaks on your text?
to find the other positions in which the number appears so just need to keep searching.
you may change your searchList() function to return a vector of all the positions, so do not break the loop after `found'
or you may change your main, when you call the function move the start of the search (don't search from the beggining, but from the last found position) position = searchList(array=stdList1, size=noelem, value=stdTest[ind], start=position+1);