Question: I found this code on chegg and I have a problem that I cannot solve. It suppose to create an output file but it does

I found this code on chegg and I have a problem that I cannot solve. It suppose to create an output file but it does not. Assignment comes with a train and test file to run the code with but I cannot upload those files here. I would be happy with any help but especially a fixed code, thank you.

#include

#include

#include

#include

#include

#include

// Structure to represent a rating given by a user to an item

struct Rating {

int user;

int item;

float rating;

};

// Read ratings from the train.csv file and store them in a vector

std::vector readRatings(const std::string& filename) {

std::vector ratings;

std::ifstream file(filename);

std::string line;

// Skip the first line with the column names

std::getline(file, line);

while (std::getline(file, line)) {

Rating rating;

std::stringstream ss(line);

std::string cell;

std::getline(ss, cell, ',');

rating.user = std::stoi(cell);

std::getline(ss, cell, ',');

rating.item = std::stoi(cell);

std::getline(ss, cell, ',');

rating.rating = std::stof(cell);

ratings.push_back(rating);

}

return ratings;

}

// Calculate the cosine similarity between two vectors of ratings

float cosineSimilarity(const std::unordered_map& ratings1, const std::unordered_map& ratings2) {

float dotProduct = 0;

float magnitude1 = 0;

float magnitude2 = 0;

for (const auto& [item, rating] : ratings1) {

if (ratings2.count(item)) {

dotProduct += rating * ratings2.at(item);

}

magnitude1 += rating * rating;

}

for (const auto& [item, rating] : ratings2) {

magnitude2 += rating * rating;

}

return dotProduct / (std::sqrt(magnitude1) * std::sqrt(magnitude2));

}

int main() {

// Read the ratings from the train.csv file

std::vector ratings = readRatings("train.csv");

// Create a map from user IDs to vectors of ratings

std::unordered_map> userRatings;

for (const Rating& rating : ratings) {

userRatings[rating.user][rating.item] = rating.rating;

}

// Open the test.csv file

std::ifstream file("test.csv");

std::string line;

// Skip the first line with the column names

std::getline(file, line);

while (std::getline(file, line)) {

// Read a test case from the file

std::stringstream ss(line);

std::string cell;

int user;

int item;

std::getline(ss, cell, ',');

user = std::stoi(cell);

std::getline(ss, cell, ',');

item

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!