My program that should display a N even digit number shows mess - c++

So recently i got a programing task from a contest and my code should display the N
even digit number from 0. In even digit numbers all numbers must be dividable by 2. When i input the number 12 it should show the number 44 on the output but it shous some kind of a mess. here's my code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int kturaParzysta = 1;
int N;
cin >> N;
int tab[N];
for(int i = 0; i < N;i++){
string cyfraStr = to_string(N);
bool parzystocyfrowa = true;
for(int j = 0;j <= cyfraStr.length();j++){
if(int(cyfraStr[j]) % 2 != 0){
parzystocyfrowa = false;
}
}
if(parzystocyfrowa){
tab[kturaParzysta] = i;
kturaParzysta++;
}
}
cout << tab[N - 1];
return 0;
}

Related

what changes should i have to do to in my cpp code to get correct output?

//Question
/*There are N seats in a row. You are given a string S with length N; for each valid i, the i-th character of S is '0' if the i-th seat is empty or '1' if there is someone sitting in that seat.
Two people are friends if they are sitting next to each other. Two friends are always part of the same group of friends. Can you find the total number of groups?
Input
The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
The first and only line of each test case contains a single string S.
Output
For each test case, print a single line containing one integer ― the number of groups.*/
// my code
#include <iostream>
#include <string>
using namespace std;
int main() {
int t;
cin>>t;
int n=1e6;
for(int i=0;i<t;i++){
string g1;
cin>>g1;
int group;
group = 0;
for(int j=0;j<g1.length();j++){
if(g1[j] == '1'){
for(int h=1;h<n;h++){
if(g1[j+h] == '1'){
h++;
}else{
break;
}
group++;
}
} else{
continue;
}
}
cout<<group<<endl;
}
return 0;}
Example Input
4
000
010
101
01011011011110
Example Output
0
1
2
4
//my output
0
0
0
9
Based on sample output, you suppose to count '1's between zeros, which is the number of groups you have. Here is your implementation with small correction to do that.
#include <iostream>
#include <string>
using namespace std;
int main() {
int t;
cin >> t;
// int n = 1e6; --> not used
for (int i = 0; i < t; i++) {
string g1;
cin >> g1;
int group;
group = 0;
for (size_t j = 0; j < g1.length(); j++) {
if (g1[j] == '1') {
group++;
//skip all '1' before the first '0'
while (g1[j] == '1' && j < g1.length())
j++;
}
else {
continue;
}
}
cout << group << endl;
}
return 0;
}
// my code
#include <iostream>
#include <string>
using namespace std;
int main() {
int t;
cin >> t;
// you don't need n variable
// it is appropriate to use the length of the string instead
// it also will remove one warning for initialization
int n = 1e6;
for (int i = 0; i < t; i++) {
string g1;
cin >> g1;
int group; // you can use int group = 0; avoiding the statement below
group = 0;
// size_t stringLength = g1.length();
for (int j = 0; j < g1.length(); j++) {
if (g1[j] == '1') {
group++; // you need to add it here to starts counting
// better this way -> for (size_t h = 1; h < stringLength; h++)
for (int h = 1; h < n; h++) { // h < n && (j+h)<stringLength
if (g1[j + h] == '1') {
// you increasing h value twice - first in for statement, second here
// instead, you need to set j to j+h value
//h++;
// you just "moving" through the string till next'0'
j = j + h;
}
else {
break;
}
// this will increase group count for each next '1' in the string
// this is why you got 9 for the last string in your's example
//group++;
}
}
// this is not needed
//else {
// continue;
//}
}
cout << group << endl;
}
return 0;
}

C++ generating random words

Write a program which generate random words (number of words = n). Max length of word = m.
Words must contain big and samll letters. Probability of big letters must eqals 50%.
Example:
Input: 2 4
Output: AbCd eFgH
How do I do that?
So far i figured out how to generate random small and big letter.
My code:
#include <iostream>
using namespace std;
int main()
{
int n,m,s;
cin >> n;
cin >> m;
s=n*m;
char Tab[s];
for(int i=0; i<n*m; i++)
{
Tab[i]= 'A' + rand()%25;
}
for(int i=1; i<n*m; i++)
{
Tab[i+2]= 'a' + rand()%25;
}
for(int i=0; i<n*m; i++)
{
cout << Tab[i] << " ";
}
return 0;
}
Code-
#include <iostream>
#include <time.h>
#include <string>
#include <stdlib.h>
using namespace std;
int main() {
int n,m;
cin>>n>>m;
srand(time(NULL));// without this rand() function might continuously give the same value
while(n--){
int stringLen = (rand() % m) +1; // getting random length
string s=""; // taking null string
for(int i=0; i<stringLen; i++){
if(rand() % 2 == 0 ){ // capital or small letter
s += 'A' + (rand() % 26);
}else{
s += 'a' + (rand() % 26);
}
}
cout<<s<<" ";
}
}

Print prime numbers in columns and rows to a file

