Java: BubbleSort

The bubblesort algorithm is one of the slowest sorting algorithms around as it’s performance is O(n²). As a result of this the algorithm is barely ever used in any real life applications, however, even though the algorithm will always stay rather slow, it can be tweaked to improve the code’s performance.

The implementation of the algorithm you see below has been optimized in various ways and it also makes use of the property that all items in an array of numbers that come after the last index that was sorted in a run through the array by the algorithm are already sorted.

public static void bubbleSort(int[] ia) {
	int l = ia.length, i = l;
	if (l == 1)
		return;
	while (i != 0) {
		int last = 0;
		for (int j = 1; j != i; j++)
			if (ia[j - 1] > ia[j]) {
				int t = ia[j];
				ia[j] = ia[j - 1];
				ia[j - 1] = t;
				last = j;
			}
		i = last;
	}
}

Read More

Delphi: Singleton Patterns

I’m a big fan of singleton patterns, basically a singleton pattern lets a class maintain a single instance of itself which you can then reuse as often as you want without having to create a new instance. This is achieved by creating a private static field inside the class that can hold an instance of itself, when the user wants to retrieve the instance for the first time, a new one is created and stored in the field, if there’s already one present, the class will return that instance. The implementation I usually use also has automated cleaning of the instance once the application terminates by adding a shared constructor. It’s also possible to add a private constructor to the class to disable the coder to create any instances of it directly without using the singleton pattern or subclassing it.

Here’s an example of the singleton pattern with cleaning:

type
  TTestClass = class
  private
    class var FInstance: TTestClass;
  public                               
    class function GetInstance: TTestClass;
    class destructor DestroyClass;
  end;

{ TTestClass }

class destructor TTestClass.DestroyClass;
begin
  if Assigned(FInstance) then
    FInstance.Free;
end;

class function TTestClass.GetInstance: TTestClass;
begin
  if not Assigned(FInstance) then
    FInstance := TTestClass.Create;
  Result := FInstance;
end;

It’s also possible to add a property named Instance or something even shorter that will get the instance from the GetInstance method which you would then make private, this will shorten the amount of code you have to write when using it.

Read More

Delphi: Static Members

Delphi comes with support for both OOP and procedural code, something you come across less every day as more languages move over to an OOP-only structure. Because of this static code in Delphi is often added as procedural code, which makes sense of course. However, Delphi also has the ability to add static members to classes which can be quite useful at times.

Delphi features several different kinds of static members. The first are fields and properties. A Delphi class can contain any number of static fields and properties which work the exact same way as a regular member would, however they can only be accessed in a static context. Same as with regular properties a static property can retrieve values by calling methods, however all of these accessors and mutators have to be static members as well.

Aside from fields, properties and methods, Delphi classes can also hold shared constructors/destructors. A shared constructor is called when the application is started and allows you to initialize static fields or other stuff you might want to initialize from a static context in or possibly outside of the class. A shared destructor is called when your application is terminated, this allows you to clean up static resources and such. This is similar to the initialization and finalization clauses, but part of a class instead of the entire unit.

Static fields have to be added by adding the keywords “class var” as prefix. For properties you just add “class”. Static methods need to have prefix “class” and they can also take a “static;” at the end, this isn’t required for regular methods, but it is for mutators and accessors. Shared constructors/destructors also only need to have “class” added in front of them. Note that static contructors/destructors can take any name, even Create/Destroy, but i personally prefer the names CreateClass/DestroyClass.

Here’s an example that will show you all of these features:

program StaticTest;

{$APPTYPE CONSOLE}

uses
  SysUtils, Classes;

type
  TTestClass = class
  private
    class var FStaticField: TStrings;
    class function GetStaticField: string; static;
    class procedure SetStaticField(const Value: string); static;
  public
    class property StaticField: string read GetStaticField write SetStaticField;
    class constructor CreateClass;
    class destructor DestroyClass;
  end;

{ TTestClass }

class constructor TTestClass.CreateClass;
begin
  FStaticField := TStringList.Create;
  FStaticField.Text := 'Hello world!';
end;

class destructor TTestClass.DestroyClass;
begin
  FStaticField.Free;
end;

