Tower of Hanoi WITHOUT using a buffer stack - recursion

Tower of Hanoi problem :
You have 3 towers and N disks of
different sizes which can slide onto any tower.
The puzzle starts with disks sorted
in ascending order of size from top to bottom (i.e., each disk sits on top of an even
larger one). You have the following constraints:
(1) Only one disk can be moved at a time.
(2) A disk is slid off the top of one tower onto the next rod.
(3) A disk can only be placed on top of a larger disk.
Write a program to move the disks from the first tower to the last using Stacks.
Question : Why do we need a second/buffer/intermediate stack ?
I have solved this without using a buffer stack.
I used the implicit stack created by method(recursion).
See code :
public void play(Stack<Integer> aSourceStack,Stack<Integer> aTargetStack){
if(aSourceStack.isEmpty()){
return;
}
Integer temp = aSourceStack.pop();
play(aSourceStack,aTargetStack);
aTargetStack.push(temp);
}
Also am I violating the second constraint : (2) A disk is slid off the top of one tower onto the next rod.
Does this mean that i can't store the plate in a temporary variable ? It has to go on stack only ?
If yes, then i think i have my answer and i can close the question.
Please confirm.

Let me search that for you ... this is a classic puzzle.
You are supposed to implement the solution using one instance of the Stack class for each tower. There are three towers, so you have three Stack instances. Yes, when you pop a disk off the top of one tower, you must immediately push it onto the next tower. An appropriate statement might be
aTargetStack.push(aSourceStack.pop())
The code you wrote does not solve the problem; it tosses each disk in turn into the air, and then shoves them onto the target stack in the desired order: N disks in N moves. A correct, ideal solution will take 2^N-1 moves.

Related

Looking to repeat a word every frame until a 1000×1000 Canvas is covered

Right now I'm generating geometric figures in processing for a sort of art narrative comic, but for the intro sequence I'd like to have the word, "scan." Repeat on screen until the whole screen is covered, each word touching end to end. If it could be initiated on click that'd be awesome.
I can get text to appear of course, but this kind of repetition isn't something I'm familiar with at all.
Let me know if you need me to post what I'm currently working with.
Thanks!
Step 1: Store the current state (where the next word should be drawn) in variables at the top of your sketch.
Step 2: Inside the draw() function, use those variables to draw one frame of your animation.
Step 3: Then just update the variables holding your state to point to the next place. Processing will call the draw() function 60 times per second, so this will create an animation.
Shameless self-promotion: I wrote a tutorial on animation in Processing available here.

Constrained (Delaunay) Triangulation

For a university project I need to implement a computer graphics paper that has been relased a couple of years ago. At one point, I need to triangulate the results I get from my simulation. I guess its easier to explain what I need looking at a picture contained within the paper:
Let's say I already have got all the information it takes to reconstruct the contour lines that you can see in the second thumbnail. Using those I need to do some triangulation using those siluettes as constrains. I have searched the internet for triangulation libraries like CGAL, VTK, Triangle, Triangle++, ... but I always ended up throwing my hands up in horror. I am not a good programmer and it seems impossible to me to get into one of those APIs before the deadline of this project passes.
I would appreciate any kind of help like code snipplets, tips, etc...
I know that the algorithms need segments (pairs of points) as input, so let's say I have got one std::vector containing all pairs of points defining the siluette as well as the left and right side of the rectangle.
Can you somehow give me a code snipplet for i.e. CGAL that I could use for my purpose? First of all I just want to achieve the state of the third thumbnail. Lateron I will have to do some displacement within the "cracks" and finally write the information into a VBO for OpenGL rendering.
I have started working it out with CGAL. One simple problem still drives me crazy:
It is possible to attach informations (like ints) to points before adding them up to the triangulator object. I do this since I need on the one hand an int-flag that I use lateron to define my texture coordinates and on the other hand an index which I use so that I can create a indexed VBO.
http://doc.cgal.org/latest/Triangulation_2/Triangulation_2_2info_insert_with_pair_iterator_2_8cpp-example.html
But instead of points I only want to insert constraint-edges. If I insert both CGAL returns strange results since points have been fed into two times (once as point and once as point of a constrained edge).
http://doc.cgal.org/latest/Triangulation_2/Triangulation_2_2constrained_8cpp-example.html
Is it possible to connect in the same way as with points information to "Constraints" so that I can only use this function cdt.insert_constraint( Point(j,0), Point(j,6)); before I iterate over the resulting faces?
Lateron when I loop over the triangles I need some way to access the int-flags that I defined before. Like this but not on acutal points but the "ends" defined by the constraint edges:
for(CDT::Finite_faces_iterator fit = m_cdt.finite_faces_begin(); fit != m_cdt.finite_faces_end(); ++fit, ++k) {
int j = k*3;
for(int i=0; i < 3; i++) {
indices[j+i] = fit->vertex(i)->info().first;
}
}

Low framerate on android using immediateLayer (and weird playn log message)

