Showing posts with label Series. Show all posts
Showing posts with label Series. Show all posts

Friday, June 28, 2013

New Series - Arrays and Indexers



Today, I'm going to start a new series of posts called "Arrays and Indexers in [Programming Language]".  As with previous posts, my aim is to show programming language's basic features, in this case, Arrays and Indexers.

There will a little program. It will show the different declaration and initialization syntax for single-dimensional, multi-dimensional and jagged (arrays of arrays) arrays, how to access elements using numerical index, how to use them as method's input parameters and return type. For the last example, I will define a class that implements the Indexer with its respective get set properties/methods and use it.

Regarding the demonstrating code, I chose an easy array-based sorting algorithm "BubbleSort" (single-dimensional array), a Matrix Transpose (multi-dimensional array) and a Random Uppercase Array. There will also be some Print Array Content methods to display the elements of the array. For the indexer part, it will just encapsulate an array of characters to store alphabets and access specific letters on it.

Each post of the series will be implemented in the latest version, available at the time of writing (stable or unstable), of the following languages targeting the latest version of the supported stable Runtime (JDK7 & .NET4.5)

CLR: C#, VB.NET, C++/CLI, F#, Boo, Phalanger, IronPython, IronRuby, Oxygene, Zonnon, Nemerle, Cobra, JScript.NET.

JVM: Java, Groovy, Jython, JRuby, Fantom, Scala, Gosu, Ceylon, Xtend, Kotlin.

And will use its respective System.Array or java.util.Array.


The Program's Structure will be (more or less) as follows:
// imports 
// namespace 
    
    // Program Class
    
        // Main Mathod            
            
            // Single-dimensional Array(s)            
            
            // Declare & Initialize Character Array
            // Reverse Array Elements
            // Print Array 
            
            // Declare & Initialize Integer Array
            // Sort Integer Array Elements
            // Print Array 
            
            // Declare & Initialize String Array
            // Sort String Array Elements
            // Print Array 
            
            // Multi-dimensional Array (Matrix row,column)
                        
            // Declare & Initialize Matrix Array
            // Transpose Matrix
            // Print Array
            
            // Jagged Array (array of array)
            
            // Upper Case Random Array 
            // Print Array
            // Graph Number of Elements
            
            // Common Array Exceptions
            
            // Print Exceptions
            
            // Indexers Usage
            
            // Declare & Initialize
            // Access Class Array Elements via Indexer
        
        // Method: ReverseChar          - Char[] 
        // Method: BubbleSortInt        - Integer[] 
        // Method: BubbleSortString     - String[] 
        // Method: TransposeMatrix      - Integer[,] 
        // Method: UpperCaseRandomArray - String[][] 
        // Method: PrintArrayChar       - Char[] 
        // Method: PrintArrayInt        - Integer[] 
        // Method: PrintArrayString     - String[] 
        // Method: PrintMatrix          - Integer[,]
        // Method: GraphJaggedArray     - String[][]
        // Method: PrintJaggedArray     - String[][]
        // Method: PrintCommonArrayExceptions - String[][]
        // Method: PrintTitle            
        
    // Indexer Class
        
        // Field: Char Array        
        // Indexer
            // Get
            // Set
        // Constructor: - Integer
        // Constructor: - String
        // Constructor: - Char Array
        // Method: toString
        // Method: Slice
        



Here below some definitions of the new concepts:

Array
"An array is a data structure that contains a group of elements. Typically these elements are all of the same data type, such as an integer or string. Arrays are commonly used in computer programs to organize data so that a related set of values can be easily sorted or searched."
Taken from: http://www.techterms.com/definition/array

One-dimensional arrays
"A one-dimensional array (or single dimension array) is a type of linear array. Accessing its elements involves a single subscript which can either represent a row or column index."
Taken from: http://en.wikipedia.org/wiki/One-dimensional_array#One-dimensional_arrays

Multidimensional arrays
"A data structure consisting of a vector of vectors, in the case of a 2-dimensional array, or, in the case of an N-dimensional array, a vector of multidimensional arrays of degree N minus 1, thereby allowing the simulation of a N-dimensional grid of storage locations using an underlying memory architecture in which storage is addressed in a linear fashion."
Taken from: http://en.wiktionary.org/wiki/multidimensional_array

