Algorithm crashing - c++

int function(int A[], int n)
{
int i = 0;
int sum = 0;
int amount = 0;
while(i<n) {
if(A[i] > 0) {
sum=sum+A[i];
amount++;
}
else {
i++;
}
}
while(!(i<n)) {
if(ile>0){
return sum/amount;
} else {
return 0;
}
}
}
I am generating random array of numbers between 0-10 , Im trying to use this with this algorithm, but all the time im getting result 6422260. Can someone tell me how should I approach this?
int n;
cin >> n;
int arr[n];
srand(time(NULL));
for (int i = 0; i < 10; i++)
{
arr[i] = rand() % 10;
}
function(arr, n);

Here is a solution to your problem:
#include <random>
#include <iostream>
void fill(int arr[]);
int random(int from, int to);
using namespace std;
int main(void)
{
int arr[10];
fill(arr);
for(int i = 0; i<10; i++)
printf("%d ", arr[i]);
return 0;
}
void fill(int arr[]){
for(int i=0;i<(*(&arr + 1) - arr);i++){
arr[i] = random(0, 10);//adjust accordngly
}
}
int random(int from, int to){
std::random_device dev;
std::mt19937 rng(dev());
std::uniform_int_distribution<std::mt19937::result_type> dist6(from, to); // distribution in range [from, to]
return dist6(rng);
}
Your problem is you are not generating random numbers your algorithm is generating the same set of numbers! You need a logic to generate random number. Usually they are generated from system time ...
Attribution : https://stackoverflow.com/a/13445752/14911094

#alkantra, your problem is not generating random numbers. Basically, you are asking your question wrong. If required, it should be separated:
What's this code doing?
How to generate a random sequence?
The algorithm you are trying to achieve is for calculating arithmetic mean (or simply average). If you remember the formula for calculating arithmetic mean you learnt in school, the formula is:
arithmetic mean = sum/n
where
sum - sum of all numbers (from the given array[] of course)
n - count of the numbers in the given array[]
The purpose of the sum variable is to sum all given numbers, if not equal to 0, and n(in your code amount) just increases for every number added to sum.
And in the end the function should return, as the formula says, sum/amount. I could write this code, i.e. the whole program (except for the random()), though it's quite easy, so I'll leave it up to you.
About the random library, I don't know much, but there are may resources on the net, so take your time.
https://www.tutorialspoint.com/cplusplus-program-to-generate-random-number
https://www.tutorialspoint.com/rand-and-srand-in-c-cplusplus

Related

Array exercise code not working as intended

So here's my problem i'm writing a c++ code to basically randomly generate X amount of numbers between [0-100] and then create a 2D array with all the numbers found sorted by smallest->biggest
and print out each number found and how many times they are found.
this is the code i've written but there is a problem with it
whenever i print the array with the numbers and how many times each one is found no matter how many times one number is found it's the same for all of them
how can i fix that
#include <random>
#include <functional>
#include <iostream>
using namespace std;
std::default_random_engine generator;
std::uniform_int_distribution<int> data_element_distribution(0, 100);
auto random_element = std::bind(data_element_distribution, generator);
int main()
{
int size, i;
int different_numbers;
cout<<"Enter the size of the Linear List:";
cin>>size;
int LinearList[size], TempList[size];
for (i=0; i < size; i++)
{
int data_element = random_element(); //Filling the Linear List with random numbers
LinearList[i]=data_element;
TempList[i]=LinearList[i];
}
int j, temp;
for(j=size;j>1;j--)
{
for ( i=1; i<j; i++)
{
if(TempList[i]<TempList[i-1])
{
temp=TempList[i]; //Sorting numbers
TempList[i]=TempList[i-1];
TempList[i-1]=temp;
}
}
}
different_numbers=1;
int numbers[size];
int *Histogram;
Histogram=new int[different_numbers,1];
for (i=0;i<size-1;i++)
{
if(TempList[i]!=TempList[i+1])
{ //Finding the Size of the Histogram
numbers[different_numbers]=TempList[i]; //Counting how many Times each Number is found
Histogram[different_numbers,1]=1;
different_numbers++;
}
else
{
Histogram[different_numbers,1]++;
}
}
for(i=1;i<different_numbers;i++)
{
Histogram[i,0]=numbers[i]; //Printing numbers and Times found
cout<<Histogram[i,0];
cout<<" Is found "<<Histogram[i,1]<<" times."<<endl;
}
return 0;
}
edit: thank you guys for your comments and help i'll give it a try you're all life savers Xd

How to fill array with random numbers in Counting Sort Algorithm in C++

