aJynks
aJynks

Reputation: 689

In LUA get a list of random numbers between a range, but allow x set of duplicates per number

There is a ton of examples of generating random numbers in LUA that have no duplicates, and just a standard math.random(x,y) can get a set of random whole numbers in a range....

... but I am having trouble finding a set of random numbers between a range, but allowing x amount of duplicates. For my immediate needs I can allow 1 set of duplicates, but it would be great to have code where you can set "duplicate value" to anything for future projects.

Example : I want to generate a list of 10 whole numbers between 1-10... each value can be anything between 1-10, but any one number can only be generated and added to the list twice.

Example Result: 1,1,2,4,5,5,7,7,8,9

In this example result math.random() tried to spit out 3 or more of the same number, but the code makes it go back and try again if it has already produced 2 of the same number.

Thanks in advance!

Upvotes: 1

Views: 446

Answers (2)

aJynks
aJynks

Reputation: 689

  • Generate a sequential list of non-random numbers between a range with no duplicates.
  • Add them to a table, but add each number X amount of times, where X is the total amount of duplicates allowed. So we know have a table x times as long with each individual number listed X amount of times.
  • Shuffle the table, or generate a list of random numbers or both.
  • Then simply extract the numbers from the table using the generated numbers as the numeric key value for the "duplicate" table.
  • You can store anything at those key values so this works for anything.. not just numbers.

Upvotes: 0

A. Denis
A. Denis

Reputation: 562

You can use "merge trick":

  1. Create "unical" array of numbers for 5 (10/number of dublicats) elements: 1,2,5,7,9

  2. Repeate #1

  3. Merge arrays.

You can generalize it with paramers of minValue, maxValue, totalNumber, numberOfDublicates, but will need to little more code for handling 10/3 problems and maxValue < totalNumber.

Upvotes: 1

Related Questions