Jagged Arrays
"In computer programming, an Iliffe vector (Jagged Arrays or Array of Arrays), also known as a display, is a data structure used to implement multi-dimensional arrays. An Iliffe vector for an n-dimensional array (where n > 2) consists of a vector (or 1-dimensional array) of pointers to an (n - 1)-dimensional array. They are often used to avoid the need for expensive multiplication operations when performing address calculation on an array element."
Taken from: http://en.wikipedia.org/wiki/Jagged_array

Bubble Sort Algorithm
"Bubble sort, sometimes incorrectly referred to as sinking sort, is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted."
Sorting Algorithm in Action: http://www.sorting-algorithms.com/bubble-sort
Taken from: http://en.wikipedia.org/wiki/Bubblesort

Matrix
"In mathematics, a matrix (plural matrices) is a rectangular array of numbers, symbols, or expressions, arranged in rows and columns.[1][2] The individual items in a matrix are called its elements or entries. An example of a matrix with 2 rows and 3 columns is: "





Taken from: http://en.wikipedia.org/wiki/Matrix_(mathematics)

Matrix Transpose
"A matrix which is formed by turning all the rows of a given matrix into columns and vice-versa. The transpose of matrix A is written AT."
1 image says more than N words









Taken from: http://www.mathwords.com/t/transpose_of_a_matrix.htm

Indexer
"In object-oriented programming, an indexer allows instances of a particular class or struct to be indexed just like arrays"
"Indexers are implemented through the not get and set accessors for the operator[]. They are similar to properties, but differ by not being static, and the fact that indexers' accessors take parameters."
Taken from: http://en.wikipedia.org/wiki/Indexer_(programming)

Array Slicing
"In computer programming, array slicing is an operation that extracts certain elements from an array and packages them as another array, possibly with different number of indices (or dimensions) and different index ranges."
Taken from: http://en.wikipedia.org/wiki/Array_slicing




Tuesday, January 25, 2011

New Series - Factorial and Fibonacci


I'm going to start a new series of posts called "Factorial and Fibonacci in [Language]". As with my previous 2 series, "OO Hello World" and "Language's Basics by Example", my aim is to show programming language's basic features, and as such, I will be showing stuff such as: static members, instance member, recursion, more loops and conditional constructs, and whatever else comes up. The idea is to write a simple OO program that implements the Factorial and Fibonacci algorithms in a Functional (Recursion) and Imperative (Statements-Loops) way using static methods and fields plus different loop statements such as Do, While, For, For each, etc. I will also add the Timer classes provided by the language's framework to count how much time those algorithms take (benchmark?) and do some comparison of the timing by language.

From now on, I will not be including 2 versions of the same program. First, to save some space and second, because counting keywords is not the main topic anymore. So, a mix of minimal and verbose syntax in each of the languages will be used instead.

The languages:
.NET/CLR: C#, VB.NET, C++/CLI, F#, Boo, Phalanger, IronPython, IronRuby, Delphi Prism, Zonnon, Nemerle, Cobra, JScript.NET
Java/JVM: Groovy, Java, Jython, JRuby, Fantom, Scala, JavaFX, Gosu


The Program's Structure will be (more or less) as follows:
// Factorial and Fibonacci in Language
    // Static Class
        // Static Fields
        // Static Constructor
        // Static Method 1
            // Recursive Fibonacci
        // Static Method 2
            // Imperative Fibonacci
        // Static Method 3
            // Recursive Factorial
        // Static Method 4
            // Imperative Factorial
        // Static Method 5
            // For Loop Range
                // Start Timer
                // Call Static Method: Recursive Fibonacci
                // Stop Timer
                // Print Result
            // While Loop Range
                // Start Timer
                // Call Static Method: Imperative Fibonacci
                // Stop Timer
                // Print Result
            // Do Loop Range
                // Start Timer
                // Call Static Method: Recursive Factorial
                // Stop Timer
                // Print Result
            // For Each Loop Range
                // Start Timer
                // Call Static Method: Imperative Factorial
                // Stop Timer
                // Print Result

    // Instance Class
        // Instance Fields
        // Instance Constructor
        // Instance Method 1
            // Call Static Recursive Fibonacci
        // Instance Method 2
            // Call Static Imperative Fibonacci
        // Instance Method 3
            // Call Static Recursive Factorial
        // Instance Method 4
            // Call Static Imperative Factorial

    // Console Program/Script
        // Calling Static Class and Methods
        // Calling Instance Class and Methods
        // Create a List of values to test
        // Benchmarking Fibonacci
        // Call Factorial Imperative
        // Call Factorial Recursive
        // Benchmarking Factorial
        // Call Fibonacci Imperative
        // Call Fibonacci Recursive
        // Stop and exit


