Define the distance for a pair of positive integers x and y, as the absolute val
ID: 3684582 • Letter: D
Question
Define the distance for a pair of positive integers x and y, as the absolute value |x y|. For example, the distance for 35 and 44 is |35 44| = 9, and the distance for 1221 and 100 is |1221 100| = 1121.
Given n distinct positive integers x1, x2, . . . , xn where n > 2. Please write a program that prints two of these numbers, say xi and xj , so that the distance for xi and xj is the smallest. For example, for positive integers 11, 55, 34, 8, the pair of numbers (11, 8) have the smallest distance, and your program should output 11 8 or 8 11.
Please take integers from standard input (System.in):
• First line of input contains the number of n positive integers, where 2 < n < 1, 000, 000. • Second line of input contains all n positive integers x1, x2, . . . , xn, where xi N and 0 < xi 1, 000, 000, 000 for all i [n].
Please print your result to standard output (System.out)
• A single output line with two positive integers
Input: 10 6 2 12 14 91 18 5 333 32 41
Correct Output: 6 5
Explanation / Answer
import java.util.*;
import java.lang.*;
class min_distance
{
public static void main(String args[])
{
int a[]=new int[10],i,j,f=0,s=0,min,m;
Scanner scan=new Scanner(System.in);
for(i=0;i<10;i++)
{
a[i]=scan.nextInt();
}
min=Math.abs(a[0]-a[1]);
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
{
if(i!=j)
{
m=Math.abs(a[i]-a[j]);
if(m<=min)
{
min=m;
f=a[i];
s=a[j];
}
}
}
}
System.out.println("Correct Output :"+f+" "+s);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.