Jump to content

Recommended Posts

Posted (edited)

Today I learned about pseudo random number generator driven FizzBuzz (https://stackoverflow.com/q/20957693) and I couldn't stop myself from porting it to Delphi ...

program FizzBuzzRandom;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

procedure FizzBuzz(upTo: integer);
var
  i: integer;
begin
  for:= 1 to upTodo begin
    if (i mod 15) = 1 then
      RandSeed := 1973472511;
    Write(TArray<string>.Create(i.ToString, 'Fizz', 'Buzz', 'FizzBuzz')[Random(521) mod 4], ' ');
  end;
end;

begin
  FizzBuzz(100);
  Readln;
end.

 

Edited by Primož Gabrijelčič
  • Confused 1

Share this post


Link to post

Just for the folks that are unfamiliar with the FizzBuzz Test: http://wiki.c2.com/?FizzBuzzTest

 

tl;dr: It's supposed to be a fairly quick and standard test to evaluate the skills of a job applicant. Considering that it needs no OOP or any other more modern language structures I guess it's pretty old.

Share this post


Link to post
Posted (edited)

Just for the fun of it, here's a parallel version of FizzBuzz. No RNGs were abused this time.

 

program ParallelFizzBuzz;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  Winapi.Windows,
  System.SysUtils, System.Classes;

var
  GWrittenOut: TArray<boolean>;

procedure FB(num: integer; output: string; extra: integer);
begin
  TThread.CreateAnonymousThread(procedure begin
    Sleep(num* 1000 + extra);
    if not GWrittenOut[num] then begin
      Write(output, ' ');
      GWrittenOut[num] := true;
    end;
  end).Start;
end;

procedure FizzBuzz(upTo: integer);
var
  i: integer;
begin
  SetLength(GWrittenOut, upTo+1);
  for:= 1 to upTodo
    FB(i, i.ToString, 900);
  for:= 1 to upTo div 3 do
    FB(i*3, 'Fizz', 500);
  for:= 1 to upTo div 5 do
    FB(i*5, 'Buzz', 500);
  for:= 1 to upTo div 15 do
    FB(i*15, 'FizzBuzz', 100);
end;

var
  Msg: TMsg;

begin
  FizzBuzz(20);
  while not GWrittenOut[High(GWrittenOut)] do
    while integer(PeekMessage(msg, 0, 0, 0, PM_REMOVE)) <> 0 do begin
      TranslateMessage(Msg);
      DispatchMessage(Msg);
    end;
  Writeln;
  Write('> '); Readln;
end.

 

Edited by Primož Gabrijelčič

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×