How this code generates random number? - data-structures

I am learning treap nowadays and I came to an implementation in which the guy used some weird way to generate random numbers for priority.I am not able to get it.Would anybody mind explaining me how does it work.
struct xor_128
{
ull x,y,z,w;
xor_128(): x(1234567892851659llu), y(3631515817918578190llu),z(711737163082llu), w(916951651388197517llu) {}
ull next()
{
ull t=x^(x<<11);// ull is unsigned long long he used
x=y;
y=z;
z=w;
return w=w^(w>>19)^t^(t>>8);
}
};

Related

Error showing begin and end "not declared" and i didnt get any reasons regarding that on google

void lcm2(){
int noe,number;
cout<<"enter the no. of elements whose lcm you want"<<endl;
cin>>noe;
int arg[noe];
long product=1;
for(number=0;number<noe;number++){
cout<<"enter the "<<number+1<<"element"<<endl;
cin>>arg[number];
product*=arg[number];
}
int maximumm=arg[0];
for(number=0;number<noe;number++){
if(maximumm<arg[number]){
maximumm=arg[number];
}
}
bool result;
result = std::all_of(begin(arg),end(arg),[](int i){return i%2==0;});
while(maximumm!=product){
if(result==true){
cout<<"the lcm of all the numbers entered is = "<<maximumm<<endl;
break;
}
else{
maximumm++;
}
}
}
HI i am trying to write a code which calculates lcm for multiple numbers and here is the code so the error i am encountering is that the begin and end arnet declared!!! why?? can i know the reason and if you dont mind please tell me the solution to it
Making the following tweaks will do it, having written #include <vector>
int arg[noe] -> std::vector<int> arg(noe);
begin(arg) -> arg.begin()
end(arg) -> arg.end()
The first one is due to variable length arrays not being supported in C++. The second two are not entirely necessary but they do save you from having to #include any more C++ Standard Library headers.

I am unable to find fault in my algorithm trying to solve spoj stavatar

I'm trying to solve spoj question stavatar http://www.spoj.com/problems/STAVATAR/.
I have tried all test cases generated random ones but still wa.
I am unable to find flaw in my algorithm.
#include<cstring>
#include<iostream>
#include<cstdio>
using namespace std;
char a[1000010],b[1000010];
int d[1000010];
int main()
{
int n;
scanf("%d",&n);
scanf("%s",a);
scanf("%s",b);
int k;
scanf("%d",&k);
for(int i=0;i<k;i++)
{
int x,y;
scanf("%d %d",&x,&y);
++d[x],++d[y+1];
}
long long sum=0;
for(int i=0;i<n;i++)
{
sum+=d[i];
if(sum%2!=0)
{
char t;
t=a[i];
a[i]=b[i];
b[i]=t;
}
}
printf("%s\n",a);
printf("%s\n",b);
return 0;
}
If you pay attention to Constraints, specifically the last part :
You might note the part in the end:
'....\t\r\x0b\0c'
These are the white-space printable characters.
Now, coming back to your solution. We can see you input the strings using scanf, which will read till the first whitespace it encounters, which could be any on '\t', '\x0b', '\x0c'. But in this specific question, a string should terminate only at '\n' character.
For example :
If the string is :
ab\tcd
which will look like
ab cd
in a CLI. The question demands that the first string be ab cd, whereas, you are taking ab as first string and cd as the second.
I guess, you understand the reason of this solution getting a WA.
Also, You might find this function helpful.
Edit :-
One could also use scanf function in this way - scanf("%[^\n]s", string); to perform the same task.

Deriving from std::function vs creating a functor manually

I am trying to create a queue of callable elements with state so I can store the callable element (with an integer indicating when it should be called) and then call it later (after checking the stored integer within it).
I have been reading about functors and the std::function template for the past few days and I am wondering which one of the following two options would be better in terms of both memory and performance (which is better for each, if different).
1st Option:
class UpdateFunction : public std::function<bool(unsigned long long int)> {
public:
unsigned long long int _intendedTime;
};
void main()
{
typedef std::deque<UpdateFunction> UpdateQueue;
UpdateQueue _updateQueue;
_updateQueue.push_back(UpdateFunction([](unsigned long long int time)->bool{return outsideFunction(time);}));
_updateQueue.back()._intendedTime = 10;
}
2nd Option:
class UpdateFunction {
bool (*_fn)(unsigned long long int);
unsigned long long int _intendedTime;
UpdateFunction::UpdateFunction(bool (*fn)(unsigned long long int), unsigned long long int time)
: _fn(fn),
_intendedTime(time)
{
}
bool operator()(unsigned long long int time)
{
return _fn(time);
}
};
void main()
{
typedef std::deque<UpdateFunction> UpdateQueue;
UpdateQueue _updateQueue;
_updateQueue.push_back(UpdateFunction(outsideFunction, 10));
}
I have never seen any code where someone derives from std::function so I'm not even sure this would work as expected.
An answer which comes close to what I'm trying to do is this: https://stackoverflow.com/a/9050114/4076418, but I don't need variable arguments (actually, I have only one single signature, which is in the code above), so I thought it might be better to just derive from std::function instead of contain an instance of it. To be honest, I have no idea how slow or fast std::function is; I've read mentions of type erasure but I'm still trying to figure out what that is.
NB: I am a C++ beginner and I'm trying to wrap my head around references and move semantics, so I apologize if there are obvious errors in the code, or if the coding style is horrible.
I would go with a variant of option 2. This gives you the flexibility of function but avoids the headache of subclassing and needing to deal with the constructors.
struct UpdateFunction {
std::function<bool(unsigned long long int)> fn;
unsigned long long int _intendedTime;
};
You don't even need a special constructor, you can just say
queue.push_back(UpdateFunction{outsideFunction, 10});

