Esempio n. 1
7
int main() {
    vector<int> vec{1, 2, 3, 4, 5, 6, 7, 8};
    int result = accumulate(vec.cbegin(), vec.cend(), 0);
    cout << result << endl;

    vector<double> doubleVec{1.11, 2.22, 3.33};
    auto res = accumulate(doubleVec.cbegin(), doubleVec.cend(), 0);     // lost precision due to the third argument, function returns a int instead of double 
    cout << res << endl;

    return 0;
}
Esempio n. 2
0
int main()
{
	vector<int>ivec(10);		//default initialized to 0
	fill(ivec.begin(), ivec.end(), 1);		//reset each element to 1

	//print elements in ivec
	auto iter = ivec.begin();
	while (iter != ivec.end())
		cout << *iter++ << " ";
	cout << endl;
	//sum the elements in ivec starting the summation with the value 0
	int sum = accumulate(ivec.begin(), ivec.end(), 0);
	cout << sum << endl;

	//set a subsequence of the container to 10
	fill(ivec.begin(), ivec.begin() + ivec.size() / 2, 10);
	cout << accumulate(ivec.begin(), ivec.end(), 0) << endl;

	//reset the same subsequence to 0
	fill_n(ivec.begin(), ivec.size() / 2, 0);
	cout << accumulate(ivec.begin(), ivec.end(), 0) << endl;

	//concatenates elements	in a vector of strings and store in sum
	vector<string>v;
	string s;
	while (cin >> s)
		v.push_back(s);
	string concat = accumulate(v.begin(), v.end(), string(""));
	cout << concat << endl;
	getchar();
}
Esempio n. 3
0
int main()
{
	vector<int> vec(10);              // default initialized to 0
	fill(vec.begin(), vec.end(), 1);  // reset each element to 1

	// sum the elements in vec starting the summation with the value 0
	int sum = accumulate(vec.cbegin(), vec.cend(), 0);
	cout << sum << endl;
	
	// set a subsequence of the container to 10
	fill(vec.begin(), vec.begin() + vec.size()/2, 10);
	cout << accumulate(vec.begin(), vec.end(), 0) << endl;

	// reset the same subsequence to 0
	fill_n(vec.begin(), vec.size()/2, 0);
	cout << accumulate(vec.begin(), vec.end(), 0) << endl;

	// create 10 elements on the end of vec each with the value 42
	fill_n(back_inserter(vec), 10, 42);
	cout << accumulate(vec.begin(), vec.end(), 0) << endl;
	
	// concatenate elements in a vector of strings and store in sum 
	vector<string> v;
	string s;
	while (cin >> s)
		v.push_back(s);
	string concat = accumulate(v.cbegin(), v.cend(), string(""));
	cout << concat << endl;
	
	return 0;
}
Esempio n. 4
0
int AlgoRecuit::random_employe_per_weight(ecosystem_sol_t * eco, bool min_or_not_max) {
    // vector of <employe_id, sum of hours>
    vector<pair<int,int>> sums;
    int total_sum = 0;
    int current_sum = 0;
    for(auto i: (*eco)){
        current_sum = accumulate(i.second.begin(), i.second.end(), 0);
        sums.push_back(pair<int, int>(i.first, current_sum));
        total_sum += current_sum;
    }

    vector<float> weights;
    if(min_or_not_max) {
        for(auto sum: sums){
            weights.push_back( (float)(total_sum - sum.second) / (float)total_sum);
        }
    } else {
        for(auto sum: sums){
            weights.push_back((float)sum.second / (float)total_sum);
        }
    }

    discrete_distribution<> dist(weights.begin(), weights.end());
    mt19937 gen(random_device{}());
    auto employe = sums[dist(gen)];
    return employe.first;
}
Esempio n. 5
0
int main(int argc, char** argv)
{
    GetPot args(argc, argv);

    int    nthreads = args.follow(1  , "--threads");
    int    samp     = args.follow(100, "--samp");
    int    reps     = args.follow(1  , "--reps");

    double shape    = args.follow(1.0, "--shape");
    double tilt     = args.follow(0.0, "--tilt");
    
    fprintf(stderr, "Will draw %i samples %i times using %i threads.\n", samp, reps, nthreads);
    fprintf(stderr, "Shape: %g; Tilt: %g\n", shape, tilt);

    vector<double> x(samp);
    vector<double> h(samp);
    vector<double> z(samp);

    fill(h.begin(), h.end(), shape);
    fill(z.begin(), z.end(), tilt);

    vector<RNG> r(nthreads);
    vector<PolyaGamma> dv(nthreads);
    vector<PolyaGammaAlt> alt(nthreads);
    vector<PolyaGammaSP> sp(nthreads);

    struct timeval start, stop;
    gettimeofday(&start, NULL);

    for (int i = 0; i < reps; i++)
	rpg_hybrid_par(&x[0], &h[0], &z[0], &samp, &nthreads, &r, &dv, &alt, &sp);

    gettimeofday(&stop, NULL);
    double diff = calculateSeconds(start, stop);
    fprintf(stderr, "Time: %f sec. for %i samp (%i times)\n", diff, samp, reps);

    // Check output
    double m1_hat = accumulate(x.begin(), x.end(), 0.0) / samp;
    double m2_hat = accumulate(x.begin(), x.end(), 0.0, addsq) / samp;

    fprintf(stderr, "Sample moments: m1: %g; m2: %g\n", m1_hat, m2_hat);
    fprintf(stderr, "Actual moments: m1: %g, m2: %g\n", dv[0].pg_m1(shape, tilt), dv[0].pg_m2(shape, tilt));

}
Esempio n. 6
0
/**
 * \brief TODO
 */
