Programming Logic

Note: I think this page is just about done. I still need to fill in some gaps but if you see anything that you feel should be included, feel free to tell me about.

This page is quick reference for common programming logic.  Keep in mind every language is different but the majority of what is covered here is more than likely covered in some fashion in the language your working in.

Relational Operators

Equal To ‘==’
Not Equal To ‘!=’
Greater Than ‘>’
Less Than ‘<‘
Greater Than Or Equal To ‘>=’
Less Than Or Equal To ‘<=’
Equivalent Values ‘===’
Not Equivalent Values ‘!==’

The ‘===’ is a relational operator in JavaScript and PHP. Lets say you have a string of the number ‘1’ and an integer of the number ‘1’. The ‘===’ operator ignores the data type and tries to compare the values. In this case, $match will be assigned a boolean true value. Likewise, the “!==” works in a similar fashion but will check if they are the same values. The variable match will be set as Boolean true value and notMatch should be false. Also take anything I say about PHP or JavaScript with a grain of salt. It’s been ages since I last did anything real in these languages but this should be right, expect for maybe the names I called them. I just referrer to them as an equivalency operator in my head and you might have look this one up.

$match = ( "1" === 1 )
$notMatch = ("1" !== 2)

Also the equal to operator won’t always work in the fashion you think it will. Google search how to create a comparable object or do a comparison operation in your programming language.

Incremental and Decremental Operators

There are generally two methods built-in that can increment and decrement numbers, pre and post.

Pre-Increment
++i
Post-Increment
i++
Pre-Decrement
--i
Post-Decrement
i--

Bitwise Operators

AND ‘&’
Inclusive OR ‘|’
Exclusive OR ‘^’
Left Shift ‘<<‘
Right Shift ‘>>’
Unary ‘~’
Note: These bitwise operators examples in C

Logical Operators

Logical AND ‘&&’
Logical OR ‘||’

If Statements

Generic If Statement
If statements are used to check the condition of a variable or function.

if( x == y )
  // Do something if true

If Else Statement

The else statement is what will be executed if the condition in the if statement isn’t matched.

if( x == y )
  // Do something if true
else
  // Do something if not true

Else IF Statement
Else if statements are just another if condition to check against.

if( x == y )
  // Do something if x == y is true
else if( y != x)
  // Do something if y == z is true

As you can see, at the core of if statements are Boolean logic. You can also throw a Boolean data type in the statement to simply things.

boolean bool = True;
if( bool )
  // Will do something if bool is true
else if ( !bool )
  // Will do something if bool is false
else
 // Will never be executed!

Tenary Operator
Personally, I love tenary operators but they might be somewhat confusing compared to if statements. In a nut shell, tenary operators are just short hand of if ‘?’ then ‘:’ else statements. The code left of the ‘?’ mark will the condition your checking in this case I’m checking if 10 is less than 5. The code to right of the ‘?’ mark and left of the ‘:’ is what will happen if the test condition returns true. Since 10 isn’t greater than 5 this code will be ignored. The code left of the ‘:’ is the else part and will be executed. This this case, the variable max will be set with the 10.

int max = (10 < 5) ? 5 : 10;

Switch Statements

Switch statements are similar to if statements. Inside the switch parenthesis, the variable that we’re going to check is referenced. The case statements are the potential values for the given switch variable. In this case, the variable number is set to 1. The case statement referencing the integer 1 will be executed and “Hello World” will be sent to standard out. Also you can default case statement when the switch variable value isn’t defined in a case statement.

int number = 1;
switch (number) {
    case 1:
        printf("Hello World!\n");
        break;
    case 3:
        printf("Arrested Development is a good show.\n");
        break;
    default:
        printf("Annyeong is Korean for hello, Annyeonghaseyo.\n");

Iteration

I’m an iteration junkie and it’s one of my favorite parts of programming. There are many forms of iteration and here are a couple of them.

For Loop
The most common form of iteration. This java for loop will iterate over 6 loops. On each loop, i will be incremented by one and sent to standard out. Sample out put will be 0, 1, 2, 3, 4, and finally 5.

for(int i = 0; i <= 5; i++)
      System.out.println(i);

For Each Loop
For each loops iterate through the contents of an array. This C# for loop will iterate through the drives of the host machine.

for( var drive in System.Environment.GetLogicalDrives() )
      // Do something

While Loop
While loops are pretty useful as long as the condition described within the while parenthesis remains valid. Also you can use a single Boolean condition to control the loop.

Boolean bool = True;
int i = 0;
while( i < 10){
    System.out.println(i++);
}

Do While Loops
Do while loops operate very much like while loops. The main diffidence is the loop block is above the while condition.

int i = 0;
do{
    i++;
}
while( i < 10);

Iterators
You can also call and work with loop iteration directly with an iterator. This java example creates an iterator from a list and displays the contents to standard out.


List<Object> objs = new List<Object>();
obj.add("Something");
obj.add(1);

for ( Iterator<Object> iter = objs.iterator(); iter.hasNext(); ) {
      System.out.println( iter.next() );

Generators
I mostly work with generator functions in python and they are the bee’s knees of iteration. They work like a for each loop but you can control how they yield data. Anyway, keep in mind that that generators are data pushers. This python example is own of David Beazley’s creations. This code creates a generator function that walks through a directory.

import os
import fnmatch

# Generator Function
def dir_walker( pattern, tree ):
    for path, dirList, fileList in os.walk( tree ):
        for name in fnmatch.filter( fileList, pattern ):
            yield os.path.join( path, name )

# Generator Expression
seeker = dir_walker( "*.py", "/" )

for fileName in seeker:
    print(fileName)

Coroutines
I’m not sure if coroutines should be under the iteration, they work similar to iteration but in reverse. As I mention above, generators are data pushers and coroutines are data pullers. This python snippet is another one of David Beazley’s creations and will code a grep function using coroutines.

def coroutine(func):
#- Decorator function to supports coroutines.
#- Coroutines functions are a little strange in python and require to have next or send called on them.
#- This function is the example provided by David Beazley
    def start(*args,**kwargs):
        cr = func(*args,**kwargs)
        cr.__next__() # You can also use send to advance a coroutine
        return(cr)
    return(start)

@coroutine
def grep(pattern):
    #- This is where the magic happens.
    try:
        while True:
            line = (yield) # This is where the pattern string is passed in.
            if pattern in line: # Checking if pattern is in the current line
                print(line) # Prints the whole line if found

    except GeneratorExit:
        print("Closing the coroutine.")

if __name__ == '__main__':
    g = grep("Bueller") # This is where you pass in the pattern

    # - Sending in non-Bueller strings
    g.send("Whats the score?\n") # Dev Note: \n = new line
    g.send("Nothing and Nothing.\n")
    g.send("Who's winning?\n")
    g.send("The Bears.\n")

    #- Sending in a Bueller string
    g.send("Random quotes from Ferris Bueller's Day Off are fun!\n")
    g.close() # Closes the coroutine and causes the code stored in the GeneratorExit exception to execute

List Comprehension
List comprehension is a pretty cool way to solve problems. I only really see this form of iteration in python and erlang. This example will create a list of binary base digits.

baseDigit = [pow(2,x) for x in range(8)]
# [1, 2, 4, 8, 16, 32, 64, 128]

You can also use multiple list comprehensions together. This example will create a list of hex values for each base digit from the prior list.

hexDigit = [hex(x) for x in baseDigit]
# ['0x1', '0x2', '0x4', '0x8', '0x10', '0x20', '0x40', '0x80']

If you’re feeling fancy, you can even nest them together like this.

hexDigit = [hex(x) for x in [pow(2,y) for y in range(8)]]
# ['0x1', '0x2', '0x4', '0x8', '0x10', '0x20', '0x40', '0x80']

You can even nest some logic into list comprehension using tenary if statements. This example will create a lists filled with strings identifying each odd or even number it encounters

print( ['even' if ( x % 2 != 0 )  else 'odd' for x in range(8)] )
# ['odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even']

Lambda

Lambda expressions and functions can be pretty cool to play around with. They can let you make some really elegant one liners. With lambda you can even pass a function as an argument. This is a dumb example. I reworked my baseDigits in a different way completely different way. One thing I will say about this version is that I made it with using a map. I haven’t really made many maps in python but they seem kinda sucky too me.

baseDigits = map(lambda x: 2**x, range(8))
for base in baseDigits:
    print(base)

Recursion

A recursive function is one that calles it self.  Here is simple counter that will start listing out numbers

public void counter( int i ){
    System.out.println(i);
    counter(++i);
}

You can also define a two functions with the same name assuming if the have different parameters.  This example will use counter() to start the recursive counter function.

public void counter(){
    counter(0);
}

public void counter( int i ){
    System.out.println(i);
    counter(++i);
}

The counter case may or may not be the best example. If you run it yourself it, the code will try to run in an infinite loop. Here is another common recursive function that you might be familiar with. This code is an inefficient Fibonacci sequence function.

public void int fib(int n) {
if (n <= 1)
        return(n);
else
        return( fib(n-1) + fib(n-2) );
}

Poorly written counters and Fibonacci numbers aren’t that interesting, so lets make a fractal with recession. This code snippet is part of a basic JApplet I wrote one night that will make a triangle inside a triangle, or Sierpinski triangle if you want to sound smart. All that this one does is draws a line between the midpoints of a triangle. I also did a blog a post about it you want to see the full to code.

https://betamoore.wordpress.com/2012/04/17/sierpinski-triangle-in-japplet/

 
I’ve also made a better version of this program written in JavaScript while playing around with the HTML canvas. The code is kinda scattared across multiply posts but it should be to hard to find them since I haven’t publish much JavaScript code here.

https://betamoore.wordpress.com/tag/javascript/

	public void draw(Graphics graph, int level, Point pt1, Point pt2, Point pt3) throws InterruptedException {

		if (level > 0){
			//Connecting the dots, la-la-la-la
			Thread.sleep(500);
			graph.drawLine(pt1.x, pt1.y, pt2.x, pt2.y);
			graph.drawLine(pt2.x, pt2.y, pt3.x, pt3.y);
			graph.drawLine(pt3.x, pt3.y, pt1.x, pt1.y);

			// Mid-points between given points
			Point pt1_pt2 = new Point( (pt1.x + pt2.x) / 2,
					                   (pt1.y + pt2.y) / 2 );
			Point pt2_pt3 = new Point( (pt2.x + pt3.x) / 2,
					                   (pt2.y + pt3.y) / 2 );
			Point pt3_pt1 = new Point( (pt3.x + pt1.x) / 2,
					                   (pt3.y + pt1.y) / 2 );

			//Recursively graph midpoints
			draw(graph, level - 1, pt1, pt1_pt2, pt3_pt1);
			draw(graph, level - 1, pt2, pt2_pt3, pt1_pt2);
			draw(graph, level - 1, pt3, pt3_pt1, pt2_pt3);

Exception Handling

You’ll probably be using exception handling pretty often. Since the idea of bug free software doesn’t exists, you’re left trying to code in a fault tolerance way. The most common form of exception handling is try/catch/finally statements. The pythons case, the catch is called except. This example attempts to add two variables. If we call foo(2,3) the number 5 will be returned. Likewise, if we call foo(2, “ASDF”) will return False. Also the finally statement will print a string when the function is about to close.

def foo(x,y):
	try:
		return(x+y)

	except:
		return(False)
	finally:
		print("We are done here!")

Threads

Threads are an aspect of concurrent programming in many languages, expect for maybe Python. Threads are just resides within a process and they can share resources between other treads. Likewise you can really share resources between processes. Python is singled thread for the time being and they’re attempt around threads is to throw process. You can do some really neat things with coroutines if you try to make python concurrent.

http://en.wikipedia.org/wiki/Thread_(computing)
Here is some poorly written Java that shows the down side of threads. If you try using multi-threading with the Deadlock class the program will lock up. I also did a blog post on this one if you want to how to make a thread safe program.

https://betamoore.wordpress.com/2012/04/17/sierpinski-triangle-in-japplet/

public class Deadlock {
    static class Friend {
        private final String name;

        public Friend(String name) {
            this.name = name;
        }

        public String getName() {
            return this.name;
        }

        public synchronized void bow(Friend bower) {
            System.out.format("%s: %s"
                + "  has bowed to me!%n",
                this.name, bower.getName());
            bower.bowBack(this);
        }

        public synchronized void bowBack(Friend bower) {
            System.out.format("%s: %s"
                + " has bowed back to me!%n",
                this.name, bower.getName());
        }
    }
}

Also I would recommend watching or reading David Beazley’s talk on Python’s GIL.  It’s crammed with great information.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s