Return value from string function - c++

i have a string array that contains 20 words. I made a function that take 1 random word from the array. But i want to know how can i return that word from array. Right now i am using void function, i had used char type but it wont work. Little help here ? Need to make word guessing game.
CODE:
#include <iostream>
#include <time.h>
#include <cstdlib>
#include <stdlib.h>
#include <algorithm>///lai izmantotu random shuffle funckiju
#include <string>
using namespace std;
void random(string names[]);
int main() {
char a;
string names[] = {"vergs", "rokas", "metrs", "zebra", "uguns", "tiesa", "bumba",
"kakls", "kalns", "skola", "siers", "svari", "lelle", "cimdi",
"saule", "parks", "svece", "diegs", "migla", "virve"};
random(names);
cout<<"VARDU MINESANAS SPELE"<<endl;
cin>>a;
return 0;
}
void random(string names[]){
int randNum;
for (int i = 0; i < 20; i++) { /// makes this program iterate 20 times; giving you 20 random names.
srand( time(NULL) ); /// seed for the random number generator.
randNum = rand() % 20 + 1; /// gets a random number between 1, and 20.
names[i] = names[randNum];
}
//for (int i = 0; i < 1; i++) {
//cout << names[i] << endl; /// outputs one name.
//}
}

Make random return string. You also only need to seed the number generator once. Since you only want to get 1 random word from the array, you don't need a for loop.
string random(string names[]){
int randNum = 0;
randNum = rand() % 20 + 1;
return names[randNum];
}
Then, in the main function, assign a string variable to the return value of the random function.
int main() {
srand( time(NULL) ); // seed number generator once
char a;
string names[] = {"vergs", "rokas", "metrs", "zebra", "uguns", "tiesa", "bumba",
"kakls", "kalns", "skola", "siers", "svari", "lelle", "cimdi",
"saule", "parks", "svece", "diegs", "migla", "virve"};
string randomWord = random(names);
cout<<"VARDU MINESANAS SPELE"<<endl;
cin>>a;
return 0;
}

In your question as well as in the previous answer, you are running out of bounds accessing the names array:
int randNum = rand() % 20 + 1;
return names[randNum];
You are never accessing names[0] but instead reach behind the array when addressing names[20].

Additionally srand(time(NULL)) should be called only one time, on the beginning of main() function.

I'm not super familiar with strings, but you should be able to just declare random() as a string function.
Ex:
string random (string names[]);

Related

(C++) Trying to populate array with random numbers in given range, populating with the same number over and over [duplicate]

This question already has an answer here:
C++ srand() function in loop [duplicate]
(1 answer)
Closed 1 year ago.
I'm trying to populate a simple array in C++ using a function that generates random numbers within a given range. For whatever reason it is giving me the same random number for each element. I think the problem has something to do with where I'm seeding the random variable.
Any ideas?
#include <iostream> // for user input/output
#include <cstdlib> // for rand/srand functions
#include <ctime> // for time usage
using namespace std;
const int SIZE = 10;
const int MIN = 100;
const int MAX = 200;
int main()
{
int Arr[SIZE];
for (int i = 0; i < SIZE; i++){
Arr[i] = rng(MIN, MAX);
}
for (int j = 0; j < SIZE; j++){
cout << Arr[j] << " ";
}
}
int rng(int lo, int hi){
static bool variable;
variable = false;
if (variable == false){
srand(time(0));
variable = true;
}
return rand() % (hi - lo + 1) + lo;
}
As mentioned in comments, you need to call srand(time(0)); only once, just call it at start of main().
The reason is that rand() itself is just a pseudorandom generator (a simple LFSR in a lot of cases) based on its starting seed. if you reseed algorithm with same number, you will get similar sequence of number from it, so your array will be filled with similar set of numbers.
In addition, it is better to use C++ random generator.

RNG in loop and printing word from string array

