Ramazan Karataş
Ramazan Karataş

Reputation: 31

delphi combination algorithm

Hello I cant write the combination algorithm. For example; I have 1 Red and 2 White balls and I want to write number red balls + number white balls. Like below;

R->Red
W->White

RWW
WRW  
WWR 

totally 3 combinasion I have. But How can I write it in Delpi? Because, may be I have 10 RED 8 White or 15 RED 20 White etc.. How can I oreder this kombination.

I have one rules .

1- I have to use all balls eveytime. My order, combination Length has to be total ball. In my example it has to be 2+1=3.

how can I do this?

Upvotes: 1

Views: 794

Answers (1)

Dsm
Dsm

Reputation: 6013

procedure Combination( pLeft : string;pRedCount, pWhiteCount : integer; pResult : strings );
begin
  if (pRedCount = 0) and (pWhiteCount = 0)  then
  begin
    pResult.Add( pLeft );
    exit;
  end;
  if pRedCount > 0 then Combination( pLeft + 'R', pRedCount - 1, pWhiteCount, pResult );
  if pWhiteCount > 0 then Combination( pLeft + 'W', pRedCount, pWhiteCount - 1, pResult )

end;

For example if in your main program you had a TMemo called Memo, a spinedit called RCount and another called WCount, then on your action button you would execute

Memo.Lines.Clear
Combination( '', RCount.Value, WCount.Value, Memo.Lines );

Upvotes: 2

Related Questions