I created a function that finds prime numbers and I need help writing those numbers to a file in a well-formatted table with columns and rows. I think I'll need some nested loops, but I don't know what could be the best implementations. Here is my code so far, I hope you guys could help me. Thanks
Right now what my code does is write the number 2 and 3 to the file and then it goes on an infinite loop of empty lines.
The file should look like this:
2 3 5 11 13 17 19 23
29 31 37 41 43 47 53
... All the way up to closest prime number to 4000
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
bool isPrime(int);
int main()
{
int counter = 0;
int currentNumber = 2;
ofstream outputFile("test.txt");
for (int i = 2; i < 4000; i++)
{
for (int row = 1; row < 4000; row++)
{
for (int col = 1; col <= 8; col++)
{
if (isPrime(i) == true)
{
outputFile << endl;
outputFile << setw(8);
outputFile << i;
outputFile << setw(10);
i++;
}
}
outputFile << endl;
}
}
system("pause");
return 0;
}
bool isPrime(int number)
{
for (int i = 2; i < number; i++)
{
if (number % i == 0)
{
return false;
}
}
return true;
}
You're so close. Just count up to 8 primes and print out a new line, then reset the counter until the next 8. You have duplicated the i++ inside the loop as well as on the "for" line, the row and col stuff is all unecessary.
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
bool isPrime(int number)
{
for (int i = 2; i < number; i++)
{
if (number % i == 0)
{
return false;
}
}
return true;
}
int main()
{
int counter = 0;
ofstream outputFile("test.txt");
for (int i = 2; i < 4000; i++)
{
if (isPrime(i) == true)
{
outputFile << setw(8);
outputFile << i;
outputFile << setw(10);
counter++;
}
if (counter == 8)
{
outputFile << endl;
counter = 0;
}
}
return 0;
}
Richq already gave you a better way to implement this but lets look at what you did wrong in your code (looking at your intent, not always what it does):
Your outer loop goes from 2 to 4000. For each number you then print a table. (Not really since you increment i inside the table too but lets ignore that.) This is somewhat wrong. You only ever want one table so the outer loop has to go. Keep the int i = 2; though.
Second loop: row goes from 1 to 4000, printing 8 prime numbers per line. But you only want numbers smaller than 4000. Clearly 4000 * 8 primes will be larger. You don't know how many lines of table you will need. Your exit condition for the rows should be i < 4000 instead.
Third loop: col goes from 1 to 8. But maybe on the last line i will exceed 4000 on the 3rd number. So if i < 4000 is a hard limit (instead of printing till the end of the line even if you already reached 4000) then you need to include that in the condition: (col <= 8) && (i < 4000).
Inner part has 2 problems:
You print a new line before every prime number. That's why you get a single 2 and 3 in a line instead of both in the same line.
You increment i only if i is a prime number. So after 2 and 3 your increment i. But then you have 4 and the rest of your table will just test that 4 is not a prime and print nothing.
Move the newline out of the inner loop. You need to only do that after each row. And inside the row always increment i. But only increment col if you found a prime number.
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
bool isPrime(int);
int main()
{
int counter = 0;
int currentNumber = 2;
ofstream outputFile("test.txt");
int i = 2;
for (int row = 1; i < 4000; row++)
{
for (int col = 1; (col <= 8) && (i < 4000); i++)
{
if (isPrime(i) == true)
{
outputFile << setw(8);
outputFile << i;
outputFile << setw(10);
col++;
}
}
outputFile << endl;
}
return 0;
}
bool isPrime(int number)
{
for (int i = 2; i < number; i++)
{
if (number % i == 0)
{
return false;
}
}
return true;
}

C++ Birthday Probability

