is visibility also a reflection of reordering?about volatile,i think visibility and reordering are the same essentially - volatile

about volatile,i think visibility and reordering are the same essentially.
for example:
atomic<int> g_payLoad = {0};
atomic<int> g_guard = {0};
// thread 0
void foo1()
{
g_payLoad.store(42, memory_order_relaxed);
g_guard.store(1, memory_order_relaxed);
}
// thread 1
void foo2()
{
int r = g_guard.load(memory_order_relaxed);
if (r)
{
r = g_payLoad.load(memory_order_relaxed);
}
}
Since g_guard and g_payLoad are both read and written in a relaxed way, we may think that g_guard.load() and g_payLoad.load() in foo2() may be out of order (load from different addresses, cpu may speculate & prefetch, etc.),But from another point of view, the fact that g_payLoad is reordered to g_guard before (the same for other types of disorder) is equivalent to g_payLoad's changes in foo1 not being seen by foo2, two different perspectives on the same thing, that's all.
Do I understand it right?

Related

Calculating number of nodes in BST using recursion c++

I'm trying to find the number of nodes in a BST using recursion. Here is my code
struct Node{
int key;
struct Node* left;
struct Node* right;
Node(){
int key = 0;
struct Node* left = nullptr;
struct Node* right = nullptr;
}
};
src_root is the address of the root node of the tree.
int BST::countNodes(Node* src_root, int sum){
if((src_root==root && src_root==nullptr) || src_root==nullptr)
return 0;
else if(src_root->left==nullptr || src_root->right==nullptr)
return sum;
return countNodes(src_root->left, sum + 1) + countNodes(src_root->right, sum + 1) + 1;
}
However my code only seems to work if there are 3 nodes. Anything greater than 3 gives wrong answer. Please help me find out what's wrong with it. Thanks!
It is a long time ago since I made anything in C/C++ so if there might be some syntax errors.
int BST::countNodes(Node *scr_root)
{
if (scr_root == null) return 0;
return 1 + countNodes(scr_root->left) + countNodes(scr_root->right);
}
I think that will do the job.
You have several logical and structural problems in your implementation. Casperah gave you the "clean" answer that I assume you already found on the web (if you haven't already done that research, you shouldn't have posted your question). Thus, what you're looking for is not someone else's solution, but how to fix your own.
Why do you pass sum down the tree? Lower nodes shouldn't care what the previous count is; it's the parent's job to accumulate the counts from its children. See how that's done in Casperah's answer? Drop the extra parameter from your code; it's merely another source for error.
Your base case has an identically false clause: src_root==root && src_root==nullptr ... if you make a meaningful call, src_root cannot be both root and nullptr.
Why are you comparing against a global value, root? Each call simply gets its own job done and returns. When your call tree crawls back to the original invocation, the one that was called with the root, it simply does its job and returns to the calling program. This should not be a special case.
Your else clause is wrong: it says that if either child is null, you ignore counting the other child altogether and return only the count so far. This guarantees that you'll give the wrong answer unless the tree is absolutely balanced and filled, a total of 2^N - 1 nodes for N levels.
Fix those items in whatever order you find instructive; the idea is to learn. Note, however, that your final code should look a lot like the answer Casperah provided.

Minimum number of jumps required to climb stairs

I recently had an interview with Microsoft for an internship and I was asked this question in the interview.
Its basically like, you have 2 parallel staircases and both the staircases have n steps. You start from the bottom and you may move upwards on either of the staircases. Each step on the staircase has a penalty attached to it.
You can also move across both the staircases with some other penalty.
I had to find the minimum penalty that will be imposed for reaching the top.
I tried writing a recurrence relation but I couldn't write anything because of so many variables.
I recently read about dynamic programming and I think this question is related to that.
With some googling, I found that this question is the same as
https://www.hackerrank.com/contests/frost-byte-final/challenges/stairway
Can you please give a solution or an approach for this problem ?
Create two arrays to keep track of the minimal cost to reach every position. Fill both arrays with huge numbers (e.g. 1000000000) and the start of the arrays with the cost of the first step.
Then iterate over all possible steps, and use an inner loop to iterate over all possible jumps.
foreach step in (0, N) {
// we're now sure we know minimal cost to reach this step
foreach jump in (1,K) {
// updating minimal costs here
}
}
Now every time we reach updating there are 4 possible moves to consider:
from A[step] to A[step+jump]
from A[step] to B[step+jump]
from B[step] to A[step+jump]
from B[step] to B[step+jump]
For each of these moves you need to compute the cost. Because you already know that you have the optimal cost to reach A[step] and B[step] this is easy. It's not guaranteed this new move is an improvement, so only update the target cost in your array if the new cost is lower then the cost already there.
Isn't this just a directed graph search? Any kind of simple pathfinding algorithm could handle this. See
https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
https://en.wikipedia.org/wiki/A*_search_algorithm
Just make sure you enforce the directional of the stairs (up only) and account for penalties (edge weights).
Worked solution
Of course, you could do it with dynamic programming, but I wouldn't be the one to ask for that...
import java.io.;
import java.util.;
public class Main {
public static int csmj(int []a,int src,int[] dp){
if(src>=a.length){
return Integer.MAX_VALUE-1;
}
if(src==a.length-1){
return 0;
}
if(dp[src]!=0){
return dp[src];
}
int count=Integer.MAX_VALUE-1;
for(int i=1;i<=a[src];i++){
count = Math.min( count , csmj(a,src+i,dp)+1 );
}
dp[src] = count;
return count;
}
public static void main(String args[] ) throws Exception {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int a[] = new int[n];
for(int i=0;i<n;i++){
a[i] = s.nextInt();
}
int minJumps = csmj(a,0,new int[n]);
System.out.println(minJumps);
}
}
bro you can have look at that solution my intuition is that

