This post will discuss the ways to generate random numbers. For example, you may have a requirement on your project to generate random numbers like Prefixed Text with a number or Random Text with a number.
Background
In my recent implementation, the application expected to generate random numbers. Found we have multiple ways to generate random numbers. This section will discuss this in detail.
Samples
We have different ways to generate random but some differences. You may choose the best method based on your needs.
- Random Number with Prefixed Text Like ORD
- Random Number with Random three chars like ABC5478
- Random Number with Prefixed Text Like ORD But Unique
Video Sample to show in Reality
Explanations
Random 1: Random Number with Prefixed Text Like ORD
UpdateContext(
{
RandNumber1: “ORD” & RandBetween(
11111,
99999
)
}
)
Random 2: Random Number with three random chars like ABC5478
ClearCollect(
Letters,
Split(
“ABCDEFGHIJKLMNOPQRSTUVWXYZ”,
“”
)
);
UpdateContext(
{
RandomSample2: RandBetween(
11111,
99999
)
}
);
Set(
RandNumber2,
First(Shuffle(Letters)).Result & First(Shuffle(Letters)).Result & First(Shuffle(Letters)).Result & RandomSample2
);
Random 3: Random Number with Prefixed Text But Unique
This code is similar to the sample Random 1, but the difference is here to check the generated number against the data source to make sure to unique. We will use a timer control to generate random numbers until it’s unique
Flow/Steps:
Step by Step explanation
Set the OnSelect property of the Random 3 button to
UpdateContext({StartRandomTimer: false}); UpdateContext({StartRandomTimer: true});
Clear(GeneratedRandoms);
ClearCollect(
Letters,
Split(
“ABCDEFGHIJKLMNOPQRSTUVWXYZ”,
“”
)
);
Insert a timer control and set the duration to 500
Set the OnTimerEnd property of the timer control to
UpdateContext({RepeatRandomTimer: false});
UpdateContext(
{
RandomSample3: RandBetween(
11111,
99999
)
}
);
Set(
RandNumber3,
“ORD” & RandomSample3
);
If(
CountRows(
Filter(
GeneratedRandoms,
Value = RandNumber3
)
) = 0,
Collect(
GeneratedRandoms,
RandNumber3
),
UpdateContext({RepeatRandomTimer: false});
UpdateContext({RepeatRandomTimer: true}););
Set the Start property of the timer control to
StartRandomTimer
Set the Repeat property of the timer control to
RepeatRandomTimer
Conclusion
Random 1 and Random 2 are straightforward. Random 3 ensures the generated random number is unique by checking against any data source using timer control.
Enjoy development and reach me if any questions