C++: In the main function, return the number of collisions and total input given
ID: 3707428 • Letter: C
Question
C++:
In the main function, return the number of collisions and total input given the code:
#include
#include
#include
#include
using namespace std;
long hashcode(char* s){
int seed = 31;
unsigned long hash = 0;
for (int i = 0; i < strlen(s); i++){
hash = (hash * seed) + s[i];
}
return hash % 10007;
}
Main():
int main(int argc, char * argv[]){
fstream input(argv[1]);
while (!input.eof()){
.
.
.
}
Given File:
lglwneynql
iufefwvzxw
wtlzotieuc
qgrgfewomj
fcuggrkvca
zwpedsmlwl
nfkotdyjkq
xnyvfhhkhk
yfuzdopdnx
ciuynoedek
ragjueltld
mlbhmvztvu
lqsotznhsm
xdpjxscwco
deryeuhhvr
ntwxlyjefe
swqkcftkug
kepnhjkgdq
xakycvqjso
gkvjvyligj
yqdevlqptn
...
Explanation / Answer
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;
long hashcode(const char* s){
int seed = 31;
unsigned long hash = 0;
for (int i = 0; i < strlen(s); i++){
hash = (hash * seed) + s[i];
}
return hash % 10007;
}
int main(int argc, char * argv[]){
fstream input("input.txt");
if(input.is_open()) {
int arr[10007] = {0};
int count = 0;
int collisions = 0;
string str;
long key;
while (!input.eof()){
input >> str;
key = hashcode(str.c_str());
if(arr[key] != 0) {
collisions++;
}
arr[key]++;
count++;
}
cout << "Total number of strings: " << count << endl;
cout << "Total number of collisions: " << collisions << endl;
} else {
cout << "Please provide file name in command line arguments and check if file exists" << endl;
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.