C
C
CodeInside2015-11-01 22:16:02
C++ / C#
CodeInside, 2015-11-01 22:16:02

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'
  }
}

How to arrange for case 'b'?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
andrewjabber, 2015-11-02
@CodeInside

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;
}

D
Dmitry Snytkin, 2015-11-01
@dima11221122

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;
}

A
Alexander Latyshev, 2015-11-01
@magalex

Try like this:

char x = 'a' + (char)rand() % ( 'd' - 'a' );
if( x >= correctAnswer )
{
    x++;
}
return x;

M
Maxim Moseychuk, 2015-11-02
@fshp

#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;
}

For c++11:
#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 question

Ask a Question

731 491 924 answers to any question