23 Beginner's Programs

[Home]   [Puzzles & Projects]    [Delphi Techniques]   [Math topics]   [Library]   [Utilities]




Search WWW

Search DelphiForFun.org

As of October, 2016, Embarcadero is offering a free release of Delphi (Delphi 10.1 Berlin Starter Edition ).     There are a few restrictions, but it is a welcome step toward making more programmers aware of the joys of Delphi.  They do say "Offer may be withdrawn at any time", so don't delay if you want to check it out.  Please use the feedback link to let me know if the link stops working.


Support DFF - Shop

 If you shop at Amazon anyway,  consider using this link. 


We receive a few cents from each purchase.  Thanks


Support DFF - Donate

 If you benefit from the website,  in terms of knowledge, entertainment value, or something otherwise useful, consider making a donation via PayPal  to help defray the costs.  (No PayPal account necessary to donate via credit card.)  Transaction is secure.

Mensa Daily Puzzlers

For over 15 years Mensa Page-A-Day calendars have provided several puzzles a year for my programming pleasure.  Coding "solvers" is most fun, but many programs also allow user solving, convenient for "fill in the blanks" type.  Below are Amazon  links to the two most recent years.

Mensa 365 Puzzlers  Calendar 2017

Mensa 365 Puzzlers Calendar 2018

(Hint: If you can wait, current year calendars are usually on sale in January.)


Feedback:  Send an e-mail with your comments about this program (or anything else).

Search DelphiForFun.org only





Beginners  often need "bootstrap" examples to get them started.  I've written dozens of these simple apps to provide this kind of sample code over the years.  This page may provide a place to post those that seem most useful.  

 Recently I've received several requests for help with a few Delphi techniques that are not too difficult once you do one.  Here are the current offerings: 

bulletImage manipulation (Parking Lot) - how to draw a picture and respond to clicks on a TImage control.
bulletTChart - graphing a function or other data by passing an array of values.  
bulletBackTracking Demo illustrates a Depth-first search for a path  through an array meeting certain conditions.
bulletDrawDice   draws random dice images.
bulletCountWords counts words in input text.
bulletExpressions 864 finds all permutations which sum to a given value and use all digits 1-9 exactly once in the equation. 
bulletAllwords displays all letter permutations or valid words only from a given set of letters.  
bulletMemLeakDemo illustrates the hazards of allocating and not freeing memory, and how to tell if it is happening..
bulletDraw Olympic Rings shows how to use "ellipse" and "arc" procedures to draw an image of the Olympic Rings logo.
bulletSimple Decrypt  implements an ancient shift cipher, "Caesar's Cipher" to encode or decode text messages. 
bulletDigit Sums counts the number of integers of given length whose digits sum  to any given value.
bulletReversed Words uses the ReverseString function and our TDict dictionary component to find valid words whose letters are reversed in given lines of text.
bullet3N + 1 explores the "Collatz Conjecture" that a sequence formed by two simple rules always degenerates the value 1. 
bulletExecutive bathroom finds 3 digit odd integers with no repeated digits (the secret combination for the executive bathroom J).
bulletTwofers (Two for the price of one): Two simple problem questions each with exactly two solutions. 
bulletDigit Products: another Mensa Puzzle-A-Day calendar puzzle, slightly extended here.    
bulletPecking Order:  Uses the "Mod" operator to help solve a poetic puzzle which could also be solved by plain old algebra if you work carefully.
bulletSquared Chess Pieces:  Another 35 line program solving a puzzle which might be very hard without a computer!
bulletDictionary Word Search: About 50 lines of user written code lines required to search for all occurrences words of a give length range with a given range of vowels and/or consonants.   
bulletCount Grid Cells:  Builds "keys" for grid rows replacing consecutive empty cells with the count (as in Chess FEN notation).
bulletCopy Truncated Strings: 25 line user requested program to remove short lines and truncate long lines from a text file.
bulletPancake Odds:  Easier than I thought to simulate selecting randomly flipped  pancakes to see what fraction are perfect. 
bulletSearch State Abbreviations: The U.S. Post Office has established standard two-letter abbreviations for each state but only one state contains the abbreviations for 4 states. This 50 line program finds it.
bullet Clocks - Fast and Slow:  Two clocks start at the same time but run at different speeds.  How long before they show the same time again? 

Features and techniques illustrated are used in a number of programs on DFF, but it's easy to lose the essential characteristics in programs that may have 1,000 or more lines of code.   Each of these programs contains less than 100 lines.

Scroll down to see all offerings.

Image Manipulation (Parking Lot)

The Image program is a "Parking Lot Simulation" that draws some parking spaces on the canvas of a TImage control.  Clicks on the spaces then show or hide automobile pictures in the spaces.   A TImage has the advantage over a TPaintBox because it can refresh itself when necessary.  Once the canvas has been drawn or modified, the image will be managed by TImage redrawn without our help if the image is moved or minimized or has other forms popup over it.     This is not the case with a TPaintBox where it is the programmer's job to make sure that it knows how to repaint itself at any time.

Click here to download Parking Lot Simulation source code

TChartDemo1 and TChartDemo2

TChart is a powerful graphing and charting facility distributed with most versions of Delphi.   It is so powerful that the hundreds of options can be rather intimidating for the beginner.  Fortunately most features have reasonable defaults and need not be changed.  Most of the rest can be defined a design time in a TChart Edit component that is accessible by a right click or double click on the TChart control image on the form.  Any of the properties can also be defined at run-time.  In this  demo, TChartDemo1,  line plots of two functions are drawn and some of the titles etc. are set via code just to illustrate the technique.

Addendum December 2, 2005: A viewer recently asked about getting user input data from a list box or memo into a chart.  Here's TChartDemo2 which shows a few additional techniques for charting user data.   It includes a "missing" Delphi function, StrToFloatDef. which tries to convert an input string to a floating point number and returns  either the numeric value of the string or a default value if the input string does not represent a valid number. 

  Click here to download TChart Demos source code


Four cells in a 4 x 4 array are randomly loaded with the letters 'A', 'B', 'C', and 'D'.  Four additional cells are loaded with the letter ''X' - these are blocked cells and may not be occupied. The other 8 cells may be passed through while picking up the A, B, C, D cells.  We need to find a path from 'S'  through all of the A, B, C, D cells by moving horizontally and vertically and without visiting any square twice.

Click here to download  Backtracking Demo source code

DrawDice (June 8, 2005)

A simple program to draw two random dice each time a button is clicked.  
Click Here to download DrawDice source

CountWords (June 8, 2005)

How do you count words in a text document?  Like loving a porcupine - very carefully.  Here's simple start though, with a Getword routine which looks for a predefined set of delimiters marking the ends of  words.  Words from a text file are extracted and listed.  There is also a Summarize button that accumulates number of occurrences  by word.

Click here to  download CountWords source code.

Expressions864 (June 8, 2005)

Find all solutions where the sum of two numbers equals 864. And by the way, the 
solution, including the "864" sum must contain all of the digits 1 through 9 exactly 
once.  Other sums to try: 594, 783,  675, 927.  You can also check Brute Force for another mode generalized approach to solving the problem.  Expressions864.prb is now included among the  sample problems. 

Click here to  download Expressions864 source code.

Allwords  (September 30, 2005)  

Given a letter string, find all possible subsets of letters ("words") that can be formed.  Optionally, list only words that can validated against  a given dictionary.   This code is fairly simple because it uses two other pre-built units as helper "tools".  UComboV2 contains the class which generates the permutations which help us form the words.  UDict contains the dictionary class that lets us validate our trial words.     

Click here to download   AllWords source

Click here to download AllWords executable


Even though the use of records and pointers is less critical today than in the pre-object days, some schools still teach their use.  And the use of record pointers in the objects field of TStringlists is sometimes convenient.  

The cardinal rule when allocating memory within your program is to make sure that it gets released. One common way to create a memory leak is to allocate a record  using the New function and not releasing the memory (using Dispose).   

Students are sometimes confused by the fact that local variables within functions and procedure are automatically released by Delphi when you exit the routine. This applies to all of the memory that Delphi allocated on your behalf, but not to the memory you allocated. If you have local variable, P, and execute New(P) within the routine, Delphi will delete the 4 bytes occupied by P, but not the memory that P points to!   And if not deleted before you exit, that memory will remain allocated until the program ends.   

Here's a program that allocates 1000 byte records within a procedure with and without releasing them just to illustrate the problem.  It uses the AllocMemSize global variable to show increasing memory usage as the program runs.  

Click here to download MemLeakDemo source

Draw Olympic Rings (February 15, 2006)

Every two years. "Olympic Rings" leads the list of search phrases at DFF.  Drawing the rings in Delphi is an interesting drawing exercise, especially if we want them to appear to be interlaced.


Click here to download  Draw Olympic Rings source

Click here to download Draw Olympic Rings  executable

  Simple Cipher (March 12, 2006)

We have a decryption program elsewhere at DFF which checks all possible substitution ciphers and check results against a dictionary to determine success. The problem is, this approach can run for hours, and if the text contains words not in the dictionary, may not succeed at all.  My  Mensa "Puzzle-A-Day" calendar periodically contains messages encrypted with a simple "shift cipher", also known as the "Caesar Cipher" because Julius Caesar used it to encrypt message in ancient Roman times.  In the shift cipher, each letter is replaced by a letter at some fixed distance away in the normal "abcd..."  listing of letters.  For example,  if all plain text  "a"s were replaced by "c"s, then "b"s, becomes "d"s, "c"s becomes "e"s  etc. to produce the encrypted text.    

It takes less than 40 lines of user written Delphi code to scan lines of input text using all 25 possible encryption choices (26 if you count the one that maps each letter back to itself).  You provide the dictionary check scanning the outputs to determine which one is correct.  And, of course it will encrypt as well as it will decrypt!

Click here to download  Simple Decrypt source

Click here to download Simple Decrypt  executable

Digit Sums  (September 12, 2009)

A recent Mensa puzzle calendar asked  "How many 4 digit numbers are there whose digits sum to 34?" That one is not too difficult since the sum cannot  exceed 36 (for the integer 9999), but it started me thinking about other sums.  This program counts and lists the  number of integers of given length which sum to any value. About 25 lines of user written Delphi code answer the question for two through five digit integers.

For programmers, the code will clarify how to extract individual digits from an integer.  Also, after the last line is added to the output display memo, how to force the top line back into view.  

Click here to download  Digit  Sums source

Click here to download Digit Sums  executable

Reversed Words  (September 24, 2009)

Another 25 line program from a recent Mensa calendar puzzle page.  We are asked to find a 7-letter word which appears  reversed in text lines and which meet a given definition.  It was surely more fun to write a program than to manually search the text for the word.  I divided the problem into two parts:

  1. Find all 7-letter reversed letter strings which will define the solution candidates.  Adding StrUtils to the Uses clause gives us access to the ReverseString function so we can reverse the entire Text property of out input TMemo, then remove spaces, punctuation and the Carriage Return/LineFeed characters which mark end-of-line for lines in the TMemo.  Finally, step though the string picking off 7 characters at a time from each possible starting position and saving them in a TListBox
  2. Check the strings in the List box from the previous step using  the IsValidWord and Lookup function of our TDict dictionary class to find the combinations which are valid words.  We'll display these in a second list box.  For ease of use, I have included the  large dictionary Full.dic in the zip files below, Also dictionary unit, UDict, is included in the source code zip file.  Latest version of  UDict  will always be available in our DFF Library file and the dictionaries from the WordStuff page

Click here to download  Reversed Words source

Click here to download Reversed Words  executable

The 3N + 1 Problem (January 17, 2010)

There is a website at  http://uva.onlinejudge.org/ which provides a virtually unlimited supply of programming problems used to train for annual ACM Programming Contests.   I am not fond of the quasi competition provided by the Online Scoring facility at the site for a couple of reasons;  Free Pascal is the only Pascal family language supported and 2) your program is run against an unknown set of inputs and feedback is not helpful in debugging ("Wrong answer"), leaving one to guess about the nature of the problem.   This does simulate the contest environment, but as a learning tool leaves much to be desired.  The problems themselves however seem to be well done and provide lots of mental challenges while developing and implementing solutions. 

This problem is first in the set of problems.  It is an unproven conjecture that, staring with a positive integer, the sequence obtained by applying these rules  below will always degenerate to a final value of 1.  Rules to generate entry i+1 are:
bullet Ni+1= 3Ni+1 if Ni is even
bullet Ni+1= Ni /2 if Ni is even.    

