Tuesday, January 22, 2019

Intervals 3

Write a program that, given two intervals, tells if one is inside the other, and computes the interval corresponding to their intersection, or tells that it is empty.

Input : Input consists of four integer numbers a1, b1, a2, b2 that represent the intervals [a1,b1] and [a2,b2]. Assume a1≤ b1 and a2≤ b2.

Output : Print ‘=’ if the intervals are equal, ‘1’ if the first is inside the second (but they are not equal), ‘2’ if the second is inside the first (but they are not equal), or ‘?’ otherwise. Also, print “[]” if the intersection is empty, or “[x,y]” if this is their non-empty intersection.

#include <iostream>
using namespace std;

int main () {
    int a, b, c, d;
    cin >> a >> b >> c >> d;
    
   // Print ‘=’ if the intervals are equal, 
   //‘1’ if the first is inside the second (but they are not equal), 
   //‘2’ if the second is inside the first (but they are not equal), 
    // or ‘?’ otherwise.
    
    if (a == c and b == d) cout << "= , "<< "[" << a << "," << b << "]" << endl;
    else {
        
        if ((a >= c and b < d) or (a > c and b <= d)) cout << "1 , "<< "[" << a << "," << b << "]" << endl;
        
        else {
            
            if ((a <= c and b > d) or (a < c and b >= d)) cout << "2 , "<< "[" << c << "," << d << "]" << endl;
            
            else {
                if (a == d) cout << "? , "<< "[" << a << "," << d << "]" << endl;
                else {
                    
                    if (b == c) cout << "? , "<< "[" << b << "," << c << "]" << endl;
                    
                    else {
                        
                        if (c>=a and c<=b and d>=b)  cout << '?' << ' ' << ',' << ' ' << '[' << c << ',' << b << ']' << endl;
                        
                        else {
                            
                            if (a>=c and a<=d and d<=b)  cout << '?' << ' ' << ',' << ' ' << '[' << a << ',' << d << ']' << endl;
                            
                            else {
                                
                                if (d>=a and d<=b and c<=a)  cout << '?' << ' ' << ',' << ' ' << '[' << a << ',' << d << ']' << endl;
                                
                                else  cout << "? , "<< "[]" << endl;
                            }
                        }
                    }
                }
            }
        }
    }
}

No comments:

Post a Comment

Modelo OSI

Open System Interconnection , Interconexión de Sistemas Abiertos, es un modelo para estudiar las categorías en que se pueden dividir los pr...