Answer the question
In order to leave comments, you need to log in
How to get a random value from two ranges?
I am writing a function that receives a character from the range 'a'-'d' and returns any other character from the same range.
char randomResponse(char correctAnswer)//принимает правильный вариант ответа, возвращает неверный
{
srand ( time(NULL) );//сбросить "random"
switch(correctAnswer)
{
case 'a': return (char)rand() %(int)'d' + (int)'b';//получение случайного символа с диапазона 'b'-'d'
}
}
Answer the question
In order to leave comments, you need to log in
This solution works for any range, like
range[] = "asdfjkl";
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
char range[] = "abcd";
int rangeLen;
char randomResponse(char correctAnswer)//принимает правильный вариант ответа, возвращает неверный
{
int r = rand() % (rangeLen-1);
if (r >= correctAnswer)
++r;
return range[r];
}
int main()
{
srand(time(0));
rangeLen = strlen(range);
// test
for (int i = 0; i < rangeLen; i++)
printf("%c ", randomResponse(range[i]));
_getch();
return 0;
}
I think it's better like this
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
char randomeResponse(char a)
{
int r = rand()%4;
while(r == (a - 'a')) r = rand() % 4;
return char(r + 'a');
}
int main()
{
srand(time(NULL));
cout << randomeResponse('b');
return 0;
}
Try like this:
char x = 'a' + (char)rand() % ( 'd' - 'a' );
if( x >= correctAnswer )
{
x++;
}
return x;
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int.hpp>
char randomResponse(const char correctAnswer) {
static boost::random::mt19937 rng;
static boost::random::uniform_int_distribution<char> uni('a', 'd');
char result;
while((result = uni(rng)) == correctAnswer);
return result;
}
#include <random>
char randomResponse(const char correctAnswer) {
static std::mt19937 rng;
static std::uniform_int_distribution<char> uni('a', 'd');
char result;
while((result = uni(rng)) == correctAnswer);
return result;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question