The Question :
If the sequence of digits in X forms a substring of the sequence of digits in Y, it outputs "X is a substring of Y"; otherwise, if the sequence of digits in X forms a subsequence of the sequence of digits in Y, then it outputs "X is a subsequence of Y"; otherwise, it outputs "X is neither substring nor subsequence of Y".
DO NOT use arrays or strings in this program
The output should be as follows
Enter Y : 239847239
Enter X : 847
X is substring of Y
Enter Y : 239847239
Enter X : 3923
X is subsequence of Y
Enter Y : 239847239
Enter X : 489
X is neither substring nor subsequence of Y
And below is what I got so far... (haven't coded anything for subsequence as i was clueless)
I know my coding is very unefficient and is only suitble to use for the above model output. Any improvements or comments how to fix this would be greatly appreciated.
#include <cmath>
#include <iostream>
using namespace std;
int main() {
cout << "Enter Y: " ;
int Y;
cin >> Y;
cout << "Enter X: ";
int X;
cin >> X;
if (Y >= X){ // Below are all the possibilities of substrings up to 9 decimal places.
if( X == (Y % 10)) cout << "X is substring of Y";
else if (X == (Y % 100)) cout << "X is substring of Y";
else if (X == (Y % 1000)) cout << "X is substring of Y";
else if (X == (Y % 10000)) cout << "X is substring of Y";
else if (X == (Y % 100000)) cout << "X is substring of Y";
else if (X == (Y % 1000000)) cout << "X is substring of Y";
else if (X == (Y % 10000000)) cout << "X is substring of Y";
else if (X == (Y % 100000000)) cout << "X is substring of Y";
else if (X == (Y % 1000000000)) cout << "X is substring of Y";
else cout << "X is neither substring nor subsequence of Y";
}
else cout << "neither subsequence nor subset"; // prints out when Y is less than X.
return 0;
}
This what i got by far:
Substring
bool substring(long x, long y){
double auxX = x;
int power = 0;
while (auxX >= 1){
auxX /= 10;
++power;
}
int mask = pow(10, power);
int reminder;
while (y > 0){
reminder = y % mask;
if (reminder == x){
return true;
}
y /= 10;
}
return false;
}
Subsequence
bool subsequence(long x, long y){
int lastX;
int lastY;
while (y > 0){
lastX = x % 10;
lastY = y % 10;
if (lastX == lastY){
x /= 10;
if (x <= 0){
return true;
}
}
y /= 10;
}
return false;
}
Main
int main()
{
long x = 21;
long y = 469721481;
if (substring(x, y)){
cout << x << " is substring of " << y << std::endl;
}
else if (subsequence(x, y)){
cout << x << " is subsequence of " << y << std::endl;
}
else{
cout << x << " is neither substring nor subsquence of " << y << std::endl;
}
return 0;
}
I've tested some cases and it seems to work fine, but you should test with edge cases (multiple repetitions of the same pattern, one digit numbers, zeros, etc) and retouch this snippet
Related
Take 4 variables from user w, x ,y ,z.
If w ‘x’ y = z print “You are right” otherwise, print
“ERROR
Below is the code I created for this problem, but it seems there is something wrong.
#include<iostream>
using namespace std;
void calculate(int w, char x, int y, int z)
{
if (x == '+') {
int z = w + y ;
cout << "You are right" <<endl;
}
else if (x == '-') {
int z = w - y ;
cout << "You are right" << endl;
}
else if (x == '*') {
int z = x * y;
cout << "You are right" << endl;
}
else
cout << "Error!" << endl;
}
int main()
{
int w, y, z;
char x;
cout << "Enter values for w, x, y, and z: " << endl;
cin >> w >> x >> y >> z;
cout << endl;
calculate(w, y, x, z);
return 0;
}
void calculate(int w, char x, int y, int z)
{
if (x == '+') {
int z = w + y ;
cout << "You are right" <<endl;
}
else if (x == '-') {
int z = w - y ;
cout << "You are right" << endl;
}
else if (x == '*') {
int z = x * y;
cout << "You are right" << endl;
}
else
cout << "Error!" << endl;
}
If you look closely int z = w + y is wrong as you are already taking z as a function parameter.
The correct statement, however, would be z = w + y.
The second thing, you need to remove int z from your function parameters, but declare and define it inside the function body. This is because when you pass z from main(), you aren't really passing the variable z. But merely the value of it which will get copied into int z in calculate.
Passing z as a reference
If you want the z in your main to update, you shall pass the value by reference.
void calculate(int w,char x,int y,int& z)
{
//updating z
}
Now, if you apply any change to z in calculate(), it will also appear your main().
Another solution is to to return int from the function and assign to the variable z in main().
#include <iostream>
int calculate(int w,int y,char x)
{
switch(x)
{
case '+':
std::cout << "You are right!\n";
return w+y;
case '-':
std::cout << "You are right!\n";
return w-y;
case '*':
std::cout << "You are right!\n";
return w*y;
default:
std::cout << "You are wrong!\n";
break;
}
}
int main()
{
int w = 5;
int y = 10;
char x = '+';
int z = calculate(w,y,x);
std::cout << z;
return 0;
}
So basically I am trying to get it to stop repeating. If I enter numbers correctly it works fine. If I enter negative numbers which are not allowed and needs a try-catch exception it keeps repeating and won't stop asking for numbers.
All I have is this source file for the code and I am trying to make a function for main.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
void gcd(int x, int y);
int main()
{
int x;
int y;
cout << "Please enter two integer values" << endl;
cin >> x;
cin >> y;
gcd(x, y);
return 0;
}
void gcd(int x, int y)
{
int gcd;
int s = 0;
while (s == 0)
{
try
{
if (x < 0 || y < 0)
throw 1;
else
{
s == 1;
break;
}
}
catch (int x)
{
cout << "Wrong negative input please type in two Positive integers" << endl;
cin >> x >> y;
continue;
}
}
for (int i = 1; i <= x && i <= y; i++)
{
if (x % i == 0 && y % i == 0)
gcd = i;
}
cout << "The gcd of x: " << x << " and y: " << y << " is: " << gcd << endl;
}
If you don't want your function gcd() to be called with negative values, throw a std::invalid_argument exception. It is not the business of gcd() to request user input. Validate the input in main() before you call gcd().
#include <limits>
#include <stdexcept>
#include <iostream>
int gcd(int, int);
int main()
{
int x, y;
while (std::cout << "Please enter two positive integers: ",
!(std::cin >> x >> y) || x < 0 || y < 0)
{
std::cerr << "Input error :(\n\n";
if (std::cin.fail()) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
std::cout << "The gcd of x: " << x << " and y: " << y << " is: " << gcd(x, y) << "\n\n";
}
int gcd(int x, int y)
{
if (x < 0 || y < 0)
throw std::invalid_argument("No negative arguments to gcd(), please :(");
return y == 0 ? x : gcd(y, x % y);
}
You can (and perhaps should) remove the logic from gcd function and instead place it where you get your input from user, that is, in main. Also, state the requirements up front. For example:
int main()
{
int x;
int y;
cout << "Please enter two positive integer values" << endl;
cin >> x;
cin >> y;
if (x < 0 || y < 0)
{
cout << "Wrong negative input please type in two Positive integers" << endl;
return 0;
}
gcd(x, y);
return 0;
}
Now, you can place assertions in gcd to enforce no negative values get in:
void gcd(int x, int y)
{
assert(x >= 0);
assert(y >= 0);
// ...
}
This is a simple introduction course question. I have to write a program that asks the user to input 3 numbers, and determines the largest and smallest number.
I need to only use if statements.
This is what I tried so far: which required 4 comparisons.
int x, y, z;
int smallest, largest;
cout << "Please enter 3 numbers to compare: " ;
cin >> x >> y >> z;
smallest = x;
largest = x;
if (y > largest)
largest = y;
if (z > largest)
largest = z;
if (y < smallest)
smallest = y;
if (z < smallest)
smallest = z;
cout << "largest: " << largest << ", and smallest: " << smallest << endl;
My question is: Is it possible to only use 3 comparisons, or less? I think when y > largest, it also tells us something else as well?
The issue with your code is that you toss out a lot of information. In "challenges" such as these, you have to make the most of what you have. So when you say, for example
if (y > largest)
don't just treat the true case. Also try to reason about the case when the condition doesn't hold.
if ( x < y )
{
smallest = x;
biggest = y;
}
else
{
smallest = y;
biggest = x;
}
if ( z < smallest )
smallest = z;
else if ( z > biggest )
biggest = z;
This contains only 3 comparisons.
Why are you checking if (y < smallest)? At this point in the flow, smallest must be x, but you've already checked if y > x in the first condition (if (y > largest)), so the third condition is redundant.
The question is finding the largest or smallest by only if else statements, and we have three variables to use, so we only need two comparisons.
{
int valueOne,
valueTwo,
valueThree,
smallest;
//User input for valueOne, valueTwo, valueThree.
smallest = valueOne;
if (smallest < valueTwo)
{
smallest = valueTwo;
}
if (smallest < valueThree)
{
smallest = valueThree;
}
//No matter what happens, smallest will have the smallest value now.
//Use >, rather than <, and "largest" rather than "smallest" for finding largest value.
//With this logic, you always will have one less comparison than the total number or variables to compare
//i.e. 7 variables means 6 comparisons.
//This contains only 2 comparisons.
In general you can determine a sort for three numbers x, y, and z using at most 3 comparisons:
if (x < y)
if (y < z)
//x,y,z -> x min
else if (x < z)
//x,z,y -> x min
else
//z,x,y -> z min
else
if (z >= x)
//y,x,z -> y min
else if (z >= y)
//y,z,x -> y min
else
//z,y,x -> z min
So getting the min can also be done with 3 comparisons.
You can get the min in 2 comparisons by doing:
m = x;
m = min(m,y);
m = min(m,z);
where min(a,b) is a < b ? a : b.
In general you can get the min of N numbers using N - 1 comparisons.
I find this easiest to understand for you.
a = 5;
b = 10;
c = 15;
//FIND MAX
if (a >= b && a >= c)
{
max = a;
} else
{
if (b >= c)
max = b
else
max = c;
}
//FIND MIN
if (a <= b && a <= c)
{
min = a;
} else
{
if (b <=c)
min = b;
else
min = c;
}
This one is just for fun and I believe the myabs function is actually supposed to be undefined behaviour, but I've only ever seen places that it works as expected.
double myabs(double x)
{
int64_t * p = (int64_t*)&x;
//clear sign bit
*p &= 0x7fffffffffffffff;
return x;
}
int main()
{
double x = 0, y = 1, z = 2;
//find max/min of first two numbers
double min = (myabs(x+y)-myabs(x-y))/2;
double max = (myabs(x+y)+myabs(x-y))/2;
//find max/min of previous max/min and third number
min = (myabs(min+z) - myabs(min-z))/2;
max = (myabs(max+z) + myabs(max-z))/2;
std::cout << min << ' ' << max << std::endl;
return 0;
}
Which outputs 0 2 correctly with 0 comparisons in total.
int a; int b; int c;
cin >> a >> b >> c;
if ( a > b && b > c ){ cout << a << " MAIXM \n" << b << " MEDIU \n" << c << " MINIM \n"; }
if ( b > a && a > c ){ cout << b << " MAIXM \n" << a << " MEDIU \n" << c << " MINIM \n"; }
if ( c > b && b > a ){ cout << c << " MAIXM \n" << b << " MEDIU \n" << a << " MINIM \n"; }
if ( a > c && c > b ){ cout << a << " MAIXM \n" << c << " MEDIU \n" << b << " MINIM \n"; }
if ( b > c && c > a ){ cout << b << " MAIXM \n" << c << " MEDIU \n" << a << " MINIM \n"; }
if ( c > a && a > b ){ cout << c << " MAIXM \n" << a << " MEDIU \n" << b << " MINIM \n"; }
I was attempting to write a program for exercise 2.19 in How to Program, but I ran into some difficulties.
The program is supposed to have the user enter three integers and then display the sum, average, and product of those integers.
The only problem I am having is with displaying the largest and smallest. When I ran the program and entered three integers (8, 9, and 10), the output read Smallest is 8 AND Smallest is 9.
I was hoping you could tell me why.
#include <iostream>
using namespace std;
int main ()
{ int x, y, z, sum, ave, prod;
cout << "Input three different integers ";
cin >> x >> y >> z;
sum = x + y + z;
cout << "\nThe sum is " << sum;
ave = (x + y + z) / 3;
cout << "\nThe average is " << ave;
prod = x * y * z;
cout << "\nThe product is " << prod;
if (x < y, x < z)
{cout << "\nSmallest is " << x;}
if (y < x, y < z)
{cout << "\nSmallest is " << y;}
if (z < x, z < y)
{cout << "\nSmallest is " << z;}
if (x > y, x > z)
{cout << "\nLargest is " << x << endl;}
if (y > x, y > z)
{cout << "\nLargest is " << y << endl;}
if (z > x, z > y)
{cout << "\nLargest is " << z << endl;}
return 0;
}
P.S. I am doing this to study, this is not homework.
You need to rewrite this if condition
if (x < y, x < z)
to be
if (x < y && x < z)
and do the same for all of the remaining if conditions you have.
Edit:
All experssions seperated by comma will be evaluated so if you have something like that
x = 5, y = 6; it will evaluate both of them and set x to 5 and y to 6
but
z = (x=5, y=6); this will cause z to be set to 6 just like y as y=6 was the last term in the list of comma separated terms.
int main() {
std::cout << "Enter three numbers: ";
int sum = 0;
double avg = 0.;
int product = 0;
int smallest = std::numeric_limits<int>::max();
int largest = std::numeric_limits<int>::min(); // the initializers here might not be correct, but the gist is in place...
for (int i = 0; i < 3; ++i) {
int val = 0;
std::cin >> val;
sum += val;
avg += val;
product *= val;
if (val < smallest) smallest = val;
if (val > largest) largest = val;
}
avg /= 3.; // This can also be done in the for loop, I just forget how.
std::cout << "Sum: " << sum;
// etc... The calculations are all done.
}
Replace your commas, with && for an AND operator, meaning both of the conditions have to be true, or || which is an OR operator, if you want any or both conditions to be satisfied.
from C++ docs:
The comma operator (,) is used to separate two or more expressions that are included
where only one expression is expected. When the set of expressions has to be evaluated
for a value, only the rightmost expression is considered.
Instead of comma, you want &&
i.e.
if (x < y , x < z)
{cout << "\nSmallest is " << x;}
should be
if (x < y && x < z)
{cout << "\nSmallest is " << x;}
Use && in place of , inside your if conditions.
By now you realize that && is for AND and that you should use this operator instead of the comma, ,. But did you know you can also use they keyword and in place of its symbol equivalent?:
if ( x < y and x < z ) {
}
Do if statements work this way? This is a "guess the number" game. The 1st if says to go higher/lower, the 2nd if says if you're within a 50, 100 or 100+ range.
Both are supposed to work simultaneously, but I get an error.
Line 37 unexpected primary expression before '| |' token, Line 38
expected ';' before 'cout'
#include <iostream>
#include <cstdlib>
#include <time.h>
#include <cstdio>
using namespace std;
int main()
{
int x;
cout << "Please enter a number\n";
srand(time(0));
int y = rand();
while (x != y)
{
cin >> x;
{
if (!(cin.good())) //1st if
{
cout << "No letters noob" << endl;
cin.clear();
cin.sync();
}
else if (x < y)
cout << "Go higher" << endl;
else if (x > y)
cout << "Go lower" << endl;
else
cout << "You win!!" << endl;
}
{
if (y - x - 50 <= 0) || (x - y - 50 <= 0) //2nd if
cout << "within 50 range" << endl;
else if (y - x - 100 <= 0) || (x - y - 100 <= 0)
cout << "within 100 range" << endl;
else
cout << "100+ value away" << endl;
}
}
cin.get();
getchar();
return 0;
}
You are missing parentheses.
For example, this line:
if (y - x - 50 <= 0) || (x - y - 50 <= 0)
Should read:
if ((y - x - 50 <= 0) || (x - y - 50 <= 0))
Because the entire if condition must be wrapped in parentheses.
Looks like you may have some other issues there as well.
In addition to the correct answer by #jonathan-wood, the following may express your intent more clearly:
#include <cstdlib>
...
const int off_by = abs(x - y);
if (off_by <= 50) {
...
} else if (off_by <= 100) {
...
}
FYI: if you think it would improve your code's readability, you can also use "or" and "and" instead of "||" and "&&". So, the following is legal:
if ((y - x - 50 <= 0) or (x - y - 50 <= 0)) {
...
}