Ok, I have this working perfectly now, and I've edited this post and code below to reflect the updated correctly working code.
Read 50 words from a text file into an array of strings
The program will use random numbers for:
a.- It will generate a random number between 2 and 7 for the selection of the words to be used in the sentence
b.- It will generate a random number for the selection of the words. The number will be between 0 and 49, because those are the positions of the words in the array
It will display the sentence on the screen.
Thank you ahead of time for any suggestions
#include <string>
#include <iostream>
#include <fstream>
#include <time.h>
#include <stdlib.h>
#include <array>
using namespace std;
int main() {
ofstream outFile;
ifstream inFile;
const int size = 50; //initiate constant size for array
string word[size]; //initialize array of string
srand(time(0)); //sets timing factor for random variables
int Random2 = rand() % 6 + 2; //determines random value beteen 2 and 7
inFile.open("words.txt"); //opens input text file
if (!inFile.is_open()) { //tests to see if file opened corrected
exit(EXIT_FAILURE);
}
while (!inFile.eof()) { //Puts file info into string
for (int i = 0; i < size; ++i)
inFile >> word[i];
}
for (int i = 0; i < Random2; i++) { //loops through array and generates second random variable each loop to determine word to print
int Random1 = rand() % size;
cout << word[Random1] << " ";
}
cin.get();
}
int generateRandom()
{
default_random_engine generator;
uniform_int_distribution<int> distribution(0, 49);
int random = distribution(generator); // generates number in the range 0..49
return random;
}
The problem is that each time you call the getRandom() function you create a new PRNG instance. Therefore, each instance is called only once and the first result is always the same.
Instead you want to create the instance once and call the same instance multiple times.
default_random_engine generator;
uniform_int_distribution<int> distribution(0, 49);
for (int i = 0; i < 5; ++i)
{
std::cout << distribution(generator) << std::endl;
}
cout << words[generateRandom()]
words is declared to be type std::string. Using [] accesses a single character within the string. What are you expecting here? Did you intend to have an array of strings (i.e., one for each line in the text file)? If so, you want something like std::vector<std::string> words. Now using words[0] accesses an element in the array and each element is of type std::string (as opposed to a single character like before).
As for printing single characters, you're only printing the character because that's how the [] operator works for strings. You'll need to tokenize the string. See strtok.

I am getting replace was not declared in this scope

This is a function I am writing that switches the characters of a string, but I am getting "replace was not declared in this scope".
#include <string>
using namespace std;
string rs(string j)
{
srand(time(NULL));
int len = j.size();
int ran1 = rand() % len;
srand(time(NULL) + 1);
int ran2 = rand() % len;
replace(j, ran1, ran2);
cout << j << endl;
return j;
}
Obviously I have something wrong with the function. Any help is appreciated.
replace() is a member function of the string class which is most probably why you're getting the error.
But also, replace() doesn't switch the substrings, it just replaces one with the other.
If you want to switch two substrings of a string using the replace function, you can try doing it by replacing the line:
replace(j, ran1, ran2);
with
string substr_at_ran1 = j.substr(ran1, 1);
j.replace(ran1, 1, j.substr(ran2, 1));
j.replace(ran2, 1, substr_at_ran1);
This is switching the substring of j starting at position ran1 and length 1 with a substring of j at position ran2 and length 1.
Not enough information was provided to properly answer the question, but I'll take a stab at it.
The replace() function I'm assuming is a function that probably doesn't exist in your program, since you didn't provide it.
Assuming that you want your function rs() to randomly swap two characters, here is a program that does just that.
#include <string>
#include <iostream>
using namespace std;
string rs(string j)
{
auto len = j.size();
if (len == 0) //added because your code didn't account for empty strings
{
return j;
}
auto ran1 = rand() % len;
auto ran2 = rand() % len;
swap(j[ran1], j[ran2]);
cout << j << endl;
return j;
}
int main()
{
srand(time(NULL)); //do not use srand in modern C++!
rs("stack overflow");
}
I would also advise against making function names like rs, since its functionality cannot be gleaned from the name alone. swap_random_characters would be a better name.

c++ random number generation not random