I am trying to teach myself C++ in preparation for graduate school this coming fall but I am having some trouble with this birthday paradox problem. My code seems to run ok but I am not getting the correct output. If anyone has any suggestions please let me know.
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
srand(time(NULL));
const int trials = 100000;
int birthdays[50];
int numMatches;
for(int i = 2; i <= 50; i++)
{
numMatches = 0;
for(int j = 1; j <= trials; j++)
{
for(int k = 1; k <= i; k++)
{
birthdays[k] = (rand() % 365) + 1;
}
int m = 1;
bool matched = false;
while(m < i && !matched){
int n = m + 1;
while(n <= i && !matched){
if(birthdays[m] == birthdays[n]){
numMatches++;
matched = true;
}
n++;
}
m++;
}
}
cout << "Probability of " << i << " people in a room sharing a birthday is \t"
<< ( float(numMatches) / float(trials) ) << endl;
}
}
Your code is not computing the probability of two people in a room of 50 sharing a birthday. There's several bugs, mostly with indexing, but here's the biggest issue:
for(int j = 1; j <= trials; j++) {
// assigns a random birthday to the first i people (should be 0 indexed)
for(k = 1; k <= i; k++)
birthdays[k] = (rand() % 365) + 1;
// Does *exactly* the same thing as the previous loop, overwriting what
// the initial loop did. Useless code
for(m = 1; m <= i; m++)
birthdays[m] = (rand() % 365) + 1;
// At this point, m = k = i + 1. Here you check if
// the i + 1st array value has the same b-day. It will, because they're
// the same thing. Note you never set the i + 1st value so the loops
// above did nothing
if(birthdays[k] == birthdays[m])
++numMatches;
}
So what you've got here is something like:
Perform 48 iterations of the following (from your first loop which goes from 2 to 50: no idea where those values came from)
For each of those 48 iterations, perform 10k iterations of:
assign a bunch of random stuff to an array overwriting stuff
Ignore the values you wrote in the array, do a comparison that's always true and increment numMatches by 1
Consider what's going on here:
for(int j = 1; j <= trials; j++) {
for(k = 1; k <= i; k++)
birthdays[k] = (rand() % 365) + 1;
for(m = 1; m <= i; m++)
birthdays[m] = (rand() % 365) + 1;
if(birthdays[k] == birthdays[m])
++numMatches;
}
You go through i birthdays and assign a random number, then you go through the same i birthdays and assign them a new random number. Then you try to find a match for just one value of k and m (which both happen to equal i+1, which isn't one of the values set!).
My suggestion is to break the problem down into smaller units that will make it easier to figure out how to code - here are the functions I would try to write.
/* randomizeBirthdays()
* Put n random birthdays into the pre-allocated array birthdays.
* birthdays must of course be of length <= n.
*/
void randomizeBirthdays(int * birthdays, int n);
/* hasMatchingBirthdays()
* Check if birthdays array has two people with the same birthday
* in the first n entries.
* Return value is boolean.
*/
bool hasMatchingBirthdays(int * const birthdays, int n);
/* probabilityOfMatch()
* Calculate the probability that at least 2 out of n people will
* have the same birthday, using nTrials number of trials.
* Return value is double.
*/
double probabilityOfMatch(int n, int nTrials);
If you break it down like this it becomes easier to write and easier to troubleshoot.
As I said in comments already:
I think your aim is to test if 2 people in room of 2-50 people share
birthday, not if 2-50 people share birthday as you say in output. And
that's 2 people out of 23 have 50.7%, not 24.
I completely reworked your code:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
#define DAYS_IN_YEAR 365
#define TRIALS 10000
void clearArray (bool * array)
{
for (int i = 0; i < DAYS_IN_YEAR; i++)
array[i] = false;
}
int main()
{
srand(time(NULL));
bool birthdays[DAYS_IN_YEAR]; //we are trying to hit same day in year twice
int r, numMatches;
for(int i = 2; i < 50; i++)
{
numMatches = 0;
for(int j = 0; j < TRIALS; j++)
{
clearArray(birthdays);
for(int k = 0; k < i; k++)
{
r = rand() % DAYS_IN_YEAR; // == 0-364
if (birthdays[r])
{
numMatches++;
break; // 2 people already have same birthdays here
}
birthdays[r] = true;
}
}
cout << "Probability of 2 people having same birthday in room of " << i << " people is "
<< (float)numMatches / TRIALS << endl;
}
}
Output:
Probability of 2 people having same birthday in room of 23 people is 0.516
I think the code must be something like this.
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int main() {
srand(time(NULL));
int birthdays[10000][50];
int numMatches;
int trials=10000,check;
for(int n=0;n<trials;n++)
{
for(int j=0;j<50;j++)
{
birthdays[n][j]=rand()%365+1;
}
}
for(int i=2;i<=50;i++)
{
numMatches=0;
for(int n=0;n<trials;n++)
{
check=1;
for(int j=0;j<i;j++)
{
for(int k=j+1;k<=i;k++)
{
if(birthdays[n][j]==birthdays[n][k]&&check)
{
numMatches++;
check=0;
}
}
}
}
cout << "Probability of " << i << " people in a room sharing a birthday is \t" <<
(static_cast<float>(numMatches) / (trials)) << endl;
}
}

Competitive programming: Solution runs a bit too slow

This is a question from a ZCO (Zonal Computing Olympiad; Indian IOI qualifying contest) paper.
Basically, it revolves around finding the number of distinct pairs of elements from a set of numbers whose sum does not exceed a certain value.
My solution works on all except the last test case (on a certain private server, the test case itself is not available), on which it exceeds the 3-second time limit by half a second.
Am I missing something, algorithmically? A few pointers would be nice.
Here is my code:
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
int main() {
int n, k;
cin >> n >> k;
vector<int> hardness;
hardness.reserve(n);
int temp;
for(int i = 1; i <= n; ++i) {
cin >> temp;
if (temp < k) {
hardness.push_back(temp);
}
}
sort(hardness.begin(), hardness.end());
int mx = hardness.back(); //Max element
int chewableCombinations = 0, cur = 0;
for(int i = 0; i < hardness.size() - 1; ++i) {
cur = hardness[i];
if(cur == 0 || cur + mx < k) {
chewableCombinations += hardness.size() - i - 1;
continue;
}
for(int j = i + 1; j < hardness.size(); ++j) {
if(cur + hardness[j] < k) {
++chewableCombinations;
} else break; //we've crossed the limit
}
}
cout << chewableCombinations << endl;
}
If hardness[i]+hardness[j] < k then hardness[i]+hardness[m] < k for all m < j.
You don't have to check them all.