The problem has been extensively studied as the Collatz Conjecture, See this Wikipedia entry for more information. 

This program has about 50 lines of user written code to collect the input values, evaluate the solution, and display it.   There is lots of room to explore here.  For example:

bulletDisplay the longest cycle found. 
bulletWhich N in a range has the highest Cycle_Length/N ratio?
bulletDoes the longest cycle in a range also have the highest maximum value?
bulletIf we define a "reversal" as a peak or valley within the sequence, how many are there?  Does the longest sequence have the most reversals?

Click here to download  ThreeNPlus1 source

Click here to download ThreeNPlus1 executable

The Executive Bathroom (April 14, 2010)

The entry code for the executive bathroom is a three-digit odd number with no repeated digits. If you want to try to break in, what is the maximum number of entry codes you'll have to try? (Remember that three-digit numbers cannot start with zero.)  Source: The Mensa Puzzle Page-A-Day Calendar for April 12, 2010.

It only takes 15 lines of code to determine and display the answer.  I also included the Mensa Calendar explanation as a hidden memo that becomes visible after the program solution is displayed.

Click here to download  Executive Bathroom  source

Click here to download Executive Bathroom executable


Twofers (May 3, 2010)

Two problems, each with exactly two solutions.  Solving each required only 10 to 15 lines of code.  Here are the questions:

bulletThere are only two 2-digit Fahrenheit temperatures (i.e. between 10 and 99) whose reversed digits give the rounded equivalent Centigrade value. What are they?
bulletWhat two pairs of positive integers, K and M, satisfy the equation 13K + 41M = 1000?

Click here to download  Twofers  source

Click here to download Twofers executable


Digit Products (June 18, 2010)

Less than 20 lines of code solves this extension of a Mensa Puzzle-A-day Calendar puzzle:

Among the 2 and 3 digit positive integers, there are one or two which are equal  to the product of their digits for some multiple from 2 through 9.  Find them.
Example: For N=24, Product ,PN=8 and for M=3, we have  N= M*PN.

April 29, 2011:  Three additional problems were added today in Version 2.  These are from Math and Logic Puzzles for PC Enthusiasts , (J.J. Cleasa, Dover Publications), originally published in 1983.  Each of these is solved with beginner's level code (30 user written lines or so).  My favorite is Problem 4 about the shopper who accidentally totaled her purchases by multiplying instead of adding, but still got the correct total! 

Click here to download  DigitProducts  source

Click here to download DigitProducts executable


Pecking Order (February 12, 2011)

The first problem in my latest  addition to my library, "Challenging Mathematical Teasers", is algebraic and poetic at the same time:

Pecking Order

Four sparrows found a dish of seed,
Fine bird food, no common seed.
Said Pip: "In turn each take 2 grains
And then a third of what remains
It's me as first, then Pep, then Pop,
With Pap the last and then we stop."

But Pap cried out: "It isn't fair.
Mine's two seeds less than half Pep's share."
Old Pip was boss, his word was law,
So little Pap got nothing more.
Poor Pap, his share was rather small!
How many seeds were there in all?

From: "Challenging Mathematical Teasers",
J.A.H. Hunter, Dover Pubs, 1980


Defining the equations, substituting, and calculating the coefficients should be enough to solve it algebraically, but one slip will lead to a dead end.  This "trial and error" solver program was quicker and surer way to the answer for me.  About 30 lines of code finds the answer in a millisecond or so.

Click here to download  Pecking Order source

Click here to download Pecking Order executable



Squared Chess Pieces (May 17, 2011)

A modernistic chess set has pieces in various geometrical shapes.  In particular, both the KING and the KNIGHT are squares of integers.  What numbers could these represent if each letter is replaced by a different digit?  (From Mathematical Bafflers , Angela Dunn,  1980, Dover Publications.  Used copies currently available via the above Amazon link starting at $.01!)

I had said that finding the solution would be very hard without the help of a computer but Dunn's solution is feasible.    Using the fact that the square root of KING must be between 32 and 99 (because the square must have 4 digits) and by checking them all, she find that there are "only"  36 whose squares contain no duplicate digits.  Plugging those into KNIGHT, we could find only one value for G and T which make KNIGHT a perfect square.  No, I still think that would be very hard and that my 35 line solution is quicker and less tedious!

This program will require downloading the DFF Library zip file to gain access to UCombosV2, a unit that will let easily generate and test the 151,000 ways to select 6 of 10 digits to find which of them provides the solution.

Click here to download  Squared Chess Pieces source

Click here to download the latest DFF Library zip file (DFFLibV15)

Click here to download Squared Chess Pieces executable


DictionaryWord Search  (July 28, 2013)

It only took 50 lines of user written code to prove that the solution given for this "Word Search"  puzzle is not as unique as the author thought!  I used our Dictionary object to find all the 7 letter words which contain a single vowel.  If we do not consider "Y"s to be vowels, there are over 200 solutions!  You will need the dictionary unit from our Library Zip file  to recompile the program.  I have included our  largest dictionary (file Full.dic with about 62,000 words) in the executable download.        

Click here to download  Word Search source

Click here to download the latest DFF Library zip file (DFFLibV15)

Click here to download Word Search  executable


Counting Empty Grid Cells (February 28, 2014)

A viewer working on a playback program for Chess games was having trouble building the keys for each rank using FEN notation.  FEN uses letters for the chess pieces (P for Pawn, B for Bishops, etc.) and numbers to represent the count of consecutive empty cells.   He didn't tell me that that was the objective though until I had written this little demo program which builds keys based on randomly placed letters on an 8x8 grid.

As a bonus, I finally took time to develop a simple way to remove that irritating highlight color that is drawn for every selected cell in a TStringGrid.  I like so much that I plan to add it to our DFFUtils utility library  unit.  

Download CountGridCells source

Download CountGridCells executable

Copy File Deleting and Truncating Strings  (August 30, 2014)

Here's an email I received the other day:

In my file is hundreds lines of tekst ... I have to cut each line to length 199 is smaller line, let it be delete from file and finally let program save new 'situation' of text ... If string is longer than 199 let it be cut to 199 of length ...

May I ask U for help? Dont know how to start with... TStringlist?

Clearly not a native English speaker but I guarantee that his English is better than my version of his native language would be! I believe he wants to delete lines less than 199 characters long and save all the others, truncating them to 199 characters if they are longer.   I suggested using procedures Readln and Writeln  procedures to copy the records, acting on each line as required. The barebones program below has about 15 lines of code to accomplish this using fixed input and output file names and defining "short" records and less than 40 characters.   Another 10 lines or so counts and displays input, deleted and written record counts.    The Delphi source code is provided as the sample "My Input File.txt" file.

Download  CopyTruncatedStrings source and executable 


Pancake Odds (September 30, 2014)

Marilyn Vos Savant of Parade magazine fame published a probability problem aboit selecting really good pancakes if some are burned on one or both sides.  It took just 25 lines of code to calculate the answer (and varify that once again, Marilyn got right)!

Download PancakeOdds source

Download PancakeOdds executable


State Abbreviation Search (May 31, 2015)

A surprising number of U.S. state names contain multiple pairs of letters which form standard two-letter state abbreviations. For example ALABAMA contains two: AL and MA (Alabama and Massachusetts).  If we disallow overlapping abbreviations, there is only one state name that contains four abbreviations.  This 50 line program finds it using  "Name=Value" type of TStringLists.    Source: The Mensa Puzzle Calendar entry for May 30,2015.

Download StateAbbreviationSearch source

Download StateAbbreviationSearch executable

Clocks - Fast and Slow:

In this puzzle we have two clocks. One loses two minutes every hour and the other gains two minutes every hour. If both clocks start while showing 12:00, how many hours will i be before both clocks again show the same time?

This program simulates the two clocks by incrementing the times by 62 minutes (Clock 1) or 58 minutes (Clock 2) for each real 60 minute interval. Starting at time 0:0, clock times are displayed for every "real" hour until they again match.  Here's an exercise in converting time of day in minutes to HH:MM format using Mod and Div operations. Also reformatting text and moving display back to 1st line for a TMemo.   Oh, it also solves the puzzleJ

Download ClocksFastSlow source

Download ClocksFastSlow executable 


Created: March 5, 2005

Modified: May 15, 2018


  [Feedback]   [Newsletters (subscribe/view)] [About me]
Copyright 2000-2018, Gary Darby    All rights reserved.