# Projects For Beginning Programmers (any language)



## Kreij (Apr 8, 2011)

*Projects For Beginning Programmers (any language)*

Since I don't have any programming projects that I am working on at the moment, I allowed myself to slip back into the nostalgic moments of the days when I was first writing code.
It was a lot of fun as everything was new and it was exciting to see the results of your coding play out on the screen in what usually turned out to be either disastrous, humorous or both.
Here are a few of ideas I put into code. These are just the descriptions as it's up to the new coders to make them work ... for better or worse. They are all text based console  programs (no GUIs).

*Who, What, Where*
This is a fun little exercise that involves random numbers and string arrays. The basic concept is to have one array that represents who, one that represents what and the last one where.
You enter strings in the arrays, and then a random number generator pick one entry from each array and make a sentence from it. For instance, you could have one of the "who" entries be "My roommate", the what could be "chewed on his soiled underwear", and the where could be "in the women's restroom at Walmart.
The more strings you add the weirder the results become. Just remember that the random numbers generated must fall within the bounds of the array they are accessing.
 Great for parties.

*Text Archery*
The concept here is that you are at location 0. The program generates a random object (bear, lion, your girlfriend, etc.) at some random distance. You then have to input the power behind your archery pull and the angle of trajectory. A simple calculation gives you where it lands. If you hit the object you win.
Beware, the first time I wrote this it was calculating to 5 decimal point precision. You may want to have the program calculate that if it is within a range, it is a hit.

*Text Dungeon*
This is the famous NSEW type of text dungeon. It's done with two-dimensional arrays which include the description of where you are at, and the directions which you can go as well as any other things you want to include (like picking things up or solving a puzzle). 
This is an exceptionally good exercise to learn a lot of programming basics.

*Text Lunar Lander*
You are in a space capsule that is x feet from the ground. Gravity is pulling it down. You must fire the retro rockets to slow it down and meet the ground at a safe speed to land successfully.
This is a good exercise in minor physics calculations.  Watch out! Just like "Text Archery", this one will bite you in the butt if you do not reduce or compensate for high precision floating point calculations.

Anyway ... have fun learning to program, and if any other coders want to get nostalgic and offer some of the fun little exercises they did when first starting, feel free.


----------



## Polaris573 (Apr 8, 2011)

I just wrote my first "program" this week using ruby.  I'm an environmental scientist so it's a little rough around the edges and probably pretty hysterical to real programmers.  It calculates the sample duration in minutes using the start and stop time for a sampling device we use (or anything really).

For example a sample that was started at 12:25 and ended 21:26 would have run for 541 minutes.  

It enforces a few QAQC checks and allows the time to be entered with or without a colon.

Yes a SQL query or excel spreadhseet would be an easier way of doing it, but this I can just hand out anybody with any level of knowledge and no math or computer skills (some temp employees were bad about that this summer.)


```
####################
#DEFs and Constants#
####################

def format
	line_width = 75
	puts ' '
	puts('----------------------------------------------------------------'.center(line_width))
	puts ' '
end

def cls
	system 'cls'
end

cont = 0
line_width = 75

#####################
#Time Entry and QAQC#
#####################

while cont == 0
	puts 'Enter Start-Time'.center(line_width)
		starttime = gets.chomp
	puts 'Enter Stop-Time'.center(line_width)
		stoptime = gets.chomp
		
	if (stoptime.length <= 3 || starttime.length <= 3 || stoptime.length > 5 || starttime.length > 5)
		qaqc = 0
	else 
		qaqc = 1
	end
	
	if (starttime.length == 5)
		start = starttime.split(':')
	elsif (qaqc == 1)
		start = []
		start[0] = starttime.slice(0..1)
		start[1] = starttime.slice(2..3)
	end
	
	if (stoptime.length == 5)
		stop = stoptime.split(':')
	elsif (qaqc == 1)
		stop = []
		stop[0] = stoptime.slice(0..1)
		stop[1] = stoptime.slice(2..3)
	end
	
	cls
	
	if (qaqc == 0 || start[0].to_i >= 24 || stop[0].to_i >= 24 || start[1].to_i > 59 || stop[1].to_i > 59)
		format
		puts('--->INVALID TIME<---'.center(line_width))
		format
		qaqc = 'no'
	else
		puts('Are These the Correct Start and Stop Times?'.center(line_width))
		puts '(Press "Y" for Yes or "N" for No)'.center(line_width)
		puts ' '
		puts(('Start-Time: ' + start[0] + ':' + start[1]).center(line_width))
		puts(('Stop-Time: ' + stop[0] + ':' + stop[1]).center(line_width))
		qaqc = gets.chomp.downcase
		cls
	end
	
############
#Calculator#
############
	
	if qaqc == 'y'
		if (stop[0].to_i <= start[0].to_i)
			format
			puts(('Badge Duration Is ' + ((((stop[0].to_i + 24)*60) + start[1].to_i) - ((start[0].to_i*60) + start[1].to_i)).to_s + ' Minutes').center(line_width))
			format
		else
			format
			puts(('Badge Duration Is ' + (((stop[0].to_i*60) + stop[1].to_i) - ((start[0].to_i*60) + start[1].to_i)).to_s + ' Minutes').center(line_width))
			format
		end
	end
	
################
#Continue Loop?#
################

	while (cont != 'y')
		puts('Would You Like to Calculate Another?'.center(line_width))
		puts '(Press "Y" for Yes or "N" for No)'.center(line_width)
			cont = gets.chomp.downcase
		if (cont == 'n')
			break
		end				
	end
	
	if (cont == 'n')
		cls
		break
	end		
	
	cont = 0
	cls
	
end
```


----------



## Kreij (Apr 9, 2011)

Polaris573 said:


> it's a little rough around the edges and probably pretty hysterical to real programmers



There is no such thing as a "real" programmer. There are only non-programmers and programmers.
At some point in the future, as you work more with code, you may look back at it and say "Why did I do it that way" or "I could have made it more efficient", but if it works as designed and is useful to the target audience, it's sucessful code.

Well done.


----------



## Completely Bonkers (Apr 9, 2011)

```
10 PRINT "Hello World!"
20 GOTO 10
```

Old skool skillz!


----------



## Zyon (Apr 9, 2011)




----------



## Kreij (Apr 9, 2011)

"Above picture said:
			
		

> No, and the requirements have changed.



 ... that is so true.


----------



## Kreij (Apr 10, 2011)

So did anyone try their hand at the little exercises in the OP?

If so, post the executable. I would love to try them out.


----------



## FordGT90Concept (Apr 10, 2011)

Kreij said:


> So did anyone try their hand at the little exercises in the OP?
> 
> If so, post the executable. I would love to try them out.


If I had a ton of time and nothing better to do, they sound like fun/challenging programs to create.

Most of my early programs, like those I make today, are to perform a very specific task.  The only one similar to the examples you gave was to find solutions to how to make a knight hit every square on a chess board.  It was heavily multithreaded and basically tried random route after random route until it found a way that worked.  The fastest time, I think, was about 0.13 seconds.  It was an interesting program.


----------



## Kreij (Apr 10, 2011)

They are beginner exercises that familiarize people with the use of various type of variables and simple calculations.
I think you are a little beyond that Ford. 

If anyone else has simple exercises for starting coders, please post them !!


----------



## streetfighter 2 (Apr 10, 2011)

FordGT90Concept said:


> The only one similar to the examples you gave was to find solutions to how to make a knight hit every square on a chess board.  It was heavily multithreaded and basically tried random route after random route until it found a way that worked.  The fastest time, I think, was about 0.13 seconds.  It was an interesting program.


Just in case anyone else wants to give that a whirl it's known as the Knight's Tour and it's quite popular in programming courses.  There are a few methods for solving it in linear time [O(n)], but brute force is always more fun.


----------



## Yukikaze (Apr 10, 2011)

There's the oldie but goodie N-Queens problem:
http://en.wikipedia.org/wiki/Eight_queens_puzzle

A Sudoku generator and/or solver is also a fun exercise.


----------



## robn (Apr 10, 2011)

My favourite little graphical practice project is to code a block bouncing around inside a square area. Use the arrow keys to start it moving, then it rebounds on it's own. Add "gravity" in one direction, and it looks surprisingly realistic.

As for that flowchart posted by Zyon... yeah doing some CS course work right now, and the lecturer has updated to the 3rd version of his web service we have to code to! Fixed requirements? Maybe he is trying to simulate "industry" for us, so we know what to expect


----------



## Yukikaze (Apr 10, 2011)

robn said:


> Fixed requirements? Maybe he is trying to simulate "industry" for us, so we know what to expect



"Walking on water and developing software from a specification are easy if both are frozen."
- Edward V. Berard.

People have no idea just how true this is. I write Firmware for a living: The requirements change, the HW specification changes, the timing requirements change, and they keep on changing, and changing, and changing...


----------



## FordGT90Concept (Apr 11, 2011)

streetfighter 2 said:


> Just in case anyone else wants to give that a whirl it's known as the Knight's Tour and it's quite popular in programming courses.  There are a few methods for solving it in linear time [O(n)], but brute force is always more fun.





> Algorithms other than the simple brute-force search to find knight's tour solutions are discussed below. It is important to note that an exhaustive brute force approach (one which iterates through all possible move sequences) can never be applied to the Knight's Tour problem (except for very small board sizes). For a regular 8x8 chess board, there are approximately 4×1051 possible move sequences,[9] and it would take an unfathomable amount of time to iterate through such a large number of moves.


Lies. If memory serves, my server was doing 13,000,000 attempts per 1.6 GHz core (has 8) so about 104 million attempts per second total.  Only one of those 104 million attempts has to be correct.

4*1051=4204 Even a 486D could probably make that many attempts in well under a second.


----------



## Kreij (Apr 11, 2011)

@ Ford : It's not 4x1051, it's supposed to be 4 * 10^51


----------



## Thrackan (Apr 11, 2011)

robn said:


> My favourite little graphical practice project is to code a block bouncing around inside a square area. Use the arrow keys to start it moving, then it rebounds on it's own. Add "gravity" in one direction, and it looks surprisingly realistic.



Bouncing balls, I did those on the C64  That must have been one of the first things I "made" that wasn't simply printing text.

One of the most widely used starting examples is building a calculator. In school, we've used that same example a couple of times: when learning to make objects, functions and the likes, and when moving from clientside to server-side programming. It's really basic, but you can do a lot with it.

Most of my pre-school progs were simple macro's. In the C64 age, I was just a little too young to make "actual" programs unfortunately.


----------



## Fourstaff (Apr 11, 2011)

http://projecteuler.net/

Going to work on this over summer


----------



## Thrackan (Apr 11, 2011)

Nice one, I might take up that challenge.


----------



## Kreij (Apr 11, 2011)

I think might give it a shot also.


----------



## FordGT90Concept (Apr 11, 2011)

Kreij said:


> @ Ford : It's not 4x1051, it's supposed to be 4 * 10^51


Oh, well still, their claim that it is impossible is false.  I think the absolute longest it took my server to find a solution was 13 seconds.  How long it takes is depend on how good the random seeds are.


----------



## streetfighter 2 (Apr 11, 2011)

I recently wrote a graphing application and I wanted a way of dividing the Y axis of the graphing region into 10 regions (which requires 11 lines).  Since the graph can be resized it means that there could be one or more regions that are one pixel larger than the others.  If all of the wider/smaller regions are grouped close together and the size of the graph is small then the discrepancy is very apparent.  Here's my solution (in C with some pseudocode):

```
#define G_LINES_Y	10 //number of lines minus one
	
	//bottom = bottom of graph region (bottom is a higher number than top because this uses win32 screen coordinates with origin at the upper left corner)
	//top = top of graph region
	int yBumps = ((bottom-top) - G_LINES_Y) % G_LINES_Y; //lines drawn with uneven spacing
	int ySkip = ((bottom-top) - G_LINES_Y) / G_LINES_Y + 1; //spacing between between lines
	int yBumpSplit = yBumps/2;  //attempt to evenly distribute the uneven and even spacings
	int yAt = top;
	Draw Horizontal Line at "yAt" //pseudocode
	for (int i=0; i < G_LINES_Y; i++) {
		if ( (yBumps > 0) && ((yBumps > yBumpSplit) || (yBumps + i == G_LINES_Y)) ) //add uneven spacing at top or bottom
		{
			yAt += ySkip+1;
			yBumps--;
		}
		else
		{
			yAt+=ySkip; //even spacing
		}
		Draw Horizontal Line at "yAt" //pseudocode
	}
```
This creates the same effect that you see on the Y axis of the MSI Afterburner graph window when you detach and resize it.  



FordGT90Concept said:


> Lies.


The knights tour would appear to be a problem that is well suited to quantum computing.  There could come a time when brute forcing an nxm board when n>>1 and m>>1 is trivial (assuming there is a solution).

Also, "on an 8 × 8 board, there are exactly 26,534,728,821,064 directed closed tours" (wikipedia).  Using a bit of math we can determine that a single brute force attempt has a 6.6*10^-37% chance of success.  Good odds for any Spartan.


----------



## FordGT90Concept (Apr 11, 2011)

Just for the hell of it, I ran the app on my Core i7 920 at stock and got:

Attempts before success: 108155
Time to find a solution: 10.6806109 seconds
Successful random seed: 1253801390
Solution:

```
+----+----+----+----+----+----+----+----+
|  0 | 47 | 58 | 49 |  2 | 43 | 14 | 29 |
+----+----+----+----+----+----+----+----+
| 59 | 50 |  1 | 44 | 13 | 30 |  3 | 42 |
+----+----+----+----+----+----+----+----+
| 46 | 57 | 48 | 51 | 22 | 41 | 28 | 15 |
+----+----+----+----+----+----+----+----+
| 63 | 60 | 45 | 12 | 31 | 16 | 23 |  4 |
+----+----+----+----+----+----+----+----+
| 56 | 11 | 62 | 21 | 52 |  5 | 40 | 27 |
+----+----+----+----+----+----+----+----+
| 61 | 20 | 55 | 32 | 17 | 24 | 37 |  6 |
+----+----+----+----+----+----+----+----+
| 10 | 33 | 18 | 53 |  8 | 35 | 26 | 39 |
+----+----+----+----+----+----+----+----+
| 19 | 54 |  9 | 34 | 25 | 38 |  7 | 36 |
+----+----+----+----+----+----+----+----+
```
Move list:


Spoiler



RightDown
RightUp
RightDown
DownRight
LeftDown
RightDown
DownLeft
LeftUp
LeftDown
LeftUp
UpRight
RightUp
UpRight
RightUp
DownRight
LeftDown
DownLeft
LeftDown
LeftDown
UpRight
RightUp
UpRight
RightDown
DownLeft
DownLeft
RightUp
UpRight
UpLeft
UpRight
LeftDown
DownLeft
DownLeft
LeftDown
RightDown
RightUp
RightDown
UpLeft
DownLeft
RightUp
UpLeft
UpLeft
RightUp
LeftUp
LeftDown
DownLeft
LeftUp
UpRight
DownRight
UpRight
LeftDown
RightDown
DownRight
DownLeft
LeftDown
UpRight
LeftUp
UpRight
UpRight
LeftDown
DownRight
DownLeft
RightUp
LeftUp
Invalid


My code must be exceptionally good. XD

It wouldn't be hard to increase the board size.  It'll just cause a (potentially) exponential growth in time it takes to solve.


----------



## Kreij (Apr 12, 2011)

Fourstaff said:


> http://projecteuler.net/
> 
> Going to work on this over summer



I had to troubleshoot database update problems all day and had the shipping computer (which manages all our UPS information) take a complete crap on me ... still managed to successfully code three of these. 
(okay, they weren't that hard, but I was crazy busy. lol)
Taking a break from running around like a madman and taking a few minutes to code something like these challenges is quite relaxing. Well for me anyway. 

This already has my little hampster wheel spinning like crazy for a coding contest. 

More nostalgia ...
When I was working a GE doing computer maintenance on the MV4000 minis that ran the MRI scanners, there was one technician who would come in everyday and type in "Hello Computer" at the command prompt.
He would then laugh when the computer responded with "Command not found, 'Hello'" and comment on how stupid computers where.
So ... I wrote a little script named "Hello". (insert evil laughter)
If there were no arguments, it would simply reply "Hello".
If the argument was "Computer", it would response with, "I am not a computer, I am an MV4000".
If the argument was "MV4000", it responded with "Hello Human".
Needless to say the morning after I put the script on his computer, he just about shit a brick when he completely fell for it.
Users are so predictable.


----------



## Polaris573 (Apr 12, 2011)

That's hilarious.


----------



## Kreij (Apr 12, 2011)

To this day I still have a lot of fun with error handling in the apps I write.
If a user is supposed to enter a number and they enter a string (or whatever) the messages will usually be something like "Whoa Hoss, can you take a moment to give me an input that is actually useful?"

The users actually like it that way. Breaks up a boring day of data entry with a little humor.


----------



## xbonez (Apr 12, 2011)

Fourstaff said:


> http://projecteuler.net/
> 
> Going to work on this over summer



I used to solve a lot of project euler puzles earlier. Definitely some great puzzles, but keep in mind that most of these won't challenge you as a programmer, but rather as a mathematician.

Most of the puzzles at euler are fairly simple to code if you just brute force them, but the real challenge is in getting to run them as fast as possible, which more often than not, requires mathematical optimizations on paper before you get down to coding.


----------



## Fourstaff (Apr 12, 2011)

xbonez said:


> I used to solve a lot of project euler puzles earlier. Definitely some great puzzles, but keep in mind that most of these won't challenge you as a programmer, but rather as a mathematician.
> 
> Most of the puzzles at euler are fairly simple to code if you just brute force them, but the real challenge is in getting to run them as fast as possible, which more often than not, requires mathematical optimizations on paper before you get down to coding.



My tutor once said that if you can do maths and code for it, you will be able to find employment everywhere


----------



## Thrackan (Apr 12, 2011)

Most of those puzzles use maths in a logical manner. Programming is 99% applying logic to your problem, and 1% writing the correct syntax.

I like this Euler thingy  Much more interesting than my boring job...


----------



## streetfighter 2 (Apr 12, 2011)

xbonez said:


> Most of the puzzles at euler are fairly simple to code if you just brute force them, but the real challenge is in getting to run them as fast as possible, which more often than not, requires mathematical optimizations on paper before you get down to coding.


There's a non-trivial tradeoff with simplicity and performance.  I can't remember how it goes precisely, but there's a programming adage about how the performance of code is inversely proportionate to it's readability.  Since my brain don't work none too good I tend to program for legibility unless the performance penalty is serious (ie. O(n) >> O(log(n)) when n>>1).  In the really dense parts of my code I put a comment on every line .



Thrackan said:


> Programming is 99% applying logic to your problem, and 1% writing the correct syntax.


That 1% can be a real pickle.  In fact you can waste a lot of time not knowing that there was an API/library that'd do it.


----------



## Thrackan (Apr 12, 2011)

streetfighter 2 said:


> There's a non-trivial tradeoff with simplicity and performance.  I can't remember how it goes precisely, but there's a programming adage about how the performance of code is inversely proportionate to it's readability.  Since my brain don't work none too good I tend to program for legibility unless the performance penalty is serious (ie. O(n) >> O(log(n)) when n>>1).  In the really dense parts of my code I put a comment on every line .
> 
> *
> That 1% can be a real pickle.  In fact you can waste a lot of time not knowing that there was an API/library that'd do it. *



So true  Basically step 1 is learning to write code, and step 2 *should* be learning to properly search documentation 

EDIT: currently cracking my head on Euler problem 9...


----------



## Zyon (Apr 15, 2011)

Anyone feel like trying something easier? How about Mandelbrot?

If memory serves me correctly it's only a few lines of math function but then it was a pain trying to render it using Pascal.


----------



## Disparia (Apr 15, 2011)

Finally had some time to write out a maze dungeon of pain and despair generator.







Next up the hero, enemies, movement, attack, etc, logic.


----------



## Brandenburg (Apr 15, 2011)

Kreij said:


> To this day I still have a lot of fun with error handling in the apps I write.
> If a user is supposed to enter a number and they enter a string (or whatever) the messages will usually be something like "Whoa Hoss, can you take a moment to give me an input that is actually useful?"
> 
> The users actually like it that way. Breaks up a boring day of data entry with a little humor.



I prefere a different approach to data validation now adays....I never give the user the option to enter the wrong data

snippet of code i wrote for a physics program several months ago that will only allow numeric...

```
Private Sub txtMagnitude_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtMagnitude.TextChanged

        Dim sTempString As String
        Dim iLength As Integer
        sTempString = sTempString + txtMagnitude.Text
        If Not IsNumeric(txtMagnitude.Text) And bVectorFlag = False And txtMagnitude.Text <> "-" Then
            iLength = sTempString.Length()
            If iLength > 0 Then
                sTempString = sTempString.Substring(0, iLength - 1)
                txtMagnitude.Text = sTempString
                txtMagnitude.SelectionStart = iLength
            End If
        End If
```

and some code I borrowed from the net...  this code is a snippet from a game I was writting that allowed only the characters A-Z to be entered.. Odly enough the code above could NOT be modified to do this.. I tried and tried but it never worked 100% of the time like it should of


```
Private Sub txtName_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtName.KeyPress

        If Char.IsLetter(e.KeyChar) Then
        Else
            e.Handled = True
        End If

    End Sub
```


----------



## Kreij (Apr 15, 2011)

I do that on occasion too.
For numbers, I usually use;
try
{
Convert.ToInt32(string);
}
catch (FormatException) {}

In C# if a Textbox is bound to a database column of type integer it won't let you type in anything but numbers automagically.

I usually use humorous errors messages when the user enters the correct type, but the data is meaningless or logically wrong (like from-to dates where the from date is cronologically later than the to date).


----------

