Showing posts with label tutorial. Show all posts
Showing posts with label tutorial. Show all posts

03 July 2011

iPhone application tutorial - Body Mass Index Calculator : Part 7


The first posting's output and this may vary since that was developed with XCode 3 and this one with XCode 4. There are slight differences between both of them, but that we don't want to know. You can download XCode 4 for $5 from Apple's website.

I wanted to keep this final section very light. Hence going to show only the output here. :)





Click here to download the entire source code for this project. It is free to develop and distribute. Hope you guys learnt something.

Cheers!!
Braga

iPhone application tutorial - Body Mass Index Calculator : Part 5

In the past section we saw how to design the view and set the basic things up. Now, its time to do some coding. Before that, to check whether everything are Ok, press the ⌘ + B button to build your project. It may prompt you to save the project. If it does, click the Save button. The build should succeed at this point. If it fails, then go and check the logs or tell me the error in the comments section, I would surely help you out!

Now, back to business. We need to dynamically update the values in the UI. To attach this with the code, we have a binding object defined called as IBOutlet. Using this object, we would be able to set stuff in the code and see it change in the UI. Looks magic. To start binding the UI components and the code. Click on the Editor icon the right top side to see both the Interface Builder and the Interface file side by side.


Select your component on the UI - the height label. Hold down the control key and draw a line from the component to the Interface definition, you should be seeing a line coming up automatically for it to be inserted as shown below.



Lets name that IBOutlet variable to be height. Do the same for weight, bmi and the result labels. So, we are done with defining our binding variables namely the IBOutlet. Now whatever change you do for these outlets will now be reflected in the UI. We have one more thing left from the hooking up perspective - the Sliders. We need to assign an action when we slide the height and weight sliders. It is pretty simple. Select the height slider, choose the properties from the side and click on the Value changed option and drag it to the interface code. All you should be naming here is the method name which would be height slider. Note, you do not need to press Control key as we did for the Outlets.


You would need to add a couple of more methods in your interface file. The final code would look something like the following


Cheers!
Braga

iPhone application tutorial - Body Mass Index Calculator : Part 4

Welcome to the part4 of the BMI Calculator iPhone application tutorial. We saw in the last section on how to set components on the UI. I had said that there was a small thing mentioned about the slider.

Before I tell more about it. Lets strategize how our application should behave. You slide two things in your application namely the heights and weights, the user will be seeing his body mass index calculated and will be given the result on whether he is normal or underweight or obese etc. We will be needing to determine the upper and lower bounds of the heights and weights. I have taken the height range as 120-210 cm and the weight range as 30-130 kg.

Whenever you click on any component, it corresponding property should be appearing at the right hand panel. Go ahead and click on the height slider. Set the minimum and maximum values of the slider as we discussed before.

You would also need to set the initial value. Since it needs to be in the center, set the height as 165 (average of 120 and 210). Same you would need to do by selecting the weight slider. 30-130 as lower upper bounds with 80 as the current value.

Thats it we are done designing our wonderful UI for the iPhone Application. We have some UI-Code hookup and some coding left before we declare our application is complete which we will be doing in the coming posts.

Cheers!
Braga

iPhone application tutorial - Body Mass Index Calculator : Part 3

Welcome to the part 3 of the tutorial. You could be thinking, "what the hell did I learn in Part 2?" Well. Lets take one baby step at a time. The second part of the tutorial's project name read "Body Mass Index Calculator". But then I had to change it to helloworldXcode, the name would not mind much, but whatever you choose, choose it wiser.

On the left hand top side of the you should be able to see your project. Expand it and you should be seeing your interface file (.h), Implementation file (.m) and the UI file (.xib). Clicking on any of these will bring up the corresponding code or UI on the main panel.


Go ahead and select the .xib ViewController file. You should now see an empty Canvas appearing on the center of the editor where you can drag and drop stuff. For our body mass index we need few UILabels that are going to be static and few UILabels that are going to change dynamically on the user action.
For dragging and dropping components on to the View you should select the Object from the drop down on the right hand side bottom corner as shown below.

We also will need a couple of slider for selecting the height and weight. Already sounds cool eh? Here is a screenshot on what stuff you should be dragging and dropping on the center of the editor.


After dropping the elements which includes totally 9 labels and two sliders you should be aligning them like shown in the following screenshot. The placement of the labels depends totally on your imagination and creativity, but lets make it professional looking so that our application should sell at least a million times in the App store. That was a joke :)



You could notice that changing the names of the labels are very simple. Just double click on it and start typing as shown in the above screenshot. With this your basic set up of the view is complete, we just have a few more things left regarding the slider functionality, but we will cover it in the next section.

