Reputation: 1169
I am writing a small password generator and have 4 CheckBoxes for the combinations, these are: Upper Case Letters, Lower Case Letters, Numbers and Special Characters.
My question is - do I have to go through each possible combination of CheckBoxes in the logic with "if" statements or is there a quicker, more simple way that could shorten the code more?
I am sorry if this question is rather silly, but it will really help me in the future to learn from this if indeed there is a better way.
All the best
Chris ( shamballa ).
Upvotes: 2
Views: 291
Reputation: 136391
Why do you think which you must through each possible combination of CheckBoxes?
check this basic function.
Suppose do you have 4 checkboxes called CbUpper, CbLower, CbNumbers, CbSymbols.
Now you can construct a function like this
function Generate(AllowUpper,AllowLower,AllowNumbers,AllowSymbols:Boolean; PassLen:Integer):AnsiString;
const
UpperList = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
LowerList = 'abcdefghijklmnopqrstuvwxyz';
NumberList = '0123456789';
SymbolList = '@#()=¿?!¡[]';
var
MyList : AnsiString;
Index : Integer;
i : Integer;
begin
Result:='';
MyList:='';
//here if the flag is set the elements are added to the main array (string) to process
if AllowUpper then MyList:=MyList + UpperList;
if AllowLower then MyList:=MyList + LowerList;
if AllowNumbers then MyList:=MyList + NumberList;
if AllowSymbols then MyList:=MyList + SymbolList;
Randomize;
if Length(MyList)>0 then
for i:= 1 to PassLen do
begin
Index:=Random(Length(MyList))+1;
Result:=Result+MyList[Index];
end;
end;
and call in this way
Var
MyPassword : AnsiString;
begin
MyPassword:=Generate(CbUpper.Checked,CbLower.Checked,CbNumbers.Checked,CbSymbols.Checked,20);
Upvotes: 11