Vector with unsigned int - c++11

My teacher assigned this question for me, where i have to create a code for fibonacci, i know how to make a fibonacci, but i can't really see what am i going to do with this code that he gave and said that it has to be on my code.
Can anyone make a code that satisfy this?
I'm really trying to understand, but i've tried googleing it, watching some yt tutorials, but couldnt understand what is this supose to do.
#include "function.h"
std::vector<unsigned int> fib_below_n( unsigned int n )
{
// ALL: add your code here
// ALL: This is just a STUB. Change the RETURN for what you judge right.
return std::vector<unsigned int>{};
}

Here's some more details to get you started:
std::vector<unsigned int> retval;
unsigned prev= 1;
unsigned current = 1;
// loop to generate fibonacci numbers
while (current < n) {
retval.push_back (current); /// <<<<< here
// >> generate the next number
}
return retval;

Related

Count of subsetsum problem, how to debug where the solution is not working?

So I'm trying to solve this problem :
Given an array arr[] of integers and an integer sum, the task is to
count all subsets of the given array with a sum equal to a given sum.
Note: Answer can be very large, so, output answer modulo 10^9+7
Now this is the solution I'm trying out here:
class Solution{
private:
vector<vector<int>> t;
public:
Solution() {
t.resize(1001, vector<int> (1001,-1));
}
int perfectSum(int arr[], int n, int sum)
{
long long int result = fmod(sumrecursive(arr, n, sum),(pow(10,9)+7));
return result;
}
long long int sumrecursive(int arr[], int n, int sum){
if(sum==0){
return 1;
}
if(n==0){
return 0;
}
if(t[n][sum] != -1){
return t[n][sum];
}
if(arr[n-1]>sum){
return t[n][sum] = sumrecursive(arr, n-1, sum);
} else {
return t[n][sum] = sumrecursive(arr,n-1, sum-arr[n-1]) + sumrecursive(arr, n-1, sum);
}
}
};
Now this code is not working after some certain input:
I don't know on how to proceed in solving this problem at this point. Ideally according to the code I have written the input is within the grasp of the code and output should've been correct but unfortunately it is not the case. I wanted to ask if someone could spot on where the problem might be in the code or guide me on how to debug where the problem is in the code.
You are probably encountering integer overflow along the way.
You are taking the mod only right before ending the function, but your cache is of type int, so when placing too big numbers - you are losing some data due to overflow.

How do i Pass a set<int> var to a function?

The function dfs() in this program operates upon the set A & array C. The program works fine when set A and int C[MAX] are declared global. But when i try to use this program t number of times, the set A and C are initialized with previous test cases's values, which gives wrong output. How can i make this program to accept new values in A & C for every next case. Note: This program is intended to find if the graph with n number of nodes and m number of edges is bipartite or not.
#include <bits/stdc++.h>
using namespace std;
const int MAX=1000000; // maximum number of vertices
int dfs(int x,const set<int>& A,int C[]){
for(int y:A[x]){
if(C[y]==C[x])return 0;// this means the graph is not bipartite
if(C[y]==0){
if(C[x]==1) C[y]=2;
else C[y]=1;
dfs(y,A,C);
return 1;
}
}
}
int main(){
int t;
scanf("%d",&t);
while(t--)
{
set<int> A[MAX];// Here, i declare set<int> A and Int C[MAX] in local scope
int C[MAX];
// Passing set<int> A and int C[] to dfs()..
int res = dfs(i,A,int C);
}
If i change my code to something like above. I get the following error.
prog.cpp: In function 'int dfs(int, const std::set<int>&, int*)':
prog.cpp:8:16: error: no match for 'operator[]' (operand types are 'const std::set<int>' and 'int')
for(int y:A[x]){
According to the c++ doc, set - C++ Reference there is not such operator[] in std::set<>so your for(int y:A[x]) is wrong. You cannot call A[x].
I'd recommend to use an vector or some other container meeting your requirement instead of a std::set

TLE in case of unsigned

I was solving a question on spoj and got TLE when I used unsigned long long while it got accepted when I used long long.
Here is the link to the problem.Click Here
Can someone please tell the reason.
I think the possible reason you get a TLE when using unsigned long long is because the question mentions that the end of the input is supposed to be a -1, so when you try to store a -1 in an unsigned long long it will be stored as a positive number (Something like this http://ideone.com/r4Pvp0). So, your loop for taking the user input never ends because you will never encounter a negative number and hence the TLE.
Something similar to your case ::
int main() {
unsigned int a = -10;
if(a < 0)
cout << "Hello";
else
cout << "Bye";
return 0;
}
Just using int a would print Hello, but using unsigned int screws it, and the output would be Bye. See this :: http://ideone.com/99qq2U
So you got to stick to long long if you want to end the user input with a -1.

C: How to find the max of an array of struct with recursion? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I just ended my first exams session, passed (thanks to you).
I have one more question for you: I have to find the max of an array of struct and then printf the element of the array that has the max value in it, using a recursive algorithm. I've been smashing my head on the keyboard for about 1 week just to solve this, but I cannot seem to be able to do it. Can you help me?
Here's the code:
PLEASE, DON'T CARE ABOUT THOSE STRCPY, ty.
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
char autori[100];
char titolo[100];
int anno;
int codice;
float prezzo;
char stato[50];
} libro;
int massimo(int m, int n );
libro ricorsivo(libro a[], int len);
void main()
{
libro max;
int len=30;
libro elenco[100];
strcpy(elenco[0].autori,"Angelo Ciaramella e Giulio Giunta");
strcpy(elenco[0].titolo,"Manuale di Programmazione in C");
elenco[0].anno=2009;
elenco[0].codice=0;
elenco[0].prezzo=0.0;
strcpy(elenco[0].stato,"Disponibile");
max=ricorsivo(elenco, len);
printf ("il massimo vale %d", max);
}
libro ricorsivo(libro a[], int len)
{
if (len==1)
return a[0];
else
return massimo(a.prezzo[len-1],ricorsivo(a,len-1));
}
int massimo(int m, int n)
{
if (n>m)
return n;
else if (m>n)
return m;
}
The algorithm is incomplete, I know, but the most problematic parts are those functions. I hope you can help me, thank you.
Here are some hints that should help you fix the code:
Firstly, your massimo (max) function is defined incorrectly. In the case where m == n this function returns nothing, this is not allowed. What you want is if n > m you return n otherwise simply return m, i.e.
int max(int m, int n) { return n > m ? n : m; }
Next, in your recursive function you have a few type errors in this line:
return massimo(a.prezzo[len-1], recorsivo(a, len-1))
a is not of type libro, it is of type libro[] so it is not going to have a prezzo field.
If a were of type libro, and you accessed its prezzo field, then that has type float, and so it would be incorrect to perform an array index on it.
If a.prezzo[len-1] did produce the prezzo value of the len-1th element of the array, then that would have type float, but your massimo function accepts only ints.
ricorsivo(a, len-1) returns a libro and it is being passed into massimo which takes an int.
To fix these issues try the following:
Remove your massimo function, you don't need it.
In the recursive case of your recursive function
Call it recursively to get the max from the rest of the array.
Compare the prezzo value from the max of the rest of the array, with the prezzo value from the element at len-1.
Return the libro with the larger prezzo.
You should be able to translate the above into some pretty straightforward C code.

GSL Uniform Random Number Generator

I want to use GSL's uniform random number generator. On their website, they include this sample code:
#include <stdio.h>
#include <gsl/gsl_rng.h>
int
main (void)
{
const gsl_rng_type * T;
gsl_rng * r;
int i, n = 10;
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
for (i = 0; i < n; i++)
{
double u = gsl_rng_uniform (r);
printf ("%.5f\n", u);
}
gsl_rng_free (r);
return 0;
}
However, this does not rely on any seed and so, the same random numbers will be produced each time.
They also specify the following:
The generator itself can be changed using the environment variable GSL_RNG_TYPE. Here is the output of the program using a seed value of 123 and the multiple-recursive generator mrg,
$ GSL_RNG_SEED=123 GSL_RNG_TYPE=mrg ./a.out
But I don't understand how to implement this. Any ideas as to what modifications I can make to the above code to incorporate the seed?
The problem is that a new seed is not being generated. If you just want a function that returns a darn random number, and care nothing about the sticky details of how it's generated, try this. Assumes that you have the GSL installed.
#include <iostream>
#include <gsl/gsl_math.h>
#include <gsl/gsl_rng.h>
#include <sys/time.h>
float keithRandom() {
// Random number function based on the GNU Scientific Library
// Returns a random float between 0 and 1, exclusive; e.g., (0,1)
const gsl_rng_type * T;
gsl_rng * r;
gsl_rng_env_setup();
struct timeval tv; // Seed generation based on time
gettimeofday(&tv,0);
unsigned long mySeed = tv.tv_sec + tv.tv_usec;
T = gsl_rng_default; // Generator setup
r = gsl_rng_alloc (T);
gsl_rng_set(r, mySeed);
double u = gsl_rng_uniform(r); // Generate it!
gsl_rng_free (r);
return (float)u;
}
Read 18.6 Random number environment variables to see what that gsl_rng_env_setup() function is doing. It is getting a generator type and seed from environment variables.
Then see 18.3 Random number generator initialization - if you don't want to get the seed from an environment variable, you can use gsl_rng_set() to set the seed.
A complete answer to this question with a sample code can be seen in in this link.
Just for completeness I am putting a copy of the code for a function to create a seed here. It is written by Robert G. Brown: http://www.phy.duke.edu/~rgb/ .
#include <stdio.h>
#include <sys/time.h>
unsigned long int random_seed()
{
unsigned int seed;
struct timeval tv;
FILE *devrandom;
if ((devrandom = fopen("/dev/random","r")) == NULL) {
gettimeofday(&tv,0);
seed = tv.tv_sec + tv.tv_usec;
} else {
fread(&seed,sizeof(seed),1,devrandom);
fclose(devrandom);
}
return(seed);
}
But from my own experience with this function, I would say that the dev/random solution is very time consuming compared to the gettimeofday(), you can check it out. So, the gettimeofday() solution, might be better for you if its level of accuracy is enough:
#include <stdio.h>
#include <sys/time.h>
unsigned long int random_seed()
{
struct timeval tv;
gettimeofday(&tv,0);
return (tv.tv_sec + tv.tv_usec);
}

Resources