Output Generation with GraphViz - c++

I am supposed to write output into a text file with C++ and then process it using GraphViz.
This extract from my code:
cout << " " << i << " -> " << j
shows this error when I run it:
Error: MyGraph5V20E:4: syntax error near line 4
context: 0 >>> - <<< > 1 [label="73"];
And this is the output file:
graph G {
node [shape=circle]
0 -> 1 [label="73"];
0 -> 2 [label="60"];
0 -> 3 [label="36",color=red];
0 -> 4 [label="71"];
1 -> 2 [label="50",color=red];
1 -> 3 [label="78"];
1 -> 4 [label="85"];
2 -> 3 [label="30",color=red];
2 -> 4 [label="23",color=red];
3 -> 4 [label="68"];
}
I suppose it has to do with " -> " in my code. How can I manouvre this??

Related

How to write these nested for-loops in Erlang

I want to implement this psuedo code in Erlang:
function()
B[1] <-- 1
for m <-- 2 to 21 do
B[m] <-- 0
for k <-- 1 to m - 1 do
B[m] <-- B[m] − 9 * B[k]
B[m] <-- B[m]/m
return B
My first thought was to do something with a list comprehension, something like
[...|| M <- lists:seq(2,21), K <- lists:seq(1,M-1)] in order to try to "translate" the nested for-loops somehow, but now I'm stuck and I don't know how to continue.
I'd really appreciate some help on how to write this code in Erlang, I feel a bit lost.
Thanks in advance!
The code may be like as follows:
test_loop2()->
M = lists:seq(2,21),
Dict = dict:new(),
Dict_a = dict:store(1,1,Dict),
Dict_b = lists:foldl(fun(X,Acc_x)->
io:format("x:~p~n",[X]),
Value = lists:foldl(fun(A,Acc_a)->
Acc_a - 9*A
end,0,lists:seq(1,X-1)),
dict:store(X,Value,Acc_x)
end,Dict_a,M),
io:format("~p",[lists:sort(dict:to_list(Dict_b))]).
In erlang, a for-loop is written like this:
loop(StopIndex, StopIndex) -> ok;
loop(CurrentIndex, StopIndex) ->
%% do stuff
loop(CurrentIndex+1, StopIndex).
Nested loops look like this:
outer_loop(StopIndex, StopIndex) -> ok;
outer_loop(Index, StopIndex) ->
io:format("---->outer_loop index: ~w~n", [Index]),
inner_loop(1, Index-1),
outer_loop(Index+1, StopIndex).
inner_loop(StopIndex, StopIndex) ->
io:format("inner_loop index: ~w~n", [StopIndex]);
inner_loop(Index, StopIndex) ->
io:format("inner_loop index: ~w~n", [Index]),
inner_loop(Index+1, StopIndex).
In the shell:
12> a:outer_loop(2, 7).
---->outer_loop index: 2
inner_loop index: 1
---->outer_loop index: 3
inner_loop index: 1
inner_loop index: 2
---->outer_loop index: 4
inner_loop index: 1
inner_loop index: 2
inner_loop index: 3
---->outer_loop index: 5
inner_loop index: 1
inner_loop index: 2
inner_loop index: 3
inner_loop index: 4
---->outer_loop index: 6
inner_loop index: 1
inner_loop index: 2
inner_loop index: 3
inner_loop index: 4
inner_loop index: 5
ok
If you need to manipulate some data in the loops, then you can add other parameter variables to the function definitions to hold the data. For instance, in your example the inner loop would need a variable to store the data structure B.
Lastly, you should be aware that lists suck at random access, e.g. B[m], so consider using the array module.

how to print this kind of pattern using swift 3?

i want to print like this output
1
121
12312
1234123
123454321
and here is my code
var no = 1
var numberOfRow = 5
for i in 1...numberOfRow {
for _ in 1..<(6-i) {
print("_", terminator: " ")
}
for _ in 1...i {
//no += 1
print("\(no)", terminator: " ")
no += 1
}
for _ in 1..<no - 1 {
no -= 1
print("\(no - 1)", terminator: " ")
}
print("\(no)")
}
but its output shows that like bellow
_ _ _ _ 1 2
_ _ _ 2 3 2 1 2
_ _ 2 3 4 3 2 1 2
_ 2 3 4 5 4 3 2 1 2
2 3 4 5 6 5 4 3 2 1 2
where is my problem in this code?
Please check this :
var no = 1
var numberOfRow = 5
for i in 1...numberOfRow {
for _ in 1..<(6-i) {
print(" ", terminator: " ")
}
for j in 1...i {
print("\(j)", terminator: " ")
no = j
}
for k in 1..<no {
no -= 1
print("\(no)", terminator: " ")
}
print(" ")
}
here is the pseudo-code for you. change your for loops accordingly.
int rc = 5;
for(int i=1;i<=rc;i++)
{
for(int j=0;j<(rc-i);j++)
{
Print("_");
}
for(int k=0;k<i;k++)
{
Print(k + 1);
}
for(int l=(i-1);l>0;l--)
{
Print(l);
}
print("\(no)")
}