And here below some definitions of the new concepts:

Factorial
"In mathematics, the factorial of a positive integer n,[1] denoted by n!, is the product of all positive integers less than or equal to n. For example:

5! = 5 x 4 x 3 x 2 x 1 = 120

0! is a special case that is explicitly defined to be 1."
Taken from: http://en.wikipedia.org/wiki/Factorial#Definition

Fibonacci
"In mathematics, the Fibonacci numbers are the numbers in the following integer sequence:

0,1,1,2,3,5,8,13,21,34,55,89,144, ...

By definition, the first two Fibonacci numbers are 0 and 1, and each subsequent number is the sum of the previous two. Some sources omit the initial 0, instead beginning the sequence with two 1s." Taken from: http://en.wikipedia.org/wiki/Fibonacci_series

Recursion
"Recursion is the process of repeating items in a self-similar way. For instance, when the surfaces of two mirrors are exactly parallel with each other the nested images that occur are a form of infinite recursion. The term has a variety of meanings specific to a variety of disciplines ranging from linguistics to logic. The most common application of recursion is in mathematics and computer science, in which it refers to a method of defining functions in which the function being defined is applied within its own definition; specifically it is defining an infinite statement using finite components." Taken from: http://en.wikipedia.org/wiki/Recursion

Imperative
"In computer science, imperative programming is a programming paradigm that describes computation in terms of statements that change a program state. In much the same way that imperative mood in natural languages expresses commands to take action, imperative programs define sequences of commands for the computer to perform." Taken from: http://en.wikipedia.org/wiki/Imperative_programming

