Amazon.com Widgets Fun Code

Fun Code of the Week #7

By Nick at February 24, 2013 09:08
Filed Under: Fun Code, Delphi

It’s all a big circle.

First, I posted a fun little way to handle the cursor in this Fun Code of the Week.

The first comment on that post was from my friend Tapper who said “What, no interface?”

Then, I post this about hints revealing errors with cursor handling as part of the demo.

And from that, we get a comment by Leif that I’m making Fun Code of the Week

So Tapper is happy, and we all have about three ways to handle the cursor. 

Wins for everyone!

 

unit CursorHandler;

interface

uses
      Controls
    ;

type
  ICursor = interface(IInterface)
  end;

function AutoCursor(const aCursor: TCursor): ICursor;

implementation

uses
  Forms;

type
  TAutoCursor = class(TInterfacedObject, ICursor)
  private
    FCursor: TCursor;
  public
    constructor Create(const aCursor: TCursor);
    destructor Destroy; override;
  end;

function AutoCursor(const aCursor: TCursor): ICursor;
begin
  Result := TAutoCursor.Create(aCursor);
end;

constructor TAutoCursor.Create(const aCursor: TCursor);
begin
  inherited Create;
  FCursor := Screen.Cursor;
  Screen.Cursor := aCursor;
end;

destructor TAutoCursor.Destroy;
begin
  Screen.Cursor := FCursor;
  inherited;
end;

end.

Fun Code of the Week #6: Primality Checking

By Nick at October 27, 2012 18:02
Filed Under: Delphi, Fun Code

 

I decided to give KhanAcademy a spin, and watched this set of videos:

Level 1: Primality Test

And that let to me writing this code:

function IsPrime(const x: integer): Boolean;
var
  i: integer;
begin
  i := 2;
  repeat
    if X mod i = 0 then
    begin
      Result := False;
      Exit;
    end;
    Inc(i);
  until i > Sqrt(x);
  Result := True;
end;

I know that this can be optimized (which I'll do if I end up watching the next video :-) ), but I don't often write really geeky code like this, so I thought I'd post it so you all can write lots of comments like you always do when I post code. ;-)

UPDATE #1: There was a bug if you passed in a negative number. 

function IsPrime(const x: integer): Boolean;
var
  i: integer;
begin
  if (x <= 2) then
  begin
    Result := False;
    Exit;
  end;
  i := 3;
  repeat
    if X mod i = 0 then
    begin
      Result := False;
      Exit;
    end;
    Inc(i);
  until i > Sqrt(x);
  Result := True;
end;

UPDATE #2:  Took the Sqrt() call out of the loop.

function IsPrime(const x: integer): Boolean;
var
  i: integer;
  Wall: double;
begin
  if (x <= 2) then
  begin
    Result := False;
    Exit;
  end;
  i := 3;
  Wall := Sqrt(x);
  repeat
    if X mod i = 0 then
    begin
      Result := False;
      Exit;
    end;
    Inc(i);
  until i > Wall;
  Result := True;
end;

UPDATE #3:   The learning and optimizing continues!  I updated the code based on more suggestions, but the special case of 2 is irritating me.  I confess I thought a while (I’m not cheating by looking up implementations on Google…) and so I came up with something of a hack.  Also, just for Julian, all the x’s are lowercase now.  Smile with tongue out  Also, I learned/re-learned that 1 is not a prime either, by definition.  Interesting.  Any more optimizations out there?  Is there a “correct” way to handle 2?  The end goal here is to have a really nice, really efficient IsPrime function. 

function IsPrime(const x: integer): Boolean;
var
  i: integer;
  Wall: integer;
begin
  if x = 2 then
  begin
    Result := True;
    Exit;
  end;
  i := 3;
  Result := not ((x < i) or (x mod 2 = 0));
  if not Result then Exit;
  Wall := Trunc(Sqrt(x));
  repeat
    Result := not (X mod i = 0);
    if not Result then Exit;
    Inc(i, 2);
  until i > Wall;
  Result := True;
end;

Fun Code of the Week #5

By Nick at October 24, 2012 21:39
Filed Under: Delphi, Fun Code

What is your FizzBuzz solution?  Any comments on mine?

If this is an interview question, what are you looking for?

Here is FizzBuzz in over 150 languages.

For the record, I spent no more than three minutes to write this. :-)