Overloaded "operator new" wants to see the type it's allocating

This seems like it ought to be obvious, but I'm blanking on it. I have
class SimpleMemoryPool {
char buffer[10000];
size_t idx;
void *Alloc(size_t nbytes) { idx += nbytes; return &buffer[idx - nbytes]; }
};
inline void* operator new (size_t size, SimpleMemoryPool& pool)
{
return pool.Alloc(size);
}
inline void* operator new[] (size_t size, SimpleMemoryPool& pool)
{
return pool.Alloc(size);
}
The idea is that I can allocate new objects out of my SimpleMemoryPool and then they'll all be "released" when the SimpleMemoryPool is destroyed:
void foo()
{
SimpleMemoryPool pool;
int *arr = new (pool) int[10];
double *arr2 = new (pool) double(3.14);
...do things with arr and arr2...
return; // and arr, arr2 are "released" at this point
}
One nitpick I've simplified away: The above code is sketchy because the double won't be 8-byte-aligned. Don't worry about that; my real SimpleMemoryPool code returns maxaligned chunks.
Here's the next thing you're probably thinking at this point: "Who calls the destructors?!" I.e., if I accidentally write
std::string *arr3 = new (pool) std::string;
then I'm in a world of hurt, because the compiler will generate a call to std::string::string() for me, but nobody will ever call std::string::~string(). Memory leaks, bad stuff follows.
This is the problem I want to solve. What I want to do is basically
class SimpleMemoryPool {
...
// (std::enable_if omitted for brevity)
template<typename T, typename... Args>
T *New(Args... args) {
static_assert(std::is_trivially_destructible<T>::value, "T must be trivially destructible!");
void *ptr = this->Alloc(nelem * sizeof (T));
return new (ptr) T(std::forward<Args>(args)...);
}
template<typename ArrayT>
auto NewArray(size_t nelem) -> std::remove_extent<ArrayT>::type {
typedef typename std::remove_extent<ArrayT>::type T;
static_assert(std::is_trivially_destructible<T>::value, "T must be trivially destructible!");
void *ptr = this->Alloc(nelem * sizeof (T));
return new (ptr) T[ nelem ];
}
};
...
int *arr = pool.NewArray<int>(10);
double *arr2 = pool.New<double>(3.14);
std::string *arr3 = pool.New<string>(); // fails the static_assert, hooray!
The problem with this approach is that it's ugly. It looks bad, and it invites later maintainers to come along and "fix" the code by adding a "proper" operator new, at which point we lose the safety of the static_assert.
Is there any way to get the best of both worlds — type-safety via the static_assert, and also a nice syntax?
You may assume C++11. I also welcome C++14 answers, even though they won't be immediately useful to me.
Adding a member operator new to all my classes (in this example int and double) is not acceptable. Whatever I do has to work out-of-the-box without changing a million lines of code.
This is probably a duplicate of Get type of object being allocated in operator new but I'd still like answers tailored to this particular use-case. There might be some nice idiom of which I'm not aware.

Construct a 'long long'

