8883. Rectangle

 

You are given four positive integers a, b, c, d. Determine is it possible to form a rectangle with side lengths a, b, c, d. If such a rectangle exists, print the sum of all four numbers. Otherwise, print “No”.

 

Input. Four positive integers a, b, c, d, each not exceeding 109.

 

Output. If the rectangle exists, print the sum of all numbers. Otherwise, print “No”.

 

Sample input 1

Sample output 1

7 4 4 7

22

 

 

Sample input 2

Sample output 2

9 9 9 6

No

 

 

SOLUTION

conditional statement

 

Algorithm analysis

A rectangle can be formed only if the numbers a, b, c, d can be grouped into pairs of equal values. All possible pairings should be considered, namely:

·        a = b and c = d;

·        a = c and b = d;

·        a = d and b = c;

 

The task can also be solved using sorting. Let the array m contain the four given integers. Sort the array. A rectangle can be formed from these numbers if and only if the condition m[0] = m[1] and m[2] = m[3] holds.

 

Algorithm implementation

Read the input data.

 

scanf("%lld %lld %lld %lld", &a, &b, &c, &d);

 

If the rectangle exists, print its perimeter.

 

if ((a == b && c == d) || (a == c && b == d) || (a == d && b == c))

  printf("%d\n", a + b + c + d);

 

Otherwise print No”.

 

else

  printf("No\n");

 

Algorithm implementationsort

Declare an array to store the four input numbers.

 

int m[4];

 

Read the input data.

 

scanf("%d %d %d %d", &m[0], &m[1], &m[2], &m[3]);

 

Sort the numbers.

 

sort(m, m + 4);

 

If the rectangle exists, print its perimeter.

 

if (m[0] == m[1] && m[2] == m[3])

  printf("%d\n", m[0] + m[1] + m[2] + m[3]);

 

Otherwise print No”.

 

else

  printf("No\n");

 

Java implementation

 

import java.util.*;

 

public class Main

{

  public static void main(String[] args)

  {

    Scanner con = new Scanner(System.in);

    int a = con.nextInt();

    int b = con.nextInt();

    int c = con.nextInt();

    int d = con.nextInt();

   

    if ((a == b && c == d) || (a == c && b == d) ||

        (a == d && b == c))

      System.out.println(a + b + c + d);

    else

      System.out.println("No");

    con.close();

  }

}

 

Python implementation

Read the input data.

 

a, b, c, d = map(int, input().split())

 

If the rectangle exists, print its perimeter.

 

if (a == b and c == d) or (a == c and b == d) or (a == d and b == c):

  print(a + b + c + d)

 

Otherwise print “No”.

 

else:

  print("No")