How do I actually generate a random number

Hello! :wave:

I’m currently making a game that generates a random game! Everything works perfectly fine, except…
The way I’m getting the games is through math.random(1, 10000000) & I’ve also tried Random.new():NextInteger(1, 10000000), but it keeps giving me the same numbers every ~30 ids generated, which means its basically around 10 games just in a big cycle. If anyone knows a better way to generate numbers it would be very helpful!

Here’s my code to generate the number:
local id = Random.new():NextInteger(1,1000000000)

Here’s what it looks like from my POV:

2 Likes

You should give Random a different seed each time.

local id = Random.new(os.time()):NextInteger(0, 1000000000)

This will take the current time as a seed, and time is always going forward.

2 Likes

1. Use More Dynamic Seeds

local someDynamicValue = --[[ some dynamic value from your game ]]
local seed = os.time() + someDynamicValue
local randomGenerator = Random.new(seed)

When I tried implementing this into my game, its very slow and is still giving me the same games, although it’s less common.

This works pretty good, except its only giving me games from around 2008-2009, heres my code (I don’t have a dynamic value in my game yet, so I just used random.new)

local someDynamicValue = Random.new():NextInteger(1, 1000000)
local seed = os.time() + someDynamicValue
id = Random.new(seed):NextInteger(0, 10000000)

What desired effect were you trying to get after this now

What do you mean?
I’m trying to get games from ROBLOX’s release to 2024 (present), I think I might be able to work out the generation being slow by adding a “queue” of some sort.

This can help further with function:


local function generateDynamicSeed()
    local someDynamicValue = Random.new():NextInteger(1, 1000000)
    local timeComponent = os.time()
    local seed = timeComponent + someDynamicValue
    return seed
end


local dynamicSeed = generateDynamicSeed()
local idGenerator = Random.new(dynamicSeed)

-- generate 
local id = idGenerator:NextInteger(0, 10000000)

This is still returning games from 2008 - 2012, heres my entire script if it helps further:

-- Services
local replicatedStorage = game:GetService("ReplicatedStorage")
local HttpService = game:GetService("HttpService")
local marketplaceService = game:GetService("MarketplaceService")

-- Variables
local signals = replicatedStorage:WaitForChild("Signals")
local getRandomGameInfo = signals:WaitForChild("GetRandomGameInfo")

-- Private Functions
local function getUniverseId(placeId)
	local url = "https://apis.roproxy.com/universes/v1/places/"..placeId.."/universe"
	local response = HttpService:GetAsync(url)
	local data = HttpService:JSONDecode(response)
	local universeId = data["universeId"]
	return universeId
end

local function getGameInfo(universeId)
	local url = "https://games.roproxy.com/v1/games?universeIds="..universeId
	local response = HttpService:GetAsync(url)
	local data = HttpService:JSONDecode(response)

	if data["data"] and #data["data"] >= 1 then
		local gameData = data["data"][1]
		local gameInfo = {
			title = gameData["name"],
			creator = gameData["creator"]["name"],
			activePlayerCount = gameData["playing"],
			favorites = gameData["favoritedCount"],
			visits = gameData["visits"],
			dateCreated = gameData["created"],
			id = gameData["rootPlaceId"],
			creatorVerified = gameData["creator"]["hasVerifiedBadge"],
		}

		print(gameInfo)
		return gameInfo
	else
		print("No game data found.")
		return nil
	end
end

local function wordInSentence(word, sentence)
	return string.find(sentence, word) ~= nil
end

local function generateDynamicSeed()
	local someDynamicValue = Random.new():NextInteger(1, 1000000)
	local timeComponent = os.time()
	local seed = timeComponent + someDynamicValue
	return seed
end

local function getRandomGameInfoFunction()
	local successfulId = false
	local dynamicSeed = generateDynamicSeed()
	local idGenerator = Random.new(dynamicSeed)

	local id = idGenerator:NextInteger(0, 10000000)

	while successfulId == false do
		task.wait()
		local someDynamicValue = Random.new():NextInteger(100000, 1000000)
		local seed = os.time() + someDynamicValue
		id = Random.new(seed):NextInteger(0, 100000000)
		
		print(id)

		local placeCheck

		local success, errorMessage = pcall(function()
			placeCheck = marketplaceService:GetProductInfo(id)
		end)

		if success and placeCheck and placeCheck.AssetTypeId == 9 then
			local successful, info = pcall(marketplaceService.GetProductInfo, marketplaceService, id)
			if success then
				if wordInSentence("'s place", string.lower(info.Name)) == false then
					print("SUCCESSFUL ID: "..id)
					break
				end
			end
		end
	end

	local universeId = getUniverseId(id)
	if universeId == nil then
		getRandomGameInfoFunction()
	else
		local gameInfo = getGameInfo(universeId)
		
		if gameInfo.creatorVerified then
			gameInfo.creator = gameInfo.creator..""
		end

		return gameInfo
	end
end

getRandomGameInfo.OnServerInvoke = getRandomGameInfoFunction

(I know :GetNextPageAsync() exists, though it makes the generation process not random, and instead just loop through the first page, second page, third page, etc.)

It’s night time I have to go but someone else might be able to solve your problem for you at some point

The number you are generating is too low, 100 million.

image
This is the place ID for one of my newer games, 16 billion. Change the number to 16 billion

This definitely seems to increase the diversity of the date created, but now the problem of having the same games over and over again is happening.

Unable to replicate this, can show this happening?

Try creating a single Random object at runtime instead of creating a new one every time you call for another random number. This way, you can eliminate the seed being a problem.

rnd = Random.new(os.time())
for i = 1, 1000 do:
  print(rnd:NextInteger(1, 1000000)
  // See if this is psuedorandom: if it is, something else in your script is the issue
end

Try isolating this function to see if the randomness is the problem as opposed to something else.

1 Like

Hm, this rarely duplicates, it must be something else in my script, I’ll try to create some new solutions, thank you!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.