CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Aug 2010
    Posts
    26

    Is is possible to randomize an if statement

    Hi,
    My question which i've been trying to search for is whether i can randomize an if statement meaning this The program can choose to randomly choose which if statement to execute rather then actually choose one. Here is my scenario.

    1) After i pull randomly 1 to 3 numbers from my list which i have already coded for.
    2) For each number i pull from the list I want to add an If statement which says
    3) 1 can be added to the number pulled , or 1 can be subtracted to the number or the program can just do nothing and just retrieve the number and pass it(eg.
    if the number is 16, the if statement can add 1 which makes it 17, or subtract 1 which makes it 15, or it can keep it at 16.)
    4) I want to randomized these if statements meaning that the program can choose either
    if statements to run. It doesnt have to choose. one.

    Is this possible. or do I need to use a different option to make this happent other then an If statement. If I don't use an if statement is there another way for me to achieve this.. Thanks any comments or help will greatly be appreciated..

  2. #2
    Join Date
    Oct 2006
    Location
    Sweden
    Posts
    3,654

    Re: Is is possible to randomize an if statement

    Oh! Sorry it should be C#...

    Something like this fragment maybe
    Code:
    using System;
    
    Random rand = new Random();
    
    switch( (3 & (1+rand.Next())) - 1 )
    {
      case 0: 
        // Add one
        break;
      case 1:
        // Subtract one
        break;
      case 2:
        // Leave as is
        break;
    }
    Last edited by S_M_A; August 22nd, 2010 at 04:12 PM.
    Debugging is twice as hard as writing the code in the first place.
    Therefore, if you write the code as cleverly as possible, you are, by
    definition, not smart enough to debug it.
    - Brian W. Kernighan

    To enhance your chance's of getting an answer be sure to read
    http://www.codeguru.com/forum/announ...nouncementid=6
    and http://www.codeguru.com/forum/showthread.php?t=366302 before posting

    Refresh your memory on formatting tags here
    http://www.codeguru.com/forum/misc.php?do=bbcode

    Get your free MS compiler here
    https://visualstudio.microsoft.com/vs

  3. #3
    Join Date
    Aug 2010
    Posts
    26

    Re: Is is possible to randomize an if statement

    Thanks very much for your help and .. for the reply SMA, I'm going to try it out..
    Last edited by wilnicm; August 22nd, 2010 at 10:37 PM. Reason: forgot to write something

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured