This was an interview question , any help would be appreciated
How do you synchronize two processes, out of which one is increments a value and the the displays it ( P.S. the process which displays the value must only display a value when its a new value )
Ex : int x = 5;
P1 : increments it to 6
P2 : must display 6 ( only once ) and must display it again when it becomes 7
I answered that I would use a semaphore something like
int c=0; // variable that I used to synchronize
// In P1
if( c = 0 )
{
c++;
x++; // value that is incremented
}
// in P2
if( c == 1 )
{
cout<<x;
c--;
}
He then asked what would you do if there's a context switch from process P1 to P2 after setting c to 1 but before incrementing x ( As in that case it would enter P2 before incrementing x )
I couldn't answer this part. Any help would be appreciated.
Here's a working solution in python, 2 semaphores will be needed.
Note that this is a solution for a single producer/printer, in case you needed multiple producers / writers it wouldn't work
from threading import Semaphore, Thread
x = 0
ITERS = 10
def producer():
global x
while x < ITERS:
s_empty.acquire()
x += 1
s_full.release()
def printer():
while x < ITERS:
s_full.acquire()
print(x)
s_empty.release()
s_empty = Semaphore(1)
s_full = Semaphore(0)
t1 = Thread(target=producer)
t2 = Thread(target=printer)
t1.start()
t2.start()
Related
I got the js code below from an archive of hackers delight (view the source)
The code takes in a value (such as 7) and spits out a magic number to multiply with. Then you bitshift to get the results. I don't remember assembly or any math so I'm sure I'm wrong but I can't find the reason why I'm wrong
From my understanding you could get a magic number by writing ceil(1/divide * 1<<32) (or <<64 for 64bit values, but you'd need bigger ints). If you multiple an integer with imul you'd get the result in one register and the remainder in another. The result register is magically the correct result of a division with this magic number from my formula
I wrote some C++ code to show what I mean. However I only tested with the values below. It seems correct. The JS code has a loop and more and I was wondering, why? Am I missing something? What values can I use to get an incorrect result that the JS code would get correctly? I'm not very good at math so I didn't understand any of the comments
#include <cstdio>
#include <cassert>
int main(int argc, char *argv[])
{
auto test_divisor = 7;
auto test_value = 43;
auto a = test_value*test_divisor;
auto b = a-1; //One less test
auto magic = (1ULL<<32)/test_divisor;
if (((1ULL<<32)%test_divisor) != 0) {
magic++; //Round up
}
auto answer1 = (a*magic) >> 32;
auto answer2 = (b*magic) >> 32;
assert(answer1 == test_value);
assert(answer2 == test_value-1);
printf("%lld %lld\n", answer1, answer2);
}
JS code from hackers delight
var two31 = 0x80000000
var two32 = 0x100000000
function magic_signed(d) { with(Math) {
if (d >= two31) d = d - two32// Treat large positive as short for negative.
var ad = abs(d)
var t = two31 + (d >>> 31)
var anc = t - 1 - t%ad // Absolute value of nc.
var p = 31 // Init p.
var q1 = floor(two31/anc) // Init q1 = 2**p/|nc|.
var r1 = two31 - q1*anc // Init r1 = rem(2**p, |nc|).
var q2 = floor(two31/ad) // Init q2 = 2**p/|d|.
var r2 = two31 - q2*ad // Init r2 = rem(2**p, |d|).
do {
p = p + 1;
q1 = 2*q1; // Update q1 = 2**p/|nc|.
r1 = 2*r1; // Update r1 = rem(2**p, |nc|.
if (r1 >= anc) { // (Must be an unsigned
q1 = q1 + 1; // comparison here).
r1 = r1 - anc;}
q2 = 2*q2; // Update q2 = 2**p/|d|.
r2 = 2*r2; // Update r2 = rem(2**p, |d|.
if (r2 >= ad) { // (Must be an unsigned
q2 = q2 + 1; // comparison here).
r2 = r2 - ad;}
var delta = ad - r2;
} while (q1 < delta || (q1 == delta && r1 == 0))
var mag = q2 + 1
if (d < 0) mag = two32 - mag // Magic number and
shift = p - 32 // shift amount to return.
return mag
}}
In the C CODE:
auto magic = (1ULL<<32)/test_divisor;
We get Integer Value in magic because both (1ULL<<32) & test_divisor are Integers.
The Algorithms requires incrementing magic on certain conditions, which is the next conditional statement.
Now, multiplication also gives Integers:
auto answer1 = (a*magic) >> 32;
auto answer2 = (b*magic) >> 32;
C CODE is DONE !
In the JS CODE:
All Variables are var ; no Data types !
No Integer Division ; No Integer Multiplication !
Bitwise Operations are not easy and not suitable to use in this Algorithm.
Numeric Data is via Number & BigInt which are not like "C Int" or "C Unsigned Long Long".
Hence the Algorithm is using loops to Iteratively add and compare whether "Division & Multiplication" has occurred to within the nearest Integer.
Both versions try to Implement the same Algorithm ; Both "should" give same answer, but JS Version is "buggy" & non-standard.
While there are many Issues with the JS version, I will highlight only 3:
(1) In the loop, while trying to get the best Power of 2, we have these two statements :
p = p + 1;
q1 = 2*q1; // Update q1 = 2**p/|nc|.
It is basically incrementing a counter & multiplying a number by 2, which is a left shift in C++.
The C++ version will not require this rigmarole.
(2) The while Condition has 2 Equality comparisons on RHS of || :
while (q1 < delta || (q1 == delta && r1 == 0))
But both these will be false in floating Point Calculations [[ eg check "Math.sqrt(2)*Math.sqrt(0.5) == 1" : even though this must be true, it will almost always be false ]] hence the while Condition is basically the LHS of || , because RHS will always be false.
(3) The JS version returns only one variable mag but user is supposed to get (& use) even variable shift which is given by global variable access. Inconsistent & BAD !
Comparing , we see that the C Version is more Standard, but Point is to not use auto but use int64_t with known number of bits.
First I think ceil(1/divide * 1<<32) can, depending on the divide, have cases where the result is off by one. So you don't need a loop but sometimes you need a corrective factor.
Secondly the JS code seems to allow for other shifts than 32: shift = p - 32 // shift amount to return. But then it never returns that. So not sure what is going on there.
Why not implement the JS code in C++ as well and then run a loop over all int32_t and see if they give the same result? That shouldn't take too long.
And when you find a d where they differ you can then test a / d for all int32_t a using both magic numbers and compare a / d, a * m_ceil and a * m_js.
When I try to solve this problem I write the following code:
int x = 1;
while(x%2 != 0 && x <= 50) { //x%2 != 0 defines odd integers and x<=50 gives the first 25
cout << pow(x,0.5) << endl;
x = x + 1;
}
This code only prints out the value of the square root of 1. So I edit the code like so:
int x = 1;
while(x%2 != 0 && x <= 50) {
cout << pow(x,0.5) << endl;
x = x + 2;
}
Now it prints out all the 25 odd integer square roots.
So the problem with the first code is clearly that the while loop is stopping once the square root cannot be executed (i.e. when the integer is even). It is executing the square root of 1, moving on to the integer 2, not executing the square root, and instead of then moving onto the integer 3 it is stopping. This is why the second code works: because I am adding 2 it is only ever meeting an odd integer, so always works and thus continues until x<=50.
How can I stop it from stopping and why is it doing this? I would have thought that it would register each and every integer that satisfies the condition but it is not doing this.
while executes while the condition is true. On the second iteration x == 2, so the condition x%2 != 0 becomes false, consequently x%2 != 0 && x <= 50 becomes false and while loop terminates.
You already solved How can I stop it from stopping part by incrementing x by 2, so it's unclear what you are asking here.
There are n groups of friends staying in the queue in front of bus station. The i-th group consists of ai men. Also, there is a single bus that works on the route. The size of the bus is x, that is it can transport x men simultaneously.
When the bus comes (it always comes empty) to the bus station, several groups from the head of the queue goes into the bus. Of course, groups of friends don't want to split, so they go to the bus only if the bus can hold the whole group. In the other hand, none wants to lose his position, that is the order of groups never changes.
The question is: how to choose the size x of the bus in such a way that the bus can transport all the groups and everytime when the bus moves off the bus station there is no empty space in the bus (the total number of men inside equals to x)?
Input Format:
The first line contains the only integer n (1≤n≤10^5). The second line contains n space-separated integers a1,a2,…,an (1≤ai≤10^4).
Output Format:
Print all the possible sizes of the bus in the increasing order.
Sample:
8
1 2 1 1 1 2 1 3
Output:
3 4 6 12
I made this code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(void)
{
int max=0,sum=0,i,n;
cin>>n;
int values[100000];
for ( i = 0; i < n; i++ )
{
cin>>values[i];
sum = sum + values[i];
if ( values[i] > max )
max = values[i];
}
int p = 0,j;
int count = 0;
vector<int> final;
for ( i = 0; i < n; i++ )
{
p = p + values[i];
j = 0;
if ( p >= max && sum%p == 0)
{
flag = 0;
while ( j < n )
{
garb = p;
while (garb!= 0)
{
garb = garb - values[j++];
if ( garb < 0 )
flag = 1;
}
}
if ( flag == 0 )
{
final.push_back(p);
count++;
}
}
}
sort(final.begin(),final.end());
for ( j = 0; j < count; j++ )
{
cout<<final[j]<<"\t";
}
return 0;
}
Edit: I did this in which basically, I am checking if the found divisor satisfies the condition, and if at any point of time, I get a negative integer on taking difference with the values, I mark it by using a flag. However, it seems to give me a seg fault now. Why?
I firstly, calculated the maximum value out of the all possible values, and then, I checked if its a divisor of the sum of the values. However, this approach doesn't work for the input as:
10
2 2 1 1 1 1 1 2 1 2
My output is
2 7 14
whereas the output should be
7 14
only.
Any other approach that I can go with?
Thanks!
I can think of the following simple solution (since your present concern is correctness and not time complexity):
Calculate the sum of all ai's (as you are already doing).
Calculate the maximum of all ai's (as you are already doing).
Find all the factors of sum that are > max(ai).
For each factor, iterate through the ai's and check whether the bus condition is satisfied.
I often find my self writing these pieces of code, specifically when I have to do something in a 2D array.
The loops are the same, except the operations inside are different and, most importantly, the operation in the last group depends on the first.
My main concern is: is there a more efficient code for large values of n,m?
for ( int y = 0 ; y < m ; ++y ) {
for ( int x = 0 ; x < n ; ++x ) {
if ( v[x][y] == z ) a = true;
}
}
for ( int y = 0 ; y < m ; ++y ) {
for ( int x = 0 ; x < n ; ++x ) {
if ( a == true ) do_something( v[x][y] );
}
}
Thanks in advance
In the general case as you describe it, the answer is probably "no" - you imply that the operation of the second look relies on the first loop being completed, so you have to do just that.
However, in the specific case you've listed, there are two easy optimisations:
fail fast out of the first loop: once a is set true there's no need to loop any further.
move the if ( a == true ) outside of the second loop, so that it's only evaluated once and you skip the entire loop if it's false.
for ( int y = 0 ; y < m && !a; ++y ) {
for ( int x = 0 ; x < n && !a; ++x ) {
if ( v[x][y] == z ) a = true;
}
}
if ( a == true ) {
for ( int y = 0 ; y < m ; ++y ) {
for ( int x = 0 ; x < n ; ++x ) {
do_something( v[x][y] );
}
}
}
As per Code Complete: It depends on your programming language. What might give you a performance gain in programming language A might actually hurt performance in another language.
There are some techniques described in Code Complete such as Loop unrolling which could be a performance gain (for the first loop or if you could inline do_something).
Perhaps you can also escape/exit the loop(s) once a certain condition is true? For example once a=true, exit the first loop. (and as Findus already pointed out, only perform the second loop if a was set)
Instead of terminating the first loop, you could continue and call do_something on the remaining values first (assuming the order doesn't matter). This will save iterations and cache. Then iterate back to the point where you found a to be true and go there.
Please forgive me if my question is not professional. I am reading tutorials of IBM's x10. Here's the code that computes PI but confuses me:
public static def countPoints(n: Int, rand: ()=>Double) {
var inCircle: Double = 0.0;
for (var j:Long = 1; j<=n; j++) {
val x = rand();
val y = rand();
if (x*x +y*y <= 1.0) inCircle++;
}
return inCircle;
}
val N = args.size() > 0 ? Long.parse(args(0)) : 100000;
val THREADS = args.size() > 1 ? Int.parse(args(1)) : 4;
val nPerThread = N/THREADS;
val inCircle = new Array[Long](1..THREADS);
finish for(var k: Int =1; k<=THREADS; k++) {
val r = new Random(k*k + k + 1);
val rand = () => r.nextDouble();
val kk = k;
async inCircle(kk) = countPoints(nPerThread,rand);
}
var totalInCircle: Long = 0;
for(var k: Int =1; k<=THREADS; k++) {
totalInCircle += inCircle(k);
}
val pi = (4.0*totalInCircle)/N;
The program itself is not hard, my question is, since in each countPoints() call it repeatedly calling the argument rand, and before spawn multi-threads, only one rand is created, will different threads share the same rand and incur race condition? If not, why?
Good that you worry about a possible race condition here. It is often overlooked in parallel invocation of random number generators.
Luckily this example is free of a RNG race condition. Each iteration of the k for-loop creates a new instance of a random number generator (and seeds it) and spawns one thread. Since countPoints calls its own RNG there is no race condition here.