Can dynamic programming problems always be represented as DAG - dynamic-programming

I am trying to draw a DAG for Longest Increasing Subsequence {3,2,6,4,5,1} but cannot break this into a DAG structure.
Is it possible to represent this in a tree like structure?

As far as I know, the answer to the actual question in the title is, "No, not all DP programs can be reduced to DAGs."
Reducing a DP to a DAG is one of my favorite tricks, and when it works, it often gives me key insights into the problem, so I find it always worth trying. But I have encountered some that seem to require at least hypergraphs, and this paper and related research seems to bear that out.
This might be an appropriate question for the CS Stack Exchange, meaning the abstract question about graph reduction, not the specific question about longest increasing subsequence.

Assuming following Sequence, S = {3,2,6,4,5,1,7,8} and R = root node. Your tree or DAG will look like
R
3 2 4 1
6 5 7
8
And your result is the longest path (from root to the node with the maximum depth) in the tree (result = {r,1,7,8}).
The result above show the longest increasing sequence in S. The Tree for the longest increasing subsequence in S look as follows
R
3 2 6 4 5 1 7 8
6 4 7 5 7 7 8
7 5 8 7 8 8
8 7 8
8
And again the result is the longest path (from root to the node with the maximum depth) in the tree (result = {r,2,4,5,7,8}).

The answer to this question should be YES.
I'd like to cite the following from here: The Soul of Dynamic Programming
Formulations and Implementations.
A DP must have a corresponding DAG (most of the time implicit), otherwise we cannot find a valid order for computation.
For your case, Longest Increasing Subsequence can be represented as some DAG like the following:
The task is amount to finding the longest path in that DAG. For more information please refer to section 6.2 of Algorithms, Dynamic programming.

Yes, It is possible to represent longest Increasing DP Problem as DAG.
The solution is to find the longest path ( a path that contains maximum nodes) from every node to the last node possible for that particular node.
Here, S is the starting node, E is the ending node and C is count of nodes between S and E.
S E C
3 5 3
2 5 3
6 6 1
4 5 2
5 5 1
1 1 1
so the answer is 3 and it is very easy to generate solution as we have to traverse the nodes only.
I think it might help you.
Reference: https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-fall-2011/lecture-videos/lecture-20-dynamic-programming-ii-text-justification-blackjack/

Related

Depth-first search how it decides to visit node

Imagine we have a graph like this:
The DFS would search it in the order of the digits in the picture.
I wonder how it knows when to pick 6 over 8.
I know it searches for the deepest part first but how does it know whether to go for 6 or 8 when the algorithm doesn't know what lies beyond nodes 6 and 8
the answer to whether to go for 6 or 8 is simply based on the implementation of the your DFS and the structure of your graph. But no matter it goes to node 6 first or node 8 first, both are the correct implementation of DFS.
let's take a look at this DFS Pseudocode (recursive implementation) as an example:
DFS(G, u)
u.visited = true
for each v ∈ G.Adj[u]
if v.visited == false
DFS(G,v)
so which line of code decides the next adjacent node to go first(pick node 6 or node 8 in your case)? It is the 3rd line
for each v ∈ G.Adj[u]
and we know that the "for loop" could have different sequences of iterating the adjacent nodes. someone could also implement it as
for(int i=0; i<G.Adj[u].length; i++)
or
for(int i=G.Adj[u].length-1; i>=0; i--)
And these two "for loop" are totally different sequences of picking the next adjacent node.
And also the arraylist of G.Adj[u] could be different from case to case (based on how your initialize the graph).
if the "for loop" gets the node 6 first, it keeps searching down the node 6, otherwise it searches the node 8.
Once again, no matter it picks 6 or 8, both are correct implementation of DFS.

From a random sequence, make appear an specific answer 5 times

I am implementing an N-back task with visual stimuli.
The stimuli is going to appear 20 times (randomly), but the correct answer must appear 5 times.
To generate a random sequence I can use "randint". But how can I tell to python to generate 5 times the correct answer.
Example of a 0-back.
The circle appears 20 times, but only 5 times it is the same as what it is needed.
So, I created 2 arrays.
right_answer, contains the position that I want to repeat 4 times.
wrong_answers, contains the other 8 positions. Each one repeats twice.
I concatenated them and then applied a permutation with a seed. With this, the array will be permuted but I will assure that the specific position/answer appear 4 times.
right_answer = np.array([[510,642],[510,642],\
[510,642],[510,642]])
wrong_answers = np.array([[510,382],[510,512],\
[640,382],[640,512],[640,642],\
[770,382],[770,512],[770,642],\
[510,382],[510,512],\
[640,382],[640,512],[640,642],\
[770,382],[770,512],[770,642]])
concat=np.concatenate((right_answer, wrong_answers))
positions = np.random.RandomState(seed=42).permutation(concat)
print (positions)

Number of Choices in a permutation given one option is fixed

I am in doubt about result of the following :
Each person can choose whether to wear a black tux or a grey tux, and whether to wear blue, yellow, or green coloured tie. In how many ways will you distribute all possible sets to 6 different people and no set repeats given that person 1 wants only a black tux.
A possible explanation will be helpful.
First of all, I don't think this question belongs on this stackexchange website. However what the hell I'll answer anyway.
So there are 6 people that can choose from 2 sets, the tux (2 options) and the tie (3 options)
Let's simplify a bit, one person can choose from 6 (3 * 2) options. A person with a fixed tux choice will only have 3 (3 * 1) options.
So to calculate it, we first take the person with limited choice and multiply that with the options the others still have.
-> the total number of options would be 3 * 5 * 4 * 3 * 2 * 1 = 360
(At least I'm fairly certain, as with most on this exchange, I'm a programmer rather than a mathematician)
For the suits you just subtract one person because one is already fixed.
The other 5 can each decide for one of 2 choices. This is similar to a coin flip for each person. That makes 2^5 combinations.
Then they choose the ties, where all 6 have 3 options. Following the example of the coin flip (but with 3 possible outcomes) we have 3^6 combinations for the ties.
Now just add the options together, because the decisions between suit and tie don't depend on each other. This will give you 729 outcomes for the ties and 32 outcomes for the tux's.
Hope I could make things clearer for you.

