Multithreading where the each thread determines when to begin the next thread - multithreading

I have almost no knowledge of multithreading, but a problem I am working on right now perhaps is a good opportunity to get started on learning concurrency and parallelism. I am hoping to get some pedagogical advice directed towards my specific problem.
The Abstract Problem
In abstract, I would like to write a program with N tasks such that
N is predetermined.
Some partial information computed by the n-th task is enough for the (n+1)-th task to start. However, we don't know beforehand how much partial information is enough. The n-th task is responsible for determining that.
So what I am hoping for is to have N threads, and the important point is that the n-th thread figures out during runtime when the (n+1)-th thread can begin. Can this be achieved with multithreading? I am familiar with Java and C++. What tools/libraries should I look into to begin with?
The Concrete Problem
The sieve of Eratosthenes is an algorithm for finding prime numbers up to a given upper limit by successively finding composite numbers as multiples of known primes. Most composite numbers have more than one prime factor and will be found multiple times. So looking for multiples of 2 and 3 in parallel can cause data race. However, the algorithm can be modified so that each composite number is found exactly once. Suppose we want to find all primes between 2 and K.
Mark 2 as prime and mark all multiples of 2 as composite. We have marked all the numbers whose smallest prime factor is 2.
The smallest unmarked number is 3. So 3 is the next prime number after 2. Multiply 3 with all numbers less than K/3 that are left unmarked after step 1. The products are all the numbers whose smallest prime factor is 3. Mark these numbers.
The smallest unmarked number is now 5. So 5 is the next prime after 2 and 3. Multiply 5 with all the numbers less than K/5 that are left unmarked after step 2 and we find all the numbers whose smallest prime factor is 5. Mark these numbers.
Repeat until we have reached floor(sqrt(K)).
Note that, for instance, step 3 can begin while step 2 is running. Early on in step 2 we find 5 as the smallest unmarked number and hence the next prime number. Therefore, once all numbers less than K/5 have been marked during step 2, we then know step 3 can begin. Step 3 will not interfere with step 1 or 2 because each composite number is found exactly once.

Related

Game puzzle: Blindfolded coin flipping with adversary

There's a table with four coins with random initial faces. You're blindfolded and each turn, you have to choose a subset of coins to flip over. Your objective is to make them all face the same way.
There is also someone else who, after you flip some coins, will rotate the table as much as they want during their turn. Their objective is to not let you win. Since you're blindfolded, you're not aware of how much the table has been rotated.
A sample game would look like: You go first, flip the top and left coins. Then, the adversary rotates the board 180 deg. Then it's your turn and you flip the bottom and right coins ( in this case, zero work was done).
What is the strategy to win?
I'm using the following moves:
1 : Flip a single coin (eg: the one in front of you)
D : (Diagonal) Flip two opposite coins (the one in front of you, the one in front of your adversary)
A : (Adjacent) Flip two adjacent coins (the one in front of you and the one on the right)
Then the sequence
D A D 1 D A D
passes always though a winning state !
This is proved by case analysis.
You don't start with a winning position. So there are at least one head and one tail coins.
I assume first that there are 2 heads and 2 tails.
Remark that, in this case, any D and A move either wins or keep 2 heads and 2 tails.
2a. If the two head are facing then D wins.
2b. If not then D doesn't change the state upto rotation (two adjacent head coins)
Then if you do A, either you win or you get two facing heads. So you arr back in 2a.
Summary : D A D wins if they are 2 heads and 2 tails.
If not, D A D keeps a state with one coins of a sort and three of the other.
So if D A D didn't win you know that you are in such a state.
Now if you just flip a coin, either you win or you end up with a 2 heads and 2 tails state. Therefore another D A D wins.
So
D A D 1 D A D
always wins !!!
I dont know in English, but in French this is a classical in automaton called "Le barman aveugle" (the blind bartender). There are a lot of page about this problem. EG:
This page
EDIT: I just dicovered an English page on Wikipedia
Note that in every turn there are precisely 2 subsets that are winning moves. The total number of subsets is 2^4=16. Therefore, in every turn there is a probability of 2/16=1/8 to win instantly if you randomly choose a subset, where the universe is {1, 2, 3, 4} and 1 denotes the coin in front of you, 2 its neighbor under clockwise order and so on.
If the number of rounds is unbounded, one winning strategy is to repeatedly 'guess' a subset of the coins to flip over. The probability to win within the first n turns is 1 - (7/8)^n. The probability is strictly increasing in n and is asymptotically 1. You will win p-a.s.
Your moves are independent of each other: Your strategy does not incorporate any information from previous turns.
Your adversary does not have any strategy to counter your efforts. Turning the table amounts to relabelling the coins in the set you draw from. You do not exploit the labelling in choosing the subset, therefore the adversary's actions cannot foil your strategy. In particular, after your k-th turn, each of your possible subset choices in turn k+1 has the same likelihood to occur and does not depend on the adversary's action.
To be precise, the relabelling is not completely arbitrary - only 4 out of 4^4=256 possible relabellings can be implemented by turning the table. Again, while this may imply a more efficient strategy for you, it cannot harm you as you do not exploit the information.
Refinement
Never choose 0 or 4 coins as your subset as this can never be a winning move (these moves only ever produce a set of coins with the same face on top if you start with such a configuration). Thus the probability for an instant win is now 2/(16-2)=1/7, with the probability to win within the first n turns becoming 1 - (6/7)^n. This refinement has no effect on the general reasoning behind the strategy.