Cheers,
Braga

iPhone application tutorial - Body Mass Index Calculator : Part 2

Welcome to the second part of the BMI Calculator Application for iPhone tutorial. I assume that you have XCode installed in your mac or Mac under VMWare. Launch XCode and select a new View based project.


Click on Next. Fill up the basic details and move on.


Once you have selected where to save your project, you should see something like this. Note: We are using Xcode 4 to develop this application, the view may vary from the previous version of Xcodes.


Thats it in this part of the tutorial. Lets start using the Interface builder and do some coding in the coming posts.

Cheers,
Braga

02 July 2011

iPhone application tutorial - Body Mass Index Calculator : Part 1

After an extensive learning on Objective C and covering the basics of iPhone development, I wanted to get my hands dirty with a working application. Following the concept of Minimal Marketable Subset, I thought I would develop a very primitive Body Mass Index calculator. Ok, into business

Our Final BMI Calculator Application is going to look like this.



Prerequisities

Since this is a very narrow development environment (yes you cannot develop this with windows), I would want to give a brief on what you will need, both hardware and software. First of all, you would need a Macbook or a Macbook Pro. A basic Macbook would do. Its based on how far you go. If you are very serious into iPhone development, then I would recommend you get a Macbook Pro. On the software side, you would need the XCode development suite. You can get it from Apple's website, it is free to download. It asks you to create an Apple Id. Go to youtube or google, you should find tons of resources there.

If you want to create clean iPhone Applications, you should have a very strong C Programming Background. And it would be nice if you are familiar with Object Oriented Concepts. You would need to learn Objective C basics and then the basics of iPhone development. Believe me, those links are simply too good. You can learn them both in just a day if you are freak like me.

Armed up with these basics, we can dive into the tutorial right away from the next post.

Cheers,
Braga

10 September 2010

Trie data structure - In C++




Having had a comprehensive coverage of the TRIE data structure in Java, me and my roommate thought it would achieve completion if we have the same implemented in C++. Don't get carried away by the length of the code. Its as simple and easy as the equivalent one in Java. You may go through the comprehensive tutorial here. Trust me, it takes only 10 minutes!!.

Please feel free to ask any questions if you face difficulties in understanding any part of the resource. I would respond to you immediately.


Demonstration of trie operations

Cheers!!
Jack.

10 April 2010

TRIE data structure Part 6 : A Sample UI




Lets have a look at a sample application in Swing. We load the TRIE data structure using a dictionary word list. And using the application we can perform a search. This application is a very much prototypical just to check the insert() and search() operations.

Input file : words.txt

Sample Application


There are two possible outcomes to our search criteria, one true and another false. The following is the dialog shown when a word "article" is entered.

And when a word something like "dasdsa" is entered the following dialog is shown.


The Java code for the Trie Loader,

