Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

C# How to make random range more random?

TheUninvited

Active Coder
So any ideas? Mostly i get like same numbers and i don't like this.

C#:
public class Randomspawn{
    public GameObject mySphere;
    public GameObject[] myCube;
    public int counter;

    private void Update()
    {

        if (Input.GetKeyDown("z"))
        {
            for (int i = 0; i < myCube.Length; i++)
            {
                counter = Random.Range(0, i);
                position = new Vector3(myCube[counter].transform.position.x, 2f, myCube[counter].transform.position.z);
            }
        }
    }

}
 
I mean random means chance. Chance means %. Percent is a specified number which can increase or decrease.

(You can increase the value to increase randomness, as for there are more to choose from.) but no. There isnt a way to "increase randomness".
 
I mean random means chance. Chance means %. Percent is a specified number which can increase or decrease.

(You can increase the value to increase randomness, as for there are more to choose from.) but no. There isnt a way to "increase randomness".
Certain random functions in various programming languages in the past we're less random once a larger data set was used. So while 1-1000 might be random, as the range is larger there were more and more flaws. However, most of those issues are fixed, but they still use algorithms to decide a number.

www.random.org has useful information about how to get "truly random" numbers. They use atmospheric noise instead of algorithms to pick numbers.
 
Does this website show the code on how to do it? Can’t seem to find it.
WEll, it actually uses physical radios scattered around the world to pick up on the noise at certain frequencies, so you can't just fire up some software.

The algorithms are as random as you can get with only code. Even if some numbers appear more than once, it's still random.

@TheUninvited
Run your random code in a loop 10,000 times and you should see that it is more random than you think!
 
It uses radios? :thinking:
YEp! They detect noise from the Earth's atmosphere in several countries to produce truly random results. random number generators in computers follow an algorithm to ensure you can get "any number", but they still aren't 100% "random". Sure, they seem random, but because an algorithm picks the numbers, you can technically reverse engineer it all to make predictions - so it's not "truly random". But with the atmosphere, it's very hard to predict the noise levels being picked up by the radios especially because they're set to only pick up on certain frequencies.

Think about it like this... A dice has 6 sides, so each side has a 1/6th chance of being on top. However, you could technically take the dice, face it a certain way, and then toss it a certain way at a certain speed... and although it's very difficult, you could theoretically get the dice to land on the same spot consistently. That's because even though the dice has 6 sides that all have the same chance of facing up, the speed, angle, and direction in which you throw it affects the outcome. So how do you make this even more random? This is the same as a coin flip. If you start the coin at the same height, same speed, same exact spot for flipping, same angle, etc... Guess what - it lands on the same side each time. The randomness is from humans flipping it.

Well - imagine if there was a way to throw the dice at a random angle, random speed, random height, and random direction. We would see more random results than if someone threw the dice at the same speed, same angle, same height and same direction every time. However, it's extremely hard to actually randomize these things. A human can try to act random, but that is actually very difficult for humans to do, so even though it appears random - everyone has a different dice throw, and let me tell you - You absolutely CAN get a dice to land on a side. There has been research into this and many people believe that some lucky streaks in dice gambling games can be partially attributed to rituals... An experienced dice player may love to start the dice with the number 1 facing up, at a certain height from the table, throw it a certain height/speed/angle/direction/etc... You may even consider this cheating, but it's really just controlling the input (how the dice is thrown) and hoping for the best... It's hard, but I have managed in the past to get a dice to land on the same "3 sides" almost each time... So while it's not entirely useful, I was able to have close to a 1/3 chance of landing a '6' on my dice fairly consistently on my flat table, throwing from the same height, same angle, same direction, and at a similar speed... Much better than a 1/6th chance at rolling a 6. So, we MUST make the input (how the dice is thrown, or the number is generated) completely random so it cannot be engineered or predicted!

An algorithm can be created to randomly choose the speed/height/angle/direction, but again - algorithms for randomness aren't good either. So, what's the solution? Picking something that is "truly random"... like the atmosphere.
You can use algorithms, but if you expect a truly random result you must have a truly random input.

So here's our algorithms:

function speed(input):
// do things with input
return speed

function height(input):
// do things with input
return height

function direction(input):
// do things with input
return direction

function angle(input):
// do things with input
return angle

In this example, there would be algorithms/formulas for taking the input and manipulating it into a number.
For example, we could take an input of "This is a sentence", and return the number of words, which would be 4. However, giving a sentence as our input is not random. And simply returning the number of words is not a very good algorithm. Now imagine we took a string as input ... "akdaloenankalktaldlt" and then returned the number of unique characters.. Okay, a bit better, but still not great.

Now imagine we take a long recording of the atmospheric noise of Earth. That input is unpredictable by humans unless you can track trillions of molecules simultaneously in the sky, and thus almost any algorithm can produce a random result. With a complex algorithm (such as observing variations, spikes, etc in noise, vibrations, temperature, etc) and returning a result, we end up with a random result. This is because even if the algorithm is defined, the input is completely random so there's no way to predict the next outcome - assuming the algorithm doesn't completely trivialize the random input.

Obviously I have simplified it a bit to explain it, and any algorithm you use should ensure a random data set still produces random results as well, but the input really should be "truly random":
For example, there is "pseudo random" and "true random" and a few other terms to refer to different types of random.

