183k views
3 votes
How to get the minimum distance between array list elements? Code.

User OpenSource
by
5.1k points

1 Answer

3 votes

Here is code in java.

//import package

import java.util.*;

class Solution {

// main method of class Solution

public static void main (String[] args) throws java.lang.Exception

{

try{

// create a list of Integer type

ArrayList<Integer> list = new ArrayList<Integer>();

// create an object of Scanner class to read input

Scanner s=new Scanner(System.in);

int i;

// ask for length of list

System.out.println("How many numbers in the list ? ");

int len=s.nextInt();

System.out.println("please enter "+len+" numbers: " );

// read input from user

for(i=0;i<len;i++)

{

int x=s.nextInt();

list.add(x);

}

// sort the list

Collections.sort(list);

// declare and initialize "dis" variable with max value of Integer

int dis=Integer.MAX_VALUE;

for( i=0;i<len-1;i++)

{ // find the minimum distance between list elements

int m=list.get(i+1)-list.get(i);

if(m<dis)

dis=m;

}

// print the minimum distance

System.out.println("minimum distance is:"+dis);

}catch(Exception ex){

return;}

}

}

Step-by-step explanation:

Create an empty list of Integer type. Ask user to give length (n) of list.

Then read n Integer into the list.Sort the list in ascending order.Create

a variable dis and initialize it with maximum value of Integer.Then travers

the list and find the distance between two consecutive elements and store

it in a variable "m" and then compare with "dis", if value of "m" is less

than value of "dis" then update the value of "dis" with value of "m". When

the loop ends, "dis" will have minimum distance between list elements.

Output:

How many numbers in the list ?

10

please enter 10 numbers:

2

5

13

90

34

56

78

86

112

40

minimum distance is:3

User Anubis
by
4.7k points