New to programming, question about exercise in Prologue of HTDP - racket

This may be a silly question but I'm completely new to programming. I'm towards the bottom of the Prologue in "How to Design Programs" (2nd ed) and there are 4 changes that you are challenged to make to the "Rocket Landing" program in DrRacket.
I'm stuck on the 4th one, specifically the bolded part:
How would you change the program so that the rocket lands on a flat rock bed that is 10 pixels higher than the bottom of the scene? Don’t forget to change the scenery, too.
; constants
(define WIDTH 200)
(define HEIGHT 400)
(define SCENE-CENTER (/ WIDTH 2))
(define MTSCN (empty-scene WIDTH HEIGHT "blue"))
(define ROCKET (overlay (circle 10 "solid" "green")
(rectangle 40 4 "solid" "green")))
(define ROCKET-CENTER-TO-TOP
(- (- HEIGHT 10) (/ (image-height ROCKET)2)))
;functions
(define (picture-of-rocket.v2 h)
(cond
[(<= h ROCKET-CENTER-TO-TOP)
(place-image ROCKET SCENE-CENTER h MTSCN)]
[(> h ROCKET-CENTER-TO-TOP)
(place-image ROCKET SCENE-CENTER ROCKET-CENTER-TO-TOP MTSCN)]))
(animate picture-of-rocket.v2)
My rocket (ufo) is doing the first part, stopping 10 pixels from the bottom but I'm not sure how I can draw a rock bed at the bottom with the commands I've learned so far. Do I (overlay) a 10 pixel rectangle at the bottom? Or does the author just mean change the scene background to grey?

Good question! I think, in this case, there is no right answer. Indeed, I think that is the very purpose of the exercise: to give you a problem to solve that requires a (very small) bit of creativity, without spelling out exactly what you ought to do. HtDP recognizes that programming requires a mixture of structured, principled process and open-ended critical thinking, and some of its questions are open-ended by design. This is not so much to test your creative skills as it is to make sure you can still apply what you’ve learned with the training wheels off.
Your first intuition—to add a rectangle at the bottom—is a good one. Again, there is no right answer, so if it works, for now, that’s okay. The intent is to get you to play around with the toolbox that’s been given to you. As for what it means to “change the scenery”, I interpret that as literally asking you to decorate the scene as you see fit.
If this open-endedness feels a little disorienting, don’t worry—that is, in large part, the point. If you read just a little further down, the final section of the prologue explains exactly why this kind of open-ended experimentation is not sufficient to become a skilled programmer. As you progress through HtDP and move beyond the prologue, you’ll be presented with a much more principled approach to program design than simply fiddling with things. For now, though, the important point of note is that you’re being thoughtful about what you’re doing, and that’s a good sign.
(By the way, this is one of the best Stack Overflow questions on anything related to HtDP I’ve seen in a long time, so thank you for that. Most are little more than thinly-veiled requests from students asking for people to do their homework for them.)

Related

How to adjust inputs for Neural Nets?

I have been wanting to try and make a neural net that controlls a game.
I'm very close to my goal, but yet I feel like I have messed up somewhere!
I'm getting values that are reasonably close to what I'm expecting. But there is one problem...
I decided to try it with the Flappy Bird concept...
I have 3 inputs currently.
1) Height from ground (goes toward 1 the closer it gets)
2) Distance
to nearest wall in the top of the screen
3) ... bottom of the screen.
3 Hidden neurons, and one output.
It kind of jump when it gets to a lower wall. But it ALSO jumps when it reaches a upper wall. Thus hitting it in steath of dropping down lower.
My question really, is there some way of turning that jump into drops insteath?
Or do any of you suspect where I might start looking?
1) I know i have trouble with the sigmoid function. I have no idea how to write it actually. It says
f(x) = 1 / (1 + e^x)
Can I just swap e with a number or something? What is that character? I never really heard about it in the physics math I had...
The derivative is actually easier it seems.
But this is the right formula, right?
fd(x) = f(x) * (1 - f(x))
The function
f(x) = 1 / (1 + e^(-x))
is just an approximation of the step function that is also differentiable.
(where e is the natural logarithm.)
You can find a number of examples of Neural Networks playing Flappy Bird. For example, this developer seems to only use 2 inputs, 2 hidden, and 1 output. His inputs only seem to be distance to the top wall and distance to the bottom wall.
I think this is a better solution than your 3 inputs - "distance from the bottom of the screen" is probably not an effective feature.
Note: This is also dependent on how you are calculating distance to each wall.

Using leaflet.js with a non-geo map (gdal2tiles.py)

I'm trying to use Leaflet.js to access a non-geo (scanned image ...) map, which I tiled using gdal2tiles.py -p raster. But I absolutely can't get it to work: I see Leaflet requesting URLs with negative coordinates and non-existent ones. (Such as: /3/-1/8.png ...)
The map in question is 1162 pixels wide and 700 pixels high.
The tilemapresource.xml file generated by gdal2tiles says, among other things:
<BoundingBox minx="0.0" miny="-700.0" maxx="1162.0" maxy="0.0"/>
<Origin x="0.0" y="-700.0"/>
So, as you can see, the Y coordinates range from a negative number to zero, and the X range from zero to a positive number. (That's just the way that gdal2tiles.py decided to do it, I guess.)
I am using CRS.Simple like all the documents say to do, and I'm setting the bounds to SouthWest=(-700,0), NorthEast=(0,1162), admitting to be already mightily-confused when I see other examples that seem to be reversing the second (Lng) coordinate.
(I realized that "Lat" corresponds to "Y" and "Lng" to "X.")
Equally puzzling to me is that when I unproject the Southwest and Northeast points using the max-zoom, I get LatLng(-36.3125, -21.875) for SouthWest. I don't know why. (Again, I am using CRS.Simple ...)
Experimentally, I set "tms: false" on the tile-layer, which caused something to show up, but now the display's doing the most amazing thing: entirely on its own, it's "ping-ponging" back and forth along a line from roughly the middle of the right-hand margin down-and-left to the middle of the bottom, and back.
I know I've been whacking at this thing for too long today...
Well, I found it. (And, since I wound up asking this question twice, let me answer it in both places.)
Add all of the layers that you are going to use on your map, when you call the Map object's constructor, using the layers option.
In other words, do not do as I was doing: try to set up the various layers first, then add them to the map. The map needs to know about the layers, and the layers need to know about the map, right from the start. So, add them, then configure them as you need.
Otherwise, "strange and default things may happen." For example, although I specified the Simple CRS, that's not what I effectively wound-up with. It appears that the various objects (map, layers), "talk to one another" quite a bit with this library, and they don't expect to be orphans.
(Some of the "strange things" that can happen are, in fact, bizarre ... like: a tiny version of the map, ping-ponging between "about three o'clock" and "about six o'clock" and back again. A funny and entertaining thing to look at, unless you don't yet know why it's happening, nor how to stop it! Whew! )
The design of "leaflet.js" certainly isn't wrong, to be sure, but it has some unpleasant surprises for the unwary. (Like me.) Hope this helps.

Simulating physics for voxel constructions (Minecraft, Dwarf Fortress, etc)?

I'm hoping to prototype some very basic physics/statics simulations for "voxel-based" games like Minecraft and Dwarf Fortress, so that the game can detect when a player has constructed a structure that should not be able to stand up on its own.. Obviously this is a very fuzzy definition -- whether a structure is impossible depends upon multitude of material and environmental properties -- but the general idea is to motivate players to build structures that resemble the buildings we see in the real world. I'll describe what I mean in a bit more detail below, but I generally want to know if anyone could suggest either an potential approach to the problem or a resource that I could use.
Here's some examples of buildings that could be impossible if the material was not strong enough.
Here's some example situations. My understanding of this subject is not great but bear with me.
If this structure were to be made of concrete with dimensions of, say, 4m by 200m, it would probably not be able to stand up. Because the center of mass is not over its connection to the ground, I think it would either tip over or crack at the base.
The center of gravity of this arch lies between the columns holding it up, but if it was very big and made of a weak, heavy material, it would crumble under its own weight.
This tower has its center of gravity right over its base, but if it is sufficiently tall then it only takes a bit of force for the wind to topple it over.
Now, I expect that a full-scale real-time simulation of these physics isn't really possible... but there's a lot of ways that I could simplify the simulation. For example:
Tests for physics-defying structures could be infrequently and randomly performed, so a bad building doesn't crumble right as soon as it is built, but as much as a few minutes later.
Minecraft and Dwarf Fortress hardly perform rigid- or soft-body physics. For this reason, any piece of a building that is deemed to be physically impossible can simple "pop" into rubble instead of spawning a bunch of accurate physics props.
Have you considered taking an existing 3d environment physics engine and "rounding off" orientations of objects? In the case of your first object (the L-shaped thing), you could run a simulation of a continuous, non-voxelized object of similar shape behind the scenes and then monitor that object for orientation changes. In a simple case, if the object's representation of the continuous hits the ground, the object in the voxelized gameplay world could move its blocks to the ground.
I don't think there is a feasible way to do this. Minecraft has no notion of physical structure. So you will have to look at each block individually to determine if it should fall (there are other considerations but this is minimum). You would therefore need a way to distinguish between ground and "not ground". This is modeling problem first and foremost, not a programming problem (not even simulation design). I think this question is out of scope for SO.
For instance consider the following model, that may give you an indication of the complexities involved:
each block above height = 0 experiences a "down pull" = P, P may be any of the following:
0 if the box is supported by another box
m*g (where m is its mass which depends on material density * voxel volume) otherwise if it is free
F represents some "friction" or "glue" between vertical faces of boxes, it counteracts P.
This friction should have a threshold beyond which it "breaks" and the block then has a net pull downwards.
if m*g < sum F, box stays where it is. Otherwise, box falls.
F depends on the pairs of materials in contact
for n=2, so you can form a line of blocks between two towers
F is what causes the net pull of a box to be larger than m*g. For instance if you have two blocks a-b-c with c being on d, then a pulls on b, so b should be "heavier" than m*g where it contacts c. If this net is > F, then the pair a-b should fall.
You might be able to simulate the above and get interesting results, but you will find it really challenging to handle the case where there are two towsers with a line of blocks between them: the towers are coupled together by line of blocks, there is no longer a "tip" to the line of blocks. At this stage you might as well get out your physics books to create a system of boxes and springs and come up with equations that you might be able to solve numerically, but in a full 3D system you will have a 3D mesh of springs to navigate iteratively to converge to force values on each box and determine which ones move.
A professor of mine suggested that I look at this paper.
Additionally, I found the keyword for what it is I'm looking for. "Structural Analysis." I bought a textbook and I have a long road ahead of me.

Tips on creating a custom view layout for a diagram

I need to create an algorithm to layout some hierarchical data but have never done this kind of thing before and need some broad tips.
Basically I need to recreate this diagram (with dynamic data):
diagram http://dl.dropbox.com/u/15126868/diagram.png
bigger
I don't have a problem with most of it but need help with two things:
How do I approach writing a layout algorithm?
Should I use UIView subclasses for all discs or use quartz (I do need interaction)
Any suggestions most welcome. I don't need too much detail.
A bit more detail:
I'm currently thinking I should use UIView subclasses and layoutSubviews. Trouble is I need to know the size (at least roughly) of all nodes before I can start to position them. Then, as the positioning involves rotation, I may need to adjust child positioning again - and I can't add labels until after any rotation.
Other considerations seem to be: that the presentation area is rectangular, not square; that I can't spill off the page; and that I will need to animate changes to the sizes of the discs.
Any pointers would be great, thanks.
This sort of thing is very difficult.
Interestingly the perhaps main actual initial constraint here is the size of the typography.
In the example given: Observe they could have chosen a different SCPT** somewhat larger (perhaps, 10%-15% larger) or somewhat smaller and it would have still worked. They made an aesthetic decision on the SCPT.
White space is critical to design. Their particular graphic designer happened to like the particular feel of white space which you see. But it would have by no means been "wrong" with a smaller SCTP. Further, observe they could have used an even larger SCPT ... IF ... they used a smaller point size on the typography.
Note that in any event you simply won't be able to display that much type that small on an iPad (or Fone4).
So straight away you have to make decisions about how the type will appear, popup, audio or whatever. Even the white type ("on the discs" type) will give you trouble.
You will have to do lots of tests with photoshop first on to your iPad before even proceeding with an algorithm. So purely for what it's worth...
Here's how I personally would do this sort of thing. In general plan: I would try to do a squishy algorithm that retries itself until it finds a result it is happy with.
IMHO, based on previously doing this type of thing: this problem is too hard to get it done in one go with some particularly smart-ass heuristic. Since there is no one smart-ass heuristic that will save the day, I'd do this:
1) calculate the total trillions to display. (it looks like about 2.5 is the total in the example image)
2) guess a SCPT value to begin with. what about for example "18" based on the actual image at the screen size we see above as posted inside your question.
3) put the big one (sun) in the dead center, and for the middle ones (planets) -- just choose a very easy heuristic, what about from biggest to smallest going anticlockwise srtaing at the top left (don't try to get clever than that with that part of the problem - which indeed could be a huge research project purely on it's own) .. and do the same with the small ones (moons).
4) for the sticks between planets and moons - adopt a trivial solution (like "always 0.5 cm"!!) and that's that. with AI you gotta cut your losses .. everywhere! :) Fix the moons to the planets and forget about them.
5) Now a hard part .. run some sort of heuristic over them that evenly balances what you have so far. treat color as mass and no color as no mass and move the "sun" until it is balancedish. (to be clear, as an example that would be likely downwards if you followed the "planet" layout mentioned in 3.) maybe also move all the planet/moon systems in-out to try to balance it.
6) next the iteration. look at that result and decide if you like it! go back to (2) and pick a new value. (maybe "16!" for example)
(7) there are two possible outcomes here. it might be that during development, there is one magic value for SCPT that always works. perhaps "14.3" or "18.2" or whatever. if you find such a value, never tell anyone. keep it as your own secret information!!!! milk it for everything it is worth with clients. conversely and more difficultly, you might find you need a different value each time. in that case: your AI will have to on it's own iterate through values until it finds one it likes. (for example, by determining whether all your labels fit or not .. and obvious things like "are they touching" "all on screen" etc.)
Anyway FWIW (perhaps nothing) that is what I would do - an iterative approach based on a first guess for the SCPT.
Incidentally: you may well want to buy and study the classic and brilliant book on this sort of display of information!!! Everyone should have a copy.
Tufte's The visual display of Quantatative Information
by Edward R. Tufte
ISBN 0961392142
Regarding the mechanics of laying out the image. You should use quartz or any other low-level drawing - forget about UIViews and the like. You should surely completely separate the logic from the drawing layer, so (even if you do want to change to UIViews, OpenGLES, or whatever) it's only changing a few lines of code.
Hope it helps somehow.
Notes...
** SCPT .. square centimeters per trillion
Followup...
"To keep the logic separate would you use a manager-type pattern?"
To be honest: if I was doing it, I would just start a whole new app purely for the "research" of getting this part, this challenge, working right. In that app (to be honest!) I would make bugger all effort to do anything in any tidy manner whatsoever! :-/ Globals everywhere! :) Unfortunately for me I can only think of the one thing at a time, so at that stage I would only be thinking about the algorithm, per se.
I believe, once you cracked the problem per se, once you came to implement it in a bigger project ... really, FWIW, if it was me, I'd simply make it a class (let's say AmazingClass) nothing more complicated than that. Personally I would set the data somewhere separately (whether in a DB or just an array or whatever) and I would just let the AmazingClass take care of getting the data, even. (My thinking - you never know how the hell you're going to need the data and when, at what point in the process of AmazingClass. So, just give up and let AmazingClass take it as and when it wants it.)
If you are familiar with these awesome-sounding manager-patterns of which you speak - yeah, why not! In short I would heavily separate it out as much as possible. I'm not good enough to speak on the best way to do that - but just completely separate it out somewhere. Sorry I can't help on that one.

Drawing Routes with iPhone

I am trying to make an iPhone application which can draw a path between two points (similar to Google Maps) but instead of the map i want to use any other image as a background, this path between the two points might not be straight and there might be multiple paths to get from one point to another then I want to draw the shortest path between the two points.
I tried using the CGContext & CGPath but I got stacked.
Can you help me plz.
Thanx,
Ghaith
I think you're looking for UIBezierPath. You can add simple lines/polygons with something like:
UIBezierPath* path = [UIBezierPath bezierPath];
[aPath moveToPoint:CGPointMake(50.0, 50.0)];
[aPath addLineToPoint:CGPointMake(10.0, 10.0)];
[aPath addLineToPoint:CGPointMake(10.0, 50.0)];
[aPath closePath];
You can also, of course, add curves (bezier ones!) and other shapes. Then to draw it use the [aPath stroke] call in your view's drawRect method.
For more information see the iPad Programming Guide
This seems like a problem that's not really related to drawing the route.
You want to find the shortest path from one point to another, given certain criteria - where you can and cannot move, for example. I don't see this problem as something you can solve with drawing, but with actually calculating the different possible ways and then compare them. When you have decided which is the best route. Drawing is pretty simple.
How you would go by deciding I'm actually not sure - sorry 'bout that. But you should probably have a look at some shortest path algorithms. But that probably means you have to represent the underlying image as a pattern, or a series of nodes but graphical problems are not my cup of tea, so I'm not really sure how.
Just a side note - If the number of possible ways of getting from point A to point B are great, this can become a computational problem, and you have to make sure that the iPhone can manage.
(this should probably be a comment somewhere, but since I can't yet and I still wanted to share my two cents, it became an answer.)
Edit:
I just thought of really naive aproach! - for fun mostly, but I couldn't keep myself from posting.
Suppose you have a representation of the image. What parts can't be traveled on and what parts can be. Each pixel that can be travelled on is represented by a 1, and every other pixel is represented by a 0. Thus the pixels represented by 1s can be seen as nodes on which we can travel.
Each node can reach, at most, 8 other nodes - the adjacent pixels. And the weight of travelling between any two nodes could be set as 1. But we have to account that travelling in a diagonal is a greater distance so that weight should be sqrt(2).
Now we have a great bunch of nodes - each with weights in between them. From here we can apply a djikstra-algorithm to find the best route. (maybe some other algorithm is more beneficial at this point - but djikstras is the only one I'm familiar with).
hum, wonder how bad of a solution this would be. ... again, you probably don't want this solution...
EDIT 2:
I will say this again that this is probably not the best way to do this! You should seriously ask someone with more experience in algorithms and in graphical problems. - This was something I thought of at 3am and was mostly for laughs.
If your question is about calculating routes instead of drawing routes, that's a whole different problem. The standard algorithm for finding efficient routes through a given space are the "A*" (pronounced A-star) algorithms, which are typically what real-time strategy games use when you click a unit and tell it to "go there". It's also got many uses in AI when searching for a transition through a space.
It's not easy to get right, though. It might be easier to find a good game engine that already includes an A* implementation and integrate that into your software.