When calling the function f4 how is the function returning 6? i really cant figure out how the function operates shouldnt it just return 1? because of (n-1)
#include <iostream>
#include<cmath>
#include<fstream>
using namespace std;
int x = 3;
void f1(int, int &);
int f4(int);
int main()
{
int x = 5; int y = 10;
f1(x, y);
cout << x << "\t" << y << endl;
x = 15; y = 20;
f1(x++, x);
cout << x << "\t" << y << endl;
x = 3;
cout << f4(x) << endl;
system("pause");
return 0;
}
void f1(int a, int &b)
{
a *= 2; b += x;
cout << a << "\t" << b << endl;
}
int f4(int n) {
if (n == 1 || n == 0)
return n;
else
return n + f4(n - 1);
}
The f4 function is recursive. This calling with a number other than 1 or 0 will make it recurse. You call it with 3, so the compiler (simplified) sees
f4(3) => 3 + f4(2) => 3 + 2 + f4(1) => 3 + 2 + 1 => 5 + 1 => 6
recursion in a nutshell..
int f4(int n) {
if (n == 1 || n == 0)
return n;
else
return n + f4(n - 1);
}
Your code states that when n is 1 or 0 just return n, otherwise add n to the result of the function.
that sets up a recursive stack where the first call n = 3 and it recurses.
on the next call n = 2 and it recurses.
on the next call n = 1 and it returns as well as the rest of the stack leading to 1 + 2 + 3 which is 6.
Related
Link of Question : https://www.codechef.com/JULY20B/problems/PTMSSNG
Question Statement
Chef has N axis-parallel rectangles in a 2D Cartesian coordinate system. These rectangles may intersect, but it is guaranteed that all their 4N vertices are pairwise distinct.
Unfortunately, Chef lost one vertex, and up until now, none of his fixes have worked (although putting an image of a point on a milk carton might not have been the greatest idea after all…). Therefore, he gave you the task of finding it! You are given the remaining 4N−1 points and you should find the missing one.
Can anyone suggest where I'm going wrong or update my code or share a few test cases.
#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#define ll long long
using namespace std;
int main()
{
int t;
cin >> t;
for (int i = 0; i < t; i++)
{
vector<pair<ll, ll>> v;
ll n, m, a;
bool checkx = false;
cin >> n;
m = 4 * n - 1;
ll x[m], y[m];
ll c, d;
a = (m - 1) / 2;
for (ll i = 0; i < m; i++)
{
cin >> x[i] >> y[i];
v.push_back(make_pair(x[i], y[i]));
}
sort(v.begin(), v.end());
for (ll i = a; i >= 1; --i)
{
if (v[2 * i].first != v[2 * i - 1].first)
{
c = v[2 * i].first;
checkx = true;
if ((2 * i) % 4 == 0 && i >= 2)
{
if (v[2 * i].second == v[2 * i + 1].second)
{
d = v[2 * i + 2].second;
}
else
{
d = v[2 * i + 1].second;
}
}
else
{
if (v[2 * i].second != v[2 * i - 1].second)
{
d = v[2 * i - 1].second;
}
else
{
d = v[2 * i - 2].second;
}
}
break;
}
}
if (checkx)
{
cout << c << " " << d;
}
else
{
if (v[0].second == v[1].second)
{
d = v[2].second;
}
else
{
d = v[1].second;
}
cout << v[0].first << " " << d;
}
cout << endl;
}
return 0;
}
You don't need to do such complex things. Just input your x and y vectors and xor every element of each vector. The final value will be the required answer.
LOGIC :
(a,b)------------------(c,b)
| |
| |
| |
| |
(a,d)------------------(c,d)
See by this figure, each variable (a, b, c, d) occurs even number of times. This "even thing" will also be true for the N rectangles. Hence, you have to find the values of x and y which are occurring odd number of times.
To find the odd one out in such cases, the best trick is to xor every element of the vector. This works because of these properties of xor : k xor k = 0 and k xor 0 = k.
CODE:
#include <functional>
#include <iostream>
#include <numeric>
#include <vector>
signed main() {
std::size_t t, n;
std::cin >> t;
while (t--) {
std::cin >> n;
n = 4 * n - 1;
std::vector<int> x(n), y(n);
for (std::size_t i = 0; i < n; ++i)
std::cin >> x.at(i) >> y.at(i);
std::cout << std::accumulate(x.begin(), x.end(), 0L, std::bit_xor<int>()) << ' '
<< std::accumulate(y.begin(), y.end(), 0L, std::bit_xor<int>()) << '\n';
}
return 0;
}
here is a test case that your code doesn't work:
1
2
1 1
1 4
4 6
6 1
9 6
9 3
4 3
the output of your code is (6,3),but it should be (6,4).
I guess you can check more cases where the rectangles intersects.
from functools import reduce
for _ in range(int(input())):
n=int(input())
li=[]
li1=[]
for i in range(4*n-1):
m,n=map(int,input().split())
li.append(m)
li1.append(n)
r =reduce(lambda x, y: x ^ y,li)
print(r,end=' ')
r =reduce(lambda x, y: x ^ y,li1)
print(r,end=' ')
print()
I have this simple function that I am calculating correctly, but my output statements are off. I have tried other places were the cout statement is commented, but not working.
int recursiveFunc(int n) {
int val; // value at nth sequence
//cout << "(" << n << ") = " << val << endl;
if (n == 1 ) { // base case 1
val = -1;
// outputs before function call
}
else if (n == 2) { // base case 2
val = -1;
// outputs before function call
}
else { // recursive case
//cout << "(" << n << ") = << val << endl;
val = 2*(recursiveFunc(n-1) + recursiveFunc(n-2));
cout << "(" << n << ") = " << val << endl; // not sure where to put cout statement
}
return val;
}
I am looking for an output like (for example n = 5):
(1) = -1
(2) = -1
(3) = -4
(4) = -10
(5) = -28
currently, my output looks like:
(1) = -1
(2) = -1
(3) = -4
(4) = -10
(3) = -4 // here an nth term is displayed twice
(5) = -28
Move your cout statement to outside the function and it works fine.
int recursiveFunc(int n) {
int val; // value at nth sequence
if (n == 1) { // base case 1
val = -1;
}
else if (n == 2) { // base case 2
val = -1;
}
else { // recursive case
val = 2 * (recursiveFunc(n - 1) + recursiveFunc(n - 2));
}
return val;
}
int main() {
for (int i = 1; i < 10; i++) {
std::cout << "(" << i << ") = " << recursiveFunc(i) << endl;
}
return 0;
}
Output:
(1) = -1
(2) = -1
(3) = -4
(4) = -10
(5) = -28
(6) = -76
(7) = -208
(8) = -568
(9) = -1552
Right off the top-of-my-head, a possible fix is to keep track of the highest n output so-far already and only output when a larger n is encountered. (This is probably not the best solution, but I'm feeling too tired and lazy to think about alternatives)
Don't use a global variable for this (mutable global state is an anti-pattern!) - you'll need to pass it as another parameter.
int output_n_and_val( int n, int val, int& biggestN ) {
if( n > biggestN ) {
cout << "(" << n << ") = " << val << endl;
biggestN = n;
}
return val;
}
int recursiveFuncImpl( int n, int& biggestN ) {
if( n == 1 ) {
return output_n_and_val( n, -1, biggestN );
}
else if( n == 2 ) {
return output_n_and_val( n, -1, biggestN );
}
else {
int val = 2 * ( recursiveFuncImpl( n - 1, biggestN ) + recursiveFuncImpl( n - 2, biggestN ) );
return output_n_and_val( n, val, biggestN );
}
}
// Entrypoint function:
int recursiveFunc( int n ) {
int biggestN = -1;
return recursiveFuncImpl( n, biggestN );
}
int main()
{
recursiveFunc( 10 );
recursiveFunc( 5 );
return 0;
}
The downside to this approach is that because of the n == 2 case-handling is encountered before n == 1 you'll never get the output (1) = -1. Fixing that is an exercise left for the reader.
you should use an array to store values that you have computed, for example
const int N = 1000000;
int values[N]; // remember to memset to 0 first
int recursiveFunc(int n) {
if(n < 0) return 0;
if(values[n] != 0) return values[n];
int val; // value at nth sequence
if (n == 1) { // base case 1
val = -1;
}
else if (n == 2) { // base case 2
val = -1;
}
else { // recursive case
val = 2 * (recursiveFunc(n - 1) + recursiveFunc(n - 2));
}
return values[n] = val;
}
int main() {
memset(values, 0, sizeof(values));
for (int i = 1; i < 10; i++) {
std::cout << "(" << i << ") = " << recursiveFunc(i) << endl;
}
return 0;
}
Problem is :
Write a function that as an input argument receives a three-digit positive number and as a result has to get the sum between the largest and the smallest number obtained by the same 3 digits divided by the median digit.
Example: input argument to function 438
The largest with the same digits is 843, the smallest is 348, so it should be calculated (843 + 348) / 4.
I have tried it and got the result ok but my code seems to complicated so iam asking is there a better way to do it?
Thanks in advance
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int check(int x) {
int a, b, c, biggestNum, smallestNum, medianNum;
a = x / 100;
b = (x / 10) % 10;
c = x % 10;
if (a > b && a > c && b > c) {
biggestNum= a * 100 + b * 10 + c;
smallestNum= c * 100 + b * 10 + a;
medianNum= b;
}
else if (a > b && a > c && b < c) {
biggestNum= a * 100 + c * 10 + b;
smallestNum= b * 100 + c * 10 + a;
medianNum= c;
}
else if (b > a && b > c && a < c) {
biggestNum= b * 100 + c * 10 + a;
smallestNum= a * 100 + c * 10 + b;
medianNum= c;
}
else if (b > a && b > c && a > c) {
biggestNum= b * 100 + a * 10 + c;
smallestNum= c * 100 + a * 10 + b;
medianNum= a;
}
else if (c > a && c > b && a > b) {
biggestNum= c * 100 + a * 10 + b;
smallestNum= b * 100 + a * 10 + c;
medianNum= a;
}
else if (c > a && c > b && a < b) {
biggestNum= c * 100 + b * 10 + a;
smallestNum= a * 100 + b * 10 + c;
medianNum= b;
}
cout << "Smallest number is: " << smallestNum<< " ,biggest is: " << biggestNum << " and median is: " << medianNum<< "." << endl;
return (biggestNum + smallestNum) / medianNum;
}
int main() {
cout << "Enter one 3 digit positive number: ";
int x;
cin >> x;
float result = check(x);
cout << "The result is: " << result << "." << endl;
system("pause");
return 0;
}
The posted code can't really produce the right answer, considering that the result is calculated with integer arithmetic:
int check(int x) // <- note the type of the returned value
{
int biggestNum, smallestNum, medianNum;
// ...
return (biggestNum + smallestNum) / medianNum; // <- This is an integer division
}
int main()
{
int x;
// ...
float result = check(x); // Now it's too late to get the right result
}
The logic also doesn't consider all the possible cases, as a matter of fact it ignores duplicated digits and the big if else if construct, lacking a default branch (a final unconditioned else), leaves those uninitialized variables undetermined so that the following operation gives a meaningless result.
Given the assignment restrictions, I'd write something like the following
#include <utility>
// The assignment is about 3-digit numbers, you should check that x is actually in
// the range [100, 999]. Note that one of the extremes is a special case.
// Well, both, actually.
double I_ve_no_idea_how_to_name_this(int x)
{
constexpr int base = 10;
int smallest = x % base;
x /= base;
int median = x % base;
x /= base;
// Note that this "works" (extracting the third digit) even if
// x isn't a 3-digit number. If you can assure the input is well
// defined, you can simplify this.
int biggest = x % base;
// Now we can sort the previous variables.
using std::swap;
if ( median < smallest ) {
swap(median, smallest);
}
// Now I know that smallest <= median
if ( biggest < median ) {
swap(biggest, median);
}
// Now I know that median <= biggest
// ...
// Is that enough or am I missing something here?
// Please think about it before running the code and test it.
// Once the variables are sorted, the result is easily calculated
return (biggest + smallest + base * (2 * median + base * (biggest + smallest)))
/ static_cast<double>(median);
}
First, you should use more descriptive variable names and should initialize each variable on definition. These two steps help greatly in squashing bugs in complex programs. I know this one isn't complex, but it's a good habit to have. Second, the standard library can help with finding the largest and smallest digit, which then makes the rest simple. So here's an example without any if statements.
Finally, using namespace std; is a bad practice and should be avoided.
double check(int x)
{
int a = x / 100;
int b = (x / 10) % 10;
int c = x % 10;
int bigdigit = std::max({ a, b, c }); // find largest
int smalldigit = std::min({ a, b, c }); //find smallest
int middledigit = a + b + c - bigdigit - smalldigit; // sum of all digits minus largest and smallest gives the remaining one
int biggest = smalldigit + middledigit * 10 + bigdigit * 100;
int smallest = smalldigit * 100 + middledigit * 10 + bigdigit;
std::cout << "biggest: " << biggest << '\n';
std::cout << "smallest: " << smallest << '\n';
std::cout << "median: " << middledigit << '\n';
return (1.0 * biggest + 1.0 * smallest) / (1.0 * middledigit); --using double instead of int, as result could be fractional
}
try this...
int check(int x) {
int a,b,c,temp;
a = x/100;
b = (x/10)%10;
c = x%10;
if(b>a){
temp=a;
a=b;
b=temp;
}
if(c>b){
temp=b;
b=c;
c=temp;
}
if(b>a){
temp=a;
a=b;
b=temp;
}
cout << "smallest: " << a+(b*10)+(c*100) << "\n";
cout << "biggest: " << (a*100)+(b*10)+c << "\n";
cout << "median: " << b << "\n";
return (((a+c)*100)+(2*b*10)+(a+c))/b;
}
check this check function.
int check(int x) {
if(x >= 1000) x %= 1000; //or return -1;
//get digits
int M = x/100;
int C = (x/10)%10;
int m = x%10;
//unrolled bubble sort.
if(M < C) swap(M,C);
if(C < m) swap(C,m);
if(M < C) swap(M,C);
//simplified formula
return ((m+M)*(101))/C + 20;
}
//derivation of formula
B = M*100 + C*10 + m;
s = m*100 + C*10 + M;
B+s = (m+M)*100 + C*20 + (m+M)
= (m+M)*(100 + 1) + C*20
(B+s)/C = ((m+M)*(100 + 1) + C*20)/C
= ((m+M)*(101))/C + 20
for an intro program, we were asked to build a program that could find every single possible working magic square of a given size. I am having trouble modifying a class variable from within a recursive function. I am trying to increment the number of magic squares found every time the combination of numbers I am trying yields a magic square.
More specifically, I am trying to modify numSquares within the function recursiveMagic(). After setting a breakpoint at that specific line, the variable, numSquares does not change, even though I am incrementing it. I think it has something to do with the recursion, however, I am not sure. If you want to lend some advice, I appreciate it.
//============================================================================
// Name : magicSquare.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
using namespace std;
/**
* MagicSquare
*/
class MagicSquare {
private:
int magicSquare[9];
int usedNumbers[9];
int numSquares;
int N;
int magicInt;
public:
MagicSquare() {
numSquares = 0;
for (int i = 0; i < 9; i++)
usedNumbers[i] = 0;
N = 3; //default is 3
magicInt = N * (N * N + 1) / 2;
}
MagicSquare(int n) {
numSquares = 0;
for (int i = 0; i < 9; i++)
usedNumbers[i] = 0;
N = n;
magicInt = N * (N * N + 1) / 2;
}
void recursiveMagic(int n) {
for (int i = 1; i <= N * N + 1; i++) {
if (usedNumbers[i - 1] == 0) {
usedNumbers[i - 1] = 1;
magicSquare[n] = i;
if (n < N * N)
recursiveMagic(n + 1);
else {
if (isMagicSquare()) {
numSquares++; //this is the line that is not working correctly
printSquare();
}
}
usedNumbers[i - 1] = 0;
}
}
}
//To efficiently check all rows and collumns, we must convert the one dimensional array into a 2d array
//since the sudo 2d array looks like this:
// 0 1 2
// 3 4 5
// 6 7 8
//the following for-if loops convert the i to the appropriate location.
bool isMagicSquare() {
for (int i = 0; i < 3; i++) {
if ((magicSquare[i * 3] + magicSquare[i * 3 + 1] + magicSquare[i * 3 + 2]) != magicInt) //check horizontal
return false;
else if ((magicSquare[i] + magicSquare[i + 3] + magicSquare[i + 6]) != magicInt) // check vertical
return false;
}
if ((magicSquare[0] + magicSquare[4] + magicSquare[8]) != magicInt)
return false;
if ((magicSquare[6] + magicSquare[4] + magicSquare[2]) != magicInt)
return false;
return true;
}
/**
* printSquare: prints the current magic square combination
*/
void printSquare() {
for (int i = 0; i < 3; i++)
cout << magicSquare[i * 3] << " " << magicSquare[i * 3 + 1]
<< " " << magicSquare[i * 3 + 2] << endl;
cout << "------------------" << endl;
}
/**
* checkRow: checks to see if the current row will complete the magic square
* #param i - used to determine what row is being analyzed
* #return true if it is a working row, and false if it is not
*/
bool checkRow(int i) {
i = (i + 1) % 3 - 1;
return (magicSquare[i * 3] + magicSquare[i * 3 + 1] + magicSquare[i * 3 + 2]) == magicInt;
}
int getnumSquares() {
return numSquares;
}
}; //------End of MagicSquare Class-----
int main() {
MagicSquare square;
cout << "Begin Magic Square recursion:" << endl << "------------------"
<< endl;
square.recursiveMagic(0);
cout << "Done with routine, returned combinations: " << square.getnumSquares() << endl;
return 0;
}
The array is being overwritten leading to overwriting the numSquares field.
class MagicSquare {
private:
int magicSquare[9];
int usedNumbers[9];
Changes to
class MagicSquare {
private:
int magicSquare[10];
int usedNumbers[10];
Also in your initializer the loop says < 9 but what you want to say is < 10. Or just use memset is better for that purpose.
I have the equation of a 2D line in the General Form a x + b y + c = 0 and I need to convert it to the proper Slope-intercept Form; with proper I mean I can choose between y = m x + q and x = m y + q.
My idea is to check if the line appears "more" horizontal or vertical and consequently choose one of the two Slope-intercept Form.
This is a sample code:
#include <iostream>
#include <cmath>
void abc2mq( double a, double b, double c, double& m, double& q, bool& x2y )
{
if ( fabs(b) >= fabs(a) ) {
x2y = true;
m = -a/b;
q = -c/b;
} else {
x2y = false;
m = -b/a;
q = -c/a;
}
}
void test(double a, double b, double c)
{
double m,q;
bool x2y;
abc2mq( a, b, c, m, q, x2y );
std::cout << a << " x + " << b << " y + " << c << " = 0\t";
if ( x2y ) {
std::cout << "y = " << m << " x + " << q << "\n";
} else {
std::cout << "x = " << m << " y + " << q << "\n";
}
}
int main(int argc, char* argv[])
{
test(0,0,0);
test(0,0,1);
test(0,1,0);
test(0,1,1);
test(1,0,0);
test(1,0,1);
test(1,1,0);
test(1,1,1);
return 0;
}
And this is the output
0 x + 0 y + 0 = 0 y = -1.#IND x + -1.#IND
0 x + 0 y + 1 = 0 y = -1.#IND x + -1.#INF
0 x + 1 y + 0 = 0 y = -0 x + -0
0 x + 1 y + 1 = 0 y = -0 x + -1
1 x + 0 y + 0 = 0 x = -0 y + -0
1 x + 0 y + 1 = 0 x = -0 y + -1
1 x + 1 y + 0 = 0 y = -1 x + -0
1 x + 1 y + 1 = 0 y = -1 x + -1
Any different or better idea? In particular, how can I handle the first two "degenerate" lines?
If you are looking for a good way to draw these lines, I would recommend using Bresenham's algorithm instead of sampling the result of the slope-intercept form of your line equation.
Apologies if this is not what you are trying to do.
You're almost done, just handle the degenerate case.
Add the check for a and b to be non-zero.
if(fabs(a) > DBL_EPSILON && fabs(b) > DBL_EPSILON)
{
... non-degenerate line handling
} else
{
// both a and b are machine zeros
degenerate_line = true;
}
Then add the parameter 'degenerate_line':
void abc2mq( double a, double b, double c, double& m, double& q, bool& x2y, bool& degenerate_line)
{
if(fabs(a) > DBL_EPSILON && fabs(b) > DBL_EPSILON)
{
if ( fabs(b) >= fabs(a) ) {
x2y = true;
m = -a/b;
q = -c/b;
} else {
x2y = false;
m = -b/a;
q = -c/a;
}
degenerate_line = false;
} else
{
degenerate_line = true;
}
}
And then check for the line to be empty set:
void test(double a, double b, double c)
{
double m,q;
bool x2y, degenerate;
abc2mq( a, b, c, m, q, x2y, degenerate );
std::cout << a << " x + " << b << " y + " << c << " = 0\t";
if(!degenerate)
{
if ( x2y ) {
std::cout << "y = " << m << " x + " << q << std::endl;
} else {
std::cout << "x = " << m << " y + " << q << std::endl;
}
} else
{
if(fabs(c) > DBL_EPSILON)
{
std::cout << "empty set" << std::endl
} else
{
std::cout << "entire plane" << std::endl
}
}
}
If all you need is to draw the line, just use Thorsten's advice - use the rasterization algorithm instead.
The equations corresponding to the two degenerated cases do not represent lines but the full plane (ℝ2) and the empty set (∅) respectively. The right thing to do is probably to discard them or to throw an error.
For the non degenerate cases, you are already handling them properly.