Static Class
"A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword.

Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.

  • The main features of a static class are:
  • They only contain static members.
  • They cannot be instantiated.
  • They are sealed.
  • They cannot contain Instance Constructors (C# Programming Guide).

Creating a static class is therefore much the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.

The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.

Static classes are sealed and therefore cannot be inherited. Static classes cannot contain a constructor, although it is still possible to declare a static constructor to assign initial values or set up some static state." Taken from: http://msdn.microsoft.com/en-us/library/79b3xss3(v=vs.80).aspx

Static Variable
"In computer programming, a static variable is a variable that has been allocated statically — whose lifetime extends across the entire run of the program. This is in contrast to the more ephemeral automatic variables (local variables), whose storage is allocated and deallocated on the call stack; and in contrast to objects whose storage is dynamically allocated." Taken from: http://en.wikipedia.org/wiki/Static_variable#Static_Variables_as_Class_Variables

Static Method
"In object-oriented programming, a method is a subroutine that is exclusively associated either with a class (in which case it is called a class method or a static method) or with an object (in which case it is an instance method).

As mentioned above, a method may be declared as static, meaning that it acts at the class level rather than at the instance level. Therefore, a static method cannot refer to a specific instance of the class (i.e. it cannot refer to this, self, Me, etc.), unless such references are made through a parameter referencing an instance of the class, although in such cases they must be accessed through the parameter's identifier instead of this. Most importantly there is no need to make an object for accessing data .i.e. without creating an object we can access the data members of a static class." Taken from: http://en.wikipedia.org/wiki/Static_method#Static_methods

Static Constructor
"A static constructor is a static data initializer. Static constructors allow complex static variable initialization.[1] Static constructors can be called once and call is made implicitly by the run-time right before the first time the class is accessed. Any call to a class (static or constructor call), triggers the static constructor execution. Static constructors are thread safe and are a great way to implement a singleton pattern. When used in a generic programming class, static constructors are called on every new generic instantiation one per type (static variables are instantiated as well)." Taken from:http://en.wikipedia.org/wiki/Constructor_(object-oriented_programming)#C.23_static_constructor

Benchmark
"In computing, a benchmark is the act of running a computer program, a set of programs, or other operations, in order to assess the relative performance of an object, normally by running a number of standard tests and trials against it. The term 'benchmark' is also mostly utilized for the purposes of elaborately-designed benchmarking programs themselves." Taken from: http://en.wikipedia.org/wiki/Benchmark_(computing)


return;

Sunday, August 1, 2010

New Series - Language's Basics by Example



I'm going to start working on a new posts series today. This time, I will extend some previous code, to show you some basic features of each of the 20 languages I have been using so far. If you haven't been following this blog, then I will remind you which those languages are:

Languages targeting the .NET/CLR runtime:
C#, VB.NET, C++/CLI, F#, Boo, Phalanger, IronPython, IronRuby, Delphi Prism, Zonnon, Nemerle, Cobra, JScript.NET

Languages targeting the Java/JVM runtime:
Groovy, Java, Jython, JRuby, Fantom, Scala, JavaFX

Now, about the content, I will show you an extended version of the Greetings Program implementing the following Language Basics statements and constructs features by using a Console Application. I will be using again 2 versions of the same program: Verbose and Minimal, so we can keep showing some numbers just for the fun.

The Program's Structure will be as follows:

// Language Basics

    // Greet Class
        // Fields or Attributes
        // Properties
        // Constructor
        // Overloaded Constructor
        // Method 1
            // "if-then-else" statement
        // Method 2
            // "for" statement
        // Overloaded Method 2.1
            // "while" statement
        // Overloaded Method 2.2
            // "switch/case" statement

    // Console Program
        // Define object of type Greet 
        // Instantiate Greet. Call Constructor
        // Call Set Properties
        // Call Method 2
        // Call Method 2.1 and Get Properties
        // Call Method 2.2
        // Stop and exit - Read Input From Console

And here below some definitions of each of the statements and constructs used on the upcoming posts:

Class
"In object-oriented programming, a class is a construct that is used as a blueprint (or template) to create objects of that class. This blueprint describes the state and behavior that the objects of the class all share. An object of a given class is called an instance of the class. The class that contains (and was used to create) that instance can be considered as the type of that object, e.g. an object instance of the "Fruit" class would be of the type "Fruit".

It encapsulates state through data placeholders called attributes (or member variables or instance variables); it encapsulates behavior through reusable sections of code called methods." Taken from: http://en.wikipedia.org/wiki/Class_(computer_science)

Constructor
"In object-oriented programming, a constructor (sometimes shortened to ctor) in a class is a special type of subroutine called at the creation of an object. It prepares the new object for use, often accepting parameters which the constructor uses to set any member variables required when the object is first created." Taken from: http://en.wikipedia.org/wiki/Constructor_(computer_science)

Attributes
"In computing, an attribute is a specification that defines a property of an object, element, or file. It may also refer to or set the specific value for a given instance of such." Taken from: http://en.wikipedia.org/wiki/Attribute_(computing)

Methods
"In object-oriented programming, a method is a subroutine that is exclusively associated either with a class (in which case it is called a class method or a static method) or with an object (in which case it is an instance method). Like a subroutine in procedural programming languages, a method usually consists of a sequence of programming statements to perform an action, a set of input parameters to customize those actions, and possibly an output value (called the return value) of some kind. Methods provide a mechanism for accessing and manipulating the encapsulated data stored in an object." Taken from: http://en.wikipedia.org/wiki/Method_(computer_science)


Method and Constructor Overloading
"Function overloading or method overloading is a feature found in various programming languages such as Ada, C#, C++, D and Java that allows the creation of several methods with the same name which differ from each other in terms of the type of the input and the type of the output of the function." Taken from: http://en.wikipedia.org/wiki/Function_overloading

Conditional Statements (if-else-then)
"In computer science, conditional statements, conditional expressions and conditional constructs are features of a programming language which perform different computations or actions depending on whether a programmer-specified boolean condition evaluates to true or false. Apart from the case of branch predication, this is always achieved by selectively altering the control flow based on some condition." Taken from: http://en.wikipedia.org/wiki/If_statement

Conditional Statements (Case and Switch)
"Switch statements (in some languages, case statements) compare a given value with specified constants and take action according to the first constant to match." Taken from: http://en.wikipedia.org/wiki/If_statement

"Its purpose is to allow the value of a variable or expression to control the flow of program execution via a multiway branch (or "goto", one of several labels). The main reasons for using a switch include improving clarity, by reducing otherwise repetitive coding, and (if the heuristics permit), offering the potential of faster execution through compiler optimization." Taken from: http://en.wikipedia.org/wiki/Switch_statement

Control Flow Statement (For loop)
"In computer science a for loop is a programming language statement which allows code to be repeatedly executed. A for loop is classified as an iteration statement.

Unlike many other kinds of loops, such as the while loop, the for loop is often distinguished by an explicit loop counter or loop variable. This allows the body of the for loop (the code that is being repeatedly executed) to know about the sequencing of each iteration. For loops are also typically used when the number of iterations is known before entering the loop." Taken from: http://en.wikipedia.org/wiki/For_statement

Control Flow Statement (While loop)
"In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The while loop can be thought of as a repeating if statement.

The while construct consists of a block of code and a condition. The condition is evaluated, and if the condition is true, the code within the block is executed. This repeats until the condition becomes false. Because while loops check the condition before the block is executed, the control structure is often also known as a pre-test loop." Taken from: http://en.wikipedia.org/wiki/While_loop 

Console Application
"A console application is a computer program designed to be used via a text-only computer interface, such as a text terminal" Taken from: http://en.wikipedia.org/wiki/Console_application


So, what do you think? interested? :D
I will start with C# then Zonnon because those are the ones I was using when I got the idea of working on this new series.

stay tuned!
bytes!

Sunday, June 13, 2010

OO Hello, World!



“A "Hello World" program is a computer program which prints out "Hello, World!" on a display device. It is used in many introductory tutorials for teaching a programming language. Such a program is typically one of the simplest programs possible in most computer languages. It is often considered to be tradition among programmers for people attempting to learn a new programming language to write a "Hello World!" program as one of the first steps of learning that particular language.” Taken from: (http://en.wikipedia.org/wiki/Hello_world_program)

Object-oriented programming (OOP) is a programming paradigm that uses "objects" – data structures consisting of datafields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction, encapsulation, modularity, polymorphism, and inheritance. Many modern programming languages now support OOP.” Taken from: (http://en.wikipedia.org/wiki/Object-oriented_programming)

If all the programming languages that target the CLR/JVM support Object Oriented Programming and the “Hello, World” program is the traditional way for start learning a new language, from today on, I will start posting an “OO Hello, World!” program using each of the languages listed in my second post. This will give you a basic taste on the language’s syntax and program structure.

It is very common to find "1 line hello world programs" in books or sites, especially if the language has dynamic support.
Python: print "Hello, World!"
Ruby: puts "Hello, World!"
F#: printfn "Hello, World!"

Of course you learn very little with such examples and that is why I decided to use the OO version.

So, what can you expect to find? 
You will learn the basic structure of a console program, creating a class, defining a private data member, defining a method, creating an instance of an object and calling the method. Also if an statement is required by the language (or it won't compile) I will add it, otherwise I will omit it.

Here below the structure of the “Hello, World” program I will be using: 

[Import / using / etc]
Class
                Data
                Constructor 
                Method
Program
                Instantiate Class
                Call Method       => OUTPUT (Hello, World!)

I will also give some info about the language and some links to more info and code samples if you are interested in the language.

Note: The code I will be using for my examples is the one in “A more sophisticated version using Object Orientation” located in Groovy’s website (http://groovy.codehaus.org/). Since it is exactly what I wanted to show, why not reusing code? :)

Bytes!