Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Submission: C++ solution #12

Open
the-fanan opened this issue Oct 9, 2019 · 0 comments
Open

Submission: C++ solution #12

the-fanan opened this issue Oct 9, 2019 · 0 comments

Comments

@the-fanan
Copy link

the-fanan commented Oct 9, 2019

  • Hardware
    Processor Name: Intel® Core™ i5-2540M CPU @ 2.60GHz × 4
    Memory: 8 GB

  • Time ~= 2.5s

  • Program

#include <stdio.h>
#include <iostream>
#include <fstream>
#include <thread>
#include <vector>

using namespace std;

string rd = "<ABSOLUTE-PATH-TO-FILES-FOLDER>";
vector<thread> threads;
long sum = 0;

string generateFolderName(int a)
{
	char fn[24];
	if (a % 10 == 0) {
		a -= 1;
	}
	int h = a + (10 - (a % 10));
	int l = h - 9;
	sprintf(fn, "%06d-%06d", l, h);
	return fn;
}

string generateFileName(int a)
{
	char fn[12];
	sprintf(fn, "%06d.csv", a);
	return fn;
}

int sumNumbersInFile(string fd)
{
	ifstream f;
	f.open(fd);
	long sum = 0;
	int num = 0;
	char c;
	while (!f.eof() ) {
		f.get(c);
		if (c != ',' && c != '\n') {
			int ic = c - '0';
			if (num == 0) {
				num = ic;
			} else {
				num = (num * 10) + ic;
			}
		} 
		if (c == ',' || c == '\n') {
			sum += num;
			num = 0;
		}
	}
	f.close();
	//last number
	//division is done because the last digit is repeated
	sum += num / 10;
	return sum;
}

int sumNumbers(int i)
{
	string fd;
	fd = rd;
	fd.append(generateFolderName(i)).append("/").append(generateFileName(i));
	sum += sumNumbersInFile(fd);
}

int main() 
{
	for (int i = 1; i <= 1000; i++) {
		threads.emplace_back(sumNumbers,i);
	}
	
	for (thread & t : threads) {
                t.join();
	}

	cout << sum << '\n';
	return 1;
}

solution hosted on https://github.com/the-fanan/sum-files-challenge/cpp-solution

  • Command
    From the root directory of the solution run the following commands
  1. g++ -std=c++11 -pthread main.cpp -o main
  2. ./main
  • Output =49947871404
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant