Checking for Palindromes and Primes
Posted by Jonathan Ng | Filed under Technical
What’s a palindrome you say? From wikipedia:
A palindrome is a word, phrase, number or other sequence of units (such as a strand of DNA) that has the property of reading the same in either direction (the adjustment of punctuation and spaces between words is generally permitted).
Examples of palindromes: “hannah”. You reverse it, you get “hannah” also. So what we’re required to do (for Data Structures and Algorithm), is to read a string and check if it’s a palindrome. I found 3 ways to do it (hey, that’s what algorithm is all about):
The first way, which I think is the quickest method, compares character for character, and returns when a match isn’t found. In Java, something like 5 / 2 returns 2. Note: assume input is the user’s input string. Read the rest of this entry »
Tags: algorithm
Delegates
Posted by Jonathan Ng | Filed under Technical
Sometimes, you want write a method that will receive another method as a parameter. You might not know at compile time, what that method is. Remember in object oriented programming, methods do not exist in isolation, but are associated to objects. Hence, you won’t know what object the method belongs to either. However, in order for your method to work, you have certain expectations of the method that you receive as parameter before making a call to it. This means that you’ll know what goes in to the method, at what it returns.
That’s where delegates come in. A delegate is a special type of object where you wrap up these details (including the method signature for type safety) of the method you want to be passed around. So in the example above, you declare a delegate (outside of the method), say DelegateA. Then in your method signature, you specify that it expects a delegate of type DelegateA. Hence, it can be said that delegates gives a name to a method signature.
Delegates are type safe in the sense that they validate the signature of the method being called. However, delegates do not care about what type of object the method is being called against or even whether the method is a static method or instance method.
One way of using delegates is to group methods together in an array, so you can call several methods in a loop. As delegates are objects, not only can you create an array of delegates, you can pass them as parameters to other methods. Read the rest of this entry »