locked
How to pick a random value from an array, when the value position to pick is in cell number: 2,5,8,11.... RRS feed

  • Question

  • I have array of string:

    string he="You may not be interested in war, but war is interested in you." ;

    and I wan't to pick the value in 2 position ,5 position and 8 position, ....

    with random number in every pick.

    Saturday, June 23, 2012 3:34 PM

Answers

  • 			std::string he="You may not be interested in war, but war is interested in you." ;
    			int r;
    			do
    			{
    				r = (rand () % he.length ()) / 3 * 3 + 2;
    			} while (r >= he.length ()); // make sure we haven't jumped off the end
    			printf ("%d\n", r);


    Saturday, June 23, 2012 7:24 PM

All replies

  • I don't understand what you mean.

    Please rephrase.

    Saturday, June 23, 2012 3:43 PM
  • I wan't in random to get the numbers 2,5,8,11,14,...   until the last item in the string

    the jump is always in 3.

    for example:

    I can get in first iteration:

    8

    and in the second iteration I will get:

    2

    that way I will gain acess to he[2].


    Saturday, June 23, 2012 5:01 PM
  • 			std::string he="You may not be interested in war, but war is interested in you." ;
    			int r;
    			do
    			{
    				r = (rand () % he.length ()) / 3 * 3 + 2;
    			} while (r >= he.length ()); // make sure we haven't jumped off the end
    			printf ("%d\n", r);


    Saturday, June 23, 2012 7:24 PM
  • Use rand() function.For getting range of values use rand()%<RangeMaximum>. This will return 0- RangeMaximum.

    http://www.cplusplus.com/reference/clibrary/cstdlib/rand/


    Thanks, Renjith V R

    Saturday, June 23, 2012 7:28 PM