package dsa.tries;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class TrieLoader {
 
 public static Trie trieDSA;

 public static void main(String[] args) {
  TrieLoader trieLoader = new TrieLoader();
  trieLoader.load();
  new TrieTestFrame();
 }
 
 public void load(){
  trieDSA = new Trie();
  BufferedReader br = null;
  try {
   br = new BufferedReader(new FileReader(new File("src/properties/words.txt")));
   String eachLine = null;
   while((eachLine=br.readLine())!=null){
    trieDSA.insert(eachLine);
   }
  } catch (Exception e) {
   e.printStackTrace();
  } finally{
   if(br!=null){
    try {
     br.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }
}

The TrieTestFrame,

package dsa.tries;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class TrieTestFrame extends JFrame {

 private static final long serialVersionUID = 1L;
 
 private JPanel basePanel = new JPanel();
 private JTextField textField = new JTextField(20);
 private JButton button = new JButton("Check");

 public TrieTestFrame(){
  designUI();
 }
 
 private void designUI(){
  this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  this.setTitle("TRIE Test");
  
  button.addActionListener(new ActionListener() {
   @Override
   public void actionPerformed(ActionEvent e) {
    if(TrieLoader.trieDSA.search(textField.getText())){
     JOptionPane.showMessageDialog(basePanel, "The word you entered exist!!");
    }else{
     JOptionPane.showMessageDialog(basePanel, "The word you entered does not exist!!","Error",JOptionPane.ERROR_MESSAGE);
    }
   }
  });
  
  basePanel.add(textField);
  basePanel.add(button);
  
  add(basePanel);
  
  this.setSize(400,100);
  
  Toolkit tk = Toolkit.getDefaultToolkit();
     Dimension screenSize = tk.getScreenSize();
     int screenHeight = screenSize.height;
     int screenWidth = screenSize.width;
     setLocation(screenWidth / 2 - 200, screenHeight / 2 - 50);
  
  this.setVisible(true);
 }
}

For the Node and Trie class please click here.

Cheers,
Bragaadeesh.

TRIE data structure Part 5 : Complexity Analysis




Now that we've seen the basic operations on how to work with a TRIE, we shall now see the space and time complexities in order to get a real feel of how good a TRIE data structure is. Lets take the two important operations INSERT and SEARCH to measure the complexity.

INSERT operation first. Lets always take into account the worst case timing first and later convince ourselves of the practical timings. For every Node in the TRIE we had something called as Collection where the Collection can be either a Set or a List. If we choose Set, the order of whatever operation we perform over that will be in O(1) time, whereas if we use a LinkedList the number of comparisons at worst will be 26 (the number of alphabets). So for moving from one node to another, there will be at least 26 comparisons will be required at each step. 

Having these in mind, for inserting a word of length 'k' we need (k * 26) comparisons. By Applying the Big O notation it becomes O(k) which will be again O(1). Thus insert operations are performed in constant time irrespective of the length of the input string (this might look lik an understatement, but if we make the length of the input string a worst case maximum, this sentence holds true).

Same holds true for the search operation as well. The search operation exactly performs the way the insert does and its order is O(k*26) = O(1).

TRIE data structure Part 4 : The SEARCH Algorithm




In the previous section we saw how to insert string into TRIE. In this section, we shall see how to perform a search in the TRIE when a string or key is passed.

Consider the following TRIE as usual.

The search alogirthm involves the following steps
  1. For each character in the string, see if there is a child node with that character as the content.
  2. If that character does not exist, return false
  3. If that character exist, repeat step 1.
  4. Do the above steps until the end of string is reached. 
  5. When end of string is reached and if the marker of the current Node is set to true, return true, else return false.
Using the above algorithm, lets perform a search for the key "do".
  1. See whether "d" is present in the current node's children. Yes its present, so set the current node to child node which is having character "d".
  2. See whether "o" is present in the current node's children. Yes its present, so set the current node to child node which is having character "o".
  3. Since "o" is the end of the word, see whether marker is set to true or false. Marker is set to false which means that "do" is not registered as a word in the TRIE. So, return false.


Using the same algorithm, lets perform a search for the key "ball"
  1. See whether "b" is present in the current node's children. Yes its present, so set the current node to child node which is having character "b".
  2. See whether "a" is present in the current node's children. Yes its present, so set the current node to child node which is having character "a".
  3. See whether "l" is present in the current node's children. Yes its present, so set the current node to child node which is having character "l".
  4. See whether "l" is present in the current node's children. Yes its present, so set the current node to child node which is having character "l".
  5. Since "l" is the end of the word, see whether marker is set to true or false. Marker is set to true which means that "ball" is registered as a word in the TRIE. So, return true



public boolean search(String s){
  Node current = root;
  while(current != null){
   for(int i=0;i<s.length();i++){    
    if(current.subNode(s.charAt(i)) == null)
     return false;
    else
     current = current.subNode(s.charAt(i));
   }
   /* 
    * This means that a string exists, but make sure its
    * a word by checking its 'marker' flag
    */
   if (current.marker == true)
    return true;
   else
    return false;
  }
  return false; 
 }

The above java code does the search operation in the TRIE data structure. We shall look more into the running time and efficiency of TRIE in the next part.

Cheers,
Bragaadeesh.

02 April 2010

TRIE data structure Part 3 : The INSERT Algorithm




In this section we shall see how the insert() method on the TRIE data structure works. We shall take a specific case and analyze it with pictorial representation.

Before we begin, assume we already have an existing TRIE as shown below.

Lets see the steps on how to insert a word "bate". Any insertion would ideally be following the below algorithm.

  1. If the input string length is zero, then set the marker for the root node to be true.
  2. If the input string length is greater than zero, repeat steps 3 and 4 for each character
  3. If the character is present in the child node of the current node, set the current node point to the child node.
  4. If the character is not present in the child node, then insert a new node and set the current node to that newly inserted node.
  5. Set the marker flag to true when the end character is reached.
Now if you go through the already written code for this, you can have a better understanding by comparing it with the above algorithm.

public void insert(String s){
  Node current = root; 
  if(s.length()==0) //For an empty character
   current.marker=true;
  for(int i=0;i<s.length();i++){
   Node child = current.subNode(s.charAt(i));
   if(child!=null){ 
    current = child;
   }
   else{
    current.child.add(new Node(s.charAt(i)));
    current = current.subNode(s.charAt(i));
   }
   // Set marker to indicate end of the word
   if(i==s.length()-1)
    current.marker = true;
  } 
 } 

Now lets see how the word "bate" is getting inserted. Since the word "bate" is having length greater than zero, we can start inspecting each word.
  • See whether "b" is present in the current node's children (which is root). Yes its present, so set the current node to the child node which is having the character "b".
  • See whether "a" is present in the current node's children. Yes its present, so set the current node to the child node which is having the character "a".
  • See whether "t" is present in the current node's children. Yes its present, so set the current node to the child node which is having the character "t".
  • See whether "e" is present in the current node's children. No, its not present, so create a new node with character set to "e". Since "e" is the end of the word, set the marker flag to true.


The above picture shows how the word "bate" is inserted into the existing TRIE data structure. This example clearly shows how the insertion in a TRIE happens.
We shall take a look on the Search operation in the next part.

Cheers,
Bragaadeesh.

TRIE data structure Part 2 : Node and TRIE class in Java




In the first part of the TRIE ADT, we saw the basics of the TRIE data structure. In this section, lets get our hands dirty by directly looking at the TRIE data structure implemented in Java.

We already saw the Node structure of the TRIE ADT had a content (char), a marker (boolean) and collection of child nodes (Collection of Node). It now has one more method called as subNode(char). This method takes a character as argument would return the child node of that character type should that be present.

package dsa.tries;

import java.util.Collection;
import java.util.LinkedList;

/**
 * @author Braga
 */
public class Node {
 char content;
 boolean marker; 
 Collection<Node> child;
 
 public Node(char c){
  child = new LinkedList<Node>();
  marker = false;
  content = c;
 }
 
 public Node subNode(char c){
  if(child!=null){
   for(Node eachChild:child){
    if(eachChild.content == c){
     return eachChild;
    }
   }
  }
  return null;
 }
}

Now that we've defined our Node, lets go ahead and look at the code for the TRIE class. Fortunately, the TRIE datastructure is insanely simple to implement since it has two major methods insert() and search(). Lets look at the elementary implementation of both these methods.

package dsa.tries;

public class Trie{
 private Node root;

 public Trie(){
  root = new Node(' '); 
 }

 public void insert(String s){
  Node current = root; 
  if(s.length()==0) //For an empty character
   current.marker=true;
  for(int i=0;i<s.length();i++){
   Node child = current.subNode(s.charAt(i));
   if(child!=null){ 
    current = child;
   }
   else{
    current.child.add(new Node(s.charAt(i)));
    current = current.subNode(s.charAt(i));
   }
   // Set marker to indicate end of the word
   if(i==s.length()-1)
    current.marker = true;
  } 
 }

 public boolean search(String s){
  Node current = root;
  while(current != null){
   for(int i=0;i<s.length();i++){    
    if(current.subNode(s.charAt(i)) == null)
     return false;
    else
     current = current.subNode(s.charAt(i));
   }
   /* 
    * This means that a string exists, but make sure its
    * a word by checking its 'marker' flag
    */
   if (current.marker == true)
    return true;
   else
    return false;
  }
  return false; 
 }
}

We shall look into the detailed working of the insert() and search() methods in separate posts, but I will tell you the gist of both those methods here. The insert() methods adds a new words to the already existing TRIE data structure. The search() method would return true or false based on whether the search string we specified exist or not.

Take a quick look at the java code above because we are going to use this in the posts that follow.

Cheers,
Bragaadeesh.

TRIE data structure Part 1: The TRIE ADT in Java





TRIE is an interesting data-structure used mainly for manipulating with Words in a language. This word is got from the word retrieve. TRIE (pronounced as 'try') has a wide variety of applications in
  • Spell checking
  • Data compression
  • Computational biology
  • Routing table for IP addresses
  • Storing/Querying XML documents etc.,
We shall see how to construct a basic TRIE data structure in Java.

The main abstract methods of the TRIE ADT are,
public void insert(String s);
public boolean search(String s);

In this data-structure, each node holds a character instead of a String. Each node has something called as 'marker' to mark the end of a word. And each node has a Collection of child nodes. This Collection can be either a Set or a List based on the speed vs space criterion.

The basic element - Node of a TRIE data structure looks like this,
char content;
boolean marker;
Collection<Node> child;

A TRIE tree would typically look like the following


The above TRIE is constructed by inserting the words ball, bat, doll, dork, do, dorm, send, sense. The markers are denoted on the Node using a red star(*). We shall look into more about the TRIE data structure in depth in the next post.