I'm going through the book mentioned in the topic, and one thing bugs me. For Barrier, the solution is the following (pseudo)code:
1 rendezvous
2
3 mutex.wait ()
4 count = count + 1
5 mutex.signal()
6
7 if count == n: barrier.signal ()
8
9 barrier.wait()
10 barrier.signal()
11
12 critical point
However, should not the counter's readout be also mutex-protected, so there are no inconsistencies while reading? I mean this:
3 mutex.wait ()
4 count = count + 1
5 if count == n: barrier.signal()
6 mutex.signal()
Or am I overly cautious about the counter var maybe?
Thank you for answers.
Yup, it should be protected, and your fix looks right.
It's possible the author oversimplified their pseudocode, and actually meant this:
3 mutex.wait ()
4 count = count + 1
5 c = count
6 mutex.signal()
7
8 if c == n: barrier.signal ()
... which would be correct.
Related
1. The Problem
Given a positive integer n. Print the pattern as shown in sample outputs.
A code has already been provided. You have to understand the logic of the code on your own and try and make changes to the code so that it gives correct output.
1.1 The Specifics
Input: A positive integer n, 1<= n <=9
Output: Pattern as shown in examples below
Sample input:
4
Sample output:
4444444
4333334
4322234
4321234
4322234
4333334
4444444
Sample input:
5
Sample output:
555555555
544444445
543333345
543222345
543212345
543222345
543333345
544444445
555555555
2. My Answer
2.1 My Code
n=int(input())
answer=[[1]]
for i in range(2, n+1):
t=[i]*((2*i)-3)
answer.insert(0, t)
answer.append(t)
for a in answer:
a.insert(0,i)
a.append(i)
print(answer)
outlst = [' '.join([str(c) for c in lst]) for lst in answer]
for a in outlst:
print(a)
2.2 My Output
Input: 4
4 4 4 4 4 4 4 4 4
4 4 3 3 3 3 3 3 3 4 4
4 4 3 3 2 2 2 2 2 3 3 4 4
4 3 2 1 2 3 4
4 4 3 3 2 2 2 2 2 3 3 4 4
4 4 3 3 3 3 3 3 3 4 4
4 4 4 4 4 4 4 4 4
2.3 Desired Output
4444444
4333334
4322234
4321234
4322234
4333334
4444444
Your answer isn't as expected because you add the same object t to the answer list twice:
answer.insert(0, t)
answer.append(t)
More specifically, when you assign t = [i]*(2*i - 3), a new data structure is created, [i, ..., i], and t just points to that data structure. Then you put the pointer t in the answer list twice.
In the for a in answer loop, when you use a.insert(0, i) and a.append(i), you update the data structure a is pointing to. Since you call insert(0, i) and append(i) on both pointers that point to the same data structure, you effectively insert and append i to that data structure twice. That's why you end up with more digits than you need.
Instead, you could run the loop for a in answer for only the top half of the rows in the answer list (and the middle row that has was created without a pair). E.g. for a in answer[:(len(answer)+1)/2].
Other things you could do:
using literals as the arguments instead of reusing the reference, e.g. append([i]*(2*i-3)). The literal expression will create a new data structure every time.
using a copy in one of the calls, e.g. append(t.copy()). The copy method creates a new list object with a "shallow" copy of the data structure.
Also, your output digits are space-separated, because you used a non-empty string in ' '.join(...). You should use the empty string: ''.join(...).
n=5
answer=[[1]]
for i in range(2, n+1):
t=[i]*((2*i)-3)
answer.insert(0, t)
answer.append(t.copy())
for a in answer:
a.insert(0,i)
a.append(i)
answerfinal=[]
for a in answer:
answerfinal.append(str(a).replace(' ','').replace(',','').replace(']','').replace('[',''))
for a in answerfinal:
print(a)
n = int(input())
for i in range(1,n*2):
for j in range(1,n*2):
if i <= j<=n*2-i: print(n-i+1,end='')
elif i>n and i>=j >= n*2 -i : print(i-n+1,end='')
elif j<=n: print(n-j+1,end="")
else: print(j-n+1,end='')
print()
n = int(input())
k = 2*n - 1
for i in range(k):
for j in range(k):
a = i if i<j else j
a = a if a<k-i else k-i-1
a = a if a<k-j else k-j-1
print(n-a, end = '')
print()
I tried various programs to get the required pattern (Given below). The program which got closest to the required result is given below:
Input:
for i in range(1,6):
for j in range(i,i*2):
print(j, end=' ')
print( )
Output:
1
2 3
3 4 5
4 5 6 7
5 6 7 8 9
Required Output:
1
2 3
4 5 6
7 8 9 10
Can I get some hint to get the required output?
Note- A newbie to python.
Store the printed value outside of the loop, then increment after its printed
v = 1
lines = 4
for i in range(lines):
for j in range(i):
print(v, end=' ')
v += 1
print( )
If you don't want to keep track of the count and solve this mathematically and be able to directly calculate any n-th line, the formula you are looking for is the one for, well, triangle numbers:
triangle = lambda n: n * (n + 1) // 2
for line in range(1, 5):
t = triangle(line)
print(' '.join(str(x+1) for x in range(t-line, t)))
# 1
# 2 3
# 4 5 6
# 7 8 9 10
Can someone help me with the method behind this linux command? I know what the outputs are, just need to know how you figure them out.
#!/bin/sh
i=0
for a in 9 8 7 6 5 4
do
j=1
for b in 1 2 3 4
do
let "j+=2"
done
let "i+=1"
done
echo "i=$i j=$j"
Fist, indenting helps make it clearer:
#!/bin/sh
i=0
for a in 9 8 7 6 5 4
do
j=1
for b in 1 2 3 4
do
let "j+=2"
done
let "i+=1"
done
echo "i=$i j=$j"
The a and b variables are never used, other than to make the outer loop execute 6 times (one loop for each number in the list 9 8 7 6 5 4) and to make the inner loop execute 4 times (one loop for each number in the list 1 2 3 4).
The outer loop adds 1 to the value of i (initialized to zero) each of the 6 times through the loop, ending up with a value of 6.
The inner loop adds 2 to the value of j each of the 4 times through the loop. Even though the inner loop itself is executed 6 times, since j is re-initialized to 1 before each execution of the inner loop, the final value of j is only 9 (1+2+2+2+2).
My dataset is in the following form:
clear
input id var
1 20
1 21
1 32
1 34
2 11
2 .
2 15
3 21
3 22
3 1
3 2
3 5
end
In my true dataset, observations are sorted by id and by year (not shown here).
What I need to do is to drop all the rows of a specific id if (at least) one of the following two conditions is met:
there is at least one missing value of var.
var decreases from one row to the next (for the same id)
So in my example what I would like to obtain is:
id var
1 20
1 21
1 32
1 34
Now, my unfortuante attempt has been to use row-wise operations together with by, in order to create a drop1 variable to be later used to subset the dataset.
Something on these lines (which is clearly wrong), :
bysort id: gen drop1=1 if var[_n] < var[_n-1] | var[_n]==.
This doesn't work, and I am not even sure that I am considering the most "clean" and direct way to solve the task.
How would you proceed? Any help would be highly appreciated.
My interpretation is that you want to drop the complete group if either of two conditions are met. I assume your dataset is sorted in some way, most likely, based on another variable. Otherwise, the structure is fragile.
The logic is simple. Check for decreasing values but leave out the first observation of each group, i.e., leave out _n == 1. The first observation, if non-missing, will always be smaller. Then, check also for missings.
clear
set more off
input id var
1 20
1 21
1 32
1 34
2 11
2 .
2 15
3 21
3 22
3 1
3 2
3 5
end
// maintain original sequencing
gen orig = _n
order id orig
bysort id (orig) : gen todrop = sum((var < var[_n-1] & _n > 1) | missing(var))
list, sepby(id)
by id : drop if todrop[_N]
list, sepby(id)
One way to do this is to create some indicator variable as you had attempted. If you only want to drop where var decreases from one observation to the next, you could use:
clear
input id var
1 20
1 21
1 32
1 34
2 11
2 .
2 15
3 21
3 22
3 1
3 2
3 5
4 .
4 2
end
gen i = id if mi(var)
bysort id : egen k = mean(i)
drop if id == k
drop i k
drop if var[_n-1] > var[_n] & _n != 1
However, if you want to get the output you supplied in the post (drop all subsequent observations where var decreases from some max value), you could try the following in place of the last line above.
local N = _N
forvalues i = 1/`N' {
drop if var[_n-1] > var[_n] & _n != 1
}
The loop just ensures that the drop if var... section of code is executed enough so that all observations where var < 34 are dropped.
Hey guys i'm not sure if the answer is out there, I don't quite know how to describe the question I have. I've looked on here for about 45 minutes and couldn't find much that answered my question. So I apologize if it has already been posted elsewhere.
I need to be able to take a series of numbers inputted on a single line and take numbers that are only 6 - 10, and find the average and maximum of the numbers between 6 - 10.
Example : 4 5 6 6 7 7 7 8 8 8 8 9 9 9
and : 8 6 3 10
Problem is that I've found answers if you are looking to receive X amount of inputs, but the assignment I'm working on is going to input anywhere from like 1 - 20 numbers on a single line.
I cannot use Array for my assignment, I wish I could since it would make things much easier. I am completely lost as what to do.
Thanks for all the help!
If your input is a String with a space as delimeter you could do something like this
String string = "4 5 6 6 7 7 7 8 8 8 8 9 9 9";
List<String> splittedStrings = Arrays.asList(string.split(" "));
After that you have a List with the splitted input that you can process in any way you imagine (like removing unwanted entries und summing them up).
Update:
Something like this should work even without an array or list:
String string = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20";
string = string.replaceAll("16|17|17|18|19|20|[1-5](?!0)", "").trim();
System.out.println(string);
int counter = 0;
int value = 0;
int max = 0;
while (!string.isEmpty()) {
String substring = "";
if (string.indexOf(" ") == -1) {
substring = string;
string = "";
} else {
substring = string.substring(0, string.indexOf(" "));
string = string.substring(string.indexOf(" ")).trim();
}
if (!substring.isEmpty()) {
int integer = Integer.valueOf(substring).intValue();
if (integer > max) {
max = integer;
}
value = value + integer;
counter++;
}
}
System.out.println("Max: " + max + "; Average: " + Double.valueOf(value) / counter);