Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
0
Question by altusi · Sep 24, 2015 at 09:05 PM · randomint

C# Random Int: How to force Even or odd number

Hello,

I made my code to choose random an int:

                 storeResult.Value = (inclusiveMax) ? 
                 Random.Range(min.Value, max.Value + 1) : 
                 Random.Range(min.Value, max.Value);

But I'm wondering how it's possible to force a random int to be even or odd? How I can integrate this to my code? I need a little help to do it, can someone give me some tips please? Thanks

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

6 Replies

· Add your reply
  • Sort: 
avatar image
2

Answer by cjdev · Sep 24, 2015 at 10:13 PM

You could try something like this:

 storeResult.Value = (inclusiveMax) ?
     min.Value + Random.Range(0, (max.Value - min.Value) / 2) * 2 + 1 : 
     min.Value + Random.Range(0, (max.Value - min.Value) / 2) * 2;

Note that you may have to adjust it depending on whether min and max are even or odd.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by snizkorod · Sep 24, 2015 at 10:03 PM

Doesnt look like Random supports a specific return but you can always just write your own. Here's a small example, with the assumption that forcing if it's even or odd is also random

 //if you get 1 then even, if you get 0 then odd.
 if(Random.Range (0,2) == 1)){
     yourInt = RandomEven(min,max);
 } else {
     yourInt = RandomOdd(min,max);
 }


 int RandomEven(int min, int max) {
         int randint = Random.Range (min, max);
         while(randint % 2 != 0) {
             randint = Random.Range (min, max);
         } 
         return randint;
     }


Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Kiwasi · Sep 25, 2015 at 01:09 AM 1
Share

You should probably think about what happens if I do

 RandomEven(7,7);
avatar image
0

Answer by GameDevSA · Jun 11, 2017 at 12:23 PM

I think this is a better way to check if a number is odd or even in some cases: http://answers.unity3d.com/questions/224860/determining-if-a-variable-is-even-or-odd.html

Basically, use something called modulo.

 if (number % 2 == 0) // it is even
 if(number % 2 == 1) // it is odd

Read the link for a slightly better explanation.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by Max_Bol · Aug 09, 2019 at 09:06 PM

There's no "native" way of handling the Even and Odd numbers, but there's a really simple way of changing either the odd or even into the other one.


To change any odd number into their higher or lower number:

1) Divide the int by 2 into a float. Let's call the result X.

2) If you want the higher even number, use Mathf.Ceil(X). If you want the lower even number, Mathf.Floor(X).

3) Multiply by 2 and you changed the Odd number into an Even number.

This can be done in a single line like this:

 public int ConvertOddToEvenUp(int a){
 int Result = Mathf.RoundToInt( Mathf.Ceil( (float)a/2) * 2 );
 return Result ;
 }
 
 public int ConvertOddToEvenDown(int a){
 int Result = Mathf.RoundToInt( Mathf.Floor( (float)a/2) * 2 );
 return Result ;
 }


Ceil round up the number always toward the highest closest integer and Floor does the same, but toward the lowest.

From this dual sets of options, you can also do the same, but with a slight change to change Even numbers into Odd numbers.

     public int ConvertEvenToOddUp(int a){
     int Result = Mathf.RoundToInt( (Mathf.Ceil( (float)a/2) * 2) +1 );
     return Result ;
     }
     
     public int ConvertEvenToOddDown(int a){
     int Result = Mathf.RoundToInt( (Mathf.Floor( (float)a/2) * 2) -1 );
     return Result ;
     }

As you noticed, in both case, I find the Even number first because it's easier to get, then I either add or subtract 1 to that number and it returns the previous or next integer after the closest even integer which, by nature, is an Odd Integer.

The reason why I used wrap the formula with Mathf.RoundToInt() instead of just putting (int) in front is because this ensure that any float imprecision issues are avoided. For example, if you divide 101 by half, you might get 50.49863948 due to float imprecision. Then you Floor or Ceil it which, from the Unity doc, supposedly return the closest integer... as a float which again can be imprecise so you might end up with 49.9987224 or 50.0023445. You then multiply it by 2 which double the previous imprecision. Mathf.RoundToInt() is an "Convert" type from float to Int and guaranties the closest integer to be outputted. So even if the imprecision is far off the mark, it will work and give an actual true Integer. (It's more like a 3rd safeguard thing.)

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Max_Bol · Aug 09, 2019 at 09:18 PM 0
Share

I'm commenting my own answer for the sake of giving one way of handling all 4 functions I mentioned above :

     public static int ConvertNumberOddEven(int a, bool hasToBeOdd, bool hasToBeHigher) {
         int Result = 0;
         if (hasToBeHigher)
         {
             Result  = $$anonymous$$athf.RoundToInt($$anonymous$$athf.Ceil((float)a / 2) * 2);
             if (hasToBeOdd) {
                 Result ++;
             }
         }
         else {
             Result  = $$anonymous$$athf.RoundToInt($$anonymous$$athf.Floor((float)a / 2) * 2);
             if (hasToBeOdd)
             {
                 Result --;
             }
         }
         return Result ;
     }

This will ask for 3 information each times : the Integer to convert, if it has to be Odd or Even and if it has to be the higher or the lowest integer when converted.

avatar image
0

Answer by DenisGLabrecque · Aug 10, 2019 at 08:38 AM

Check whether it's even and increment by 1 if so.

 oddNumber = random.Next();
 if(isEven(oddNumber)) {
    oddNumber++;
 }

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
  • 1
  • 2
  • ›

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

35 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

random range to pick from two specific numbers only. 3 Answers

trying to get an Array string to read an Int 0 Answers

Turning a int into a possibility of 19 different outcomes 1 Answer

Can I create a GameObject Array then fill UI text elements and then somehow use a For Loop to drop an Array of Int values inside those UI text boxes from largest to lowest? 0 Answers

Why are my float rounding themselves out to the lowest int without me coding it out? 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges