Bay 12 Games Forum

Please login or register.

Login with username, password and session length
Advanced search  
Pages: [1] 2

Author Topic: Programming Algorithms  (Read 2054 times)

metime00

  • Bay Watcher
  • Adequate Dwarf Fortresser
    • View Profile
Programming Algorithms
« on: April 14, 2011, 05:07:23 pm »

I have read several times how important being able to create algorithms is for programming. I'm a super noob in C# and I'm wondering a few things.

What exactly is an algorithm and how does one learn how to make good algorithms?

And if none of this makes sense, please explain what the deal is with algorithms, as they confuzzle my brain. Or try to explain what skills or knowledge are most important to get on the path to being a good programmer.
Logged
Live long if you can, and prosper by any means necessary.  Any means, Urist.  So pull that lever, or by Armok, I'll lock you outside come next siege.
He who plays with dwarves must take care that he does not become a dwarf.  And when you stare into DwarfFort, Dwarffort stares back into you.

Virex

  • Bay Watcher
  • Subjects interest attracted. Annalyses pending...
    • View Profile
Re: Programming Algorithms
« Reply #1 on: April 14, 2011, 05:10:46 pm »

An algorithm is basically a description for the computer as to how it should do something. In most cases you'll be packing the algorithm in a function, but in theory they can also be implemented in the form of macros in languages that support it.
Logged

Levi

  • Bay Watcher
  • Is a fish.
    • View Profile
Re: Programming Algorithms
« Reply #2 on: April 14, 2011, 05:18:41 pm »

A good example of an algorithm is a sorting algorithm.   If you have a list of numbers, there are quite a few different ways to get them to sort.  Some sorting algorithms are extremely fast for small sets of numbers, but extremely slow for more than a thousand numbers.  Some are designed to do well with large amounts of data, but aren't quite as efficient for small amounts.

Here is a bunch of different ones:

http://en.wikipedia.org/wiki/Sorting_algorithm

So basically an algorithm is just the series of steps you do to solve a problem.
Logged
Avid Gamer | Goldfish Enthusiast | Canadian | Professional Layabout

metime00

  • Bay Watcher
  • Adequate Dwarf Fortresser
    • View Profile
Re: Programming Algorithms
« Reply #3 on: April 14, 2011, 05:36:55 pm »

hmm, so it's basically everything in programming? Thanks, that cleared it up. I was always so confused. I guess now it's time to join that programming contest thingy here.
Logged
Live long if you can, and prosper by any means necessary.  Any means, Urist.  So pull that lever, or by Armok, I'll lock you outside come next siege.
He who plays with dwarves must take care that he does not become a dwarf.  And when you stare into DwarfFort, Dwarffort stares back into you.

Virex

  • Bay Watcher
  • Subjects interest attracted. Annalyses pending...
    • View Profile
Re: Programming Algorithms
« Reply #4 on: April 14, 2011, 05:41:06 pm »

Yeah, but the point of developing an algorithm is to get a write-once description. As soon as you have an algorithm (usually written in pseudocode) you can implement it in whatever language you would like (ok, not really. If your algorithm needs coroutines to function there's no way you're going to be able to copy that to C without seriously rewriting things)
Logged

metime00

  • Bay Watcher
  • Adequate Dwarf Fortresser
    • View Profile
Re: Programming Algorithms
« Reply #5 on: April 14, 2011, 06:07:36 pm »

So an algorithm is more of a broad function that can be easily adapted to other languages? Where do algorithms fall in something like a videogame, where there aren't really any "problems" to solve per se?
Logged
Live long if you can, and prosper by any means necessary.  Any means, Urist.  So pull that lever, or by Armok, I'll lock you outside come next siege.
He who plays with dwarves must take care that he does not become a dwarf.  And when you stare into DwarfFort, Dwarffort stares back into you.

Levi

  • Bay Watcher
  • Is a fish.
    • View Profile
Re: Programming Algorithms
« Reply #6 on: April 14, 2011, 06:13:17 pm »

So an algorithm is more of a broad function that can be easily adapted to other languages? Where do algorithms fall in something like a videogame, where there aren't really any "problems" to solve per se?

You'll always find a problem to solve.   ;D

I wouldn't worry to much about things like this yet.  Just try to make something that works, and as you get better you'll start to understand more about algorithms. 

An example from my own projects is a map generator.  I've been playing around with different algorithms to generate 2d cave systems.  So far none of the algorithms really fit my requirements so I'll probably have to write my own algorithm rather than using one I find on the internet.

In practice, this means me mashing my head on the keyboard until I get some code that does what I want.  :D
Logged
Avid Gamer | Goldfish Enthusiast | Canadian | Professional Layabout

metime00

  • Bay Watcher
  • Adequate Dwarf Fortresser
    • View Profile
Re: Programming Algorithms
« Reply #7 on: April 14, 2011, 06:23:10 pm »

I just remembered that in my current project I'm going to need to write an algorithm that populates a map with items and beasties as well as one for their AI.

Are there any general tips for getting an algorithm to be elegant and fast as opposed to rough and brute forcey?

The map generator would need to make sure nothing is spawned in a wall or too close to the player or too close to the other monsters/items. That's definitely going to count as an algorithm. Is there anything I can really do besides have them try and spawn and check for things around them before they do for real?
Logged
Live long if you can, and prosper by any means necessary.  Any means, Urist.  So pull that lever, or by Armok, I'll lock you outside come next siege.
He who plays with dwarves must take care that he does not become a dwarf.  And when you stare into DwarfFort, Dwarffort stares back into you.

Starver

  • Bay Watcher
    • View Profile
Re: Programming Algorithms
« Reply #8 on: April 14, 2011, 06:54:44 pm »

I'll just add my voice to this that "Algorithm" to some people might mean the idea (shorn of any specific programming language) of the process you're attempting[1].  Others will use "Algorithm" as exactly the same as a function, procedure or even a one-line operation just contained within the code, and thus actual lines of that code.

So "The ability to create algorithms" might mean as little as "know what it is you want the programme to do, which must then be followed up by the ability to make the programming environment within which you're working bend to your will and do that task.

Insofar as it is insufficient to say "I want this programme to pin-point a human face in an image", because unless there's a "getHumanFaceLocation(image:imageType):selectionType" sort of function, that's not really good enough.  But if you start with some more of an idea[2], and perhaps drill down into that idea to work out that you will require a more narrowly defined algorithm[3], then you're likely to be able to combine that with your 'raw programming knowledge' to create a procedure or function using the commands you have available to accomplish the desired algorithm.


On the other hand, the author of the phrase might be talking about how to group the commands into "write-once, use on demand" code structures (procedures, functions or just blocks of code within a loop or decision tree).  i.e. getting that 'raw programming language' in the first place.


I err towards the former, I suppose, because I would say that the path towards being a good programmer cannot be 100% knowledge of the commands but 0% understanding of the task and thus no possibility of working out how to put them together to accomplish your purpose.  Whereas it may be possible (if still vastly ill-advised) to start off with a perfect understanding of what needs accomplishing, and by what method, and then start bashing through the reference books, etc, in order to work out what code has to be jammed together in what format in order to get the whole concept implemented.

In reality, of course, knowing that something is possible in code vastly helps when it comes to putting the idea together.  The fact that you can perhaps generate an arbitrary number of registers capable of keeping count of the number of occurrences of arbitrary words, in a certain programming language, simplifies the job of finding the most common word (or words) in a given sample of text.  Without that apparent ability, you may resort to something more inefficient[4][5] than you need have.


(I suppose a much glibber answer could have been "Be the code!", and perhaps it might be less potentially contentious than what I just wrote, but I'm sure it wouldn't have been any more helpful...)


To reference your ninjaed query about the lack of "problems in a video game", there are always problems.  Everything from how to (frexample) represent a picture of your hero, his various foes and the environment in which they are battling upon the screen, through to how to ensure that if the hero/foes land on certain parts of the environment they will die and also about how to work out what happens to each if the hero and a foe interact with each other.  Does the hero fire bullets?  How do you understand that the player wants to fire bullets (grab keyboard/mouse/other input, and check to see if there are bullets to fire, and whether or not it's too soon to fire a bullet so soon after a previous one)?  How do you understand that the foe wants to fire grenades (check foe-character's profile to see whether they throw grenades regardless, or do they throw when they work out (by some manner or other) that the hero is within range, plus check that they've not run out of grenades or it's (again) not too soon since the last grenade throw)?  When a bullet hits a foe, what should happen?  When a grenade hits the hero, what should happen?  What about if a bullet/grenade somehow manages to hit the hero/a foe (however unlikely the former is, or the latter if there's not multiple foes)?  What about a bullet hitting a grenade, or a grenade blast overtaking a bullet?  How do these circumstances get detected, and how might that affect the way the entities work (die, be injured, slow down, or have a more "beaten up" image be used instead of the original one, which you must now make sure is used to represent the entity concerned until something else changes this (healing, more damage, death/evaporation/running-off-screen/whatever), and might this make the entity change tactics)?

Stuff...  The above describes a very simple scenario that might resonate as describing any one of a number of games that have been written.  I could as easily have described a racing game where the problem was how to generate (or retrieve from some pre-generated storage or other) the twists and turns of the track, and display all aspects of the track environment, but again work out what the user wants the car to do, and if it can do that at this time, plus if the car is in a valid bit of track, in the rough and thus slow, has hit a barrier, is over a power-up... never mind the question of any opponents (how are they programmed to behave... do they have Artificial Stupidity to cause them to make mistakes, or are they 'perfect', just handicapped in speed so that a decent human driver can beat them?), etc, etc...

But as to whether each and (deconstructed) every point I've made should be considered equivalent to "An algorithm" is another question.  You may find you need to implement each question using a combination of 'simpler' algorithms, or that the algorithm to check to see if the player's character/car is in a valid position on the screen can also be used to check whether the foes/competitive-cars are in a valid position on the screen.  Whether the method to detriment the health/speed/whatever of the out-of-bounds entity is part of the same algorithm, a common second algorithm or one of various party-specific additional algorithms is also easy to argue about.  It's all probably a lot of simple algorithms which are in turn called by a few less simple algorithms that have a choice within them of which of the simpler algorithms are called, which in turn are grouped by small subset of higher algorithms, which will even boil down to one "master control" algorithm.  At least that's how it will work procedurally (although in an object orientated environment, the "master control" one is as likely the programming language's own core controlling code which manages the real-time switching and prioritising between the various 'objects' you've designed to work on a semi-independent basis... that's an argument and a half... but you get the idea).  And, as I said, some people would equate algorithms to procedures.  And others might go so far as to accept that 'algorithm' is to 'theory' as 'procedure' is to 'practice'.


Double-ninjaed response about elegance.  Perhaps one solution would be to have a number of 'floating' spawning points which get randomly placed prior to the wall-emplacement, but as walls get computed they check against the limited number of spawning points and if there's a collision the SP gets moved to one side of the wall.  Unless the wall gets expanded, or T-junctioned with another new bit of wall, the SP won't need to move again.  (Or could move, randomly, in-between the ticks when everything else moved, but only into adjacent non-wall spaces.  Would produce a more random spawning, and could be tuned to ensure that the points don't get close enough to your 'hero' so as to land on top of them, or lets you ensure a more 'realistic' distribution of newly spawning 'enemy' units.

But I don't know enough about your design to know if this would be so necessary to do, or if the problem of spawning wouldn't be so trivial as to need such advance insight.  Get random point, check to see if too close to something (or on top of wall) and if so, generate another random point.  Or screen-slice to prevent "too close" incidents and then allow any wall-incidents to try the spots on the screen adjacent to the wall in each cardinal direction (randomly) until one without a wall is found.  Or "drunkard's walk" it around until it 'falls off' a wall and into an acceptable space.  Or. Or. Or...  Loads of ways.  As I said, don't know enough (anything!) about your game, but you should have an idea what would work best.

At last, not further ninjaed.  Sorry, this is probably now a TL;DR; but hopefully (we shall see) it shall at least post.


[1] e.g. "Start a count at zero.  Look at the first item in a list.  If that item is a badger, then stop looking and inform the user of the current count.  But, otherwise, if that item is the name of a fruit increase the count by one and look at the next item, before going back to the badger-test point again", for a completely spurious example that has several in-built problems.

[2] Like "Look for localised maxima and minima in the image array.  For all maxima/minima, create associations with neighbouring maxima/minima to narrow down to one's with <some relationship or other indicative of eyes>.  Repeat with all possible pairings to assess association with further relationship with further features with <some mouth-like indication>, rejecting all sets without that relationship.  Repeat with all remaining sets to identify some feature with <nose-like indication> within the bounds of the points defining the existing set of features. <etc>", as a completely and utterly bastardised and abbreviated concept of one possible facial-recognition algorithm that couldn't detect faces in profile anyway, but you get the idea.

[3] Something along the lines of getMaximaOrMinima, at the very least, in the above example, and how you do the mouth and nose might or might not be a mere extension of the same, but probably not.

[4] "Set a maximum-count register to zero.  Set a frequentest-word register to blank.  Go to first word.  Make note of word.  Set counter to one.  Check every word following this and if that word is the noted one, increment the counter.  At end, check if counter is greater than maximum-count.  If it is, set maximum-count register to the value in the counter, and at the same time set frequentest-word register to the noted word.  Go to word after the one just looked at and return to 'Make not of word' part, unless there is no next word, in which case report the maximum-count value and the frequentest-word word."  (Which could be slightly optimised by if the noted word is equal to the maximum-count word, then go the next word and forget counting, you'll only be counting one less than last time.)

[5] Compare that to the possible "For each word, if there is no counter relating to that word, set the counter to one, otherwise set the existing counter to one more than it is now.  When having no more words, sort the list of words that have been counted by [ascending/descending] final count and report the [last/first] counter's word.  If the [next|previous] listed counter has the same value, report that word also, and repeat this line again until it isn't." as another slightly abbreviated solution, but one which (assuming the possibility of arbitrary counters and a monolithic sort function that can work on such counters) would be a far better algorithm.  Even if you have to use Levi's sorting algorithms as well (or, simpler, do a single-pass "go through counters, recording any increasingly large counter values and the counter", which you could modify to similarly keep score of tied 'frequentest' values), it is still a quicker single-pass process.  And even if the language doesn't have a core ability to keep so many counters, there may be ways to implement that, if you know what 'the code' is capable.
Logged

metime00

  • Bay Watcher
  • Adequate Dwarf Fortresser
    • View Profile
Re: Programming Algorithms
« Reply #9 on: April 14, 2011, 07:41:11 pm »

Now that was an awesome and helpful post! Other than the insightful extended definition of "algorithm", I found the spawning point idea very helpful. It never occurred to me to use a randomized set of predetermined spawn points to spawn enemies/items, but now that you mention it, it seems as obvious as using a seed to generate a random world.

As well, I will keep in mind the paragraph on "problems in videogames" for when I have to write the AI for enemies.

It seems that the key is to know what you're capable of doing in a language, as well as your goal. I think perhaps better planning and thinking beforehand would be useful. Maybe make an outline for every large function before I write it.

Maybe it's just the fact that I finished writing an essay, but I'm seeing quite a few similarities between making a good program and a good essay. You have to plan beforehand and proofread afterward...
Logged
Live long if you can, and prosper by any means necessary.  Any means, Urist.  So pull that lever, or by Armok, I'll lock you outside come next siege.
He who plays with dwarves must take care that he does not become a dwarf.  And when you stare into DwarfFort, Dwarffort stares back into you.

Max White

  • Bay Watcher
  • Still not hollowed!
    • View Profile
Re: Programming Algorithms
« Reply #10 on: April 14, 2011, 07:57:15 pm »

Are there any general tips for getting an algorithm to be elegant and fast as opposed to rough and brute forcey?

Yes. Don't have a single algorithm, have many that are called by a controller class. 'Algorithms' (In this context referring to a single two dimensional function, rather then your entire freaking app) should only be responsible for a single task. Doing this will almost certainly save you some trouble later on down the path when you want some more functionality. Also, remember that logic is handles on the lowest level possible. So if you made a 'square' object, and wanted to get the area, you wouldn't do 'double area = square.Length * square.Hight;' but rather you would get a function (Or a getter) to return the area for you. so...

Code: [Select]
Class Square
{
double _height;
double _length;

public Square (double height, double length)
{
this._height = height;
this._lenght = lenght;
}

public double Height
{
get
{
return _height;
}
set
{
_height = value;
}
}

public double Lenght
{
get
{
return _lenght;
}
set
{
_lenght= value;
}
}

public double Area
{
get
{
return _lenght * _height;
}
}
}

metime00

  • Bay Watcher
  • Adequate Dwarf Fortresser
    • View Profile
Re: Programming Algorithms
« Reply #11 on: April 14, 2011, 08:21:58 pm »

I had a bit of trouble earlier in my programming ventures with trying to have a method that calls other methods to do work by running into the C# garbage collect *shudders*

I've found a balance now, where I can have that easier to manage and modify controller class and not run into the garbage collect. It makes for a much easier to read, organize, and add to a program. Also then I can use virtual methods for different AI for different enemies :D

Although I've never gotten to that point, so the concept remains a concept as of right now.
Logged
Live long if you can, and prosper by any means necessary.  Any means, Urist.  So pull that lever, or by Armok, I'll lock you outside come next siege.
He who plays with dwarves must take care that he does not become a dwarf.  And when you stare into DwarfFort, Dwarffort stares back into you.

Briggsy16

  • Bay Watcher
    • View Profile
Re: Programming Algorithms
« Reply #12 on: April 14, 2011, 08:34:50 pm »

You know I'm planning on teaching myself programming over this summer and one day I'll go into a topic like this and have a clue what you're all on about.
Logged

Lord Dullard

  • Bay Watcher
  • Indubitably.
    • View Profile
    • Cult: Awakening of the Old Ones
Re: Programming Algorithms
« Reply #13 on: April 14, 2011, 11:48:32 pm »

An algorithm is just a pattern of code that does something in particular. It can be as complicated or simple as desired. Or perhaps a better description would be 'a sequence of steps [in code] taken to achieve a desired outcome'. It's never really necessary to use the word 'algorithm' when describing a particular piece of code because you can instead describe it in terms of methods, functions, classes, et cetera; but 'algorithm' is a useful way to refer to a specific section of that code that may be smaller than a function or that may consist of an amalgam of functions and classes. If I refer to a 'path-finding algorithm' it might be a section of code that takes up several functions and one or more classes. A 'tile-counting algorithm' might take up only five lines of code and simply be a subset of a function. For that matter, it is entirely possible for one algorithm to be nested in another.

In summary, it's really just a synonym for 'process' or 'set of directions'. As with anything else, 'set of directions' might refer to something as simple as cooking an egg or something as complicated as building a rocket to fly to the moon. Algorithms can be algorithms regardless of scope.
« Last Edit: April 14, 2011, 11:52:07 pm by Lord Dullard »
Logged

eerr

  • Bay Watcher
    • View Profile
Re: Programming Algorithms
« Reply #14 on: April 15, 2011, 12:09:36 am »

An algorithm is a pattern for solving a problem.

Logged
Pages: [1] 2