[Help] Array looping, sum

03/14/2013 09:18 Hikarim#1
Hi, well i got a problem, I am trying to fill my array with random numbers.. and i want to make it so that the filling ends as soon as the sum of filled elements in that array exceeds and integer (lets say int i=50; )

Code:
void fillArray() {
                         


        srand((unsigned)time(0));
       
        for(int i=0; i<50; i++){
                   v[i] = (rand()%50);          
        }
       
        int sum = 0;
        for(int a=0; a<50; a++){
          sum+=v[a];
              
        }

}
i got the filling and the sum, but when i try to make it in a do-while loop, and compare it with sum i get error, as sum is not defined..etc...
03/14/2013 12:47 Schlüsselbein#2
Code:
#include <iostream>
#include <iterator>
#include <vector>
#include <random>
#include <chrono>

template<typename Generator, typename OutputIterator>
OutputIterator generate_random_numbers(Generator gen, OutputIterator result, int sum_limit, int min, int max)
{
	int sum = 0;
	std::uniform_int_distribution<int> dist(min, max);
	while(sum < sum_limit)
	{
		int rand_int = dist(gen);
		*result = rand_int;
		++result;
		sum += rand_int;
	}
	return result;
}

int main()
{
	std::vector<int> vec;
	std::default_random_engine re;
	re.seed(std::chrono::high_resolution_clock::now().time_since_epoch().count());
	
	generate_random_numbers(re, std::back_inserter(vec), 50, 0, 10);

	for(int i : vec)
	{
		std::cout << i << std::endl;
	}
}
03/15/2013 07:03 Delinquenz#3
Schlüsselbein, maybe he's coding in C, not in C++.
03/15/2013 12:03 .SkyneT.#4
Quote:
Originally Posted by Delinquenz View Post
Schlüsselbein, maybe he's coding in C, not in C++.
It's not hard to translate the essential functionality to C.