How do you construct a long long in gcc, similar to constructing an int via int()
The following fails in gcc (4.6.3 20120306) (but passes on MSVC for example).
myFunctionCall(someValue, long long());
with error expected primary-expression before 'long' (the column position indicates the first long is the location).
A simple change
myFunctionCall(someValue, (long long)int());
works fine - that is construct an int and cast to long long - indicating that gcc doesn't like the long long ctor.
Summary Solution
To summarize the brilliant explanation below from #birryree:
many compilers don't support long long() and it may not be standards compliant
constructing long long is equivalent to the literal 0LL, so use myFunctionCall(someValue, 0LL)
alternatively use a typedef long_long_t long long then long_long_t()
lastly, consider using uint64_t if you are after a type that is exactly 64 bits on any platform, rather than a type that is at least 64 bits, but may vary on different platforms.
I wanted a definitive answer on what the expected behavior was, so I posted a question on comp.lang.c++.moderated and got some great answers in return. So a thank you goes out to Johannes Schaub, Alf P. Steinbach (both from SO), and Francis Glassborrow for some information
This is not a bug in GCC - in fact it will break across multiple compilers - GCC 4.6, GCC 4.7, and Clang complain about similar errors like primary expression expected before '(' if you try this syntax:
long long x = long long();
Some primitives have spaces, and that is not allowed if you want to use the constructor-style initialization because of binding (long() is bound, but long long() has a free long). Types with spaces in them (like long long) can not use the type()-construction form.
MSVC is more permissive here, though technically non-standard compliant (and it's not a language extension that you can disable).
Solutions/Workarounds
There are alternatives for what you want to do:
Use 0LL as your value in place of attempting long long() - they would produce the same value.
This is how most code will be written too, so it will be most understandable to anyone else reading your code.
From your comments it seems like you really want long long, so you can typedef yourself to always guarantee you have a long long type, like this:
int main() {
typedef long long MyLongLong;
long long x = MyLongLong(); // or MyLongLong x = MyLongLong();
}
Use a template to get around needing explicit naming:
template<typename TypeT>
struct Type { typedef TypeT T(); };
// call it like this:
long long ll = Type<long long>::T();
As I mentioned in my comments, you can use an aliased type, like int64_t (from <cstdint>), which across common platforms is a typedef long long int64_t. This is a more platform dependent than the previous items in this list.
int64_t is a fixed-width type that is 64-bits, which is typically how wide long long is on platforms like linux-x86 and windows-x86. long long is at least 64-bit wide, but can be longer. If your code will only run on certain platforms, or if you really need a fixed-width type, this might be a viable choice.
C++11 Solutions
Thanks to the C++ newsgroup, I learned some additional ways of doing what you want to do, but unfortunately they're only in the realm of C++11 (and MSVC10 doesn't support either, and only very new compilers either way would):
The {} way:
long long ll{}; // does the zero initialization
Using what Johannes refers to as the 'bord tools' in C++11 with std::common_type<T>
#include <type_traits>
int main() {
long long ll = std::common_type<long long>::type();
}
So is there a real difference between () and initializing with 0 for POD types?
You say this in a comment:
I don't think default ctor returns zero always - more typical behaviour is to leave memory untouched.
Well, for primitive types, that is not true at all.
From Section 8.5 of the ISO C++ Standard/2003 (don't have 2011, sorry, but this information didn't change too much):
To default-initialize an object of type T means:
— if T is a non-POD class type (clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default
constructor);
— if T is an array type, each element is
default-initialized;
— otherwise, the object is zero-initialized.
The last clause is most important here because long long, unsigned long, int, float, etc. are all scalar/POD types, and so calling things like this:
int x = int();
Is exactly the same as doing this:
int x = 0;
Generated code example
Here is a more concrete example of what actually happens in code:
#include <iostream>
template<typename T>
void create_and_print() {
T y = T();
std::cout << y << std::endl;
}
int main() {
create_and_print<unsigned long long>();
typedef long long mll;
long long y = mll();
long long z = 0LL;
int mi = int();
}
Compile this with:
g++ -fdump-tree-original construction.cxx
And I get this in the generated tree dump:
;; Function int main() (null)
;; enabled by -tree-original
{
typedef mll mll;
long long int y = 0;
long long int z = 0;
int mi = 0;
<<cleanup_point <<< Unknown tree: expr_stmt
create_and_print<long long unsigned int> () >>>>>;
<<cleanup_point long long int y = 0;>>;
<<cleanup_point long long int z = 0;>>;
<<cleanup_point int mi = 0;>>;
}
return <retval> = 0;
;; Function void create_and_print() [with T = long long unsigned int] (null)
;; enabled by -tree-original
{
long long unsigned int y = 0;
<<cleanup_point long long unsigned int y = 0;>>;
<<cleanup_point <<< Unknown tree: expr_stmt
(void) std::basic_ostream<char>::operator<< ((struct __ostream_type *) std::basic_ostream<char>::operator<< (&cout, y), endl) >>>>>;
}
Generated Code Implications
So from the code tree generated above, notice that all my variables are just being initialized with 0, even if I use constructor-style default initialization, like with int mi = int(). GCC will generate code that just does int mi = 0.
My template function that just attempts to do default construction of some passed in typename T, where T = unsigned long long, also produced just a 0-initialization code.
Conclusion
So in conclusion, if you want to default construct primitive types/PODs, it's like using 0.

Resources