Print singly linked list in reverse order

Okay, this was the bonus question in CMPS 280's test at southeastern Louisiana Univ. Print singly linked list in reverse in three lines. Any ideas?
C implementation of your bonus question, in three lines:
#include <stdio.h>
struct node {
int data;
struct node* next;
};
void ReversePrint(struct node* head) {
if(head == NULL) return;
ReversePrint(head->next);
printf("%d ", head->data);
}
int main()
{
struct node first;
struct node second;
struct node third;
first.data = 1;
second.data = 2;
third.data = 3;
first.next = &second;
second.next = &third;
ReversePrint(&first); // Should print: 3 2 1
printf("\n");
return 0;
}
If you are allowed to use another Data Structure, then use a Stack.
Step 1: Traverse the linked list from the head node and put the key into the stack, till you reach the last node. This will take O(n) time.
Step 2 : Pop the elements out from the stack. This will take O(1) time.
Therefore, code will be
while(head != null){
stack.push(head.val);
head = head.next;
}
while(stack.isEmpty() != true){
stack.pop();
}
Generally, when asking for help on SO, you should always try to do the problem yourself first. Then, if you are stuck, come here with what you have done so far and clearly show what your problem is to maximize your chances of getting help.
How to ask a good question on SO
However, since it is a past exam question and my answer wont help you cheat :), here's pseudo-code how you can do it recursively:
reversePrint(head)
if head is null then return // Line 1: base case
reversePrint(head.next) // Line 2: print the list after head
print(head.data) // Line 3: print head
Below are the different ways of doing it. Complete source code can be at found the hyperlinks below.
1) Printing using extra memory : https://www.geeksforgeeks.org/print-reverse-linked-list-using-stack/
2) Printing using recursion : https://www.geeksforgeeks.org/print-reverse-of-a-linked-list-without-actually-reversing/
3) Printing by modifying original list - i.e. first reverse the list and then print from start.
Source Code for reversing list : https://www.geeksforgeeks.org/reverse-a-linked-list/
4) Printing without using extra space or modifying original list : https://www.geeksforgeeks.org/print-reverse-linked-list-without-extra-space-modifications/
5) Printing using Carriage return (“r”) : https://www.geeksforgeeks.org/an-interesting-method-to-print-reverse-of-a-linked-list/
Below is my iterative Java solution without stacks. I suppose the space complexity is still O(n) because the length of the StringBuilder grows linearly with the number of items in the list. However, we can get away without using a stack (either the data structure or the recursive call stack), neither of which is necessary if all we're doing is printing the elements to console. Also, the iterative stack solutions use two loops whereas this method only requires one. Finally, the time complexity is still O(n), which is much better than the quadratic algorithm by Geeks for Geeks referenced in another answer.
void printInReverse(ListNode head) {
StringBuilder sb = new StringBuilder();
ListNode n = head;
while (n != null) {
sb.insert(0, "<-" + n.data);
n = n.next;
}
System.out.println(sb.toString());
}

By reference a pointer in C

