Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Does this lottery code allow duplicates?

Author  Topic 

Rasta Pickles
Posting Yak Master

174 Posts

Posted - 2015-04-26 : 06:51:11
Hi all,

I was sent the following code that generates random numbers for the UK lottery but I can't work out whether it allows duplicates (the variable concerned is @allowdups)

Also, is there a more efficient way of doing this?

Anyway, here it is:


DECLARE @allowdups BIT = 0
DECLARE @uppermain INT = 50
DECLARE @lowermain INT = 1
DECLARE @upperbon INT = 11
DECLARE @lowerbon INT = 1
DECLARE @maincount INT = 5
DECLARE @bonuscount INT = 2

CREATE TABLE #MainNumberBoundaries
(
Number TINYINT,
UpperLimit DECIMAL (15, 10)
)

CREATE TABLE #BonusNumberBoundaries
(
Number TINYINT,
UpperLimit DECIMAL (15, 10)
)

INSERT #MainNumberBoundaries (Number, UpperLimit)

SELECT sv.Number, (1.0000000/(@uppermain + 1 - @lowermain) * (sv.Number + 1 - @lowermain)) AS UpperLimit
FROM master..spt_values sv
WHERE sv.Number <= @uppermain
AND sv.Number >= @lowermain
AND sv.type = 'P'

INSERT #BonusNumberBoundaries (Number, UpperLimit)

SELECT sv.Number, (1.0000000/(@upperbon + 1 - @lowerbon) * (sv.Number + 1 - @lowerbon)) AS UpperLimit
FROM master..spt_values sv
WHERE sv.Number <= @upperbon
AND sv.Number >= @lowerbon
AND sv.type = 'P'

CREATE TABLE #MainNumbersToOutput
(
Number TINYINT NOT NULL
)

WHILE (SELECT COUNT(*) FROM #MainNumbersToOutput) < @maincount
BEGIN
WITH MyNumber (Number)
AS
(
SELECT TOP 1 nb.Number
FROM #MainNumberBoundaries nb
WHERE RAND() < nb.UpperLimit
ORDER BY nb.Number ASC
)

INSERT #MainNumbersToOutput
SELECT mn.Number
FROM MyNumber mn
WHERE @allowdups = 1
OR mn.Number NOT IN (SELECT Number FROM #MainNumbersToOutput)
END

CREATE TABLE #BonusNumbersToOutput
(
Number TINYINT NOT NULL
)

WHILE (SELECT COUNT(*) FROM #BonusNumbersToOutput) < @bonuscount
BEGIN
WITH MyNumber (Number)
AS
(
SELECT TOP 1 nb.Number
FROM #BonusNumberBoundaries nb
WHERE RAND() < nb.UpperLimit
ORDER BY nb.Number ASC
)

INSERT #BonusNumbersToOutput
SELECT mn.Number
FROM MyNumber mn
WHERE @allowdups = 1
OR mn.Number NOT IN (SELECT Number FROM #BonusNumbersToOutput)
END

SELECT Number, 'M'
FROM #MainNumbersToOutput
UNION ALL
SELECT Number, 'B'
FROM #BonusNumbersToOutput

DROP TABLE #MainNumberBoundaries
DROP TABLE #BonusNumberBoundaries
DROP TABLE #MainNumbersToOutput
DROP TABLE #BonusNumbersToOutput

bitsmed
Aged Yak Warrior

545 Posts

Posted - 2015-04-26 : 17:26:43
This code can generate duplicates between mainnumbers and bonusnumbers, even if you set @allowdups to 0.
Go to Top of Page
   

- Advertisement -