Haha.. I'm done my assignment but I'm still not happy about the result of optimization. I guess I don't let go when I bite. As someone else was saying, cracking 4x4 tippy might be a fun task.
Although in class, Diane emphasized the big picture and the O(g(n)), I think at this point of the Tippy assignment, it might be worth considering the details.
One thing about minimax is that the overall speed of minimax depends on the speed of the game. For example, we will be calling apply_move very often and also be checking whether the game has ended. To that effect, it's useful to be able to perform all of these tasks faster. Suppose minimax goes through N iterations of suggest_move_helper. Then the overall speed boost the USER gets is N*improvement_time.
In practical terms, I don't care what N is as long as N*time_per_N < thresh-hold.
Anyhow, I have a new idea about how to make TippyGameState faster. So, if you read my following post, I mentioned that my game was stored as a nested list, which looking back was a horrible idea. It's one of the first structures that came to mind. Another structure was a dictionary whose elements are "p1", "p2", "p0" and the values are the locations of the possible moves, but I gave up on this approach since I thought that when I look for the value at some location x,y, that the nested list would be faster since I need to iterate through "all" the elements to see if something is in "p1", "p2" or "p0".
But now, I know hashing and that finding an element in "hashed space" only requires O(1).
This means now I know that the following is fast:
D = {"p1":set((x,y), (x2,y2)), "p2":set((x3,y3), (x4,y4)), "p0":set((x5,y5), (x6,y6))}
When you are looking for (x2, y2), you need to ask whether its in D['p1'], D['p2'], or D['p0'].
Overall, this only requires "3 lookups". (for is this value 'p1', you only need "1 lookup" and this is something that is probably often done).
Also, when you look for the possible moves, you just need to get D['p0'].
And thinking of implementing symmetry (about p1 and p2), you just need to swap D['p1'] and D['p2'].
In my implementation, it's sometimes useful to know from time to time what moves have been made by 'p1' or 'p2'... Now, this is also super fast.
Hashing is ingenious.
Monday, 30 March 2015
Friday, 27 March 2015
Still about A3 :0
I'm finding A3 pretty boring... but the overall topic very interesting. Especially, optimization algorithm analysis :)
Right now, I'm working on understanding the effectiveness of Pruning. This is something I'm not sure about. As mentioned previously, I decided to try using cProfile to obtain all the function calls.
I've just completed it and I'm finding that compared to my original minimax, it's significantly faster for Tippy, but not so much for SubtractSquareState, since I already do some pruning (return win if I just get a winning state; this is a no-brainer form of pruning... Not complete pruning tho).
I also "fixed" that just now to do a better testing. My fixed version basically goes through everything...
I'm testing for subtract square where I seed it with current sum of 29.
StrategyMinimax: 612235 function calls (572894 primitive calls) in 6.180 seconds
Wow... out of those, if we look at the recursive calls only:
ncalls tottime percall cumtime percall filename:lineno(function)
39342/1 0.973 0.000 6.180 6.180 strategy_minimax.py:66(_suggest_move_helper)
1 0.000 0.000 6.180 6.180 strategy_minimax.py:46(suggest_move)
FYI, _suggest_move_helper was the helper function that gets called recursively.
so... here...I am... maybe I should just do it for size 6... sighs...
Actually surprisingly simple and my calculation says 16... but my code says less??? Right... my hand checking ability sucks... Retry... got 9... awesome. =) Partial analysis shown below (fyi, I traverse the nodes in my minimaxPrune in the same order as shown in the tree):
For further checking, I will probably use a print statement showing cur_val to check that only the "expected" states are being checked. Doing that now... checked awesome. Repeat for 1 other case... Or not. I'm actually confident it should work. I'll just think about whether there are any special boundary cases I need to worry about.
Just as a side note, I want to add that just by returning when you see a WIN get's you what in a two state (-1, 1) game. I'll leave out the detailed analysis but it should be somewhat obvious.
Right now, I'm working on understanding the effectiveness of Pruning. This is something I'm not sure about. As mentioned previously, I decided to try using cProfile to obtain all the function calls.
I've just completed it and I'm finding that compared to my original minimax, it's significantly faster for Tippy, but not so much for SubtractSquareState, since I already do some pruning (return win if I just get a winning state; this is a no-brainer form of pruning... Not complete pruning tho).
I also "fixed" that just now to do a better testing. My fixed version basically goes through everything...
I'm testing for subtract square where I seed it with current sum of 29.
StrategyMinimax: 612235 function calls (572894 primitive calls) in 6.180 seconds
Wow... out of those, if we look at the recursive calls only:
ncalls tottime percall cumtime percall filename:lineno(function)
39342/1 0.973 0.000 6.180 6.180 strategy_minimax.py:66(_suggest_move_helper)
1 0.000 0.000 6.180 6.180 strategy_minimax.py:46(suggest_move)
FYI, _suggest_move_helper was the helper function that gets called recursively.
Now, I want to compare this to pruning... which calls move_score... I should change that too... fixed.
StrategyMinimaxPrune: 865 function calls (814 primitive calls) in 0.010 seconds
ncalls tottime percall cumtime percall filename:lineno(function)
52/1 0.002 0.000 0.010 0.010 strategy_minimax_prune.py:69(_suggest_move_helper)
1 0.000 0.000 0.020 0.020 strategy_minimax_memoize.py:53(suggest_move)
No wonder it's so much faster... but now, I want to CHECK how many times it should be checking... To do that... I added a function called tree_form to game_state_tree. I only show the docstring below since I'm not sure if code sharing is allowed... So, the idea was to use this new thing to visualize the tree with current node 29 and to "prune" by hand... but then you see that 39342/1 function calls... what does that mean? That should be the number of nodes right? since it's called at EVERY node... so... This might be hard to SEE. Kind of funny side note is that code is often more accurate than my doctests -_-; haha. Anyhow, I decided to check pruning on just current number 10.
Actually surprisingly simple and my calculation says 16... but my code says less??? Right... my hand checking ability sucks... Retry... got 9... awesome. =) Partial analysis shown below (fyi, I traverse the nodes in my minimaxPrune in the same order as shown in the tree):
For further checking, I will probably use a print statement showing cur_val to check that only the "expected" states are being checked. Doing that now... checked awesome. Repeat for 1 other case... Or not. I'm actually confident it should work. I'll just think about whether there are any special boundary cases I need to worry about.
Just as a side note, I want to add that just by returning when you see a WIN get's you what in a two state (-1, 1) game. I'll leave out the detailed analysis but it should be somewhat obvious.
Wednesday, 25 March 2015
Minimax-other potential "upgrades"
So my digression about minimax from my last post got moved here :)
Before I go in, I would like to mention that in class we do worst case analysis. I don't like that. I want to talk about the average needed time. For example, we can easily see that the worst time for pruning is the same as checking everything... but on average for Tippy... it saves so much time... (3x3 tippy first point runs fast enough that you're not waiting for computation). Kind of interesting aspect of average time analysis is to think about when the averages change. In a sense, the average time is just an expected value and it depends on the probability distribution of the input feeds.
First:
Combine pruning and memoizing... these two techniques are obviously somewhat mutually exclusive. I would try to prune first and then if I need the data, see if I can fetch from my memos... An interesting twist / implementation detail might be whether I should store the partial info I get from pruning. Let's say I exit early since I know 0 is a guaranteeable score, should I remember this to take advantage of the next potential pruning step??? I think this is a design decision and probably what's better is game dependent. I'm not sure what's best, but I'm thinking in along the following lines. 1) suppose the tree can be pruned often... that's good right? I'm saving a lot of computation... but this also means that I'm not collecting much memos and it's kind of useless. Suppose I do keep partial info... then I would need two different notes for each state I encounter... 1) The minimum gauranteed or actual score depending on 2) whether the value I have is the actual score. Upon some thought, I'm starting to wonder if there would be significant boost in performance. Here's why: Suppose you pruned... but you actually need this value then you need to go back and evaluate everything anyways, regardless of the minimum gauranteed score. This means even with the memo, you might need to compute that many more times, but of course on your second try... you might get some help when you prune since you know the minimum value you can achieve out of it... but then you need to be careful about what to do when the values are the same... Also, you need to check if it's in your set, which takes time. Here, I used python Set() which uses hashing, but if I used a list... the finding time would be nlogn... Overall, I CAN see it potentially beneficial... but I'm not sure if it would be so much.
Second:
Notice that the last child can be "pruned". The actual value at the last node doesn't matter This is probably beneficial where the number of children is small...
Third:
and most interesting in my opinion is symmetry considering memoize.
In all the two player games, the score is symmetric in that score for p1 in state1 is the same as the score for p2 in -state1... where -state1 is the condition where all the "stuff" are as though p2 and p1 are switched... To illustrate, in subtract squares game, suppose the score for state p1: 500000 is 1.0 then I know that the score for p2: 500000 is 1.0 (score for p2). In tippy, take the stones in the grid and exchange p1 and p2's play... you get the mirror image state. Now, you can cut the number of states to memorize in half.
For the implementation of this, I think that concept of hashing might be interesting thing to introduce to GameState. Make a method that returns an ID of this game... some sort of number which encapsulates all the stuff about the state. And make it such that if it's symmetric, this tag is the same... That would provide a really cool handle for the implementation of memoize. I would call it memoizeSymmetry. Another interesting thing about tippy is that there's also rotational symmetry that can be taken advantage of. The score does not depend on the rotational state of the grid. You can use this to further cut the checks. The best part is that the memoizeSymmetry would work in both cases but in subtract sq game get a 2x boost and in tippy get ~8x boost (the rotations may be identical in some grids). I think this is a really cool class to write.
Do you have any extra ideas about other minimax implementations? Criticisms or runtime/resource analysis?
Before I go in, I would like to mention that in class we do worst case analysis. I don't like that. I want to talk about the average needed time. For example, we can easily see that the worst time for pruning is the same as checking everything... but on average for Tippy... it saves so much time... (3x3 tippy first point runs fast enough that you're not waiting for computation). Kind of interesting aspect of average time analysis is to think about when the averages change. In a sense, the average time is just an expected value and it depends on the probability distribution of the input feeds.
First:
Combine pruning and memoizing... these two techniques are obviously somewhat mutually exclusive. I would try to prune first and then if I need the data, see if I can fetch from my memos... An interesting twist / implementation detail might be whether I should store the partial info I get from pruning. Let's say I exit early since I know 0 is a guaranteeable score, should I remember this to take advantage of the next potential pruning step??? I think this is a design decision and probably what's better is game dependent. I'm not sure what's best, but I'm thinking in along the following lines. 1) suppose the tree can be pruned often... that's good right? I'm saving a lot of computation... but this also means that I'm not collecting much memos and it's kind of useless. Suppose I do keep partial info... then I would need two different notes for each state I encounter... 1) The minimum gauranteed or actual score depending on 2) whether the value I have is the actual score. Upon some thought, I'm starting to wonder if there would be significant boost in performance. Here's why: Suppose you pruned... but you actually need this value then you need to go back and evaluate everything anyways, regardless of the minimum gauranteed score. This means even with the memo, you might need to compute that many more times, but of course on your second try... you might get some help when you prune since you know the minimum value you can achieve out of it... but then you need to be careful about what to do when the values are the same... Also, you need to check if it's in your set, which takes time. Here, I used python Set() which uses hashing, but if I used a list... the finding time would be nlogn... Overall, I CAN see it potentially beneficial... but I'm not sure if it would be so much.
Second:
Notice that the last child can be "pruned". The actual value at the last node doesn't matter This is probably beneficial where the number of children is small...
Third:
and most interesting in my opinion is symmetry considering memoize.
In all the two player games, the score is symmetric in that score for p1 in state1 is the same as the score for p2 in -state1... where -state1 is the condition where all the "stuff" are as though p2 and p1 are switched... To illustrate, in subtract squares game, suppose the score for state p1: 500000 is 1.0 then I know that the score for p2: 500000 is 1.0 (score for p2). In tippy, take the stones in the grid and exchange p1 and p2's play... you get the mirror image state. Now, you can cut the number of states to memorize in half.
For the implementation of this, I think that concept of hashing might be interesting thing to introduce to GameState. Make a method that returns an ID of this game... some sort of number which encapsulates all the stuff about the state. And make it such that if it's symmetric, this tag is the same... That would provide a really cool handle for the implementation of memoize. I would call it memoizeSymmetry. Another interesting thing about tippy is that there's also rotational symmetry that can be taken advantage of. The score does not depend on the rotational state of the grid. You can use this to further cut the checks. The best part is that the memoizeSymmetry would work in both cases but in subtract sq game get a 2x boost and in tippy get ~8x boost (the rotations may be identical in some grids). I think this is a really cool class to write.
Do you have any extra ideas about other minimax implementations? Criticisms or runtime/resource analysis?
Lab 10, sorting
Today's post will not be about big O... which is what we learned in class. It will be more about sorting algorithms which is this week's lab.
I think the most interesting thing about this week's lab could be the intro to various sorting algorithms (more so than the big O). Diane talked about merge sort and maybe several other sorting algorithms were covered in the prerequisite course (csc108), but either I forgot or never learned so they are not very fresh in my mind. The labs have really interesting concepts, but it's too much boring work recently... so I end up getting the gist of doing them and just spending my time analyzing the implications. Anyhow, while "learning" about some of these, I came across a super cool visualization of various algorithms that instantly taught me about it in a sense.
overall in this lab, we should have seen that it's not just the number of loops you go through, but also what operations you do in it. I think this is somewhat trivial. When I code, I have been aware of this and even if it may save some lines, I often say A = function(), if I know I will need A more than once. An obvious implication of this that I hadn't considered before is the memory that I am using.
One cool thing was the profile_comparisons() method... It uses cProfile module to findout about all the function calls. Now... where might that come in handy??? I think anyone who read some of my previous posts would realize that this would solve (at least partly) the testing of pruning. Whether I will end up doing that instead of trying to make my own other "minimax improvements"... I'm not sure. At the moment, I have several ideas in mind that could potentially further improve the runtime. I will write about this in my next post, since I want to keep things somewhat organized...
I will update this post later ... (I ended up digressing and writing about minimax again -_-)
I think the most interesting thing about this week's lab could be the intro to various sorting algorithms (more so than the big O). Diane talked about merge sort and maybe several other sorting algorithms were covered in the prerequisite course (csc108), but either I forgot or never learned so they are not very fresh in my mind. The labs have really interesting concepts, but it's too much boring work recently... so I end up getting the gist of doing them and just spending my time analyzing the implications. Anyhow, while "learning" about some of these, I came across a super cool visualization of various algorithms that instantly taught me about it in a sense.
overall in this lab, we should have seen that it's not just the number of loops you go through, but also what operations you do in it. I think this is somewhat trivial. When I code, I have been aware of this and even if it may save some lines, I often say A = function(), if I know I will need A more than once. An obvious implication of this that I hadn't considered before is the memory that I am using.
One cool thing was the profile_comparisons() method... It uses cProfile module to findout about all the function calls. Now... where might that come in handy??? I think anyone who read some of my previous posts would realize that this would solve (at least partly) the testing of pruning. Whether I will end up doing that instead of trying to make my own other "minimax improvements"... I'm not sure. At the moment, I have several ideas in mind that could potentially further improve the runtime. I will write about this in my next post, since I want to keep things somewhat organized...
I will update this post later ... (I ended up digressing and writing about minimax again -_-)
Monday, 23 March 2015
Tippy Implementation
I know it's very late but I would like to share my implementation of Tippy today. Fortunately, though it doesn't feel so untimely since we covered running time analysis and maybe I can add a few words about why my implementation is good.
So this is how my algorithm checks for the presence of Tippy and some rationale.
First, figure out where the stone was placed last. I do this by remembering the last move that was made.
Now, we know that if there exists a tippy, it MUST involve this stone.
we just need to check whether there exists a tippy here.
I did this by using recursion. Based on the z shape you can see that essentially you are travelling in zigzag patterns. if you think about it as a person driving from the "center", it's like turning left right left right in sequence. There are two general directions and two possible assymetries (go left first or right first).
My partial code is shown below and I think it might make my explanation clearer so it's somewhat worth skimming through. I just want to add that I used a list in list to store the game_state. In retrospect, think tuple in tuple might have been better since things are immutable...
I also want to briefly add a time analysis for my tippy versus if you did it without remembering last move applied. For this coarse analysis, I will suppose say time is proportional to the number of grid spots that are checked for grid size n
Remember last_move:
Maximum number of checks = 1+9+3+4+3= 20
I'm not sure about this... but I think the following is the worst case... marked in yellow is the last position. Notice in my code that I don't exit even when I find 4. I just go till the end. I did this since time is not a huge issue in this assignment and since most of the time unless the players aren't being crazy... this will not happen.
Don't remember last_move:
I don't know for sure since I don't have any such algorithm at hand. I will say we do a "similar" seeding position analysis. Even with the entire grid on the line, we still know that only the last person to have gone could have made a tippy. This means that we can do a similar analysis on the last few players. Suppose we have size n grid. This means that we have n^2 grid positions and thus at maximum around n^2./2 positions in which the last player played. say we do a check around this point. This means we need to check around n^2/2*(const).
Another method is perhaps to do a subgrid analysis where we find a 3x3 matrix inside. Still this means there's a (n-3)(n-3) grids so (n-3)^2*const. still n^2
I don't know how I can show it, but without remembering anything, the analysis must be scaling n^2.
In some sense, the rationale here is similar to the problem of finding an element in a list. We know that we must see all the elements to know that something does not exist in the list.
But still you can see that if we think about each of these actually run, they do multiple checks on the same point. Probably, there is a way to do better, which reduces that constant time, but for sure it cannot be a constant time.
Friday, 20 March 2015
My Lab 9 Work
Lab 9 was really boring I think. It's one thing to come up with test cases and it's another to write them up. On the bright side, there were some interesting "testing" questions. For delete, what's the best way to test it works? Obviously, you can ask if the result is "what you should have gotten based on the known algorithm" but as I briefly touched upon last post, there may be more than one valid trees outputted after deleting. My approach was to 1) check that the value disappears if any, 2) check that the tree remains in "good shape" (ie. the BST conditions are maintained) by travelling in order.
You can easily see that in-order traversal results in "sorted nodes" iff the BST is maintained.
Also, I found a bug in bt_functions.py for the bst_contains method.
I think based on this lab, I think I know how to autotest my minimax. I can add a tester function that keeps track of all the states it visited (or print something about it) and then see if it matches my expectation.
In any case, this week there should have been a very wide range of possible solutions. Mine is shown below, but I would recommend that you don't waste your time reading through it:
Also, I found a bug in bt_functions.py for the bst_contains method.
I think based on this lab, I think I know how to autotest my minimax. I can add a tester function that keeps track of all the states it visited (or print something about it) and then see if it matches my expectation.
In any case, this week there should have been a very wide range of possible solutions. Mine is shown below, but I would recommend that you don't waste your time reading through it:
Assignment 3: Memoization, Pruning, Myopia
Continuing from the previous assignment, the goal of Assignment 3 is to extend the game by adding computer strategies. Minimax strategy, which effectively looked at all the possible combination of moves leading to an end of game was really slow and impractical for Tippy. Here, three different "optimization" techniques are employed to speed up the minimax strategy. Myopia is really an optimization in my opinion because it does not neccessarily generate the same result as minimax.
Memoization: avoids redundancy by storing the value returned by recursive calls
Pruning: avoid "travelling" through states that you will never choose anyways
Myopia: Avoid "travelling" through all the states by limiting how far you look ahead
At the end, to decrease computation time, what you need to do is decrease the number of states you consider. What these options show for the most part is something like "entropy-enthalpy tradeoff" in chemistry. To speed things up, you need to use more memory(memoization) or give up accuracy (myopia). To gain speed, you need to trade something else. Pruning is particularly interesting since it does not seem to compensate speed. My guess is that the "tradeoff" lies in what happens where there are no avoidable paths. Since pruning tries to avoid checking certain states, it needs to check whether things can be avoided. In some sense, this is a time investment. In certain (probably very many) situations, you may get the benefit, but you may not.
I currently have a more or less working version of all three. I am very surprised by the speed at which these work, particularly pruning. One big problem though is that I'm not entirely sure HOW to test these. Maybe I can see that they are faster and they give accurate results but that does not mean that the algorithm is implemented perfectly. Maybe it is still visiting certain nodes that it can avoid. One sloppy way of checking of course is to verify that the results agree, but does not ensure that the code is working properly.
At the end, I think option B is way easier. You don't need to write any docstrings or care about formatting too much and the functions are similar to what we have seen in labs. Also, to check your code for the minimax optimizations, you kind of need game_state_tree. I think the only way to truly check your minimax optimization algorithms is to collect which nodes have been visited and show that it matches your expectations. To obtain your expectations, you probably need a game state tree...
Time to get working... I will do my lab 9 and post my soln probably today. I don't like to get behind on weekly commitments...
Memoization: avoids redundancy by storing the value returned by recursive calls
Pruning: avoid "travelling" through states that you will never choose anyways
Myopia: Avoid "travelling" through all the states by limiting how far you look ahead
At the end, to decrease computation time, what you need to do is decrease the number of states you consider. What these options show for the most part is something like "entropy-enthalpy tradeoff" in chemistry. To speed things up, you need to use more memory(memoization) or give up accuracy (myopia). To gain speed, you need to trade something else. Pruning is particularly interesting since it does not seem to compensate speed. My guess is that the "tradeoff" lies in what happens where there are no avoidable paths. Since pruning tries to avoid checking certain states, it needs to check whether things can be avoided. In some sense, this is a time investment. In certain (probably very many) situations, you may get the benefit, but you may not.
I currently have a more or less working version of all three. I am very surprised by the speed at which these work, particularly pruning. One big problem though is that I'm not entirely sure HOW to test these. Maybe I can see that they are faster and they give accurate results but that does not mean that the algorithm is implemented perfectly. Maybe it is still visiting certain nodes that it can avoid. One sloppy way of checking of course is to verify that the results agree, but does not ensure that the code is working properly.
At the end, I think option B is way easier. You don't need to write any docstrings or care about formatting too much and the functions are similar to what we have seen in labs. Also, to check your code for the minimax optimizations, you kind of need game_state_tree. I think the only way to truly check your minimax optimization algorithms is to collect which nodes have been visited and show that it matches your expectations. To obtain your expectations, you probably need a game state tree...
Time to get working... I will do my lab 9 and post my soln probably today. I don't like to get behind on weekly commitments...
Friday, 13 March 2015
Binary Tree Mutation and Structure (related to lab 8)
We had a test this week and on Monday lecture, we talked about mutating trees. The lab was also about tree mutation. In this post, I want to provide my analysis on trees (particularly relating to the lab)
Personally, I found the first bit of the course very straight forward. I see algorithms that can be applied to solve the problem. Okay done. Now, we are thinking about different algorithms and how they compare to one another. I think this makes one of the most interesting topics we ever touched on.
The lab was easy in some sense but I think it raised a lot of interesting questions. To fully (mathematically) answer the question, I needed to think really hard.
For lab 8, we had to tinker with insert. Here are my observations on insert:
1. the insertion only occurs at the "edge".
This is significant because if there were nodes with only one child, there is an opportunity for insert to work there. First, let's examine for how many positions insertion is "valid" for the following example (blue is the tree and red is after inserting). I see 2.
From this example, it could be seen that there are at maximum possible positions in general: one "sandwitched between nodes" and one at the leaf. It is also easy to reason out considering the >, < relations that must hold. Just as side node, also notice that the "sandwitched between nodes" option may not exist when the value is the new max or min.
2. based on the current algorithm there is a "best" order of insertion and it is to insert the "middle values" first.
By this I mean to say that if you have a list of 7 values, you would first insert the 3rd largest, then the (6-1)/2 = 2nd largest and 6th largest, and then finally the remaining values.
Try it with [1, 2, 3, 4, 5, 6, 7] and you will see that you get a tree with minimum height.
This can be reasoned based on 1. Since we know that insertion only happens at the edges, once we have a point in the "non-edge" you need certain numbers to populate that edge. With a sorted list, you will never actually get that "certain number".
3. One related observation is that the total number of valid ways to arrange a tree with node count n is the number of possible node arrangements.
So, you can easily see that given the shape of the tree, it is always possible to fill in the values fitting that tree in exactly one way (since exactly x values must be < the node at every point, where x is the number of nodes in the left subtree; as an aside, you and easily fill this tree with sorted values by travelling "inorder"). So what are the possible arrangement of nodes given size n?
I have yet to figure that out... but I have three leads:
a) thinking inductively, what are the possible combinations for size n-1; what is the number of child nodes where that 1 new node can be added for each? things to sort out with this approach are:
i) degenerate trees are created and I'm not sure how to account for them
ii) the number of child changes depending on the structure, how can I generalize?
b) at every node, you have at maximum 4 choices: to add to left, to add to right, to add to none, to add to both. Problems:
i) adding to none is not an always accessible choice.
i) again only the leafs get this kind of choice. all other nodes have no choice (already fixed)
In a sense, method b is the same as option a I think.
c) Somehow the order of the list will influence the tree arrangement. How?
i) again there are issues of degeneracies. It is easy to calculate the total possible list order tho.
If you have any hints on the latter, I would be really interested to hear about it.
I will not be posting my work on lab 8, since it should be obvious that you just need to shuffle the list for insert and when deleting randomly choose to "fill" using left or right (at least based on the hint)
Personally, I found the first bit of the course very straight forward. I see algorithms that can be applied to solve the problem. Okay done. Now, we are thinking about different algorithms and how they compare to one another. I think this makes one of the most interesting topics we ever touched on.
The lab was easy in some sense but I think it raised a lot of interesting questions. To fully (mathematically) answer the question, I needed to think really hard.
For lab 8, we had to tinker with insert. Here are my observations on insert:
1. the insertion only occurs at the "edge".
This is significant because if there were nodes with only one child, there is an opportunity for insert to work there. First, let's examine for how many positions insertion is "valid" for the following example (blue is the tree and red is after inserting). I see 2.
From this example, it could be seen that there are at maximum possible positions in general: one "sandwitched between nodes" and one at the leaf. It is also easy to reason out considering the >, < relations that must hold. Just as side node, also notice that the "sandwitched between nodes" option may not exist when the value is the new max or min.
2. based on the current algorithm there is a "best" order of insertion and it is to insert the "middle values" first.
By this I mean to say that if you have a list of 7 values, you would first insert the 3rd largest, then the (6-1)/2 = 2nd largest and 6th largest, and then finally the remaining values.
Try it with [1, 2, 3, 4, 5, 6, 7] and you will see that you get a tree with minimum height.
This can be reasoned based on 1. Since we know that insertion only happens at the edges, once we have a point in the "non-edge" you need certain numbers to populate that edge. With a sorted list, you will never actually get that "certain number".
3. One related observation is that the total number of valid ways to arrange a tree with node count n is the number of possible node arrangements.
So, you can easily see that given the shape of the tree, it is always possible to fill in the values fitting that tree in exactly one way (since exactly x values must be < the node at every point, where x is the number of nodes in the left subtree; as an aside, you and easily fill this tree with sorted values by travelling "inorder"). So what are the possible arrangement of nodes given size n?
I have yet to figure that out... but I have three leads:
a) thinking inductively, what are the possible combinations for size n-1; what is the number of child nodes where that 1 new node can be added for each? things to sort out with this approach are:
i) degenerate trees are created and I'm not sure how to account for them
ii) the number of child changes depending on the structure, how can I generalize?
b) at every node, you have at maximum 4 choices: to add to left, to add to right, to add to none, to add to both. Problems:
i) adding to none is not an always accessible choice.
i) again only the leafs get this kind of choice. all other nodes have no choice (already fixed)
In a sense, method b is the same as option a I think.
c) Somehow the order of the list will influence the tree arrangement. How?
i) again there are issues of degeneracies. It is easy to calculate the total possible list order tho.
If you have any hints on the latter, I would be really interested to hear about it.
I will not be posting my work on lab 8, since it should be obvious that you just need to shuffle the list for insert and when deleting randomly choose to "fill" using left or right (at least based on the hint)
Saturday, 7 March 2015
Thinking about recursion
Way back, I asked a question about what kinds of problems are best for recursive functions. Since then, I have solved many problems such as lab exercises and in particular I have implemented minimax which is a strong strategy which finds the best move by evaluating all possible move combinations in a two player game. Through these exercises, I have reached a conclusion that recursive functions can always be drawn as a tree where each node represents a recursive "state".
Let's think about what happens when we do a recursive call. The name space changes. If you were in name space X, now you are in X in X. As described, function calls can be dealt with using stacks. So at the top of the stack is where you are currently. Each node is like that name space. In our exercises, we only dealt with a node having only one value, but that's not a requirement. In fact, I think we can think of the whole recursive process as a tree where each node contains information about all the local variables at that point.
With the context of the meaning of recursive functions defined above let's see how this might be true. If the problem at hand matches all properties of a tree, then it must follow that the problem can be expressed as a tree.
So what are the requirements/properties of a tree?
Let's think about what happens when we do a recursive call. The name space changes. If you were in name space X, now you are in X in X. As described, function calls can be dealt with using stacks. So at the top of the stack is where you are currently. Each node is like that name space. In our exercises, we only dealt with a node having only one value, but that's not a requirement. In fact, I think we can think of the whole recursive process as a tree where each node contains information about all the local variables at that point.
With the context of the meaning of recursive functions defined above let's see how this might be true. If the problem at hand matches all properties of a tree, then it must follow that the problem can be expressed as a tree.
So what are the requirements/properties of a tree?
Tree – A kind of directed graph
1. (Composed of set of nodes
with directed edges between nodes)
2. (Edge
connects parent node to a child
node)
3. (Nodes
may (or may not) contain values)
4. Where
each node has exactly one parent except the root has none
So...
1. yes the recursive problem has nodes and directed edges. The directed edges are function calls.
A calling on B is not symmetric (it is directed).
2. yes the edge connects between two nodes only. There cannot be three way connections.
3. yes the nodes (name space) may or maynot have values
4. yes each function call can only have one "caller". The root is the "original" call.
All of them are satisfied and I think it makes sense. I often think of recursive problems as a reference shift (I guess in actuality it is a name space change). You can call a child node from the parent node and once you move along that path (calling), now the previously child node is the new parent node. I think this kind of thinking might have shown slightly in my lab 6 explanation.
As to the above, I suppose it is not a formal proof and I am not yet convinced that this must be True. At the moment, it is a running hypothesis and possibly another way to think about recursion. It partly answers the question of when recursion may be appropriate: when you can create a tree that is finite... But then it still does not answer the question... just asks the question in a different angle (provides an answer in a different angle).
Wednesday, 4 March 2015
My Lab 7 Work
There's a strike... so no tutorials this week... But still did my lab. I was in a hurry, so I will probably revisit and make sure I updated front and back and so forth... This version passes the doctests.
But you should note that the doctest doesn't check all possibilities. It typically prints lnk. That means lnk.back is never checked or size is never checked. For some functions that matters. If you find any errors, feel free to comment. As always, my solution is posted below.
But you should note that the doctest doesn't check all possibilities. It typically prints lnk. That means lnk.back is never checked or size is never checked. For some functions that matters. If you find any errors, feel free to comment. As always, my solution is posted below.
Monday, 2 March 2015
proof(?) for tree height approx log (n)
In Diane's morning lecture, we talked bout height of a "perfect" tree being approximately log (n). Here, I want to show a "proof" for it. It probably will not be a formal proof, but I will show something that hopefully can be written in that form.
let's think of a tree with arity k. Then at "level" n, there will be k^(n-1) nodes.
At level 1, there is 1 node, at level 2 there is k nodes, at level 3 there is k^2... everytime you go one more level there will be k times more.
#Nodes(n) = #Nodes(n-1) * k, #Nodes(1) = 1
explicitly, #Nodes(n) = k^(n-1)
Then the total number of nodes leading to n is sum (k^(i)) for i = 0...n-1
S = (1-k^n)/(1-k)
This can be shown by subtracting S from rS and rearranging. I believe this kind of technique is called telescoping.
Conceptually, you have x + y + z - (y + z + A) = x + y - y + z - z - A
Anyhow, rearranging
S = (1-k^n)/(1-k),
we get log(S) = log(1-k^n) - log(1-k).
if r is const and as n-> inf,
log(S) = n*log(k), rearranging, the height n is ...
n = log(S)/log(k) = log base k of S
remembering that S was the total number of nodes, we are where we want to be. :)
This post I diverted a little... Next post for sure, I will discuss my realization about what kinds of problems might be suitable for recursion. It's kind of obvious when you think about it, and I think I understood kind of intuitively but couldn't really exactly describe it...
let's think of a tree with arity k. Then at "level" n, there will be k^(n-1) nodes.
At level 1, there is 1 node, at level 2 there is k nodes, at level 3 there is k^2... everytime you go one more level there will be k times more.
#Nodes(n) = #Nodes(n-1) * k, #Nodes(1) = 1
explicitly, #Nodes(n) = k^(n-1)
Then the total number of nodes leading to n is sum (k^(i)) for i = 0...n-1
S = (1-k^n)/(1-k)
This can be shown by subtracting S from rS and rearranging. I believe this kind of technique is called telescoping.
Conceptually, you have x + y + z - (y + z + A) = x + y - y + z - z - A
Anyhow, rearranging
S = (1-k^n)/(1-k),
we get log(S) = log(1-k^n) - log(1-k).
if r is const and as n-> inf,
log(S) = n*log(k), rearranging, the height n is ...
n = log(S)/log(k) = log base k of S
remembering that S was the total number of nodes, we are where we want to be. :)
This post I diverted a little... Next post for sure, I will discuss my realization about what kinds of problems might be suitable for recursion. It's kind of obvious when you think about it, and I think I understood kind of intuitively but couldn't really exactly describe it...
Subscribe to:
Posts (Atom)