#include iostream
using namespace std;
int k=0;
void sort_func(int A[],int B[],int n)
{
int count[k+1],t;
for(int i=0;i<=k;i++)
{
count[i] = 0;
}
for(int i=0;i<n;i++)
{
t = A[i];
count[t]++;
}
for(int i=1;i<=k;i++)
{
count[i] = count[i]+count[i-1];
}
for(int i=0;i<n;i++)
{
t = A[i];
B[count[t]] = t;
count[t]=count[t]-1;
}
}
int main()
{
int n;
cout<<"Enter the size of the array :";
cin>>n;
int A[n],B[n];
cout<<"Enter the array elements: ";
for(int i=0;i<n;i++)
{
cin>>A[i];
if(A[i]>k)
{
k = A[i];
}
}
sort_func(A,B,n);
for(int i=1;i<=n;i++)
{
cout<<B[i]<<" ";
}
cout<<"\n";
return 0;
}
This is the C++ code for Counting Sort Algorithm and i can not change the code to create random array without entering values one by one
edit:Yes i meant to create random values in array A by using rand() function.
You have different options for filling an array with random elements. Just to name a few:
rand() without a seed: pseudo-random number generator; and you get the same sequence of numbers every time you run the program. Demo
std::generate(A, A + n, []() { return std::rand() % 101; });
rand() with a seed: pseudo-random number generator; depending on the seed you use, you can get a new sequence of numbers every time you run the program; for example, if you use time(NULL) as seed, which returns the current time in seconds since a given date, you would get a new sequence of numbers whenever you get a new output from time. Demo
std::srand(static_cast<unsigned int>(std::time(NULL)));
std::generate(A, A + n, []() { return std::rand() % 101; });
default_random_engine with a seed from random_device, for generating random numbers, and uniform_int_distribution, for distributing those random numbers uniformly in a given range: non-deterministic number generator or, in case a non-deterministic source is not available to the implementation, a pseudo-random number generator. Demo
As #NO_NAME pointed out in one of their comments, random_device() can throw. If you use this option, you can fall back to a rand() solution if you catch an exception. Demo
using random_generator = std::function<int()>;
random_generator rg{};
try
{
std::default_random_engine random_engine{ std::random_device{}() };
std::uniform_int_distribution<int> uniform_dist{0, 100};
rg = [&uniform_dist, &random_engine]() { return uniform_dist(random_engine); };
}
catch (const std::exception& ex)
{
std::srand(static_cast<unsigned int>(std::time(NULL)));
rg = []() { return std::rand() % 101; };
}
std::generate(A, A + n, rg);
As an aside note, you could use max_element to calculate k in your code:
k = *std::max_element(A, A + n);

Find the first and last indices of an array for which the sequential sum of elements from and to will be the largest