class function TTestClass.GetStaticField: string;
begin
  Result := FStaticField.Text;
end;

class procedure TTestClass.SetStaticField(const Value: string);
begin
  FStaticField.Text := Value;
end;

begin
  WriteLn(TTestClass.StaticField);
  ReadLn; // Stop window from closing
end.

Read More

Delphi: Thread Variables

A somewhat less known feature of Delphi is thread variables. Thread variables are variables that can contain a different value for each thread in the application. They are defined like regular variables, the only difference is that the “var” keyword is replaced with “threadvar”. In the example below I’ll show you how they work in a small console application. Note that I used the TThread class for convenience, however in reality you’ll only ever need this for procedural code as you can add fields to your TThread subclass to store data in for each thread. The example uses the main thread and a separated thread to show you how it works.

program ThreadVarTest;

{$APPTYPE CONSOLE}

uses
  SysUtils, Classes;

type
  TTestThread = class(TThread)
  protected
    procedure Execute; override;
  public
    constructor Create;
  end;

threadvar
  TestVar: string;

var
  i: Integer;

procedure Test;
begin
  WriteLn('Original TestVar: ' + TestVar);
  TestVar := 'Asdf' + IntToStr(i);
  Inc(i);
  WriteLn('New TestVar: ' + TestVar);
end;

{ TTestThread }

constructor TTestThread.Create;
begin
  inherited Create(False);
  FreeOnTerminate := True;
end;

procedure TTestThread.Execute;
begin
  Test;
end;

begin
  i := 0;
  Test;
  WriteLn('Starting thread.');
  TTestThread.Create;
  ReadLn;
  WriteLn(TestVar);
  ReadLn; // Prevent window from closing
end.

As you can see when running it, even though the content of the thread variable was changed, the variable was still empty when accessed by the new thread. I’ve added the incremental number to show you that when after you press a key when the thread has exited and you check the thread variable content for the main thread, it will show Adsf0 as it was stored by the main thread originaly.

Read More

Delphi: Decimal color to RGB and back

Converting a decimal color value (24-bit) to RGB in Delphi is easy using bitshifts, the reverse is true as well. Here’s how it’s done:

procedure ColorToRGB(const Color: Integer; out R, G, B: Byte);
begin
  R := Color and $FF;
  G := (Color shr 8) and $FF;
  B := (Color shr 16) and $FF;
end;

function RGBToColor(const R, G, B: Byte): Integer;
begin
  Result := R or (G shl 8) or (B shl 16);
end;

Take in mind that Delphi TColor is a 24-bit integer decimal color representation.

Read More

RemObjects Internet Pack for .NET

RemObjects is the company that provided the Oxygene compiler technology that forms the base of Delphi Prism, the new Delphi.NET which integrates with Microsoft Visual Studio. They also have several products which rely a lot on sockets. To make things easier they built a custom library on top of the .NET socket library which contains a bunch of components which make it very easy to use sockets for various purposes. One of these components for example is the HttpClient component which lets you grab the contents of a webpage by simply calling it’s Get method and passing an URL to it. Next to this there’s also HttpServer, FtpClient, FtpServer and more! The components are included with Delphi Prism by default, but for those of you who use other Visual Studio languages it’s certainly recommended!

Find it here: http://www.remobjects.com/ip.aspx

Read More

Java: Reading and writing text files

A lot of people starting off with Java will often want to read or write text files. Here’s some code to do just that:

public static String readFile(String fileName) throws IOException {
	FileInputStream fis = new FileInputStream(fileName);
	BufferedInputStream bis = new BufferedInputStream(fis, 1024);
	byte[] buffer = new byte[1024];
	String result = "";
	int len;
	while ((len = bis.read(buffer)) != -1) {
		byte[] tmp = new byte[len];
		System.arraycopy(buffer, 0, tmp, 0, len);
		result += new String(tmp);
	}
	bis.close();
	return result;
}

public static void writeFile(String fileName, String content)
		throws IOException {
	FileOutputStream fos = new FileOutputStream(fileName);
	BufferedOutputStream bos = new BufferedOutputStream(fos, 1024);
	bos.write(content.getBytes());
	bos.close();
}

Read More