I have made a random password generator.In function void passwordGenerator(int sizeOfPassword)
The problem here is this I am trying to save the password generated by the program in sum but I don't know how to do it properly.
How do I save random digits password in sum.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void passwordGenerator(int sizeOfPassword)
{
srand(time(NULL));
char allChars[] = {"0123456789!##$%^&*abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"};
char sum;
for(int i = 0; i < sizeOfPassword; i++){
sum = sum + allChars[rand()%sizeOfPassword];
}
std::cout<<sum<<std::endl;
}
int main()
{
int sizeOutput;
char wannaPlay = 'y';
while(wannaPlay == 'y'){
std::cout<<"Enter the size of password: ";
std::cin>>sizeOutput;
passwordGenerator(sizeOutput);
std::cout<<"\nRun Again[y/n]? : ";
std::cin>>wannaPlay;
}
return 0;
}
Thank you
You might display letter by letter:
void passwordGenerator(int sizeOfPassword)
{
const char allChars[] = {"0123456789!##$%^&*abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"};
for (int i = 0; i < sizeOfPassword; i++){
std::cout << allChars[rand() % sizeof (allChars)];
}
}
or building a string:
std::string passwordGenerator(int sizeOfPassword)
{
const char allChars[] = {"0123456789!##$%^&*abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"};
std::string password;
for (int i = 0; i < sizeOfPassword; i++){
password += allChars[rand() % sizeof (allChars)];
}
return password;
}
Related
It's a practice problem I'm trying to do, but so far I've had no luck. Here's what I tried so far:
#include <iostream>
using namespace std;
string updateList(char arr[],char key, int n);
int main()
{
char usernames[10];
int sizeOf = 2;
usernames[0] = 'a'; usernames[1] = 'b';
string x = updateList(usernames, 'c', sizeOf);
cout << x;
}
string updateList(char arr[],char key, int n)
{
int arrLength = sizeof(arr)/sizeof(char);
int i;
for (i = 0; i < arrLength; i++) {
if (arr[i] == key) {
return "Username already exists";}
else {
arr[n++] = key;
int arrLength = sizeof(arr)/sizeof(char);
for (i = 0; i < arrLength; i++) {
cout << arr[i];
return "\n Username added";
}
} }
}
Any help would be appreciated.
Problem with your approach is that you are not updating the value of n(sizeOf) and you are using n to add element which will create error.instead of that use pass by reference so that n(i,e here sizeOf will updated) will updated Try something like
#include <iostream>
using namespace std;
string updateList(char arr[],char key, int *n);
int main()
{
char usernames[10];
int sizeOf=2;
usernames[0] = 'a'; usernames[1] = 'b';
string x = updateList(usernames, 'c', &sizeOf);
cout << x;
int updateList(char arr[],char key, int n)
{
int i;
for (i = 0; i < arrLength; i++) {
if (arr[i] == key) {
return "Username already exists";}
else {
arr[n++] = key;
for (i = 0; i < arrLength; i++) {
cout << arr[i];
}
return 0; } }
}
You can either use string or vector in order to keep the array of chars dynamic. This is an example of string and it also acts as an array of characters.
#include <iostream>
using namespace std;
int main()
{
string usernames="ab";
char key = 'b';
int i=0;
for(;i<usernames.size();i++)
if(usernames[i]==key)
{
printf("Key exists already");
break;
}
if(i==usernames.size())
{
usernames.push_back(key);
cout << usernames <<endl;
}
return 0;
}
How to counting the same word in a string
Input
Number of String
String1 = dadymathewdadreadad
String2 = sdgfghhjdjrjjyjjrtfdhe
Search = dad
Output
Number of dad in string1 = 3
Number of dad in string2 = 0
Code:
#include <iostream>
#include <string.h>
using namespace std;
int main() {
string str[50];
int n;
cin>>n;
for(int i = 0; i < n;i++) {
cin>>str[i];
}
for(int i = 0; i < 50;i++) {
if(substr(i,4) == "dad"){
n += 1;
}
}
cout<<n;
return 0;
}
ERROR
In function 'int main()':
[Error] 'substr' was not declared in this scope
One trick you could use here would be to just replace the search term (e.g. dad) with empty string, and then compare the length of the string before and after the replacement.
string input = "dadymathewdadreadady";
string search = "dad";
int size_orig = input.size();
replace(string, search, "");
cout << "number of 'dad' is: " << (size_orig - input.size()) / search.size();
You can use the find() member function of std::string, adjusting the start position after every successful find until the end of the string:
#include <string>
int count(const std::string& sentence, const std::string& word)
{
int total = 0;
size_t start = 0;
size_t pos = 0;
while ((pos = sentence.find(word, start)) != std::string::npos)
{
++total;
start = pos + word.size();
}
return total;
}
int main()
{
std::string input = "dadymathewdadreadady";
int c = count(input, "dad");
return 0;
}
Other Solution:
#include <iostream>
#include <string>
using namespace std;
int main(){
int n;
string s[50];
int c;
cin>>n;
for (int i=0;i<n;i++){
cin>>s[i];
}
for (int i=0;i<n;i++) {
c=0;
int found=s[i].find("jack");
while(found!=string::npos){
found=s[i].find("jack",found+1);
if(found) c++;
}
cout<<c<<endl;
}
}
I am working on creating a simulation of a test that will
1. randomize multiple choice answers
2. display the choices from a) b) c) d)
I have both codes done separately however can I use on for-loop to go about displaying this? Is this the best way to do this? All help is appreciated thank you!
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main (){
const int TEST_SIZE = 13;
srand(time(0));
string animals[TEST_SIZE] = {"dog","cat","fish","elephant","rhinoceros","cheetah","tiger","lion","zebra","giraffes","alligators","sloths","kangaroos" };
for (int i = 0; i < TEST_SIZE; i++){
//generate random index number (0,1,2,3,4,5...)
int index = rand() % FACE_SIZE;
//swap animals[i] with animals[index]
string temp = animals[i];
animals[i] = animals[index];
animals[index] = temp;
}
//loop through array and print values
for (int i = 0; i < 7; i++){
cout << animals[i] << " ";
}
}
//separate code for part 2: choices from a-g
#include <iostream>
#include <string>
using namespace std;
int main()
{
const int CHOICE_SIZE = 7;
string choices[] = { "a)", "b)","c)","d)","e)","f)","g)" };
for (int i = 0; i < CHOICE_SIZE; i++) {
cout << choices[i] << " ";
}
}
You can iterate over both arrays and stop when smaller will ends
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main (){
const int TEST_SIZE = 13;
srand(time(0));
string animals[TEST_SIZE] = {"dog","cat","fish","elephant","rhinoceros","cheetah","tiger","lion","zebra","giraffes","alligators","sloths","kangaroos" };
for (int i = 0; i < TEST_SIZE; i++){
//generate random index number (0,1,2,3,4,5...)
int index = rand() % FACE_SIZE; // maybe here should be TEST_SIZE?
//swap animals[i] with animals[index]
string temp = animals[i];
animals[i] = animals[index];
animals[index] = temp;
}
//loop through array and print values
for (int i = 0; i < 7; i++){
cout << animals[i] << " ";
}
const int CHOICE_SIZE = 7;
string choices[] = { "a)", "b)","c)","d)","e)","f)","g)" };
for (int i = 0; i < CHOICE_SIZE && i < TEST_SIZE; i++) {
cout << choices[i] << " " << animals[i] << ", ";
}
}
Also, consider that if you want to use fixed-size array, you can use std::array:
#include <array>
std::array<string, TEST_SIZE> animals = {...};
And for shuffling you can use std::shuffle from 'algorithm' header .
I am trying to convert this code that works for '0' - '3' strings to integer so that it will work for higher numbers
#include <string>
#include <iostream>
using namespace std;
void permutate(char[], int );
bool recurse(char[], int );
int main()
{
int strLength;
cout << "Enter your desired length: ";
cin >> strLength;
char strArray[strLength];
for (int i = 0; i<strLength; i++)
strArray[i] = '0';
permutate(strArray, sizeof(strArray));
return 0;
}
void permutate(char charArray[], int length)
{
string wait;
length--;
bool done = false;
while(!done)
{
for (int i = 0; i <= length; i++)
cout << charArray[i];
cout << endl;
if (charArray[length] == '3')
done = recurse(charArray, length);
else
charArray[length] = (char)(charArray[length]+1);
}
}
bool recurse(char charArray[], int length)
{
bool done = false;
int temp = length;
if (temp > 1)
{
charArray[temp] = '0';
if (charArray[temp-1] == '3')
{
temp--;
done = recurse(charArray, temp);
}
else
(charArray[temp-1] = (char)(charArray[temp-1] + 1));
}
else
{
charArray[temp] = '0';
if (charArray[temp-1] == '3')
done = true;
else
charArray[temp-1] = (char)(charArray[temp-1]+1);
}
return done;
}
I changed every char to int,
every '0' = 0, '3' = 3
every (charArray[temp-1] = (char)(charArray[temp-1] + 1)); to charArray[temp-1]++;
I tried to debug but I still can`t make it work :(
Manged to fix it( works for high numbers):
#include <string>
#include <iostream>
using namespace std;
void permutate(int[], int, int );
bool recurse(int[], int, int );
int main()
{
int strLength, nrElem;
cout << "Enter your desired length: ";
cin >> strLength;
cout << "Enter nr elem: ";
cin >> nrElem;
int strArray[strLength];
for (int i = 0; i<strLength; i++)
strArray[i] = 0;
permutate(strArray, strLength, nrElem );
cout << "\nSTOP";
return 0;
}
void permutate(int charArray[], int length, int nrElem)
{
// length--;
bool done = false;
while(!done)
{
for (int i = 0; i < length; i++)
cout << charArray[i] << " ";
cout << endl;
if (charArray[length - 1] == nrElem)
//done = true;
done = recurse(charArray, length, nrElem);
else
charArray[length - 1]++;
}
}
bool recurse(int charArray[], int length, int nrElem)
{
bool done = false;
int temp = length ;
if (temp > 1)
{
charArray[temp] = 0;
if (charArray[temp-1] == nrElem)
{
temp--;
done = recurse(charArray, temp, nrElem);
}
else
charArray[temp-1]++;
}
else
{
charArray[temp] = 0;
if (charArray[temp-1] == nrElem)
done = true;
else
charArray[temp-1]++;
}
return done;
}
In your permutate function, you're incrementing charArray[length] but checking to see if charArray[length - 1] is equal to nrElem, so you never end up calling recurse.
Here is a short piece of code to do the same (not an answer, however it did not look right in a comment field), not sure if you need the recursion, if you do not this code may be of interest:
#include <iostream>
#include <sstream>
using namespace std;
string output(int firstIntSize, int secondIntSize)
{
std::ostringstream oss;
for (int i = 0; i<firstIntSize; i++)
{
for (int j = 0; j< secondIntSize; j++)
{
oss << i << j << " ";
}
}
return oss.str();
}
int main()
{
cout << output(2,3);
return 0;
}
hmmm... Why not simply make a Permutations algorithm and then use a generic function to print whatever you are permutating. Here's how I would do it for strings:
#include <iostream>
#include <string>
template<class T>
void print(T * A, unsigned n){ //for printing purposes
for(unsigned i=0;i<n;i++){
std::cout<<A[i]<<" ";
}
std::cout<<std::endl;
}
void generate_permutations(unsigned k, std::string str, char *A, bool *U){
// k is the position that we need to fill, starts from 0 and goes to the end.
if(k<str.size()) //if k==str.size() then we will print it
for(unsigned i=0;i<str.size();i++){
if(U[i]==0){
A[k]=str[i]; U[i]=1;
generate_permutations(k+1, str, A,U);
U[i]=0; //after the recursion is finished and printed, we can release the letter.
}
}
else
print(A,str.size());
}
int main(){
std::string str;
std::cout<<"Enter the string to be permutated: \n";
std::cin>>str;
int n;
n = str.length(); // You don't really need to ask the user the size of the string he/she wants to enter.
bool *U; // we will keep track of the used letters with the help of this boolean vector
char *A; // we will copy the contents of str here, so that we keep the str intact
U = new bool[n];
for (int i=0;i<n;i++) U[i]=false;
A = new char[n];
for (int i=0;i<n;i++) A[i]=str[i];
generate_permutations(0,str,A,U);
return 0;
}
Now if you want to convert to numbers (ints), it's almost the same:
#include <iostream>
template<class T>
void print(T * A, int n){
for(int i=0;i<n;i++){
std::cout<<A[i]<<" ";
}
std::cout<<std::endl;
}
void generate_permutations(int k, int *A, bool *U, int n){
if(k==n)
print(A,n);
else {
for(int i=0;i<n;i++){
if(U[i]==0){
A[k]=i; U[i]=1;
generate_permutations(k+1,A,U,n);
U[i]=0;
}
}
}
}
int main(){
int n;
std::cout<<"Permutations of how many objects? \n";
std::cin>>n;
int * A;
bool *U;
A = new int[n];
U = new bool[n];
for (int i=0;i<n;i++) U[i]=false;
print(U, n);
generate_permutations(0,A,U,n);
return 0;
}
I have modified the code from my previous question, and now it looks like this:
//#include "stdafx.h"
#include <iostream>
#include <cstring>
#include <chrono>
#include <cassert>
using namespace std;
const int MAX_SIZE=10000;
const int MAX_STRINGS = 10;
char** strings=new char*[10];
int len;
char* GetLongestCommonSubstring( char* str1, char* str2 );
inline void readNumberSubstrings();
inline const char* getMaxSubstring();
void readNumberSubstrings()
{
cin >> len;
assert(len >= 1 && len <=MAX_STRINGS);
for(int i=0; i<len;i++)
strings[i]=new char[MAX_SIZE];
for(int i=0; i<len; i++)
cin >> strings[i];
}
const char* getMaxSubstring()
{
char *maxSubstring=strings[0];
auto begin = chrono::high_resolution_clock::now();
for(int i=1; i < len; i++)
maxSubstring=GetLongestCommonSubstring(maxSubstring, strings[i]);
cout << chrono::duration_cast <chrono::milliseconds> (chrono::high_resolution_clock::now()-begin).count() << endl;
return maxSubstring;
}
char* GetLongestCommonSubstring( char* string1, char* string2 )
{
if (strlen(string1)==0 || strlen(string2)==0) cerr << "error!";
int *x=new int[strlen(string2)+ 1]();
int *y= new int[strlen(string2)+ 1]();
int **previous = &x;
int **current = &y;
int max_length = 0;
int result_index = 0;
int length;
int M=strlen(string2) - 1;
for(int i = strlen(string1) - 1; i >= 0; i--)
{
for(int j = M; j >= 0; j--)
{
if(string1[i] != string2[j])
(*current)[j] = 0;
else
{
length = 1 + (*previous)[j + 1];
if (length > max_length)
{
max_length = length;
result_index = i;
}
(*current)[j] = length;
}
}
swap(previous, current);
}
delete[] x;
delete[] y;
string1[max_length+result_index]='\0';
return &(string1[result_index]);
}
int main()
{
readNumberSubstrings();
cout << getMaxSubstring() << endl;
return 0;
}
It's still solving the generalised longest common substring problem, and now it's rather fast.
But there's a catch: if a user specifies, say, 3 as a number of strings he's about to enter, and then only actually enters one string, this code waits forever.
How do I change that?
If you read from a file and the number of arguments isn't equal to the number of arguments provided, just print a nice, clean error message to the user.
"Expected 7 arguments, received 3:"
Print out the arguments you found so the user has an idea of what the program is looking at when it spits out the error.
As for human input, I agree with the comments. The program should wait until the user close it or enters all the needed arguments.