Hello I am trying to generate a random array of the length that the user inputs. My array should then print and display the occurences of those letters in the array. So far this only prints up to the letter g and the occurences are incorrect. If someone could tell me what I am doing wrong it would help alot. Thank you.
#include <iostream>
#include <cstring>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
srand(time(0));
int i, num;
char ch;
char chars[]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
int freq[26]={0};
cout << "How many letters do you want in your string? ";
cin >> num;
for (i=0; i < num; i++)
{
ch = chars[rand()%26];
chars[i]=ch;
freq[i] +=1;
cout << ch;
}
for (char lower = 'a'; lower <='z'; lower++)
{
cout << "\nLetter" << lower << "is " << freq[lower] << "times";
}
}
Problem 1
The lines
chars[i]=ch;
freq[i] +=1;
are not right. You need to use:
int index = ch - 'a';
freq[index] += 1;
Problem 2
The index in the for loop for printing the data is not correct either.
You need to use:
for (char lower = 'a'; lower <='z'; lower++)
{
int index = lower - 'a';
cout << "\nLetter" << lower << "is " << freq[index] << "times";
}
Important Note
It is worth noting that the C++ standard does not guarantee that lower case letters are contiguous. (Thanks #MartinBonner). For instance, if your system uses EBCDIC encoding your program won't work.
To make your code robust, it will be better to use a std::map.
int main()
{
srand(time(0));
int i, num;
char ch;
char chars[]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
std::map<char, int> freq;
// Initialize freq.
for ( ch : chars )
{
freq[ch] = 0;
}
cout << "How many letters do you want in your string? ";
cin >> num;
for (i=0; i < num; i++)
{
ch = chars[rand()%26];
freq[ch] +=1;
}
for (auto item : freq )
{
cout << "\nLetter" << item.first << "is " << item.second << "times";
}
}
You might wanna give a look to C++11 Pseudo-random number generation here is a short way of generating the range that you want using this:
#include <algorithm>
#include <array>
#include <random>
#include <vector>
using namespace std;
int main()
{
int arraySize = 35;
mt19937 engine{random_device{}()};
uniform_int_distribution<> dist{'a', 'z'};
vector<char> vec;
generate_n(back_inserter(vec), arraySize, [&]() { return static_cast<char>(dist(engine); }));
//To count occurrences
array<int, 26> freq;
for (auto c : vec) { ++freq[c-'a']; }
return 0;
}
You should not write into chars, and freq should be extended to cover the a...z range (the ASCII codes), which it does not. Also, increase at index ch, not at i.
I do not even know that range from the top of my head, but it could be modified to track all possible bytes instead (0...255), see result on https://ideone.com/xPGls7
List of changes:
int freq[256]={0}; // instead of int freq[26]={0};
// chars[i]=ch; is removed
freq[ch] +=1; // instead of freq[i] +=1;
Then it works.
Using lambda functions to do most of the work.
#include <algorithm>
#include <functional>
#include <iostream>
#include <map>
#include <numeric>
#include <ostream>
#include <random>
#include <string>
#include <utility>
#include <vector>
using namespace std::string_literals;
int main()
{
std::mt19937::result_type seed = std::random_device{}();
auto engine = std::mt19937(seed);
auto dist = std::uniform_int_distribution<>('a', 'z');
auto random_letter = [&engine, &dist]() { return static_cast<char>(dist(engine)); };
std::cout << "How many letters do you want to generate? "s;
int n;
if (!(std::cin >> n)) { return EXIT_FAILURE; }
auto letters = std::vector<char>();
std::generate_n(std::back_inserter(letters), n, random_letter);
auto zero = std::map<char, int>();
auto const frequencies = std::accumulate(std::cbegin(letters), std::cend(letters), zero,
[](auto& acc, auto c)
{
++acc[c];
return acc;
});
for (auto const [c, freq] : frequencies)
{
std::cout << "The letter '"s << c << "' appeared "s << freq << " times." << std::endl;
}
return 0;
}
I am trying to generate a random number between 0 and 2 (inclusive) for a C++ program:
#include <iostream>
#include <string>
#include <cstdlib>
#include <random>
using namespace std;
int generateRowMovement(){
//http://www.cplusplus.com/reference/random/uniform_int_distribution/
default_random_engine generator;
uniform_int_distribution<int> distribution(0,2);
int row = distribution(generator);
return row;
}
int main(){
int row = generateRowMovement();
cout << row << endl;
int row2 = generateRowMovement();
cout << row2 << endl;
int row3 = generateRowMovement();
cout << row3 << endl;
return 0;
}
All 3 results are:
0
0
0
I have been testing this for 30 minute and it is always zero. I have tried following this link and this SO post (which posts link back to), but none of their solution is fix this problem. How can I generate 0, 1, and 2?
There are two issues with the code you posted that keeps it from working how you intend it to. The first is that generator is never given a seed, or as is commonly shown online, a random_device, ie
random_device rd;
default_random_engine generator(rd());
The second is that every time you call the function, you're creating a new random engine, and a new distribution. It would be better to create a random device, give it to to the engine only once, and then let your function return the values based on those.
#include <iostream>
#include <string>
#include <cstdlib>
#include <random>
using namespace std;
random_device rd;
default_random_engine generator(rd());
uniform_int_distribution<int> distribution(0,2);
int generateRowMovement(){
return distribution(generator);
}
int main(){
int row = generateRowMovement();
cout << row << endl;
int row2 = generateRowMovement();
cout << row2 << endl;
int row3 = generateRowMovement();
cout << row3 << endl;
return 0;
}
Something I am working on is making a code that focuses on making a class that reverses an order of numbers. This will then get put into the main code that will eliminate any trailing zeroes. I can't seem to wrap my head around how classes work and where I am going wrong. Here is my code:
Numbers.h
#pragma once
#include <iostream>
class Numbers
{
public:
int digit
private:
void Numbers::reverse();
};
Numbers.cpp
#include "Numbers.h
#include <iostream>
using namespace std;
void Numbers::reverse(){
int n, reversedNumber = 0, remainder;
cout << "Enter the number you would like to manipulate! " << endl;
cin >> n;
while (n !=0)
{
remainder = n % 10;
reversedNumber = reversed Number * 10 + remainder;
n /= 10;
}
//return *this;
}
Main.cpp
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>
#include "Numbers.h"
using namespace std;
int main()
{
Numbers.reverse;
system("pause");
return 0;
}
I can't seem to make the reverse function in my Numbers.cpp work in the main function. I am new to C++ and am not sure where I am going wrong. Any help would be appreciated!
OK, there are a lot of mistakes or learning errors in your code. Your header file should look something like:
#pragma once
class Numbers
{
public:
Numbers();
~Numbers();
int Reverse(int input); // Function is 'public'.
};
Your CPP file will then be (parts taken from S.O. post here):
#include "Numbers.h"
Numbers::Numbers()
{
}
Numbers::~Numbers()
{
}
// No need to store the value in 'digit' since this
// is just an algorithm which can return the result.
int Numbers::Reverse(int input)
{
int ret = 0;
while(input > 0)
{
ret = ret * 10 + (input % 10);
input = input / 10;
}
return ret; // Return the reversed number and let the user decide what to do.
}
Then you can use your class as follows:
#include "Numbers.h"
#include <iostream>
using namespace std;
int main()
{
int num;
cout << "Enter a number to reverse: ";
cin >> num;
Numbers numClass;
cout << "Reversed number is: " << numClass.Reverse(num) << endl;
return 0;
}
I'm trying to return or repeat the function if the results of it do not meet the criteria. I've tried various things, such as do while statements, settings a BOOL flag, etc. and have been unsuccessful. What's the best way to restart the function until the criteria is met?
CODE:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
int main() {
std:int nine;
std::srand(std::time(NULL));
std::cout << nine << (rand() % 10);
std::cout << '\n';
if (nine == 9) {
std::cout << 'nine';
} else {
main();
}
}
You may not recursively call main in C++. Also your code contains some other errors. The program could look the following way.
#include <iostream>
#include <cstdlib>
#include <ctime>
int main()
{
std::srand( ( unsigned )std::time( NULL) );
int nine;
do
{
nine = std::rand() % 10;
} while ( nine != 9 );
std::cout << "nine" << std::endl;
}
You could also add an output statement
#include <iostream>
#include <cstdlib>
#include <ctime>
int main()
{
std::srand( ( unsigned )std::time( NULL) );
int nine;
do
{
nine = std::rand() % 10;
std::cout << nine << std::endl;
} while ( nine != 9 );
std::cout << "nine" << std::endl;
}
A while loop should work just fine:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
int main() {
int nine = 0;
srand(std::time(NULL));
while (nine != 9)
{
nine = (rand() % 10);
std::cout << nine << std::endl;
if (nine == 9) {
std::cout << 'nine';
}
}
}
i think your problem is in nine , you don't assign it
nine = rand()%10;
and with the basic loop it should be fine
while ( nine != 9){
nine = rand()%10;
}
You can do as follows:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
int main() {
std::srand(std::time(NULL));
do {
std:int nine;
std::cout << nine << (rand() % 10);
std::cout << '\n';
if(nine == 9) {
std::cout << 'nine';
break;
}
} while(true);
}
Note that you don't ever change nine in your code, the loop will go forever.
This particular code wouldn't even compile due to the std:int (missing colon typo). But assuming the typo was fixed, it also wouldn't do anything because you never assign a value to nine.
Anyway, if you want to repeat an action in your code, your best bet is a loop:
int nine = 0;
do {
nine = rand() % 10;
} while (nine != 9);
I want the exact time to run a program, I use it from clock(). But there is a problem that I can not give an exact time for small n like 2000.
I want it to return the correct answer for n=1000.
#include <iostream>
#include <ctime>
#include <algorithm>
using namespace std;
#define show_time(x, y) cout << endl << #x << " : " << y << endl;
int main()
{
int n;
cin >> n;
int *a = new int[n];
for(int i=0; i<n; i++)
a[i] = i;
random_shuffle(a, a+n);
int last = clock();
//STL_sort:
sort(a, a+n);
int lastP = clock();
show_time(STL_sort, (double)(lastP-last)/CLOCKS_PER_SEC);
return 0;
}
The output is 0. (Definitely 0 will not be the answer)
What platform are you running on? If you're on Windows, you could try the high-resolution time library.
If you have access to C++11, there is a header called chrono that has similar functionality, and is portable (ish)!