Why is this an infinite recursion?

I wrote the following function to find out the number of paths we can reach from the start cell (0,0) to the destination cell (n,n). I cannot, for the life of me, figure out why this is infinite recursion.
Code is as follows:
#include <iostream>
using namespace std;
int numOfPathsToDestUtil(int start, int end, int noOfPaths, int n) {
cout<<"Start: "<<start<<" and end: "<<end<<"and n: "<<n<<"\n";
if(start==end && start==n)
return noOfPaths;
if(end<start)
return 0;
numOfPathsToDestUtil(start+1, end, noOfPaths+1,n) + numOfPathsToDestUtil(start, end+1, noOfPaths+1,n);
}
int numOfPathsToDest( int n )
{
cout<<"n is: "<<n<<"\n";
return numOfPathsToDestUtil(0,0,0,n);
}
int main() {
int ans = numOfPathsToDest(4);
cout<<ans;
return 0;
}
Note: I am not requesting help with the code (saying so, because conditions like end<start are implementation-specific. Request you to let me understand why this recursion does not stop:
n is: 4
Start: 0 and end: 0and n: 4
Start: 1 and end: 0and n: 4
Start: 0 and end: 1and n: 4
Start: 1 and end: 1and n: 4
Start: 2 and end: 1and n: 4
Start: 1 and end: 2and n: 4
Start: 2 and end: 2and n: 4
Start: 3 and end: 2and n: 4
Start: 2 and end: 3and n: 4
Start: 3 and end: 3and n: 4
Start: 4 and end: 3and n: 4
Start: 3 and end: 4and n: 4
Start: 4 and end: 4and n: 4 --> I expect it to stop here as start=end and start=n
Start: 3 and end: 5and n: 4
Start: 4 and end: 5and n: 4
Start: 5 and end: 5and n: 4
Start: 6 and end: 5and n: 4
Start: 5 and end: 6and n: 4
Start: 6 and end: 6and n: 4
Thank you so much!
Let's label your calls
numOfPathsToDestUtil(0,0,0,n) # original (O)
numOfPathsToDestUtil(start+1, end, noOfPaths+1,n) # first-recursive (FR)
numOfPathsToDestUtil(start, end+1, noOfPaths+1,n) # second-recursive (SR)
Your output:
n is: 4
Start: 0 and end: 0and n: 4 # O - numOfPathsToDestUtil(0,0,0,4)
Start: 1 and end: 0and n: 4 # FR - numOfPathsToDestUtil(0+1,0,0,4)
Start: 0 and end: 1and n: 4 # SR - numOfPathsToDestUtil(0,0+1,0,4)
Start: 1 and end: 1and n: 4 # SR -> FR
Start: 2 and end: 1and n: 4 # SR -> FR -> FR
Start: 1 and end: 2and n: 4 # SR -> FR -> SR
Start: 2 and end: 2and n: 4 # SR -> FR -> SR -> FR
Start: 3 and end: 2and n: 4 # SR -> FR -> SR -> FR -> FR
Start: 2 and end: 3and n: 4 # SR -> FR -> SR -> FR -> SR
Start: 3 and end: 3and n: 4 # SR -> FR -> SR -> FR -> SR -> FR
Start: 4 and end: 3and n: 4 # SR -> FR -> SR -> FR -> SR -> FR -> FR
Start: 3 and end: 4and n: 4 # SR -> FR -> SR -> FR -> SR -> FR -> SR
Start: 4 and end: 4and n: 4 # SR -> FR -> SR -> FR -> SR -> FR -> SR -> FR (stops and returns value)
Start: 3 and end: 5and n: 4 # SR -> FR -> SR -> FR -> SR -> FR -> SR -> SR (never reaches where end==4 and n==4, keeps going and going)
Start: 4 and end: 5and n: 4
Start: 5 and end: 5and n: 4
Start: 6 and end: 5and n: 4
Start: 5 and end: 6and n: 4
Start: 6 and end: 6and n: 4
How to debug: I will suggest you to draw a calling tree
You are missing return statement on this line
numOfPathsToDestUtil(start+1, end, noOfPaths+1,n) + numOfPathsToDestUtil(start, end+1, noOfPaths+1,n);
Consider numOfPathsToDestUtil(start, end+1, noOfPaths+1,n) only.
Initial value (start,end) will be (0,0) then calling => (0,1) => then calling (0,2) => (0,3) =>(0,4) =>(0,5)... no termination constraint on end. This part will go into infinite loop
Now let's consider as a whole (hope below explanation is easy for you to understand)
Init(start, end,n, status)
(0,0,4,calling)
=>(1,0,4, will end)+(0,1,4,calling)
=>(1,1,4,calling)+(0,2, 4,calling)
=>(2,1,4,will end)+(1,2,4,calling)+(0,2, 4,calling)
=>(1,2,4,calling)+(0,2, 4,calling)
=>(2,2,4,calling)+(1,3,4,calling) +(0,2,4,calling)
I think you are able to derive the rest, and it shows that your recursion will not easily get out.
You need to modify your constraint to ensure what only "desired" condition will continue with recursion.
if end > n, will you continue recursion?
if start == end but start < n will continue recursion?
I will not list all. Hope it provide you a good thinking direction.

Building list of tuples from list in Erlang

I am trying to read content from a file and then organize it into a list of tuples. I have read the file into a list of numbers, however it seems to skip numbers immediately after newlines, how to prevent this behaviour?
I am guaranteed a file of even number of characters.
-module(brcp).
-export([parse_file/1]).
parse_file(Filename) ->
read_file(Filename).
read_file(Filename) ->
{ok, File} = file:read_file(Filename),
Content = unicode:characters_to_list(File),
build_tuples([begin {Int,_}=string:to_integer(Token), Int end|| Token<-string:tokens(Content," /n/r")]).
build_tuples(List) ->
case List of
[] -> [];
[E1,E2|Rest] -> [{E1,E2}] ++ build_tuples(Rest)
end.
Here is a sample input file:
1 7 11 0
1 3 5 0 7 0
1 8 10 0 1 11
99 0
-module(tuples).
-export([parse/0]).
parse() ->
{ok, File} = file:read_file("tuples.txt"),
List = binary:split(File, [<<" ">>, <<"\t">>, <<"\n">>], [global, trim_all]),
io:format("~p~n", [List]),
build_tuples(List, []).
build_tuples([X,Y|T], Acc) ->
build_tuples(T, [{X,Y}|Acc]);
build_tuples([X|T], Acc) ->
build_tuples(T, [{X, undefined}|Acc]);
build_tuples([], Acc) ->
lists:reverse(Acc).
The text file I used is almost as yours but I added tabs and multiple spaces to make it more realistic:
1 7 11 0
1 3 5 0 7 0
1 8 10 0 1 11
99 0
You can of course convert binaries to integers when adding them to tuples with erlang:binary_to_integer/1. The binary:split/3 function used in the code parses all empty characters (tabs, spaces, new lines) to empty binaries and then trim_all ignores them. You can skip them if your input is always well-formed. Result:
14> tuples:parse().
[<<"1">>,<<"7">>,<<"11">>,<<"0">>,<<"1">>,<<"3">>,<<"5">>,<<"0">>,<<"7">>,<<"0">>,<<"1">>,<<"8">>,<<"10">>,<<"0">>,<<"1">>,<<"11">>,<<"99">>,<<"0">>]
[{<<"1">>,<<"7">>},{<<"11">>,<<"0">>},{<<"1">>,<<"3">>},{<<"5">>,<<"0">>},{<<"7">>,<<"0">>},{<<"1">>,<<"8">>},{<<"10">>,<<"0">>},{<<"1">>,<<"11">>},{<<"99">>,<<"0">>}]

how to do align outcome values in python

i am having trouble with aligning outcome values.
Alist = ["1,25,999",
"123.4,56.7890,13.571",
"1,23.45,6,7.8"]
c = 0
while c < len(Alist):
r = 0
tokens = Alist[c].split(',')
while r < len(Alist[c].split(',')):
if '.' in tokens[r]:
print "%7.2f" %float(tokens[r]), " ",
else :
print "%3d" %float(tokens[r]), " ",
r += 1
print
c += 1
I want to print such as
1 25 999
123.40 56.79 13.57
1 23.45 6. 7.80
but somehow it is printing
1
25
999
123.40
56.79
13.57
1
23.45
6
7.8
and i cannot figure out what is wrong with my coding.
after the r+1, you have a lone print statement. it is at the wrong indention level - move it to the left by 4 spaces (or one tab) and it should work fine.
The print statement should'nt in the 2nd while loop. just:
Alist = ["1,25,999",
"123.4,56.7890,13.571",
"1,23.45,6,7.8"]
c = 0
while c < len(Alist):
r = 0
tokens = Alist[c].split(',')
while r < len(Alist[c].split(',')):
if '.' in tokens[r]:
print "%7.2f" %float(tokens[r]), " ",
else :
print "%3d" %float(tokens[r]), " ",
r += 1
print
c += 1
In [59]: %paste
myList = ["1,25,999",
"123.4,56.7890,13.571",
"1,23.45,6,7.8"]
rows = [r.split(',') for r in myList]
widths = {i:max(len(c) for c in col) for i,col in enumerate(itertools.izip_longest(*rows, fillvalue=""))}
for row in rows:
for i,val in enumerate(row):
print " "*((widths[i] - len(val))/2), val, " "*((widths[i] - len(val))/2) if not (widths[i]-len(val))%2 else " "*((widths[i] - len(val)+1)/2),
print
## -- End pasted text --
1 25 999
123.4 56.7890 13.571
1 23.45 6 7.8