Construct a precedence graph from a code segment - MATLAB Cody - MATLAB Central

Problem 2732. Construct a precedence graph from a code segment

Difficulty:Rate

A hypothetical MATLAB code segment containing n lines is given in the form of a cell array. The i-th cell contains the i-th line of the code. Each of the lines contains simple arithmetic expressions.

Now, construct an adjacency matrix of a graph containing n-vertices. The i-th vertex will represent the i-th line of the code. There should be a directed edge from i-th vertex to j-th vertex only if the values generated at i-th line are used in the j-th line.

All the variables in the code will have single letter names (e.g.: a,b,x,y etc).

Example:

C = {'a=1;'
     'b=1;'
     'c=a+b;'
     'c=c+1;'};

Here, the cell array C contains a code segment. The first two lines are independent in the sense that they do not use values generated at any other lines. The third line uses information generated at line 1 and 2. The fourth line uses information generated at line 1,2 and 3.

Thus the resulting adjacency matrix will be as follows:

mat = [0 0 1 1;
       0 0 1 1;
       0 0 0 1;
       0 0 0 0];

Definition of adjacency matrix: http://en.wikipedia.org/wiki/Adjacency_matrix

Solution Stats

36.84% Correct | 63.16% Incorrect
Last Solution submitted on Nov 02, 2024

Problem Comments

Solution Comments

Show comments
Why should you share code?
In a discussion on LInkedin about my recent blog post, Do these...
1
3

Problem Recent Solvers5

Suggested Problems

More from this Author44

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!