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 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 implementation – sort
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")