I have an array of integers A [N]. I want to find indices n and m such that the sequential sum from the nth element to the mth is maximum. Search time is limited by the value of N.
It's my code:
#include <iostream>
#include <vector>
using namespace std;
int MaxSum(vector<int> &A){
int N=A.size();
int n=0;
int m=0;
int prev_max=A[0];
int sol_max=A[0];
for (int i=1; i<N; i++){
prev_max=max(A[i], A[i]+prev_max);
if (prev_max>=sol_max){
sol_max=prev_max;
}
}
cout<<"m="<<m<<endl;
cout<<"n="<<n<<endl;
// cout<<sol_max<<endl;
}
int main()
{
vector<int> a={{-2},{1},{-3},{4},{-1},{2},{1},{-5},{4}};//for example: n=3; m=6
MaxSum(a);
}
I tried to insert these counters and each time the program didn't work correctly, and it is clear why. But, unfortunately, I don't know how to put them correctly (I hope you can fix it
This type of problem can be solved using Kadane's Algorithm and the complexity is linear.
The primary idea of this problem is to look for positive contiguous segments of the array. And finding the maximum sum among all positive contiguous segment. And also ignore segment that has negative sum (as we are intended to find the maximum sum).
Note: This idea will fail if all the values are negative. To fix this issues you can check if all the elements are negative or not and find the maximum value.
int MaxSum(vector<int>&A) {
int n=0,m=0;
int max_so_far=0,max_ending_here=0;
int prevIndex = 0;
for(int i=0;i<A.size();i++) {
max_ending_here += A[i];
if(max_ending_here > max_so_far) {
max_so_far = max_ending_here;
n = prevIndex;
m = i;
}
if(max_ending_here < 0) {
max_ending_here = 0;
prevIndex=i+1;
prevIndex=i+1;
}
}
cout<<"n: "<<n<<endl;
cout<<"m: "<<m<<endl;
}

Newton's binomial - doesn't work for bigger numbers

I wrote a program which is supposed to print the value of Newton's binomial.
number - number of tests, t[i][0] - n, t[i][1] - k. It seems to be ok for small numbers n and k, but when I want to type bigger numbers it prints 0, 1 or small, negative integer. Basically I used long intead of int so it should work with bigger numbers. Could you explain why is that?
#include <iostream>
long fact(int x);
using namespace std;
int main()
{
int number;
cin>>number;
int t[number][2];
for(int i=0; i<number; i++)
{
cin>>t[i][0];
cin>>t[i][1];
if (t[i][0]<t[i][1]) return 0;
}
for(int i=0; i<number; i++)
{
cout<<fact(t[i][0])/(fact(t[i][0]-t[i][1])*fact(t[i][1]))<<endl;
}
return 0;
}
long fact(int x)
{
long factt=1;
for(int i=1; i<=x; i++)
{
factt=factt*i;
}
return factt;
}
#edit
Thanks for advice. I tried implementing this but it doesn't compute the binomial well. It prints 11 for n=4 and k=2. May you have a look at this?
#include <iostream>
long fact(int n, int k);
using namespace std;
int main()
{
int number;
cin>>number;
int t[number][2];
for(int i=0; i<number; i++)
{
cin>>t[i][0];
cin>>t[i][1];
if (t[i][0]<t[i][1]) return 0;
}
for(int i=0; i<number; i++)
{
cout<<fact(t[i][0],t[i][1])<<endl;
}
return 0;
}
long fact(int n, int k)
{
if(n==0 || n==k)
return 1;
else if(n>k)
return fact(n-1,k-1)+fact(n-1, k);
else
return 0;
}
Factorial grows really fast and even unsigned 64-bit integers overflow n! for n>20. The overflow free way to implement the binomial coefficient is to use this recursive definition:
binom(n, k) = binom(n-1, k-1) + binom(n-1, k)
This ensures that you get an overflow only when binom(n,k) is too large to fit in your integral type's size.
On Linux 32bit long is the same as int and fits into 32bit. On Linux 64bit long is 64bit long.
On Windows both 32bit and 64bit long is 32bits entity
You have to use long long to guaranteed to use 64bit, though it might be not enough to overcome overflow. Use recursive formula for binominal, if possible

Floating point exception

#include <cstdio>
#include <ctime>
int populate_primes(int array[])
{
const int max = 1000000;
char numbers[max+1];
int count=1;
array[0]=2;
for(int i=max;i>0;i-=2)numbers[i]=0;
for(int i=max-1;i>0;i-=2)numbers[i]=1;
int i;
for(i=3;i*i<=max;i+=2){
if(numbers[i]){
for(int j=i*i;j<max+1;j+=i)numbers[j]=0; array[count++]=i;
}
}
int limit = max/2;
for(;i<limit;i++) if(numbers[i])array[count++]=i;
return count;
}
int factorize(int number,int array[])
{
int i=0,factor=1;
while(number>0){
if(number%array[i]==0){
factor++;
while(number%array[i]==0)number/=array[i];
}
i++;
}
printf("%d\n",factor);
return factor;
}
int main()
{
int primes[42000];
const int max = 1000000;
int factors[max+1];
clock_t start = clock();
int size = populate_primes(primes);
factorize(1000,primes);
printf("Execution time:\t%lf\n",(double)(clock()-start)/CLOCKS_PER_SEC);
return 0;
}
I am trying to find the no. of factors using simple algo. The populate primes part is running okay , but the factorize part does not execute and gives the floating point exception error.
Please see the code and tell my mistake.
In your factorize method you access array[0], because the initial value of i is 0.
This array is the primes array which is populated by populate_primes. But populates prime doesn't write to primes[0], since the initial value of count is 1.
Thus the first element is not initialized and you probably get a div by 0 error.
You need to pass the size which you got from populate to factorize.
factorize(int number, int array[], int size);
problem is your array[] is not fully loaded, it is loaded only till size variable. So you may want to check for that.
Also the logic inside factorize is wrong. You need to check (number > 1) rather than (number >0).
Try with the function below to see some problems:
#define MAX_PRIMES 42000
int factorize(int number,int array[])
{
int i=0,factor=1;
for (i=0; number>0 && i< MAX_PRIMES; i++){
if (array[i] == 0 || array[i] == 1) {
printf("Error: array[%d] = %d\n", i, array[i]);
} else {
if(number%array[i]==0){
factor++;
while(number%array[i]==0 && number>0) {
printf("%d %d\n", number, array[i]);
number/=array[i];
}
}
}
}
printf("%d\n",factor);
return factor;
}