Find the 10 smallest numbers in a large dataset?

I am coding specifically in python, but right now in the phase of designing psuedocode for an algorithm that will take all the data points in a data set that has n values, n being very large and pick out the 10 smallest values (or finite number m << n, where m is the m smallest numbers). I wish to have an optimally efficient algorithm for the requirements.
My idea:
1) Heapsort the data then pick the smallest 10 values. O(nlog(n))
2) Alternatively,use a loop to identify a 'champion' that runs 10 times. With the first 'champion' determined remove from the dataset and then repeat this loop. O(n) (given m is small)
Which suggestion or if there is another would be best?
One approach among many possible:
Grab 10 values and sort them. Now compare the largest with the 11th through nth values one at a time. Whenever the new value is smaller replace the 10th smallest with it and resort your 10 values.
The list of 10 values, sorting them etc will all be in cache so fast even with rough code. The whole list will be accessed once through so will be fast as well.

Minimum cost to group same characters in a string

I got stuck in a problem. The overall problem statement is big. I have solved the other pieces of it.
Got stuck in one piece.
Given a string containing some dashes('-') and some character lets say ('A'). Also, we are given with cost C to shift a character to its adjacent place. We need to find minimum cost such that all 'A' characters are grouped.
Example1: A-A--A---A and cost = 10
Minimum cost to group all 'A's would be: 80
Example2: AAAA------A and cost = 10
Minimum cost to group all 'A's would be: 60
Hint: for the cost to be minimum possible, one of the median As (2nd or 3rd of 4 in your first example, 3rd of 5 in your second example) can be left in place. Using this, you can compute the cost in O(n), where n is either the length of the string or the number of As, whichever is your input format.
I don't think this problem needs dynamic-programming.
You only need to move all A's towards the median A because this is the least total distance between all A's.
Just make sure not to move the media A. If the A at the median is moved to the right, each of the A's to its left will have to move one more step and each of the A's to its right will have to move one step less. This should cancel out, but you already added one unneeded step.

How to calculate modulus without the operator and any round function?

I have to calculate the modulus of a number to check if it's even or not, but the only instruction to compare two numbers is checking if they're equal, and there isn't the modulus operator and a function\operator to round numbers.
A way to round numbers would be an alternative to modulus operator, but i can't find a solution to either modulus and round.
Just need a pseudo code to work with.
We're learning some assembly basics at school with a "pseudo" assembly (DuplOne).
Thanks in advance!
Assuming the number to test is not negative, and that subtract and jump instructions are available, check if the number is 1 (i.e. the original number was odd) or 0 (i.e. the original number was even), otherwise subtract 2 and go back to the checks.
:label
if number = 1 then
original number is odd
finish
if number = 0 then
original number is even
finish
subtract 2 from number
go to label

associativity of operations regarding floating points

I am trying to understand tthe associativity of operations when it comes to floating points.
In the lecture notes i have, the following is stated:
"suppose floating-point values store seven digit of accuracy.
Considee the problem of adding 11 numbers together, where one of the numbers is 10^7 and the other ten are 1.
If the small numbers (the 1s) are each added to the large number, one at a time, there is no effect on that number, because the small numbers occur in the eighth digit of the large number ". So here I understood that the result is 1,000,001.
"however, if the small numbers are first added together and the result is added to the large number, the result is a seven-digit accurancy 1.000001 * 10^7"
But both approaches seemed the same to me: we are adding the 10 numbers to the larger number.
Can someone please clarify this problem ?
Thank you
Let's go over the first method first. When the small numbers are added one by one to the large number, the following will happen ten times:
10,000,000 + 1 = 10,000,001
However since the floating-point values store only seven digits of accuracy this last digit, the eight digit, will be rounded in the seventh digit to zero. This operation will happen 10 times, and so the value will remain 10,000,000.
Next let's go over the second method. The 10 number 1's are added together first and so this will sum up to 10. When this is added to 10^7 the following will happen:
10,000,000 + 10 = 10,000,010
Since the floating-point values store seven digits of accuracy this number will remain!

Resources