Pseudo random is used in programming languages all the time - Some versions of PHP for example use a combination of the current system time(), a unique id, a process ID, and some math...
This is problematic because if you can figure out the server's exact time and either the unique ID or the PID, you can bruteforce the algorithm to try to identify a "random" result in use, or the next random result. However, imagine if PHP's rand() used atmospheric noise in the function. Because it would be near impossible for a hacker to guess the randomness of Earth's atmospheric noise they would not be able to bruteforce their way into guessing the next random number or a randomly generated number already in use. This is because the noise is the "seed" that the algorithm uses to generate a random number. For PHP, there was a fairly common thing where if you used the seed "1024" and then used rand(0,100), you would get a pattern of 97, 97, 39, 77, 93 ...etc. Even though it's supposed to be random, because you know the seed of 1024, you could re-generate the "randomness". This is the downfall of algorithms... the input decides the output. This is why a "truly random" input such as atmospheric noise, CPU processing times, temperatures, lava lamps, etc are so important for generating random results - which can be numbers, cryptographic keys, etc.

So, if you can take a random input (examples: atomic decay in nuclear material, lava lamp visuals, atmospheric noise, etc) then you can feed the random input into an algorithm to output a random number. You can still say you want a random number between 1 and 10 but instead of the algorithm just following hackable/discoverable inputs (like PHP's server time use in rand() ), you are using a completely random and unpredictable input to generate an output.

CloudFlare for example uses a wall of 100 lava lamps on a 24/7/365 video stream to take the randomness of the lava lamp blobs (and anyone else there in the video), feed screenshot data (input) into algorithms, and return completely random cryptographic results. Because nobody can predict the lava lamp blobs down to the milisecond, it's a lot more secure than CloudFlare just picking a random number or series of numbers to use for their crypto keys!
cloudflare-lava-lamps.jpg
 
@TheUninvited
you should sacrifice some randomness to make it better. Pick a random number, but make sure its X numbers away from the last position, or even the last 3 positions. It will be "less random" but still appear to be "more random" because you won't have spawns close to each other! :)
 
@TheUninvited
you should sacrifice some randomness to make it better. Pick a random number, but make sure its X numbers away from the last position, or even the last 3 positions. It will be "less random" but still appear to be "more random" because you won't have spawns close to each other! :)
thank you so much man i appreciate i like the information above you gave somehow i read half of it :p haha
 
thank you so much man i appreciate i like the information above you gave somehow i read half of it :p haha
No problem! I'm happy to help :)

I noticed some *potential* issues...
Because you are using "i" for the Range, you are finding ranges like this...

LOOP 1: i = 0, so Range is 0-0
LOOP 2: i = 1, so Range is 0-1
LOOP 3: i=2 so Range is 0-2
Loop 4: i=3 so Range is 0-3
etc... Is this what you want?

Because i starts at 0 and increments by 1 each loop, it appears you would be getting almost no randomness in the beginning.
If your first loop is 0,0 for Range, the position = 0. For loop 2, it's either 0 or 1 - 50% chance of either. In loop 3, it can only be 0,1, or 2. In loop 4 it can only be 0,1,2,3 .. and so on and so on. This is most likely the reason your results are very similar and not so random. Of course, once you reach the end of you looping you probably have a range of 0 - *insert high number here* so it's more random by the end... but your 'counter' variable is limited by the increments of i in the beginning. Not sure if this is intended.

Perhaps you meant to use Range(0, myCube.Length) so that it's always a random number between 0 and the length of myCube?
I don't know what you want exactly, so please clarify if I have misunderstood... I have never coded in C# really, but for loops, increments, etc are very very similar in PHP, JS, Java, and Python, so I think I've understood :)
 
No problem! I'm happy to help :)

I noticed some *potential* issues...
Because you are using "i" for the Range, you are finding ranges like this...

LOOP 1: i = 0, so Range is 0-0
LOOP 2: i = 1, so Range is 0-1
LOOP 3: i=2 so Range is 0-2
Loop 4: i=3 so Range is 0-3
etc... Is this what you want?

Because i starts at 0 and increments by 1 each loop, it appears you would be getting almost no randomness in the beginning.
If your first loop is 0,0 for Range, the position = 0. For loop 2, it's either 0 or 1 - 50% chance of either. In loop 3, it can only be 0,1, or 2. In loop 4 it can only be 0,1,2,3 .. and so on and so on. This is most likely the reason your results are very similar and not so random. Of course, once you reach the end of you looping you probably have a range of 0 - *insert high number here* so it's more random by the end... but your 'counter' variable is limited by the increments of i in the beginning. Not sure if this is intended.

Perhaps you meant to use Range(0, myCube.Length) so that it's always a random number between 0 and the length of myCube?
I don't know what you want exactly, so please clarify if I have misunderstood... I have never coded in C# really, but for loops, increments, etc are very very similar in PHP, JS, Java, and Python, so I think I've understood :)
Basically this code works for me so is fine:

C#:
private Vector3 RandomPointInBox(Vector3 position, Vector3 localScale)
    {



        try
        {
          

                
                if (counter == previousCounter)
                {
                    counter = Random.Range(min, max);
                }



            //position = new Vector3(myCube[1].transform.position.x, 6f, myCube[1].transform.position.z);
            position = new Vector3(myCube[counter].transform.position.x, 6f, myCube[counter].transform.position.z);
            previousCounter = counter;
            
        }
        catch (Exception)
        {
            Debug.Log("exception handler");
            do { counter = Random.Range(min, myCube.Count); }
            while (counter == previousCounter);
        }
            

            



        

        //position = new Vector3(Random.Range(-2f, 4f),Random.Range(3f, 4f),Random.Range(-5f, 0.8f));
        localScale += new Vector3(0.1F, 0, 0);

        return position;
    }
 
Back
Top Bottom