I am trying to get my game running smoothly on android using PlayN, everything works as expected but I have a verry low framerate.
I think i might be doing it the wrong way so it'd be great if someone could give me some help :D.
So I'm currently creating an ImmediateLayer and cleaning it and drawing every objet at every frame, images are loaded once using graphics.getImage(...). I get around 10 fps on a HTC Desire (connected in debug mode) while drawing around 100 images. It gets slower as I add objetcs.
What makes me think I am doing something really wrong is that PlayN is spamming the log (I use DDMS to check the log) with these messages.
X Textures remaining
Y Textures created
It appears around 20 times per second.
So basically i am doing something like this:
public void draw(Surface s){
for (Drawable d : toDraw) {
surface.drawImage(d.getImage(), d.x, d.y, d.w, d.h); }}
Where draw is called in the renderer of an immediateLayer.
thank you for your time!
Lucas
Edit:
I found a possible answer reading that thread on playn mailing list.
https://groups.google.com/forum/?fromgroups#!topic/playn/XJTlBgmfzaQ
especially that message
Most of the tiles share the same image, but different parts of it (atteined
by subImage, which to my knowledge doesn't copy but rather only creates a
reference to a sub part to the image?). Would different sub parts cause a
texture change?
Sub-images will share the same texture, but you have to be sure to
render all the images that share the same texture together. If you
have a bunch of sub images from image A and a bunch from image B and
you render A, B, A, B, A, B, A, B, you are getting same performance as
if you rendered eight different images. You need to render A, A, A, A,
B, B, B, B.
It seems I am in a worst case scenario.
I have many different textures (say 50), They're all part of a different image and all rendered randomly. I may end up with something close to N texture switch where N is the number of objet i render.
I'll update this when i get something to work :).
Edit 2:
I am now rendering 100 objet pointing to the same Image (so no texture swap?). I still get about 10 fps on android and the debug log is still saying in each frame:
1 textures remain
2 textures created
I feel like i'm missing something important... help :).
After some deeper testing I found that :
1) The htc desire cannot be expected to get 60 fps drawing hundreds of objects even sharing the same image.
2) imageLayer attached to a group layer seems to provide better performance on android
3) Calling surface.clear() at the beginning of the renderer callback (using immediate layer) greatly improved the performance of the draw and removed the "textures created" debug log.
4) Finally sorting the object by texture and reducing the number of texture swap (drawing A A A A B B B istead of A B A B A B) gave me better results.
The app is now runnig at 30 fps on the desire and 60 fps on a galaxy S2 drawing around 500 object on screen.

Generate subdivided triangle-strip cube?

I want to generate a cube where each face is divided into bits, like the following image:
http://img59.imageshack.us/img59/2504/gridcube165c3.jpg
Now, I can do this pretty simply if I'm just rendering quads, by just spacing vertices along each face plane at regular intervals, but my problem comes in when I want to turn the whole thing into a triangle strip. I've just got no idea how to unwrap it programmatically- is there some pattern to unwrapping that I'd follow?
I'm thinking of starting with the vertex at the top left corner as Row 0 Column 0 (R0C0), I'd want (first triangle) R0C0, ROC1, R1C1, (second triangle) R0C0, R1C0, R1C1 and so forth, and then when I reach the end of a row I guess I'd use a degenerate triangle to move to the next row, and then when I reach the end of the face I'd do the same to start a new face.
My main problem is that I can't visualize the program loop that would do this. I can reason out which vertex comes next visually, which is how I worked out the order above, but when I try to think programmatically I just stare blankly.
Even worse, with the end product I want the generated cube to be UV-mapped with a simple cube-map unwrap (the kind that looks like a T or t).
I guess, really, the best solution would be to find a library that already does this for me.
You could take a look at Ignacio Castaño's 'Optimal Grid Rendering' even though it's not triangle strips, it may inspire you.
Otherwise, you could use NVTriStrip library and be done with it.

how to find out moment after rotationX has finished

i am playing around with the rotationX/Y/Z properties available in flashplayer since version 10. for testing purpose i created a cube and put canvas objects on three sides of it (top, front, bottom) and created a tween to get the values required for turing by 90 deg. turning the cube (a canvas) using rotationX = xx works well when the three side-canvas objects are small and filled with a not-to-complex element hierarchy. when using larger and more complex content it slows down. the next idea was to remove the canvas elements content and replace it by a snapshotimage of the content instead before starting the turn, after the turn is performed the original content is put back on the sides again. this results in a good perfomance increase. using a tween the last step of rotation is done in the function that is called as the tweenEnd handler. in this function also the process of copying the canvases content back is performed. unfortunately this results in a short hang of the cube right in that last rotation step, the reason for which is that rotation and copying back takes place at the same time.
so i could wait for some time after having called cube.rotationX = endValue by using a timer or setTimeout(func, 500), but this is ugly.
so my question is: after having called cube.rotationX = endValue a period of time is required to calculate data for the rotation and do the rotation itself. is there a way to find out the point in time when the rotation has ended, so that then the copying can be started ?
thank you in advance
tyler
There's no any default event, dispatching when rotation is completed. But I think of using callLater() function to copy back content. Try it.
that is exactly the point, there is not an event indicating the end of the rotation. the solution using callLater() instead of using setTimeout() appears to be an improvement however since waiting for a certain amount of time is always invloving some 'hope it works on machine x'. thank you very much for the hint !
greetings
tyler

Resources