void foo(structT* P){
P = P->next;
return;
}
void func(structT* P){
foo(P);
return 0;
}
In func(), it calls foo(P) which passes a pointer. And in foo(), the P get updated. Now, how do I get the updated value in func()? How do I use passing by reference in this case in C?
Without further judging whether this is a good idea for your real-world design (a foo function has by definition unspecified purpose; just note that mutating input params is often not a good idea), here is a quick solution.
You cannot in C. But you can pass a pointer to pointer:
void foo(structT** P){
*P = (**P).next; // or "(*P)->next"
return;
}
void func(structT* P){
foo(&P);
return 0;
}
Anecdote and warning from http://c2.com/cgi/wiki?ThreeStarProgrammer:
Three Star Programmer
A rating system for C-programmers. The more indirect your pointers are (i.e. the more "*" before your variables), the higher your reputation will be. No-star C-programmers are virtually non-existent, as virtually all non-trivial programs require use of pointers. Most are one-star programmers. In the old times (well, I'm young, so these look like old times to me at least), one would occasionally find a piece of code done by a three-star programmer and shiver with awe.
Some people even claimed they'd seen three-star code with function pointers involved, on more than one level of indirection. Sounded as real as UFOs to me.
Just to be clear: Being called a ThreeStarProgrammer is usually not a compliment.
structT* foo(structT* P)
{
if ( P != NULL )
return P->next;
else
return NULL;
}
void func(structT* P){
structT* P1 = foo(P);
}

Connectivity of a Graph

int dfs(int graph[MAXNODES][MAXNODES],int visited[],int start) {
int stack[MAXNODES];
int top=-1,i;
visited[start]=1;
stack[++top]=start;
while(top!=-1)
{
start=stack[top];
for(i=0;i<MAXNODES;i++) {
if(graph[start][i]&&visited[i]==0) {
stack[++top]=i;
printf("%d-",i);
visited[i]=1;
break;
}
}
if(i==MAXNODES)
top--;
}
return 0;
}
The above code implements the dfs on a Graph stored as an Adjacency Matrix, I request a suggestion, what change should i be doing to know whether the generated graph is connected or not.
See my answer to an earlier question about strongly connected components.
Your dfs is also very inefficient as written, because you start over scanning at i=0 repeatedly; your stack should remember where you left off and continue from there. Recursion is more natural, but if you have bounded call stack size, then an explicit stack is best (for huge trees only).
Here's a recursive dfs. If you're not interested in storing the dfs tree, you can just store 1 in predecessor[] instead of the node you reached it from):
const unsigned MAXNODES=100;
/* predecessor must be 0-initialized by the caller; nodes graph[n] that are
reached from start will have predecessor[n]=p+1, where graph[pred] is the
predecessor via which n was reached from graph[start].
predecessor[start]=MAXNODES+1 (this is the root of the tree; there is NO
predecessor, but instead of 0, I put a positive value to show that it's
reached).
graph[a][b] is true iff there is a directed arc from a->b
*/
void dfs(bool graph[MAXNODES][MAXNODES],unsigned predecessor[]
,unsigned start,unsigned pred=MAXNODES)
{
if (predecessor[start]) return;
predecessor[start]=pred+1;
for (unsigned i=0;i<MAXNODES;++i)
if (graph[start][i])
dfs(graph,predecessor,i,start);
}
Here's a non-recursive dfs patterned on the above, but using the same stack variable for pred and i (in general you'd have a stack variable for every local variable and parameter that can change in your recursion):
void dfs_iter(bool graph[MAXNODES][MAXNODES],unsigned predecessor[]
,unsigned start)
{
unsigned stack[MAXNODES]; // node indices
unsigned n,pred;
int top=0;
stack[top]=start;
for(;;) {
recurse:
// invariant: stack[top] is the next (maybe reached) node
n=stack[top];
if (!predecessor[n]) { // not started yet
pred=top>0?stack[top-1]:MAXNODES;
//show(n,pred);
predecessor[n]=pred+1;
// the first thing we can reach from n
for (unsigned i=0;i<MAXNODES;++i)
if (graph[n][i] && !predecessor[i]) {
stack[++top]=i; goto recurse; // push
}
}
if (top>0) {
pred=stack[top-1];
// the next thing we can reach from pred after n
for (unsigned i=n+1;i<MAXNODES;++i)
if (graph[pred][i]) {
stack[top]=i; goto recurse; // replace top
}
--top;
} else
return;
}
}
This could be structured without the goto (it's just a named continue to the outmost loop), but without any more real clarity in my opinion.
Anyway, recursive calls are far simpler. There's recursive pseudocode for Tarjan's strongly connected components algorithm you can transcribe fairly directly. If you need help making it non-recursive (explicit stack), ask.
You'd need to store the edges generated by travelling from one node to the next. Then you could verify that all the nodes in the graph are connected by edges.
Run Dijkstra's algorithm. If at the end your queue is empty and some of the vertices aren't colored your graph isn't connected. This is guaranteed linear time, the dfs approach has a worst case analysis of quadratic.

Resources