Is there a programming language that reads right to left? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 1 year ago.
Improve this question
I'm quite sure that modern industrial strength programming languages, all read left to right
But out of the whole ecosystem of programming languages are there examples of right to left read languages ?
Apart from better alignment with human languages that written this way, would there be any advantage in such a language?
examples :
int a = 5; // read left to right
tfel ot thgir daer // ;5 = a tni
APL is a language which overcomes the inconsistencies (and difficulty in typing / parsing / executing) traditional mathematical notation by unifying certain constructs, such as:
multi-dimensional array reduction (where the reduce construct was first named as such)
+⌿2 4 6 ⍝ Sum of a list
12
×⌿2 4 6 ⍝ Product of a list
48
2 3⍴⍳6 ⍝ A 2 row, 3 column matrix
1 2 3
4 5 6
+⌿2 3⍴⍳6 ⍝ Sum down the columns
5 7 9
or the inner product:
2 3 4+.×1 0 ¯1 ⍝ Vector inner (dot) product
¯2
+/2 3 4×1 0 ¯1 ⍝ Equivalent expression for vectors
¯2
(2 2⍴1 0 1)(2 2⍴2 5 4 3) ⍝ Two matrices
┌───┬───┐
│1 0│2 5│
│1 1│4 3│
└───┴───┘
(2 2⍴1 0 1)+.×(2 2⍴2 5 4 3) ⍝ Matrix inner product
2 5
6 8
1 2 3 ∧.= 1 2 2 ⍝ Are all elements equal?
0
Since it is inspired by traditional mathematics then it follows f(g(x)):
f g x means apply g to x and then apply f to the result of that, hence right to left. f(g(x)) is also valid APL.
The easiest way to demonstrate how this affects things is:
84 - 12 - 1 - 13 - 28 - 9 - 6 - 15
70
which gives 0 in traditional mathematic execution order. With parentheses:
84 - (12 - (1 - (13 - (28 - (9 - (6 - 15)))))) ⍝ APL
70
(((((((84 - 12) - 1) - 13) - 28) - 9) - 6) - 15) ⍝ Traditional maths
0
Although it is a general purpose programming language, used for applications from finance to 3D graphics, you can see more comparisons with mathematical notation on the APL Wiki: https://aplwiki.com/wiki/Comparison_with_traditional_mathematics
And having said all that, APL is still generally "read" (by humans) basically left to right, even though it is parsed and executed "right-to-left", and even then it's more of "functions have a long right scope and short left scope". For example, using the statement separator ⋄ to have multiple statements in a single line:
2+2 ⋄ 3 4 5 ⋄ ⎕A⍳'APL'
4
3 4 5
1 16 12
The left-most statements are executed first, but each individual statement is parsed as described above.
Befunge is such a language :)
"!dlrow olleH">:#,_#
Is a standard Hello world program, however this actually evaluates left-to-right.
<v_##:<"Hello world!"
>,>>>^
This ^ evaluates right-to-left, with some up-to-down and down-to-up movement too. You can run this program at https://www.bedroomlan.org/tools/befunge-playground/#prog=hello,mode=edit .
Unefunge is a variant without up-down movement, but it is still turing-complete. If you want strictly right-to-left programs, you can write in unefunge as long as your program starts with < to send the instruction pointer in the right direction.
For more information, Stack Overflow has a befunge tag.
There was a language for children called logowriter which later got translated into hebrew as תמלילוגו, since hebrew is RTL, so was the translated language.
The תמלילוגו language was taught as part of the CS sylabus in Israeli highschools on 2008,
http://www.csit.org.il/TSTBAG/2008/899122.pdf
A bit late to the party, but now there is Avsha. That is a whole new language based on Hebrew, or ChavaScript that uses Hebrew words and translates them to JS in English (including variable names, that are translated when found in the dictionary, or written in with each letter translated to the relevant English letter).
tfel ot thgir daer // ;5 = a tni
AFAIK, there are no such languages, at least, not a serious one (thanks for tohava for the interesting example). Simply because it's mostly pointless.
You can pick any existing language, write a one liner script that reverses every line, and you have a converter (and back converter) for this "new language". You can incorporate it into your build environment - transform before compilation, reverse the lines of the compiler error messages and so on...
But really, what's the point? The only people who would benefit from this are the the ones who use right to left for their native language (BTW, AFAIK, none of them use the latin ABC). They have to learn something completely new anyways, and it makes a lot more sense to do what the rest of the world does. All the blogs, tutorial, blogs, SO, everything is written in "left-to-right" programming languages.

String operations

Can anyone help me with this question:.This is not homework,I am preparing for my technical interview.
Given a series of N strings, find a set of repeating string of size 3
e.g. ababadefb
I think we might suffer from not knowing the full problem. I am going to direct you to a blog entry by a friend of mine where he talks about his interview with Microsoft.
A simple solution would be to construct a Suffix array from the string, sort it and compute the longest common prefix between the current suffix and the one before it. Now all LCPs of length 3 or more will give you the answer (aba in this case).
ababadefb 0
abadefb 3
adefb 1
b 0
babadefb 1
badefb 2
defb 0
efb 0
fb 0
As an alternate solution you can build a Radix tree from all suffixes then get all edges that are labeled with strings of length 3 or more.

Resources