I'm trying to perform a random shuffle of a vector using Visual Studio 2013 C++. The following is the code that I have
static void shuffle(vector<int>& a){
int N = a.size();
unsigned long long seed = chrono::system_clock::now().time_since_epoch().count();
default_random_engine generator(seed);
for (int i = 0; i < N; i++){
uniform_int_distribution<int> distribution(0,(N-1)-i);
int r = i + distribution(generator);
swap(a[i], a[r]);
}
}
My problem is when I call this method multiple times in succession the shuffle is not random. What could be wrong with the code?
Any help would be much appreciated.
Uhm, I'm curious... why isn't the following sufficient for your needs:
static void shuffle(vector<int>& a)
{
// There are better options for a seed here, but this is what you used
// in your example and it's not horrible, so we'll stick with it.
auto seed (std::chrono::system_clock::now().time_since_epoch().count());
// Don't bother writing code to swap the elements. Just ask the standard
// library to shuffle the vector for us.
std::shuffle(std::begin(a), std::end(a), std::default_random_engine(seed));
}
std::shuffle dosent remove duplicates, it just swaps the positions of the random numbers generated.
How can I efficiently select several unique random numbers from 1 to 50, excluding x?
You can home cook your own shuffle code otherwise:
#include <ctime>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
void myShuffleWithNoRepeats( int random_once_buf[] , int size=100)
{
srand(time(0));
for (int i=0;i<size;i++)
{
// call made to rand( ) , stored in random_once_buf[ ]
random_once_buf[i]=rand() % 100;
//////////////////////////////////////////////////////////////////////////////////////
// The line below generates unique random number only once //
// //
// the variable i is the random_once_buffer[i] buffer array index count, //
// j is the check for duplicates, j goes through the random_once_buffer[i] buffer //
// from 0 to i at every iteration scanning for duplicates, reversing one step if one duplicate is found.. //
//////////////////////////////////////////////////////////////////////////////////////
for(int j=0;j<i;j++) if (random_once_buf[j] == random_once_buf[i]) i--;
}
cout<<" \n\n\n ";
}
int main(void)
{
const int size=100 ;
int random_once_buffer[100] ;
// Call made to function myShuffleWithNoRepeats( )
myShuffleWithNoRepeats( random_once_buffer , size );
// Loop to display the array random_once_buffer[ ]
for ( int i=0;i<size;i++) cout<<""<<random_once_buffer[i]<<"\t";
cout<<" \nPress any key to continue\n";
cin.ignore();
cin.get();
return 0;
}

display 25 randomnumbers from an array

I have in C++ an array of 100 elements, so v[1], ... ,v[100] contains numbers. How can i display, 25 random numbers from this array? So i wanna select 25 random positions from this array and display the values.. How can i do this in C++?
Thanks!
#include <cstdlib>
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <vector>
using namespace std;
int aleator(int n)
{
return (rand()%n)+1;
}
int main()
{
int r;
int indexes[100]={0};
// const int size=100;
//int a[size];
std::vector<int>v;
srand(time(0));
for (int i=0;i<25;i++)
{
int index = aleator(100);
if (indexes[index] != 0)
{
// try again
i--;
continue;
}
indexes[index] = 1;
cout << v[index] ;
}
cout<<" "<<endl;
system("pause");
return 0;
}
The idea is that i have this code, and i generate 100 random numbers. What i want is an array with random 25 elements from those 100 generated.. But i don't know how to do that
Regards
Short Answer
Use std::random_shuffle(v.begin(),v.end()) to shuffle the array, and then display the first 25 elements.
Long Answer
First of all, the elements would be v[0]...v[99] (C++ uses 0-based indexing), not v[1]...v[100]. To answer your question, though, it depends on whether it is acceptable to repeat elements of the array or not. If you aren't worried about repeats, then simply use the index rand()%v.size(), repeatedly until you have selected a sufficient number of indices (25 in your question). If repeats are not acceptable, then you need to shuffle the array (by swapping elements at random), and then display the first (or last, or any contiguous region of) N elements (in this case N=25). You can use std::random_shuffle to shuffle the array. That does the bulk of the work for you. Once you've done that, just show 25 elements.
If you want to print 25 numbers of an array V you can use this code do:
int V[100]={1,2,5,...} ;
srand ( time (0) ) ;
for (int i=0;i<25;i++)
{
cout << V[rand() % 100 + 1]<<" " ;
}
I modified the version of Mehdi a little in order to make it choose differnet indexes
NOTE: This makes the algorithm not deterministic - it relies on the RNG.
int indexes[100]={0};
srand ( time (0) );
for (int i=0;i<25;i++)
{
int index = rand() % 100;
if (indexes[index] != 0)
{
// try again
i--;
continue;
}
indexes[index] = 1;
cout << v[index] ; cout << endl;
}