Jump to content

[TOPIC: topicViewTemplate]
[GLOBAL: userSmallPhoto]
Photo

Weighted Random
Started by Garrettsavo Nov 24 2014 02:30 AM

- - - - -
4 replies to this topic
[TOPIC CONTROLS]
This topic has been archived. This means that you cannot reply to this topic.
[/TOPIC CONTROLS]
[modOptionsDropdown]
[/modOptionsDropdown]
[reputationFilter]
[TOPIC: post.html]
#1

Garrettsavo

[GLOBAL: userInfoPane.html]
Garrettsavo
  • Enthusiast

  • 36 posts
  • Enterprise

I'm trying to create a weighted random. The easy solution to this is to use a table where the weighted % is equal to the number of values in table. Like so:

 

values = {1,1,1,2,2,3}

 

I'm curious as to 1; how would I select a single random value from a table like this?

 

And 2; is there a better way to do this in corona? I.E is there another way that would be worth the added complexity it may involve?



[TOPIC: post.html]
#2

horacebury

[GLOBAL: userInfoPane.html]
horacebury
  • Corona Geek

  • 3,070 posts
  • Corona SDK

The random number selection is easy - you want to look at randomSeed and random in the math library:

http://docs.coronalabs.com/daily/api/library/math/index.html

 

The weighted logic can be found on google: https://www.google.co.uk/search?q=weighted+random&oq=weighted+random&aqs=chrome..69i57j69i60&sourceid=chrome&es_sm=93&ie=UTF-8

 

Am I missing something in your requirements?



[TOPIC: post.html]
#3

Garrettsavo

[GLOBAL: userInfoPane.html]
Garrettsavo
  • Enthusiast

  • 36 posts
  • Enterprise

I guess just how I would actually apply a randomSeed or random to this table. I've already looked at the documentation for both randomSeed and random. Using math.random was my first inclination, but from what I understand it chooses a random value between a min and max. In this case if I used math.random(1,3) (or for the purpose of this example), math.random(values[1],values[6]), the random would not be weighted, but a purely random value between the min and max.

 

I'm probably just over complicating this, but I'm not sure exactly how to do this in corona. In Game Maker there is just a Choose() function that would work perfectly for this situation. If you could be more specific as to how would I apply math.random to give me the result I'm looking for in this scenario, I would greatly appreciate it.



[TOPIC: post.html]
#4

Burhan J

[GLOBAL: userInfoPane.html]
Burhan J
  • Contributor

  • 131 posts
  • Corona SDK

Hi @Garrettsavo,

 

You may want to try this function I get from others.

        local function either (...)
            if #arg == 0 then
                return nil
            else
                return arg[ math.random( #arg ) ]
            end
        end

Then call,

 

local values = either( 1,1,1,2,2,3 )

 

 

Good Luck!

 

 

burhan



[TOPIC: post.html]
#5

Garrettsavo

[GLOBAL: userInfoPane.html]
Garrettsavo
  • Enthusiast

  • 36 posts
  • Enterprise

Thanks, that's perfect ^^




[topic_controls]
[/topic_controls]