program FizzBuzz;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

var
  i: integer;
  WriteNumber: Boolean;

begin
  try
    for i := 1 to 100 do
    begin
      WriteNumber := True;
      if i mod 3 = 0  then
      begin
        Write('Fizz');
        WriteNumber := False;
      end;
      if i mod 5 = 0 then
      begin
        Write('Buzz');
        WriteNumber := False;
      end;
      if WriteNumber then
      begin
        Write(i);
      end;
      WriteLn;
    end;
    Readln;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

Fun Code of the Week #4

By Nick at June 08, 2012 15:14
Filed Under: Delphi, Fun Code

Adapted from my answer on StackOverflow:

function RemoveChars(const aString: string; aCharsToRemove: TSysCharSet): string;
var
  C: Char;
begin
  Result := '';
  for C in aString do
  begin
    if not CharInSet(C, aCharsToRemove) then
    begin
      Result := Result + C;
    end;
  end;
end;

Fun Code of the Week #3

By Nick at May 01, 2012 17:44
Filed Under: Fun Code, Delphi
procedure ShowHourGlass(Proc: TProc);
begin
  Screen.Cursor := crHourGlass;
  try
    Proc;
  finally
    Screen.Cursor := crDefault;
  end;
end;

Fun Code of the Week #2

By Nick at November 07, 2011 15:51
Filed Under: Delphi, Fun Code, Software Development
function RandomString(aLength: Integer; aInputChars: string): string;
begin
  Result := '';
  if Length(aInputChars) <= 0 then
  begin
    Exit;
  end;
  Randomize;

  repeat
    Result := Result + aInputChars[Random(Length(aInputChars)) + 1];
  until (Length(Result) = aLength);
end;

Fun Code of the Week #1

By Nick at October 06, 2011 20:20
Filed Under: Delphi, Fun Code
unit uIsPalindrome;

interface

function IsPalindrome(const aString: string): Boolean;

implementation

uses
       Spring.Collections
     , {$IF CompilerVersion >= 230}System.{$IFEND}SysUtils
     ;

function CleanString(const aString: string): string;
var
  C: char;
begin
  // Remove all non-alpha chars and make all lower case
  // Spaces don't matter, so let's count only letters
  Result := '';
  for C in LowerCase(aString) do
  begin
    if CharInSet(C, ['a'..'z', 'A'..'Z']) then
    begin
      Result := Result + C;
    end;
  end;
end;

function IsPalindrome(const aString: string): Boolean;
var
  Stack: IStack<Char>;
  C: Char;
  NoSpaces: string;
  Temp: string;
begin
  NoSpaces :=  CleanString(aString);

  Stack := TCollections.CreateStack<Char>;
  for C in NoSpaces do
  begin
    Stack.Push(C);
  end;
  Temp := '';
  repeat
    Temp := Temp + Stack.Pop;
  until Stack.Count = 0;
  Result := Temp = NoSpaces;
end;

end.

Added: I always enjoy posting code like this. Note that it is entitled "Fun Code", not "Highly optimized, perfectly written Code". ;-)

My Book

A Pithy Quote for You

"There are no such things as limits to growth, because there are no limits to the human capacity for intelligence, imagination, and wonder"    –  Ronald Reagan

Amazon Gift Cards

General Disclaimer

The views I express here are entirely my own and not necessarily those of any other rational person or organization.  However, I strongly recommend that you agree with pretty much everything I say because, well, I'm right.  Most of the time. Except when I'm not, in which case, you shouldn't agree with me.