code to solve the "Theater Row" brain teaser - c++

I was reading a book called "Fifty Challenging Problems in Probability", which is filled with lots of probability-related brain teasers. I wasn't able to solve one of the problems there, and wasn't able to understand the solution, either. So, I was writing a code to get a better feeling. Here is the original problem.
The Theater Row:
Eight elegible bachelors and seven beautiful models happen randomly to have purchased single seats in the same 15-seat row of a theater. On the average, how many pairs of adjacent seats are ticketed for marriageable couples?
And here is my code, getting an average number of adjacent pairs out of 100 random sampling:
#include <iostream>
#include <vector>
#include <cstdlib>
#include <algorithm>
#include <numeric>
using namespace std;
// computes the probability for the "theater row" problem
// in the book fifty challenging probabilty problems.
vector<int> reduce(vector<int>& seats); // This function reduces a sequence to a form
// in which there is no adjacent 0's or 1's.
// *example: reduce(111001)=101*
int main()
{
srand(time(0));
int total=15;
int Num=100;
int count0=0; // number of women
int count1=0; // number of men
vector<int> seats; // vector representing a seat assignment,
// seats.size()=total
vector<int> vpair; // vector that has number of adjacent pairs
// as its element, size.vpair()=Num
for (int i=0; i<Num; ++i) {
count0=count1=0;
while ((count1-count0)!=1) {
count0=count1=0;
seats.clear();
for (int j=0; j<total; ++j) {
int r=rand()%2;
if (r==0)
++count0;
else
++count1;
seats.push_back(r);
}
}
for (int k=0;k<seats.size();++k)
cout<<seats[k];
reduce(seats);
for (int k=0;k<seats.size();++k)
cout<<" "<<seats[k];
vpair.push_back(seats.size()-1); // seats.size()-1 is the number
// of adj pairs.
cout<<endl;
}
double avg=static_cast<double>(accumulate(vpair.begin(),vpair.end(),0))/vpair.size();
cout<<"average pairs: "<<avg<<endl;
return 0;
}
vector<int> reduce(vector<int>& seats)
{
vector<int>::iterator iter = seats.begin();
while (iter!=seats.end()) {
if (iter+1==seats.end())
++iter;
else if (*iter==*(iter+1))
iter=seats.erase(iter);
else
++iter;
}
return seats;
}
The code generates random series of 0's (representing women) and 1's (men). It then "reduces" the random sequence so that there are no repeating 0's or 1's. For example, if the code generates a random sequence of 011100110010011 (which has 7 adjacent pairs), the sequence is reduced to 01010101. In the reduced format, to figure out the number of adjacent pairs, you just need to get the "size-1".
Here are my questions.
The answer to the question (according to the book) is 7.47, while I get an average of about 7 or so from the code. Does anybody see where the discrepancy originates?
My code seems quite inefficient sometimes. Is it due to the way I generate a random sequence? (As you can see, to generate a random sequence of 8 men and 7 women, I keep asking for a random sequence of size 15 until it happens to have 8 men(or "1") and 7 women(or "0"). Is there a better way to produce a random sequence when there is a constraint like this?
I am not so proficient when it comes to programming. I'd appreciate any comments. Thank you for you help!!

This Problem is hilarious.
There are 1307674368000 possible combinations.
There is 203212800 combinations where 1 couple gets together.
But there are 3048192000 combinations where 2 couples get together.
Think the key to this problem would be doing a smaller scale problem first and use that info to create your answer. This is just a expected value problem.
Edit: Instead of running simulations, you could just get the exact answer using expected value, will have to think harder, but you also will be exact. I'll take a little bit to see if I can come up with the exact answer and post it.
Important Edit(Read):
Does your code account for if you if you get more than 8 0's or 8 1's. Sense you only can at most have 8 men and 7 women, then it should automatically feel the rest with the left over symbols.

Related

Go through the array from left to right and collect as many numbers as possible

CSES problem (https://cses.fi/problemset/task/2216/).
You are given an array that contains each number between 1…n exactly once. Your task is to collect the numbers from 1 to n in increasing order.
On each round, you go through the array from left to right and collect as many numbers as possible. What will be the total number of rounds?
Constraints: 1≤n≤2⋅10^5
This is my code on c++:
int n, res=0;
cin>>n;
int arr[n];
set <int, greater <int>> lastEl;
for(int i=0; i<n; i++) {
cin>>arr[i];
auto it=lastEl.lower_bound(arr[i]);
if(it==lastEl.end()) res++;
else lastEl.erase(*it);
lastEl.insert(arr[i]);
}
cout<<res;
I go through the array once. If the element arr[i] is smaller than all the previous ones, then I "open" a new sequence, and save the element as the last element in this sequence. I store the last elements of already opened sequences in set. If arr[i] is smaller than some of the previous elements, then I take already existing sequence with the largest last element (but less than arr[i]), and replace the last element of this sequence with arr[i].
Alas, it works only on two tests of three given, and for the third one the output is much less than it shoud be. What am I doing wrong?
Let me explain my thought process in detail so that it will be easier for you next time when you face the same type of problem.
First of all, a mistake I often made when faced with this kind of problem is the urge to simulate the process. What do I mean by "simulating the process" mentioned in the problem statement? The problem mentions that a round takes place to maximize the collection of increasing numbers in a certain order. So, you start with 1, find it and see that the next number 2 is not beyond it, i.e., 2 cannot be in the same round as 1 and form an increasing sequence. So, we need another round for 2. Now we find that, 2 and 3 both can be collected in the same round, as we're moving from left to right and taking numbers in an increasing order. But we cannot take 4 because it starts before 2. Finally, for 4 and 5 we need another round. That's makes a total of three rounds.
Now, the problem becomes very easy to solve if you simulate the process in this way. In the first round, you look for numbers that form an increasing sequence starting with 1. You remove these numbers before starting the second round. You continue this way until you've exhausted all the numbers.
But simulating this process will result in a time complexity that won't pass the constraints mentioned in the problem statement. So, we need to figure out another way that gives the same output without simulating the whole process.
Notice that the position of numbers is crucial here. Why do we need another round for 2? Because it comes before 1. We don't need another round for 3 because it comes after 2. Similarly, we need another round for 4 because it comes before 2.
So, when considering each number, we only need to be concerned with the position of the number that comes before it in the order. When considering 2, we look at the position of 1? Does 1 come before or after 2? It it comes after, we don't need another round. But if it comes before, we'll need an extra round. For each number, we look at this condition and increment the round count if necessary. This way, we can figure out the total number of rounds without simulating the whole process.
#include <iostream>
#include <vector>
using namespace std;
int main(int argc, char const *argv[])
{
int n;
cin >> n;
vector <int> v(n + 1), pos(n + 1);
for(int i = 1; i <= n; ++i){
cin >> v[i];
pos[v[i]] = i;
}
int total_rounds = 1; // we'll always need at least one round because the input sequence will never be empty
for(int i = 2; i <= n; ++i){
if(pos[i] < pos[i - 1]) total_rounds++;
}
cout << total_rounds << '\n';
return 0;
}
Next time when you're faced with this type of problem, pause for a while and try to control your urge to simulate the process in code. Almost certainly, there will be some clever observation that will allow you to achieve optimal solution.

count the number of products of all possible subarrays where product should be divisible by four or it is odd

i tried to count the number of products which are odd or divisible by 4 , generated by all possible sub-arrays but my implementation get O(n^2).... i need in O(n) time . I also tried to get some pattern but cant found it
here is my code
#include<bits/stdc++.h>
#define lli long long int
using namespace std;
int main()
{
lli testcases,x,M=1000000007;
cin>>testcases;
for(x=0;x<testcases;x++){
lli n,i,j,temp,count1=0;
cin>>n;
vector<lli>v;
for(i=0;i<n;i++){
cin>>temp;
v.push_back(temp);
}
for(i=0;i<n-1;i++){
if(v[i]%2!=0 || v[i]%4==0){
++count1;
}
temp=v[i];
for(j=i+1;j<v.size();j++){
temp*=v[j];
if(temp%2!=0 || temp%4==0){
++count1;
}
}
}
if(v[n-1]%2!=0 || v[n-1]%4==0){
++count1;
}
cout<<count1<<"\n";
count1=0;
}
return 0;
}
thanks in advance !
The question is asking for the number of subarrays whose product is odd (zero factors of two) or a multiple of four (at least two factors of two).
We can also invert this: take the number of subarrays (2**N) and subtract the number of subarrays that have exactly one factor of two.
So, first preprocess the array and replace every number with its factors of two (ie 7 becomes 0, 8 becomes 3, etc).
The question is then "how many subarrays sum to exactly one", which has a known solution.
this question is directly linked to ( april long challenge) from codechef. i don't think its a good idea to ask directly here before the closing of contest (3:00 pm , 13/04/2020).
please obey rules and regulations of codechef. you can check out at this link if you don't believe my words.
https://www.codechef.com/APRIL20B/problems/SQRDSUB or directly visit codechef april challenge (squared subsequence).

Trying to produce a unique sequence of random numbers per iteration

As the title states, I'm trying to create a unique sequence of random numbers every time I run this little program.
However, sometimes I get results like:
102
201
102
The code
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
int main() {
for (int i = 0; i < 3; i++) {
srand (time(NULL)+i);
cout << rand() % 3;
cout << rand() % 3;
cout << rand() % 3 << '\n' << endl;
}
}
Clearly srand doesn't have quite the magical functionality I wanted it to. I'm hoping that there's a logical hack around this though?
Edit1: To clarify, this is just a simple test program for what will be implemented on a larger scale. So instead of 3 iterations of rand%3, I might run 1000, or more of rand%50.
If I see 102 at some point in its operation, I'd want it so that I never see 102 again.
First of all, if you were going to use srand/rand, you'd want to seed it once (and only once) at the beginning of each execution of the program:
int main() {
srand(time(NULL));
for (int i = 0; i < 3; i++) {
cout << rand() % 3;
cout << rand() % 3;
cout << rand() % 3 << '\n' << endl;
}
Second, time typically only produces a result with a resolution of one second, so even with this correction, if you run the program twice in the same second, you can expect it to produce identical results in the two runs.
Third, you don't really want to use srand/rand anyway. The random number generator in <random> are generally considerably better (and, perhaps more importantly, are enough better defined that they represent a much better-known quantity).
#include <random>
#include <iostream>
int main() {
std::mt19937_64 gen { std::random_device()() };
std::uniform_int_distribution<int> d(0, 2);
for (int i = 0; i < 3; i++) {
for (int j=0; j<3; j++)
std::cout << d(gen);
std::cout << "\n";
}
}
Based on the edit, however, this still isn't adequate. What you really want is a random sample without duplication. To get that, you need to do more than just generate numbers. Randomly generated numbers not only can repeat, but inevitably will repeat if you generate enough of them (but the likelihood of repetition becomes quite high even when it's not yet inevitable).
As long as the number of results you're producing is small compared to the number of possible results, you can pretty easily just store results in a set as you produce them, and only treat a result as actual output if it wasn't previously present in the set:
#include <random>
#include <iostream>
#include <set>
#include <iomanip>
int main() {
std::mt19937_64 gen { std::random_device()() };
std::uniform_int_distribution<int> d(0, 999);
std::set<int> results;
for (int i = 0; i < 50;) {
int result = d(gen);
if (results.insert(result).second) {
std::cout << std::setw(5) << result;
++i;
if (i % 10 == 0)
std::cout << "\n";
}
}
}
This becomes quite inefficient if the number of results approaches the number of possible results. For example, let's assume your producing numbers from 1 to 1000 (so 1000 possible results). Consider what happens if you decide to produce 1000 results (i.e., all possible results). In this case, when you're producing the last result, there's really only one possibility left--but rather than just producing that one possibility, you produce one random number after another after another, until you stumble across the one possibility that remains.
For such a case, there are better ways to do the job. For example, you can start with a container holding all the possible numbers. To generate an output, you generate a random index into that container. You output that number, and remove that number from the container, then repeat (but this time, the container is one smaller, so you reduce the range of your random index by one). This way, each random number you produce gives one output.
It is possible to do the same by just shuffling an array of numbers. This has two shortcomings though. First, you need to shuffle them correctly--a Fischer-Yates shuffle works nicely, but otherwise it's easy to produce bias. Second, unless you actually do use all (or very close to all) the numbers in the array, this is inefficient.
For an extreme case, consider wanting a few (10, for example) 64-bit numbers. In this, you start by filling an array with numbers from 264-1. You then do 264-2 swaps. So, you're doing roughly 265 operations just to produce 10 numbers. In this extreme of a case, the problem should be quite obvious. Although it's less obvious if you produce (say) 1000 numbers of 32 bits apiece, you still have the same basic problem, just to a somewhat lesser degree. So, while this is a valid way to do things for a few specific cases, its applicability is fairly narrow.
Generate an array containing the 27 three digit numbers whose digits are less than 3. Shuffle it. Iterate through the shuffled array as needed, values will be unique until you've exhausted them all.
As other people have pointed out, don't keep reseeding your random number generator. Also, rand is a terrible generator, you should use one of the better choices available in C++'s standard libraries.
You are effectively generating a three digit base 3 number. Use your RNG of choice to generate a base 10 number in the range 0 .. 26 and convert it to base 3. That gives 000 .. 222.
If you absolutely must avoid repeats, then shuffle an array as pjs suggests. That will result in later numbers being 'less random' than the earlier numbers because they are taken from a smaller pool.

Would this method be efficient at finding string permuations

#include <iostream>
#include <string>
using namespace std;
int main()
{
string word;
cin>>word;
int s = word.size();
string original_word = word;
do
{
for(decltype(s) i =1; i!= s;++i){
auto temp =word[i-1];
word[i-1] = word[i];
word[i] = temp;
cout<<word<<endl;
}
}while(word!=original_word);
}
Is this solution efficient and how does it compare by doing this recursively?
Edit: When I tested the program it displayed all permutations
i.e cat produced:
cat
act
atc
tac
tca
cta
Let's imagine tracing this code on the input 12345. On the first pass through the do ... while loop, your code steps the array through these configurations:
21345
23145
23415
23451
Notice that after this iteration of the loop finishes, you've cyclically shifted the array one step. This means that at the end of the next do ... while loop, you'll have cyclically shifted the array twice, then three times, then four times, etc. After n iterations, this will reset the array back to its original configuration. Since each pass of bubbling the character to the end goes through n intermediary steps, this means that your approach will generate at most n2 different permutations of the input string. However, there are n! possible permutations of the input string, and n! greatly exceeds n2 for all n ≥ 4. As a result, this approach can't generate all possible permutations, since it doesn't produce enough unique combinations before returning back to the start.
If you're interested in learning about a ton of different ways to enumerate permutations by individual swaps, you may want to pick up a copy of The Art of Computer Programming or search online for different methods. This is a really interesting topic and in the course of working through these algorithms I think you'll learn a ton of ways to analyze different algorithms and prove correctness.

Optimization algorithm with numbers

Given a list of numbers in increasing order and a certain sum, I'm trying to implement the optimal way of finding the sum. Using the biggest number first
A sample input would be:
3
1
2
5
11
where the first line the number of numbers we are using and the last line is the desired sum
the output would be:
1 x 1
2 x 5
which equals 11
I'm trying to interpret this https://www.classle.net/book/c-program-making-change-using-greedy-method using stdard input
Here is what i got so far
#include <iostream>
using namespace std;
int main()
{
int sol = 0; int array[]; int m[10];
while (!cin.eof())
{
cin >> array[i]; // add inputs to an array
i++;
}
x = array[0]; // number of
for (int i; i < x ; i++) {
while(sol<array[x+1]){
// try to check all multiplications of the largest number until its over the sum
// save the multiplication number into the m[] before it goes over the sum;
//then do the same with the second highest number and check if they can add up to sum
}
cout << m[//multiplication number] << "x" << array[//correct index]
return 0;
}
if(sol!=array[x+1])
{
cout<<endl<<"Not Possible!";
}
}
Finding it hard to find an efficient way of doing this in terms of trying all possible combinations starting with the biggest number? Any suggestions would be greatly helpful, since i know im clearly off
The problem is a variation of the subset sum problem, which is NP-Hard.
An NP-Hard problem is a problem that (among other things) - there is no known polynomial solution for it, thus the greedy approach of "getting the highest first" fails for it.
However, for this NP-Hard problem, there is a pseudo-polynomial solution using dynamic programming. The problem where you can chose each number more then once is called the con change problem.
This page contains explanation and possible solutions for the problem.