3

I need a delphi solution for this solution in java JAVA CODE

type
 TColors = (red, green, blue, white, purple, orange, yellow, black);
type
 TForm1 = class(TForm)
 Button1: TButton;
 Memo1: TMemo;
 procedure Button1Click(Sender: TObject);
 private
 { Private-Deklarationen }
 public
 { Public-Deklarationen }
 end;

 var Form1: TForm1;

 implementation

 {$R *.fmx}

 function RandomColor: TColors;
 begin
  result := blue;  //   make this random value from enum ????
end;

procedure TForm1.Button1Click(Sender: TObject);
var
s: string;
begin
  s := GetEnumName(TypeInfo(TColors), integer(RandomColor));
 Memo1.Lines.Add(s);   ///  print random color to memo 
end;

2 Answers 2

5
function RandomColor: TColors;
begin
  Result := TColors(Random(Succ(Ord(High(TColors)))));
end;

var
  MyColor: TColors;
begin
  Randomize; //call this once at startup
  MyColor := RandomColor;
Sign up to request clarification or add additional context in comments.

9 Comments

I would add a +1 to the Ord(), otherwise you will never see the highest possible enum value. The upper limit is exclusive.
There seems to be a mistake. Random(A) returns range of 0..A-1, so if you want to have last element included you need to use Random(A+1).
@JensG and Krom - completely right, thanks - I've now added a Succ call.
With the Succ() and RANGECHECKS ON my Delphi XE doesn't even compile this. Nice solution, indeed. BTW, why do you earn all the points while we do the work correcting your stuff?
@JensG - the Succ call is against an integer, so works fine with range checking enabled - I have no idea why your Delphi XE 'doesn't even compile this'. Perhaps you haven't copied and pasted correctly?
|
0

Here's a complete test program, including a check against Low(TColors) not being zero, which must otherwise taken into account within the RandomColor function, if that later changes for some reason.

program Project7;

{$APPTYPE CONSOLE}
{$RANGECHECKS ON}

uses
  SysUtils;

type
  TColors = (red, green, blue);

const NAMES : array[TColors] of string = ('red','green','blue');

function RandomColor: TColors;
begin
  ASSERT( Ord(Low(TColors)) = 0);
  Result := TColors(Random(1+Ord(High(TColors))));
end;

var i : integer;
begin
  Randomize; 
  while true do begin
    for i := 0 to 7 do write('"', NAMES[RandomColor], '" ');
    writeln;
    writeln('press Ctrl+C to break, ENTER to continue ');
    readln;
  end;
end.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.