Is there any standard algorithm that finds all possible paths in a directed a-cyclic graph.
If not, how can i make changes in BFS/Dijkstra/any other algorithm to enumerate all paths in a DAG
Finding all the possible paths in any graph in Exponential. It can be solved by using Backtracking.
For DAG's we can do it using Depth first search(DFS).
In DFS code, Start at any node, Go to the extreme dead end path and note down all the nodes visited in that path using some array or list. As soon as you find a dead end print the array containing the visited nodes and pop the last stored node and start in the other path of the (n-1)th node. If all the paths of the (n-1)th node are exhausted pop that node from list and start at (n-2)node. Do this untill you reach all the dead ends and reach the first node.
All the Printed paths are the Paths in the given DAG.
You can check the code http://pastebin.com/p6ciRJCU
Here is a short python example of a modified DFS to achieve this:
data = {1 : [2,3], # Directed acyclic graph adjacency list
2 : [3],
3 : [4,5],
4 : [5],
6 : [7,8]} # These nodes are disconnected from the rest of the graph
def dfs(data, path, paths):
datum = path[-1]
if datum in data:
for val in data[datum]:
new_path = path + [val]
paths = dfs(data, new_path, paths)
else:
paths += [path]
return paths
def enumerate_paths(graph):
nodes = list(graph.keys())
all_paths = []
for node in nodes:
node_paths = dfs(graph, [node], [])
all_paths += node_paths
return all_paths
Input:
enumerate_paths(data)
Output:
[[1, 2, 3, 4, 5], [1, 2, 3, 5], [1, 3, 4, 5], [1, 3, 5], [2, 3, 4, 5], [2, 3, 5], [3, 4, 5], [3, 5], [4, 5], [6, 7], [6, 8]]
My idea is to extends all path starting from inserting the first edge when there are no path candidates, then proceeding by extending each edge in the path sets at the head, at the tail, or splitting a path when the edge considered create a divergence (conflicting path).
It is an iterative method base on the idea of stability: each time all edges are considered, and if in a turn there were no action to do, then the turn is stable, and there is no more left to do.
One thing this method take care is to not fork path too soon: the first turn is a preparation turn, so the fork-phase is active only on the next turns.
I am evaluating if it is better (I mean: more correct) to alternate forks and extends phases, and considering stable_turn as stable couple of turns
Here the code:
https://gist.github.com/danielecr/6abd8ad48461347238ad1caf3714fe6a
(sorry, it is javascript, not really easy to read, but I need this exactly in this language)
Related
I am still learning and I have a question. What excatly in flutter means? -
`'...[]'`
Just wondering.. When im using 'for in' to fetch data from my database I have to use this '...[]' but why? What does it doing?
I couldn't find answer in the google, probably im pretty bad in googling stuff but ofcourse I got you guys!
Thanks for reply!
This is the spread operator, is used when you want to separate the items, imagine a situation that you want to join two lists:
List<int> a = [1, 2, 3];
List<int> b = [4, 5, 6];
If you just put them inside a list, you will get a List of lists.
List<int> combinedLists = [a, b];
// [[1, 2, 3], [4, 5, 6]]
But when you use spread operator, you will get the items out of list, like this:
List<int> combinedLists = [...a, ...b];
// [1, 2, 3, 4, 5, 6]
Background
Hi, I'm trying to solve a programming problem and I'm stuck on the following problem:
Assume you have multiple lists of numbers. All are sorted in decreasing order.
You now have to take exactly one number from each list to make the biggest possible sum.
So far so easy, to solve this you could just take the first number of each list and you're done.
But now, I need the second-largest sum while still using exactly one number from each list.
To achieve this, I would take the first element in each list but for the list which has the least difference between the first and second number the second number will be used.
This is still pretty doable.
The Problem
But I need an Iterator over every possible sum using exactly one number of each list sorted in decreasing order.
For performance reasons, it isn't possible to just compute every sum and then sort it. The algorithm must already provide the sums in decreasing order. If there are multiple combinations for a sum then the sum must be returned multiple times.
Additional Requirements
The Iterator should be lazy (only calculate the next sum when required).
The Lists are already lazy, which means you should require as few values as possible to calculate the fitting sum.
Example
For the Lists:
List 1: [5, 2, 1]
List 2: [10, 2]
List 3: [6, 1]
The Iterator then should return:
[5, 10, 6] = 21
[2, 10, 6] = 18
[1, 10, 6] = 17
[5, 10, 1] = 16
[5, 2, 6] = 13
[2, 10, 1] = 13
[1, 10, 1] = 12
[2, 2, 6] = 10
[1, 2, 6] = 9
[5, 2, 1] = 8
[2, 2, 1] = 5
[1, 2, 1] = 4
Comment
I don't need code as an answer to my question (you're still welcome to provide it if it helps to explain). What I'm looking for are ideas to solve this, or solutions that I can implement myself.
Thanks in advance!
First of all, Thanks to wlui155 for the help.
For Anyone interested, I coded a BFS algorithm that acts as follows:
Definitions:
Entry: Struct containing indices of used numbers and sum
BSet: Ordered set which can only contain unique Entries
Algorithm:
Pop Entry with biggest sum from BSet
Create a clone for each list
Advance in each clone a different index by one
Put new entries in BSet
Print current Entry
Goto 1.
Now you only have to ensure that no entry appears again after you've popped it. This can be ensured with a separate set containing all combinations for the current sum. Once the current sum gets smaller this set can be cleared.
If you have ideas to improve this, you're welcome to tell me.
I know that the following breaks up a list and put it into two lists depending on whether an index is even or odd. But not sure how [n::2] for n in [1,0] works.
[[1,2,3,4,5][n::2] for n in [1, 0] ]
[[2, 4], [1, 3, 5]]
Can you point me to post that explain and walk me through the logic behind it? Thank you.
The left part happens with each value of n. n indicates the starting position to take the 2nd element including the n'th one.
print([[1,2,3,4,5][n::2] for n in [1, 0] ] )
print([[1,2,3,4,5][1::2]]) # outputs [[2, 4]]
print([[1,2,3,4,5][0::2]]) # outputs [[1, 3, 5]]
print([[1,2,3,4,5][4::2]]) # outputs [[5]]
Intro
I'm trying to do something that sounds simple, but so far I'm not having luck finding the answer. I have 2 lists in a redis 2.6.4 standalone server(no cluster):
list1 = [4, 5 ,6]
list2 = [1, 2, 3]
The problem
And I need to concatenate the lists to produce something like this:
list3 = list1 + list2
list3 = [4, 5, 6, 1, 2, 3] <- I need to preserve order, list1 and then list 2
list4 = list2 + list1
list4 = [1, 2, 3, 4, 5, 6]
The question
Since redis use linked lists to store this lists I was expecting to have a straightforward way of doing this, does such a way exists? what's the usual way of doing this in redis?
Thanks in advance!
The easiest way to do this safely is to use LUA scripting, this way you have the guarantee that the resulting list is not missing any element (and you can easily preserve the order).
If LUA is not an option then you need to do this client side and use watch those keys for changes (see transaction in redis and WATCH command)
Here is the Redis command using Lua:
eval "for i,l in ipairs(ARGV) do for i,v in ipairs(redis.call('lrange',l,0,-1)) do redis.call('rpush',KEYS[1],v) end end" 1 list3 list1 list2
As an added bonus you can specify any number of lists to append into your master list by simply adding more list keys at the end
I have the following question for homework
Define a function append lists that
takes a list of lists and returns a
new list containing the sublist
values. For example, append lists([[1,
2], [3, 4], [5]]) should return the
list [1, 2, 3, 4, 5] and append
lists([[1, 2], [3], [[4, 5]]]) should
return the list [1, 2, 3, [4, 5]].
I've tried various ways of creating this function in order to append the list so it gives the desired output to no avail so I came here looking for some help. I've found a few other ways of going about this online, but they use extensive methods that we haven't even dabbled in as of yet in my CPSC 121 class. We're limited to the basics in what we've learned.
Any help would be much appreciated!
By now, it is likely that the assignment is gone, but here is a solution:
def append_lists(lists):
output = []
for l in lists:
for e in l:
output.append(e)
return output
This appends each element of each list to the output of the function, which eliminates exactly one level of nesting in the elements.