double
RegressionModel::loglikelihood(const vector<double>& responses,
                               const vector<double>& probs,
                               const vector< vector<double> >& covars) const {
  double ll = 0;
  for (size_t i=0; i<responses.size(); i++) {
    ll += (this->loglikelihood(responses[i], covars[i]) + log(probs[i]));
  }
  return ll - log(accumulate(probs.begin(), probs.end(), 0.0));
}
Esempio n. 7
0
                        inline static typename field<Vector>::type eval(Vector const & v, typename field<Vector>::type const & init_value, BinaryFunctor binary_op)
                        {
                            using std::accumulate;

                            return accumulate(
                                v.begin(),
                                v.end(),
                                init_value,binary_op
                            );
                        }
Esempio n. 8
0
int AlgoRecuit::random_animal_per_weight(vector<int> * tasks) {

    int sum = accumulate(tasks->begin(), tasks->end(), 0);
    vector<float> weights;
    for(auto w: *tasks){
        weights.push_back((float)w/(float)sum);
    }

    discrete_distribution<> dist(weights.begin(), weights.end());
    mt19937 gen(random_device{}());
    return dist(gen);
}
Esempio n. 9
0
double dirdisc_lpdf(const vector<double> &cts, double alpha)
{
    double n = accumulate(cts.begin(), cts.end(), 0);
    double k = static_cast<double>(cts.size());
    double sum_a = alpha*k;

    double prd_xa = 0;
    for (const auto &ct : cts)
        prd_xa += lgamma(ct + alpha);

    return lgamma(sum_a) - lgamma(n+sum_a) + prd_xa - k*lgamma(alpha);
}
FileSplit::FileSplit ( const IntVector& nFileSpec, const DoubleVector& prop, int maxSpectra )
{
	totSpec = accumulate ( nFileSpec.begin (), nFileSpec.end (), 0 );
	int maxSpecPerProcess = static_cast<int> ( totSpec * prop [0] );
	numSerial = ( maxSpecPerProcess / maxSpectra ) + 1;		// Number of serial searches
	IntVector nSearchSpec;
	for ( DoubleVectorSizeType i = 0 ; i < prop.size () ; i++ ) {
		for ( int j = 0 ; j < numSerial ; j++ ) {
			nSearchSpec.push_back ( static_cast<int> ( ( totSpec / numSerial ) * prop [i] ) );
		}
	}
	int rem = accumulate ( nSearchSpec.begin (), nSearchSpec.end (), 0 ) - totSpec;
	while ( rem != 0 ) {
		int inc = ( rem < 0 ) ? 1 : -1;
		for ( DoubleVectorSizeType i = 0 ; i < prop.size () ; i++ ) {
			nSearchSpec [i] += inc;
			rem += inc;
			if ( rem == 0 ) break;
		}
	}
	init ( nFileSpec, nSearchSpec );
}
Esempio n. 11
0
QString join(const FSAMorphemeList& v, const QString& delim)
{
	using linguistica::join_helper::cat_with_delim;
	using std::accumulate;

	FSAMorphemeList::const_iterator iter = v.constBegin();
	if (iter == v.constEnd())
		// empty list
		return QString();

	const QString first = (*iter)->toStr();
	return accumulate(++iter, v.constEnd(), first, cat_with_delim(delim));
}
Esempio n. 12
0
void
add_sequencing_errors(const vector<vector<double> > &errors, 
		      vector<vector<double> > &prb) {
  for (size_t i = 0; i < prb.size(); ++i) {
    size_t base = max_element(prb[i].begin(), prb[i].end()) - prb[i].begin();
    const double sum = accumulate(errors[i].begin(), errors[i].end(), 0.0);
    prb[i][base] -= sum;
    prb[i][base] = std::max(0.0, prb[i][base]);
    transform(prb[i].begin(), prb[i].end(), 
	      errors[i].begin(), prb[i].begin(),
	      std::plus<double>());
  }
}
Esempio n. 13
0
// ---
double dirmul_lpdf(const vector<size_t> &cts, double alpha)
{
    double n = static_cast<double>(accumulate(cts.begin(), cts.end(), 0));
    double k = static_cast<double>(cts.size());
    double sum_a = alpha*k;

    double prd_xa = 0;
    double prd_x1 = 0;
    for (const auto &ct : cts){
        prd_xa += lgamma(ct + alpha);
        prd_x1 += lgamma(ct + 1.);
    }

    return lgamma(sum_a) + lgamma(n+1) - lgamma(n+sum_a) - prd_x1 +\
        prd_xa - k*lgamma(alpha);
}
Esempio n. 14
0
void
prob_to_quality_scores_solexa(const vector<vector<double> > &prb, 
			      vector<vector<double> > &quality) {
  quality = prb;
  for (size_t i = 0; i < prb.size(); ++i) {
    std::transform(prb[i].begin(), prb[i].end(),
		   quality[i].begin(), std::bind2nd(std::plus<double>(), 1e-3));
    const double column_sum = accumulate(quality[i].begin(), quality[i].end(), 0.0);
    std::transform(quality[i].begin(), quality[i].end(),
		   quality[i].begin(), std::bind2nd(std::divides<double>(), column_sum));
  }
  for (size_t i = 0; i < quality.size(); ++i)
    for (size_t j = 0; j < smithlab::alphabet_size; ++j) {
      assert(quality[i][j] > 0);
      quality[i][j] = 10*(log(quality[i][j]) - log(1 - quality[i][j]))/log(10);
    }
}
Esempio n. 15
0
template <> float calculateGBCEAllShareIndex<float>::operator() (const vector<float>& prices) {
  if (prices.size() == 0) {
    return 0.0f;
  }
    
  float PriceSum = accumulate(prices.begin(), prices.end(), 1.0f,
                              [] (float sum, const float& entry) {
                                return sum * entry;
                              });
  if (PriceSum == 0) {
    return 0.0f;
  }
  
  float vectorLength = (float)prices.size();
  float powerToRaiseTo = 1.0 / vectorLength;
  
  return pow(PriceSum, powerToRaiseTo);
}
FileSplit::FileSplit ( const IntVector& nFileSpec, int numProcesses, int maxSpectra )
{
	totSpec = accumulate ( nFileSpec.begin (), nFileSpec.end (), 0 );
	int nSpecPerProcess = totSpec / numProcesses;			// Number of spectra per process
	numSerial = ( nSpecPerProcess / maxSpectra ) + 1;		// Number of serial searches
	int numSearches = numProcesses * numSerial;				// Number of searches
	int nSpecPerSearch = totSpec / numSearches;				// Number of spectra per search
	int rem = totSpec % numSearches;
	IntVector nSearchSpec;
	for ( int i = 0 ; i < numSearches ; i++ ) {
		int n = nSpecPerSearch;
		if ( rem != 0 ) {
			n += 1;
			rem--;
		}
		nSearchSpec.push_back ( n );
	}
	init ( nFileSpec, nSearchSpec );
}
Esempio n. 17
0
void
add_sequencing_errors(const Runif &rng, const double max_errors,
		      string &seq, vector<vector<double> > &quality_scores) {
  
  // first make the pwm:
  quality_scores.resize(seq.length(), vector<double>(smithlab::alphabet_size, 0.0));
  for (size_t i = 0; i < seq.length(); ++i)
    quality_scores[i][base2int(seq[i])] = 1.0;
  
  double total_error = max_errors;
  while (total_error > 0) {
    // sample an error position:
    const size_t error_pos = rng.runif(0ul, seq.length());
    // sample an error amount:
    double remaining_freq = min(quality_scores[error_pos][base2int(seq[error_pos])], 
				total_error);
    const double error_amount = min(min(rng.runif(0.0, 1.0), max_errors), 
				    remaining_freq);
    size_t error_base = base2int(seq[error_pos]);
    while (error_base == base2int(seq[error_pos]))
      error_base = rng.runif(0ul, smithlab::alphabet_size);
    
    quality_scores[error_pos][base2int(seq[error_pos])] -= error_amount;
    quality_scores[error_pos][error_base] += error_amount;
    
    total_error -= error_amount;
  }

  for (size_t i = 0; i < quality_scores.size(); ++i) {
    std::transform(quality_scores[i].begin(), quality_scores[i].end(),
		   quality_scores[i].begin(), std::bind2nd(std::plus<double>(), 1e-3));
    const double column_sum = accumulate(quality_scores[i].begin(),
					 quality_scores[i].end(), 0.0);
    std::transform(quality_scores[i].begin(), quality_scores[i].end(),
		   quality_scores[i].begin(), std::bind2nd(std::divides<double>(), column_sum));
  }
  
  for (size_t i = 0; i < quality_scores.size(); ++i)
    for (size_t j = 0; j < smithlab::alphabet_size; ++j)
      quality_scores[i][j] = 10*(log(quality_scores[i][j]) - 
				 log(1 - quality_scores[i][j]))/log(10);
}
Esempio n. 18
0
config_option::config_option(string_view category, string_view name,
                             string_view description, const meta_state* meta,
                             void* value)
    : meta_(meta),
      value_(value) {
  using std::copy;
  using std::accumulate;
  auto comma = name.find(',');
  auto long_name = name.substr(0, comma);
  auto short_names = comma == string_view::npos ? string_view{}
                                                : name.substr(comma + 1);
  auto total_size = [](std::initializer_list<string_view> xs) {
    return (xs.size() - 1) // one separator between all fields
           + accumulate(xs.begin(), xs.end(), size_t{0},
                        [](size_t x, string_view sv) { return x + sv.size(); });
  };
  auto ts = total_size({category, long_name, short_names, description});
  CAF_ASSERT(ts <= std::numeric_limits<uint16_t>::max());
  buf_size_ = static_cast<uint16_t>(ts);
  buf_.reset(new char[ts]);
  // fille the buffer with "<category>.<long-name>,<short-name>,<descriptions>"
  auto first = buf_.get();
  auto i = first;
  auto pos = [&] {
    return static_cast<uint16_t>(std::distance(first, i));
  };
  // <category>.
  i = copy(category.begin(), category.end(), i);
  category_separator_ = pos();
  *i++ = '.';
  // <long-name>,
  i = copy(long_name.begin(), long_name.end(), i);
  long_name_separator_ = pos();
  *i++ = ',';
  // <short-names>,
  i = copy(short_names.begin(), short_names.end(), i);
  short_names_separator_ = pos();
  *i++ = ',';
  // <description>
  i = copy(description.begin(), description.end(), i);
  CAF_ASSERT(pos() == buf_size_);
}
Esempio n. 19
0
int main()
{
	ifstream input("./salesdata.txt");
	istream_iterator<Sales_item> in(input), eof;
	vector<Sales_item> sales_vec(in, eof);

	for (auto s : sales_vec)
	{
		cout << s << endl;
	}
	sort(sales_vec.begin(), sales_vec.end(), compareIsbn);
	cout << endl;
	for (auto beg = sales_vec.cbegin(), end = beg; beg != sales_vec.cend(); beg = end)
	{
		end = find_if(beg, sales_vec.cend(), [beg](const Sales_item &item){ return item.isbn() != beg->isbn(); });
		cout << accumulate(beg, end, Sales_item(beg->isbn())) << endl;
	}
	
	return 0;
}
Esempio n. 20
0
void reportResults(istream &in, ostream &os, const Stores &files)
{
	string s;   // book to look for
	while (in >> s) {
		// stores that sold this book
		vector<matches> trans = findBook(files, s);  
		if (trans.empty()) {
			cout << s << " not found in any stores" << endl;
			continue;  // get the next book to look for
		}
		// for every store with a sale
		for (vector<matches>::const_iterator store = trans.begin();
				store != trans.end(); ++store)
			// get<n> returns the specified member from the tuple in store
			os << "store " << get<0>(*store) << " sales: "
			   << accumulate(get<1>(*store), get<2>(*store), 
			                 Sales_data(s))
			   << endl;
	}
}
Esempio n. 21
0
void StepStat2StdDev(StepStat_t const &stepStat, StdDevStat_t &meanStdDev){
	int reactantsToTrack=stepStat.cbegin()->second.size();
	for(auto it=stepStat.cbegin(); it!=stepStat.cend(); ++it){
		vector<vector<double>> const &timeSlice=it->second;
		vector<pair<double, double>> &stdDevTimeSlice=meanStdDev[it->first];
		stdDevTimeSlice.resize(reactantsToTrack);
		for(int reactant=0; reactant<reactantsToTrack; ++reactant){
			vector<double> const &data=timeSlice[reactant];
			double avg=accumulate(data.begin(), data.end(),0.);
			avg/=double(data.size());

			double stdDev=0.;
			for(size_t i=0; i<data.size(); ++i){
				stdDev+=(avg-data[i])*(avg-data[i]);
			}
			stdDev=sqrt(stdDev/double(data.size()-1));
			stdDevTimeSlice[reactant]=make_pair(avg, stdDev);
		}
	}

}
Esempio n. 22
0
void Algorithm::init() {
	periods_.clear();
	std::queue<Node> empty;
	std::swap(visit_queue_, empty);
	visited_.clear();
	//visited_.resize(5040, bitset<25*25>(0) );
	//visited_.resize(841, vector<char>(25*25, 0) );
	visited_.resize(5040, vector<char>(25*25, 0) );

	visit_count_.clear();
	visit_count_.resize(26, vector<char>(26, 0) );

	end_reached_ = false;
	time_spent_ = 0;
	for (int line = 0; line < grid_size_; ++line) {
		for (int column = 0; column < grid_size_; ++column) {
			if (schedule_[line][column] > 0)
				periods_.insert(schedule_[line][column]);
		}
	}
	lcm_ = accumulate(periods_.begin(), periods_.end(), 1, lcm);
}
Esempio n. 23
0
int main()
{
  deque<int> data;
  deque<int>::iterator iter;             // Stores an iterator
  deque<int>::reverse_iterator riter;    // Stores a reverse iteraotr
 
  // Read the data 
  cout << "Enter a series of non-zero integers separated by spaces."
       << " Enter 0 to end." << endl;
  int value(0);
  while(cin >> value, value != 0)
    data.push_front(value);

  // Output the data using an iterator
  cout << endl << "The values you entered are:" << endl;
  for(iter = data.begin() ; iter != data.end() ; iter++)
    cout << *iter << "  ";
  cout << endl;

  // Output the data using a reverse iterator
  cout << endl << "In reverse order the values you entered are:" << endl;
  for(riter = data.rbegin() ; riter != data.rend() ; riter++)
    cout << *riter << "  ";

  // Sort the data in descending sequence
  cout << endl;
  cout << endl << "In descending sequence the values you entered are:" << endl;
  sort(data.rbegin(), data.rend());
  for(iter = data.begin() ; iter != data.end() ; iter++)
    cout << *iter << "  ";
  cout << endl;

  // Calculate the sum of the elements
  cout << endl << "The sum of the elements in the queue is: " 
       << accumulate(data.begin(), data.end(), 0)  << endl;

  return 0;
}
Esempio n. 24
0
Matrix
Matrix::combine(const Matrix &matrix1, const Matrix &matrix2, int offset) {
  Matrix newmat;
  newmat.width = std::max(matrix1.width,
			  matrix2.width + offset);
  newmat.matrix = new float*[newmat.width];
  for (size_t i = 0; i < newmat.width; ++i) {
    newmat.matrix[i] = new float[alphabet_size];
    fill(newmat.matrix[i], newmat.matrix[i] + alphabet_size, 0);
  }
  for (size_t i = 0; i < matrix1.width; ++i)
    for (size_t j = 0; j < alphabet_size; ++j)
      newmat.matrix[i][j] += matrix1.matrix[i][j];
  for (size_t i = 0; i < matrix2.width; ++i)
    for (size_t j = 0; j < alphabet_size; ++j)
      newmat.matrix[i + offset][j] += matrix2.matrix[i][j];
  for (size_t i = 0; i < newmat.width; ++i) {
    const float total = accumulate(newmat.matrix[i],
				   newmat.matrix[i] + alphabet_size, 0.0);
    transform(newmat.matrix[i], newmat.matrix[i] + alphabet_size,
	      newmat.matrix[i], bind2nd(divides<float>(), total));
  }
  return newmat;
}
Esempio n. 25
0
double average(const Vec<double>& v)
{
    return accumulate(v.begin(), v.end(), 0.0) / v.size();
}
Esempio n. 26
0
int main()
{
    vector<int> ivec = {1,2,3,4,5,6,7,8,9};
    cout << accumulate(ivec.cbegin(), ivec.cend(), 0) << std::endl;
    return 0;
}
Esempio n. 27
0
// Either packs or unpacks data from/to buffers.
void TeaLeafChunk::PackUnpackKernel(
		const int* fields,
		const int* offsets,
		const int depth,
		const int face,
		double* buffer,
		const bool pack)
{
	const int exchanges = accumulate(fields, fields+NUM_FIELDS, 0);

	if(exchanges < 1) return;

	PackKernel kernel;

	switch(face)
	{
		case CHUNK_LEFT:
			kernel = pack ? PackLeft : UnPackLeft;
			break;
		case CHUNK_RIGHT:
			kernel = pack ? PackRight : UnPackRight;
			break;
		case CHUNK_TOP:
			kernel = pack ? PackTop : UnPackTop;
			break;
		case CHUNK_BOTTOM:
			kernel = pack ? PackBottom : UnPackBottom;
			break;
		default:
			TeaLeafChunk::Abort(__LINE__, __FILE__, 
					"Incorrect face provided: %d.\n", face);
	}

	for(int ii = 0; ii < NUM_FIELDS; ++ii)
	{
		if(fields[ii])
		{
			double* deviceField = NULL;
			switch(ii+1)
			{
				case FIELD_DENSITY:
					deviceField = density;
					break;
				case FIELD_ENERGY0:
					deviceField = energy0;
					break;
				case FIELD_ENERGY1:
					deviceField = energy;
					break;
				case FIELD_U:
					deviceField = u;
					break;
				case FIELD_P:
					deviceField = p;
					break;
				case FIELD_SD:
					deviceField = sd;
					break;
				default:
					TeaLeafChunk::Abort(__LINE__,__FILE__,
							"Incorrect field provided: %d.\n", ii+1);
			}

			kernel(xCells, yCells, deviceField, buffer+offsets[ii], depth);
		}
	}
}
Esempio n. 28
0
T accumulate(Forward_Range&& rg, T init, Binary_Operation&& op)
{
    return accumulate(rg.begin(), rg.end(), init, std::forward< Binary_Operation >(op));
}
Esempio n. 29
0
T accumulate(Forward_Range&& rg, T init)
{
    return accumulate(rg.begin(), rg.end(), init);
}
Esempio n. 30
0
int main()
{
    vector<int> vec{1, 2, 3, 4, 5, 6, 7, 8, 9};
    cout << accumulate(vec.cbegin(), vec.cend(), 0) <<endl;
    return 0;
}